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/9.0 | <file_sep># -*- coding: utf-8 -*-
from openerp.addons.report_xlsx.report.report_xlsx import ReportXlsx
class PartnerXlsx(ReportXlsx):
def generate_xlsx_report(self, workbook, data, libro):
for obj in libro:
report_name = obj.name
# One sheet by partner
sheet = workbook.add_worksheet(report_name[:31])
bold = workbook.add_format({'bold': True})
sheet.write(0, 0, obj.name, bold)
sheet.write(0, 1, obj.company_id.name, bold)
sheet.write(0, 2, obj.periodo_tributario, bold)
sheet.write(0, 3, obj.tipo_operacion, bold)
sheet.write(0, 4, obj.tipo_libro, bold)
sheet.write(0, 5, obj.tipo_operacion, bold)
sheet.write(2, 0, u"Fecha", bold)
sheet.write(2, 1, u"Número", bold)
sheet.write(2, 2, u"Tipo de Identificación", bold)
sheet.write(2, 3, u"Número de Documento", bold)
sheet.write(2, 4, u"Compañia", bold)
sheet.write(2, 5, u"Referencia", bold)
sheet.write(2, 6, u"Total", bold)
line = 3
for rec in libro.move_ids:
sheet.write(line, 0, rec.date, bold)
sheet.write(line, 1, rec.document_number, bold)
sheet.write(line, 2, rec.document_class_id.name, bold)
sheet.write(line, 3, rec.sii_document_number, bold)
sheet.write(line, 4, rec.partner_id.name, bold)
sheet.write(line, 5, rec.ref, bold)
sheet.write(line, 6, rec.amount, bold)
line += 1
PartnerXlsx('report.account.move.book.xlsx',
'account.move.book')
<file_sep># -*- coding: utf-8 -*-
from . import libro
from . import consumo_folios
from . import export
| bbff4b1c45fa188ca4c895cbfdd761f7561f7188 | [
"Python"
] | 2 | Python | odoo-chile/l10n_cl_libro_compra_venta | b83e0f5765ace05e0107b384b75f39391f9259e3 | 67855f5faa075f0d64943cb80ab7ba0f526918d4 |
refs/heads/master | <file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: { type: String },
password: { type: String },
create_at: { type: Date, default: Date.now },
update_at: { type: Date, default: Date.now }
});
mongoose.connect('mongodb://127.0.0.1/democh05');
var User = mongoose.model('user', UserSchema); // 与users集合关联
exports.getUserByUserName = function (username, callback) {
User.findOne({ 'username': username }, callback);
}
exports.save = function (userinfo, callback) {
var user = new User();
user.username = userinfo.username;
user.password = <PASSWORD>;
user.save(callback);
}
exports.update = function (username, callback) {
var user=new User();
User.update(
{ 'username': username },
{ $set: { update_at: new Date() } },
callback);
}<file_sep>var express = require('express');
var router = express.Router();
/*
* 1.基本语法
* 2.html转义
*
*
*
* */
router.get('/', function(req, res, next) {
res.render('index',
{ title: 'Express',
article:{title:'副标题'},
htmlEscape:'<p>This is a post about <p> tags</p>',
nohtmlEscape:'<p>This is a post about <p> tags</p>',
layout:null
});
});
/*
* 1.block块表达式
*
*
* */
router.get('/block',function(req,res,next) {
res.render('block',
{
author: {firstName: "Alan", lastName: "Johnson"},
body: "I Love Handlebars",
comments: [{
author: {firstName: "Yehuda", lastName: "Katz"},
body: "Me too!"
}],
layout:null
}
)
});
module.exports = router;
<file_sep>var models = require('../models');
var WechatUserInfo = models.WechatUserInfo;
/**
* 根据用户的OpenID查找用户
* Callback:
* - err, 数据库异常
* - wechantuserinfo, 用户
* @param {Array} openid 用户的openid
* @param {Function} callback 回调函数
*/
exports.getwechatuserinfobyopenid = function (openid, callback) {
WechatUserInfo.findOne({ 'openid': openid }, callback);
};
exports.update = function (wechatuserinfo, callback) {
WechatUserInfo.update
(
{ 'openid': wechatuserinfo.openid },
{
$set:
{
nickname:wechatuserinfo.nickname,
sex:wechatuserinfo.sex,
province:wechatuserinfo.province,
city:wechatuserinfo.city,
country:wechatuserinfo.country,
headimgurl:wechatuserinfo.headimgurl,
privilege:wechatuserinfo.privilege,
unionid:wechatuserinfo.unionid,
update_at:new Date(),
}
},
callback
);
};
/**
* 保存用户的授权记录
*
*
*/
exports.newAndSave = function (wechatuserinfo, callback) {
var wechatuser = new WechatUserInfo(wechatuserinfo);
wechatuser.save
(
callback
);
};<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WechatUserSchema = new Schema({
//用户的唯一标识
openid: { type: String },
//用户昵称
nickname: { trype: String },
//sex
sex: { type: String },
//用户个人资料填写的省份
province: { type: String },
//城市
city: { type: String },
//国家
country: { type: String },
//用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
headimgurl: { type: String },
//用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
privilege: [{ type: String }],
//只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
unionid: { type: String },
//公众号的appid
create_at: { type: Date, default: Date.now },
update_at: { type: Date, default: Date.now },
});
var WechatUserInfo = mongoose.model('wechatuser', WechatUserSchema); //
/**
* 根据用户的OpenID查找用户
* Callback:
* - err, 数据库异常
* - wechantuserinfo, 用户
* @param {Array} openid 用户的openid
* @param {Function} callback 回调函数
*/
exports.getwechatuserinfobyopenid = function (openid, callback) {
WechatUserInfo.findOne({ 'openid': openid }, callback);
};
exports.update = function (wechatuserinfo, callback) {
WechatUserInfo.update
(
{ 'openid': wechatuserinfo.openid },
{
$set:
{
nickname:wechatuserinfo.nickname,
sex:wechatuserinfo.sex,
province:wechatuserinfo.province,
city:wechatuserinfo.city,
country:wechatuserinfo.country,
headimgurl:wechatuserinfo.headimgurl,
privilege:wechatuserinfo.privilege,
unionid:wechatuserinfo.unionid,
update_at:new Date(),
}
},
callback
);
};
/**
* 保存用户的授权记录
*
*
*/
exports.newAndSave = function (wechatuserinfo, callback) {
var wechatuser = new WechatUserInfo(wechatuserinfo);
wechatuser.save
(
callback
);
};<file_sep>var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res) {
if (!req.session || !req.session.userinfo) {
res.redirect('/login?returnurl=' + req.originalUrl);
return;
}
res.render('users/index',
{
title: '个人中心',
layout: 'layouts/main',
user: req.session.userinfo
});
});
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var User = require('../models/user');
var md5=require('md5');
/*
* 1.首页
*
*
*
*
* */
router.get('/', function (req, res, next) {
res.render('index',
{
title: 'Express',
layout: null
});
});
/*
* 登录
*
*
* */
router.route('/login')
.get(function (req, res) {
res.render('login',
{
title: '用户登录',
returnurl: req.query.returnurl,
layout: 'layouts/main'
}
)
})
.post(function (req, res) {
// var user = { username: 'frank', password: '123' };
// console.log(req.body);
var username = req.body.username;
var password = <PASSWORD>;
User.getUserByUserName(username, function (err, user) {
if (user) {
if (username == user.username && md5(password) == user.password) {
User.update(username, function () {
req.session.userinfo = user;
if (req.body.returnurl) {
res.redirect(req.body.returnurl);
}
else {
res.redirect('/');
}
return;
});
}
else {
res.send('用户密码不对');
return;
}
}
else {
res.send('用户不存在');
return;
}
});
}
)
router.route('/register')
.get(function (req, res) {
res.render('register',
{
title: '用户注册',
returnurl: req.query.returnurl,
layout: 'layouts/main'
}
)
})
.post(function (req, res) {
// var user = { username: 'frank', password: '123' };
// console.log(req.body);
var username = req.body.username;
var password = req.body.password;
User.getUserByUserName(username, function (err, user) {
if (user) {
res.send('该用户名已经存在');
return;
}
else {
var userinfo = { 'username': username, 'password': <PASSWORD>) };
User.save(userinfo,function()
{
res.redirect('login');
return;
});
}
});
}
)
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('users/index',
{ title: '个人中心',
layout:'layouts/main'
});
});
router.get('/index2', function(req, res, next) {
res.render('users/index2',
{ title: '个人中心_局部文件',
layout:'layouts/main'
});
});
router.get('/index3', function(req, res, next) {
res.render('users/index3',
{ title: '个人中心3_局部文件',
layout:'layouts/main'
});
});
router.get('/home/', function(req, res, next) {
res.render('users/index3',
{ title: '个人中心home_局部文件',
layout:'layouts/main'
});
});
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var urlencode = require('urlencode');
var urllib = require('urllib');
var WechatUserInfo = require('../proxy/wechatuser');
/* GET users listing. */
router.get('/', function (req, res) {
if (!req.session || !req.session.wechatuserinfo) {
var redirect_uri = 'http://frank.ompchina.net/wechat/callback/?returnurl=' + urlencode(req.originalUrl);
res.redirect('http://wx.ompchina.net/sns/oauth2?appId=wx1f984cba30eb34b7&oauthscope=snsapi_userinfo&redirecturl=' + urlencode(redirect_uri));
return;
}
res.render('wechat/index',
{
title: '授权登录个人中心',
layout: 'layouts/main',
wechatuser: req.session.wechatuserinfo
});
});
/* GET users listing. */
router.get('/callback', function (req, res) {
var returnurl = req.query.returnurl;
var openid = req.query.openid;
console.log(returnurl);
console.log(openid);
//查询用户信息
var params = {
dataType: 'json',
contentType: 'json',
data: {
appId: 'wx1f984cba30eb34b7',
openid: openid
}
};
urllib.request('http://wx.ompchina.net/sns/UserInfo', params, function (err, data) {
console.log(data);
WechatUserInfo.getwechatuserinfobyopenid(data.openid, function (err, getwechatuserinfo) {
req.session.wechatuserinfo =
{
openid: data.openid,
nickname: data.nickname,
headimgurl: data.headimgurl
};
if (!getwechatuserinfo) {
WechatUserInfo.newAndSave(data, function () {
return res.redirect(returnurl);
});
}
else {
WechatUserInfo.update(data, function () {
return res.redirect(returnurl);
});
}
});
});
});
module.exports = router;
<file_sep>var mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/democh06", {
server: { poolSize: 20 }
}, function (err) {
if (err) {
process.exit(1);
}
});
// models
require('./wechatuser');
exports.WechatUserInfo = mongoose.model('wechatuser');
| e064cf9a16e7d67ebf0faacc6f71fbceee8fb29e | [
"JavaScript"
] | 9 | JavaScript | heshiliang/node-and-express | de9e6ac340cf3a11e4b70cf2cbde44b152755024 | 678dd9fadb8de6e6becd6b6843b8b73c0ebd3bb5 |
refs/heads/master | <file_sep>train_data=[72,70,75,62,55,58,65,45,55,60,55,76,77,55,105,74,82,90,66,63,73,61,59,50,60,80,70,60,47]
train_target=[177,171,168,162,160,162,168,148,160,170,152,171,179,151,162,153,165,180,165,180,165,167,176,182,160,160,180,155,176]
print(len(train_data))
print(len(train_target))
import numpy as np
train_data=np.array(train_data)
train_target=np.array(train_target)
train_data=train_data.reshape(len(train_data),1) # make a 2d array with set of one element array list
#requirement in sklearn. train_data should be a 2D array
#print(train_data)
from sklearn.linear_model import LinearRegression
Algo=LinearRegression() #load linear regression to the black box named Algo
Algo.fit(train_data,train_target) # training the ML-algorithm
test_data=[[84]]
result=Algo.predict(test_data)
print(result)
from matplotlib import pyplot as plt
plt.scatter(train_data,train_target)
plt.show()<file_sep>from sklearn import datasets #importing datasets
iris=datasets.load_iris() #loading iris flower data set into iris
data=iris.data #iris flower data, 150*4 array will be loaded to data
target=iris.target #iris flower targets, 150*1 array will be loaded to data
from sklearn.model_selection import train_test_split
train_data,test_data,train_target,test_target=train_test_split(data,target,test_size=0.1)
from sklearn.neighbors import KNeighborsClassifier #load KNN classifier
clsfr=KNeighborsClassifier(n_neighbors=3) #KNN classifier with k value=3
clsfr.fit(train_data,train_target)
result=clsfr.predict(test_data)
print('Predicted',result)
print('Actual',test_target)
from sklearn.metrics import accuracy_score
accuracy=accuracy_score(test_target,result)
print('accuracy:',accuracy)
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # Axes 3D used for 3 axis graphs
fig=plt.figure() #initialize 3D graph
ax=fig.add_subplot(111,projection='3d') #adding 3 axes to fig graph, 111-xyz true
for i in range(0,len(train_target)):
if(train_target[i]==0): # if target is setosa
ax.scatter(train_data[i][0],train_data[i][1],train_data[i][2],c='g')
elif(train_target[i]==1): # if target is verginica
ax.scatter(train_data[i][0],train_data[i][1],train_data[i][2],c='r')
elif(train_target[i]==2): # if target is versicolor
ax.scatter(train_data[i][0],train_data[i][1],train_data[i][2],c='b')
print(result[0],test_target[0])
ax.scatter(test_data[0][0],test_data[0][1],test_data[0][2],c='c',marker='x')
plt.show()<file_sep>from sklearn import datasets
wine= datasets.load_wine()
##print(wine.feature_names)
##print(wine.target_names)
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(wine.data,wine.target,test_size=0.3)
from sklearn.neighbors import KNeighborsClassifier
clsfr=KNeighborsClassifier(n_neighbors=10)
clsfr.fit(x_train,y_train)
result=clsfr.predict(x_test)
from sklearn import metrics
print('Accuracy:',metrics.accuracy_score(y_test,result))
<file_sep>import pandas as pd
import numpy as np
datasets= pd.read_csv('2.0 Salary_Data.csv')
x = datasets.iloc[:, :-1].values #makes a 2d array
y = datasets.iloc[:, 1].values #makes simple array
##retrieving rows by iloc method
#values to get only values to an array
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.1,random_state=0)
from sklearn.linear_model import LinearRegression
clsfr=LinearRegression()
clsfr.fit(x_train,y_train)
result=clsfr.predict(x_test)
print('test values:',y_test)
print('predicted values:',result)
import matplotlib.pyplot as plt
plt.scatter(x_train,y_train,color='red')
plt.scatter(x_test, y_test, color = 'green')
plt.plot(x_train, clsfr.predict(x_train), color = 'blue')
plt.xlabel('Years of experience')
plt.ylabel('Salary')
plt.show()
| 328163b1a19e18acba7c5acd2ff4a7fd442a1a75 | [
"Python"
] | 4 | Python | EANimesha/Machine-Learning | 7126691d7ab9f9e94036600c1d1539dfed40c4eb | 7c94abeaa79a0425a1ef96a2281883c331bdc357 |
refs/heads/master | <file_sep>import time
import requests
import os
import json
from datetime import datetime
import logging
logging.basicConfig(filename="Log.log", filemode="w", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
class YaUploader:
def __init__(self, ya_token):
self.ya_token = ya_token
def upload(self, file_path):
response = requests.put(self.get_upload_link(file_path), data=open(file_path, "rb"), timeout=5)
if response.status_code == 201:
return "Success"
def get_path_for_vk_photos(self, vk_id, username):
if vk_id == 0 and username == "owner":
path = "vk_app_owner_photos_reserve"
elif vk_id == 0:
path = f"vk_{username}_photos_reserve"
elif username == "owner":
path = f"vk_{vk_id}_photos_reserve"
else:
path = f"vk_{username}_{vk_id}_photos_reserve"
return path
def get_headers(self):
return {"Content-type": "application/json", "Authorization": f"OAuth {self.ya_token}"}
def get_upload_link(self, file_path):
url = "https://cloud-api.yandex.net/v1/disk/resources/upload"
params = {"path": os.path.basename(file_path), "overwrite": "true"}
response = requests.get(url, params=params, headers=self.get_headers(), timeout=5)
time.sleep(0.3)
return response.json()["href"]
def ya_disk_create_folder(self, vk_id, username):
url = "https://cloud-api.yandex.net/v1/disk/resources"
logging.info(f"Getting path for new folder on Yandex Disk")
params = {"path": "/" + self.get_path_for_vk_photos(vk_id, username)}
logging.info(f"Path created: {params['path']}")
logging.info(f"Creating folder for Yandex Disk")
resp = requests.put(url, params=params, headers=self.get_headers(), timeout=5)
if resp.status_code == 201:
logging.info(f"Status code: {resp.status_code}, folder created")
elif resp.status_code == 409:
logging.warning(f"Status code: {resp.status_code}, folder already exists")
else:
logging.error(f"Status code: {resp.status_code}")
time.sleep(0.3)
return resp.json()
def ya_disk_upload_from_link(self, file_url, file_name, vk_id, username):
url = "https://cloud-api.yandex.net/v1/disk/resources/upload"
params = {"url": file_url,
"path": "/" + self.get_path_for_vk_photos(vk_id, username) + "/" + file_name
}
resp = requests.post(url, params=params, headers=self.get_headers(), timeout=5)
if resp.status_code == 202:
logging.info(f"Status code:{resp.status_code}, file {file_name} uploaded")
else:
logging.error(f"Error, status code{resp.status_code}")
time.sleep(0.3)
return
class VkLoader(YaUploader):
Vk_url = "https://api.vk.com/method/"
def __init__(self, ya_token, vk_token):
super().__init__(ya_token)
self.vk_token = vk_token
self.params = {
"access_token": self.vk_token,
"v": "5.130"
}
def get_photo(self, owner_id, count, vk_url=Vk_url):
url = vk_url + "photos.get"
photo_params = {
"album_id": "profile",
"extended": 1,
"count": count,
"photo_sizes": 1
}
if owner_id != 0:
photo_params["owner_id"] = owner_id
logging.info(f"Getting photos dict for user id: {owner_id}")
else:
logging.info(f"Getting photos dict for app owner(id = 0)")
resp = requests.get(url, params={**self.params, **photo_params}, timeout=5)
if resp.status_code == 200:
logging.info(f"Dict recieved, status code: {resp.status_code}")
else:
logging.error(f"Error, Status code: {resp.status_code}")
time.sleep(0.4)
return resp.json()["response"]["items"]
def photos_sort(self, vk_id, count):
photos_list = []
for photo in self.get_photo(vk_id, count):
photo_dict = {"likes": photo["likes"]["count"], "date": photo["date"], "size": photo["sizes"][-1]["type"],
"url": photo["sizes"][-1]["url"]}
photos_list.append(photo_dict.copy())
photo_dict.clear()
final_photos_list = []
names_list = []
for photo in photos_list:
if photo["likes"] not in names_list:
photo_dict["file_name"] = photo["likes"]
names_list += [photo["likes"]]
else:
date = str(datetime.fromtimestamp(photo["date"]))
date = date.replace(" ", "_")
date = date.replace(":", ".")
photo_dict["file_name"] = date
photo_dict["size"] = photo["size"]
photo_dict["url"] = photo["url"]
final_photos_list.append(photo_dict.copy())
names_list.clear()
logging.info("Original photos dict transformed to list")
return final_photos_list
def upload_vk_profile_photos_to_ya_disk(self, vk_id=0, count=10, username=None):
logging.info("Program started")
if count > 1000 or count < 0 or type(count) != int:
logging.error("Wrong input (count type must be int and value >=0 and <=1000)")
return
if type(vk_id) != int:
logging.error("Wrong input (vk_id type must be int)")
return
photos_list = self.photos_sort(vk_id, count)
if username is None:
username = "owner"
self.ya_disk_create_folder(vk_id, username)
logging.info("Started uploading to Yandex Disk")
for photo in photos_list:
self.ya_disk_upload_from_link(photo.pop("url"), str(photo["file_name"]) + ".jpg", vk_id, username)
self.write_to_json(photos_list, vk_id, username)
return
def write_to_json(self, photos_list, vk_id, username):
logging.info("Dumping photos info to json file")
with open(f"{self.get_path_for_vk_photos(vk_id, username)}.json", "w") as f:
json.dump({"Photos": photos_list}, f, indent=2)
logging.info(f"Created file: {self.get_path_for_vk_photos(vk_id, username)}.json")
return
<file_sep>import logging
from vk_photos_to_ya_disk import VkLoader
ya_token_file = "ya_token.txt"
vk_token_file = "vk_token.txt"
vk_id = 0
vk_username = None
count = 15
with open(ya_token_file) as f:
ya_token = f.read()
with open(vk_token_file) as f:
vk_token = f.read()
if __name__ == "__main__":
loader = VkLoader(ya_token, vk_token)
loader.upload_vk_profile_photos_to_ya_disk(vk_id, count, vk_username)
logging.info("End")
| 4fa05173e8819fd780ae74319392c80fcbfd665d | [
"Python"
] | 2 | Python | PavelZigrit/intermediate_thesis_1 | 1f9a830afddc7d3801326f841126a57fa03d9ebf | 443d2e8baef0b35e2e886d9c88c953f750de3af6 |
refs/heads/master | <file_sep># Prayer wall
Feature:
Scenario: The user will be able to log on to the website and submit a prayer request.
Once the user logs on to the page, they will be ask to continue anonymously or to enter a name.
The user will be able to select if they want to submit a prayer request or click on one of the other options: Video, Prayer chain, Request for contact.
Submitting Prayer request example:
The user will be directed to the notepad screen where they can input their request. The user will then type in there request. The text will be check for grammatical errors with squiggle lines. The users will be allowed to proof the request before submitting the request. The user will have options to change the font, add highlighted words and underline. There will be an edit button, undo button, preview button affixed to the top of the notepad screen. Once the user has previewed their message, they can click the post button at the bottom of the screen.
Prayer request will be posted on the page labeled "Prayers". They will be listed by dates in order of the date they were posted.
Functional:
The system must post submissions to the prayer main page. The system must include name of person submitting or label as anonymous. The system must allow the user to select options to watch videos or join the prayer chain, or request to be contacted by clicking on the buttons on the main page.
The system must be able to take information from users requesting to join the prayer chain. The system will store the information in a database. The system will be able to pull names and email address from database and send out weekly email organized by the administrator.
The system will allow the user to select the video repository and search for videos related to the topic they enter. System will present related video on a new page where the user will be allowed to click a button to go to the next page or select the video they want to watch. The system will secure the videos so that it can not be downloaded.
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace PrayerWall.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Wall",
columns: table => new
{
WallId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Url = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Wall", x => x.WallId);
});
migrationBuilder.CreateTable(
name: "Chains",
columns: table => new
{
PostId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Title = table.Column<string>(nullable: true),
Content = table.Column<string>(nullable: true),
BlogId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Chains", x => x.PostId);
table.ForeignKey(
name: "FK_Chains_Walls_WallId",
column: x => x.WallId,
principalTable: "Walls",
principalColumn: "WallId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Chains_WallId",
table: "Chains",
column: "WallId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Chains");
migrationBuilder.DropTable(
name: "Walls");
}
}
}
<file_sep>using System;
using System.Linq;
namespace PrayWall
{
class Program
{
static void Main()
{
using (var db = new PrayerRequest())
{
// Create
Console.WriteLine("Inserting a new prayer request");
db.Add(new Wall { Url = "http://blogs.msdn.com/adonet" });
db.SaveChanges();
// Read
Console.WriteLine("Querying for a request");
var blog = db.Walls
.OrderBy(b => b.WallId)
.First();
// Update
Console.WriteLine("Updating the prayer request");
wall.Url = "https://devblogs.microsoft.com/dotnet";
wall.Chains.Add(
new Chain
{
Title = "Thanks for praying",
Content = "I added a new prayer request!"
});
db.SaveChanges();
// Delete
Console.WriteLine("Delete the request");
db.Remove(wall);
db.SaveChanges();
}
}
}
}}
<file_sep>using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace PrayerWall
{
public class PrayerRequest : DbRequest
{
public DbSet<Wall> Walls { get; set; }
public DbSet<Chain> Chains { get; set; }
protected override void OnConfiguring(DbRequestOptionsBuilder options)
=> options.UseSqlite("Data Source=prayer.db");
}
public class Wall
{
public int WallId { get; set; }
public string Url { get; set; }
public List<Chain> Chains { get; } = new List<Chain>();
}
public class Chain
{
public int ChainId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int WallId { get; set; }
public Wall Wall { get; set; }
}
}
| fc09ae464f0277cc28822de71afda097fbbd2871 | [
"Markdown",
"C#"
] | 4 | Markdown | darianpace/CourseProject | ce4a6679d9ed0402a96fd8aae3bdc64251f38a3d | 3f9104a4a14b0398ab2281be081cdb0d849e096f |
refs/heads/master | <repo_name>u-u-z/ts-practice<file_sep>/src/index.ts
let bool: boolean = false
let num: number = 123
num = 0b11001
num = 0o177
num = 0x7ba
let str: string
str = 'abc'
str = `number ${num}`
let arr1: number[] = [1, 2, 3, 4, 5]
let arr2: Array<number> = [1, 2, 3, 4]
let arr3: (string | number)[] = [1, 'num']
//元組
let tuple1: [string, number] = ['1', 2]
//枚舉
enum Roles {
SUPER_ADMIN,
ADMIN,
USER,
}
console.log(Roles.SUPER_ADMIN) // 0
console.log(Roles[0]) // SUPER_ADMIN
let i: any[] = [1, 2, false]
//void 類型
const consoleText = (text: string): void => {
console.log(text)
}
let v: void
v = consoleText("test")
//null undefined
//never 類型
//任何類型的子類型
const errorFunc = (msg: string): never => {
throw new Error(msg)
}
const initFunc = (): never => {
while (true) { }
}
let neverTest = (() => {
while (true) { }
})()
// 類型斷言
const getLength = (target: string | number) => {
if ((<string>target).length || (target as string).length === 0) {
//jsx時不可以寫尖括號
return (<string>target).length
} else {
return target.toString().length
}
}
/*
* Symbol
*/
//獨一無二的值
const s1 = Symbol('lison')
const s2 = Symbol(123)
//不能操作 s1 + s2
console.log(s2.toString())
console.log(Boolean(s2)) // true
console.log(!s2)//false
const s5 = Symbol('pop')
let sttr = "test"
const a1InfoObj = {
name: 'lison',
[`my${sttr}`]: "",
[s5]: 'test', //獨一無二不可修改只能如下修改
}
a1InfoObj[s5] = 'haha'
//for in 的時候遍歷不出來
//Object.keys() 也獲取不到Symbol
//Object.getOwnPropertyNames() 獲取不到Symbol
//JSON.stringify(a1InfoObj) //對象轉字符串獲取不到Symbol
//只有
console.log(Object.getOwnPropertySymbols(a1InfoObj))
console.log(Reflect.ownKeys(a1InfoObj)) //可以獲取所有包括symbol
//可以用Symbol 作為對象私有屬性
//Symbol.for()
//Symbol.keyFor()
const s6 = Symbol('zhizhang')
const s7 = Symbol('zhizhang')
const s8 = Symbol.for('zhizhang')
//在全局範圍搜索是否有 創建 zhizhang 字符串的 Symbol
const s9 = Symbol.for('zhizhang')
//全局包括頁面、iframe、serviceWork
//s8 === s9 true
Symbol.keyFor(s8) // 傳入 Symbol.for 在全局註冊的標識,如果是 Symbol註冊 傳入的將會undefined
/**
* 11 個內置的 Symbol值
*
*
*/
//Symbol.hasInstance
//當你給一個對象 設置 Symbol.hasInstance 屬性名的時候
//
const objSy1 = {
[Symbol.hasInstance](otherObj: any) {
console.log(otherObj)
}
}
console.log({ a: 'a' } instanceof <any>objSy1)
//{a:'a'}不是 objSy1 創建的實例
//isConcatSpreadable 設置為 true
// [1,2,3,4] 若不是 [Array(2),3,4]
// 扁平化操作
//let arr4 = [1, 2]
//console.log([].concat(arr4, [3, 4]))
//arr4[Symbol.isConcatSpreadable] = false //可讀寫的布爾值
//console.log([].concat(arr4, [3, 4]))
class C extends Array {
constructor(...args: any) {
super(...args)
}
static get [Symbol.species]() {
return Array
}
getName() {
return 'jack'
}
}
const c = new Array(1, 2, 3)
const d = new C(1, 2, 3)
const a = c.map(item => {
return item + 1
})
const b = d.map((item: number) => {
return item + 1
})
// a [2,3,4] a是c的延伸數據
// c instanceof Array //true
// a instanceof C //JS/TS false 去掉Symbol.species]true
// a instanceof Array //true
/*
用 Symbol.species 來指定創建衍生對象的對象函數
*/
let obj3 = {
[Symbol.match](string: string) {
console.log(string.length)
},
[Symbol.replace](string: string) {
console.log(string.length)
}
}
'abcde'.match(<RegExp><unknown>obj3)
//5
//Symbol.replace
//Symbol.search
//Symbol.split
//////////////
// Symbol.iterator 返回 數組的遍歷器
const arr5: number[] = [1, 2, 3, 4]
const iterator = arr5[Symbol.iterator]()
iterator.next() //{value:1,done:false}
iterator.next() //{value:2,done:false}
iterator.next() //{value:3,done:false}
iterator.next() //{value:4,done:false}
iterator.next() //{value:undefined,done:true}
let obj4: unknown = {
[Symbol.toPrimitive](type: any) {
console.log(type)
}
}
// const res1 = (obj4 as number)++
const res2 = `abc${obj4}`
//===================
//Symbol.toStringTag
let obj5 = {
[Symbol.toStringTag]:'remi'
}
let obj51 = {
get [Symbol.toStringTag](){
return 'remi'
}
}
console.log(obj5.toString()) //[object remi]
console.log(obj51.toString()) //[object remi]
const objExp1 = {
a:'test1',
b:'test2'
}
console.log(Array.prototype[Symbol.unscopables])
// with(<any>objExp1){
// console.log()
// } | eac44bba4e05c9f03c39ec0fc5659d02eacd8f64 | [
"TypeScript"
] | 1 | TypeScript | u-u-z/ts-practice | 695be283850daddadc1cf4dc7a96a9484c5d89aa | 7cc03348c772cb118f8d8db7607c5ca3614d2210 |
refs/heads/master | <file_sep>docker build -t goshako/multi-client:latest -t goshako/multi-client:$SHA -f ./client/Dockerfile ./client
docker build -t goshako/multi-server:latest -t goshako/multi-server:$SHA -f ./server/Dockerfile ./server
docker build -t goshako/multi-worker:latest -t goshako/multi-worker:$SHA -f ./worker/Dockerfile ./worker
docker push goshako/multi-client:latest
docker push goshako/multi-server:latest
docker push goshako/multi-worker:latest
docker push goshako/multi-client:$SHA
docker push goshako/multi-server:$SHA
docker push goshako/multi-worker:$SHA
kubectl apply -f k8s
kubectl set image deployments/client-deployment client=goshako/multi-client:$SHA
kubectl set image deployments/server-deployment server=goshako/multi-server:$SHA
kubectl set image deployments/worker-deployment worker=goshako/multi-worker:$SHA
| a085740f695011574b8765d4e7ced98286f4046e | [
"Shell"
] | 1 | Shell | Bakly23/multi-k8s | c7bce219c74e149be29d517cfa8f1895dcf3ff67 | 64cd1a7a3aa443ac4a0bcea5d465584319cf2c7f |
refs/heads/master | <repo_name>tringalama2/recipe-multiplier<file_sep>/js/Views/print-recipe.js
class PrintRecipe {
constructor(recipe, element) {
this.recipe = recipe;
this.element = element;
this.element.textContent = "";
this.heading = document.createElement("h3");
this.heading.textContent = this.recipe.name;
this.element.appendChild(this.heading);
this.list = document.createElement("ul");
element.appendChild(this.list);
this.recipe.ingredients.forEach((ingredient) => {
this.appendIngredient(ingredient);
});
}
appendIngredient(ingredient) {
const listItem = document.createElement("li");
listItem.textContent =
ingredient.getCurrentQuantity() +
" " +
ingredient.getUnit() +
" " +
ingredient.getName();
this.list.appendChild(listItem);
}
}
module.exports = PrintRecipe;<file_sep>/js/Recipe/recipe.js
const PrintRecipe = require("../Views/print-recipe");
class Recipe {
constructor(name) {
this.name = name;
this.ingredients = [];
}
addIngredient(ingredient) {
this.ingredients.push(ingredient);
}
multiply(multiplier) {
this.ingredients.forEach((ingredient, index, array) => {
ingredient.multiply(multiplier);
});
}
printHtml(element) {
new PrintRecipe(this, element);
}
}
module.exports = Recipe;
<file_sep>/js/Recipe/ingredient.js
import { Fractionalize, FractionalizeOptions } from "fractionalize";
import pluralize, { singular, plural, isSingular } from "pluralize";
class Ingredient {
constructor(name, quantity, unit) {
this.name = name;
this.baseQuantity = quantity;
this.currentQuantity = quantity;
this.unit = unit;
this.opts = new FractionalizeOptions();
this.opts.maxDenominator = 12;
this.opts.tolerance = 0.05;
}
getName() {
// shouldn't we just pluralize the unit?
// if (!isSingular(this.name) && this.quantity === 1) {
// return singular(this.name);
// } else if (isSingular(this.name) && this.quantity !== 1) {
// return pluralize(this.name);
// }
return this.name;
}
getUnit() {
if (!isSingular(this.unit) && this.isSingleQuantity(this.currentQuantity)) {
return singular(this.unit);
} else if (isSingular(this.unit) && !this.isSingleQuantity(this.currentQuantity)) {
return pluralize(this.unit);
}
return this.unit;
}
getBaseQuantity() {
return Fractionalize(this.baseQuantity, this.opts);
}
getCurrentQuantity() {
return Fractionalize(this.currentQuantity, this.opts);
}
multiply(multiplier) {
this.currentQuantity = multiplier * this.baseQuantity;
}
isSingleQuantity(quantity) {
if (quantity <= 1 && quantity > 0) {
return true;
}
return false;
}
}
module.exports = Ingredient;<file_sep>/package.json
{
"name": "recipe-multiplier",
"version": "1.0.0",
"description": "double or triple your recipes",
"main": "./js/app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "<NAME>",
"license": "ISC",
"dependencies": {
"date-fns": "^2.16.1",
"fraction-calculator": "^1.0.14",
"fractionalize": "^1.0.3",
"parcel-bundler": "^1.12.4",
"pluralize": "^8.0.0"
}
}
| 4e5a69383cfda193b5b9f364c3e4b1d072b8026b | [
"JavaScript",
"JSON"
] | 4 | JavaScript | tringalama2/recipe-multiplier | b89c36f1a7bbca07dad1821a718085f7e4764d49 | 34b92060227b39a601cbc2111e726d1d51ec4e6c |
refs/heads/master | <repo_name>test987654123/reboot_learnning<file_sep>/README.md
# reboot_learnning
notepad Learnning
<file_sep>/go_project_pachong/localtion/local_var.go
package main
import "fmt"
// const defen method
func consts() {
const (
a, b = 2, 3
)
const filename = "gopher"
// 枚举类型
const (
cpp = iota
java
python = iota + 100
ruby
golang
)
fmt.Println(golang, a, b, filename)
fmt.Printf("%T \n", a)
}
func main() {
consts()
}<file_sep>/mytcp/utils/base_struct.go
package utils
type ServerInfo struct {
Proto string `json:"proto"`
Host string `json:"host"`
Port int `json:"port"`
}
<file_sep>/mytcp/tcpclient/tcpclient_test.go
package tcpclient
import (
"awesomeProject/reboot_learnning/mytcp/utils"
"testing"
)
func TestConnServer(t *testing.T) {
var client = utils.ServerInfo{
Proto: "tcp",
Host: "127.0.0.1",
Port: 11234,
}
ConnServer(&client)
}<file_sep>/mytcp/tcpserver/tcpserver_test.go
package tcpserver
import (
"awesomeProject/reboot_learnning/mytcp/utils"
"testing"
)
func TestRunningServer(t *testing.T) {
var server = utils.ServerInfo{
Proto: "tcp",
Host: "127.0.0.1",
Port: 11234,
}
RunningServer(&server)
}
<file_sep>/go_project_pachong/localtion/branch.go
package main
import (
"fmt"
"io/ioutil"
"log"
)
const fielpath = "example.txt"
func main() {
contents, err := ioutil.ReadFile(fielpath)
if err != nil {
log.Fatal("collect file not exist", err.Error())
}
fmt.Println(contents)
}
<file_sep>/mytcp/tcpserver/tcpserver.go
package tcpserver
import (
"fmt"
"log"
"net"
)
import (
"awesomeProject/reboot_learnning/mytcp/utils"
)
func RunningServer(s *utils.ServerInfo) {
addr := fmt.Sprintf("%s:%d", s.Host, s.Port)
Listener, err := net.Listen(s.Proto, addr)
if err != nil {
log.Fatal("running server is panic, ", err.Error())
}
defer Listener.Close()
// 阻塞式
for {
conn, err := Listener.Accept()
if err != nil {
log.Println("client connection is question ",err.Error())
}
go handFunc(conn)
}
}
func handFunc(conn net.Conn) {
defer conn.Close()
var buffer = make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
log.Println("server get data is question, ", err.Error())
}
conn.Write(append( buffer, []byte(fmt.Sprintf("recevice length is %d \n", n))...))
}
<file_sep>/base_socket/setting.md
# 传统的socket 通信模式,一般都是服务端主动断开连接
# 但是 socket 小程序,第一版本就出现类似“死锁”情况
# a. 客户端在等待服务端断开 tcpconn
# b. 服务端在等待客户端主动断开 tcpconn
#### demo1 ###
func client(num int64, wg *sync.WaitGroup) {
defer wg.Done()
times := time.Now()
conn, err := net.Dial("tcp", ":23600")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
conn.Write([]byte(strconv.FormatInt(num, 10) + " 我们是一群爱学习的golang learnning student \n"))
message, err := bufio.NewReader(conn).ReadString('\n')
fmt.Println("runtime: ", time.Since(times).Nanoseconds())
}
# 程序运行启动, 服务端可以接受客户端发起的请求,但客户端无法收到由服务端响应的消息体
#
# 第二版本,增加由 服务端主动断开tcpconn
for {
// wait for a connection
fmt.Println("accept...")
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// remote client address
fmt.Printf("new connection is %s \n", conn.RemoteAddr().String())
go func(conn net.Conn) {
/*defer conn.Close()
io.Copy(conn, conn)*/
buffer := make([]byte, 1024)
conn.Read(buffer)
conn.Write(buffer)
conn.Close()
}(conn)
}<file_sep>/base_socket/socker_client/client.go
package main
import (
"flag"
"sync"
"time"
"net"
"strconv"
"fmt"
"log"
)
const NUM = 10
func main() {
defer func() {
if r := recover(); r != nil {
log.Println("client connection server is error, ", r)
}
}()
var nums int64
flag.Int64Var(&nums, "n", NUM, "input XunHuan number ")
flag.Parse()
wg := new(sync.WaitGroup)
for i := 0; i < int(nums); i++ {
wg.Add(1)
go client(int64(i), wg)
}
wg.Wait()
}
func client(num int64, wg *sync.WaitGroup) {
defer wg.Done()
times := time.Now()
conn, err := net.Dial("tcp", ":23600")
if err != nil {
log.Fatal(err)
}
conn.Write([]byte(strconv.FormatInt(num, 10) + " 我们是一群爱学习的golang learnning student \n"))
buffer := make([]byte, 1024)
for {
n, err := conn.Read(buffer[0:])
if err != nil {
goto end
}
fmt.Print(string(buffer[:n]))
}
end:
conn.Close()
fmt.Println("runtime: ", time.Since(times).Nanoseconds())
}
<file_sep>/mytcp/tcpclient/tcpclient.go
package tcpclient
import (
"fmt"
"log"
"net"
)
import (
"awesomeProject/reboot_learnning/mytcp/utils"
)
func ConnServer(s *utils.ServerInfo ) {
data, addr := "gopher \n", fmt.Sprintf("%s:%d", s.Host, s.Port)
conn, err := net.Dial(s.Proto, addr)
if err != nil {
log.Fatal("client to server is panic, ", err.Error())
}
n, err := conn.Write([]byte(data))
if err != nil {
log.Println("client send data is question, ", err.Error())
}
var buffer = make([]byte, 1024)
conn.Write([]byte(data))
m, err := conn.Read(buffer)
if err != nil {
log.Println("client recevice data is question, ",err.Error())
}
if n == m {
fmt.Println("server health active")
}
// client active close conn
conn.Close()
}<file_sep>/zabbix/sender.go
// zabbix sender 在传送数据的时候, 首先数据包的头部是 ZBXD 数据的长度 及数据
// 数据是以json 格式
/*
{
"request":"sender data",
"data": [
{
"host":"",
"key":"",
"value":""
},
{
"host":"",
"key":"",
"value":""
}
]
}
*/
package zabbix
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
"time"
)
type Metric struct {
Host string `json:"host"`
Key string `json:"key"`
Value interface{} `json:"value"`
}
func NewMetric(host, key string , value interface{}) *Metric {
m := &Metric{
Host: host, Key: key, Value: value }
return m
}
// defen zabbix sender datapacket
type Packet struct {
Request string `json:"request"`
Data []*Metric `json:"data"`
}
func NewPacket( data []*Metric) *Packet{
p := &Packet{
Request: `sender data`, Data: data }
return p
}
func (p *Packet) DataLen() []byte {
dataLen := make([]byte, 0)
jsonData, _ := json.Marshal( p)
binary.LittleEndian.PutUint32(dataLen, uint32( len(jsonData)))
return dataLen
}
type SendClient struct {
ZBServer string
Port int
}
func NewSendClient( host string, port int) *SendClient {
s := &SendClient{
host, port ,
}
return s
}
func (s *SendClient) addHeader() []byte {
return []byte("ZBXD\x01")
}
func (s *SendClient) conn() (conn net.Conn, err error) {
type DialResp struct {
Conn net.Conn
Error error
}
ch := make(chan DialResp)
go func() {
conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", s.ZBServer, s.Port))
ch <- DialResp{ Conn: conn, Error: err}
}()
select {
case <- time.After( 10 * time.Second) :
err = fmt.Errorf(" conn server timeout time is 10 ")
case resp, ok := <- ch :
if ok {
if resp.Error != nil {
err = resp.Error
break
}
}
conn = resp.Conn
}
return
}
func (s *SendClient) read(conn net.Conn) error {
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
return fmt.Errorf("client recevice server respon data, ", err.Error())
}
return err
}
func (s *SendClient) Send(packet *Packet ) error {
conn, err := s.conn()
if err != nil {
return fmt.Errorf("client conn server is panic", err.Error())
}
dataJson, _ := json.Marshal( packet)
buffer := append(s.addHeader(), packet.DataLen()...)
buffer = append( buffer, dataJson...)
// send data to server
_, err = conn.Write(buffer)
if err != nil {
return fmt.Errorf( "send data to server is error, %v", err.Error())
}
err = s.read(conn)
if err != nil {
return fmt.Errorf( "send data, server respon is %v", err.Error())
}
return err
}
<file_sep>/base_socket/socker_server/server.go
package main
import (
"fmt"
"log"
"net"
)
func main() {
l, err := net.Listen("tcp", "127.0.0.1:23600")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// wait for a connection
fmt.Println("accept...")
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// remote client address
fmt.Printf("new connection is %s \n", conn.RemoteAddr().String())
go func(conn net.Conn) {
/*defer conn.Close()
io.Copy(conn, conn)*/
buffer := make([]byte, 1024)
conn.Read(buffer)
conn.Write(buffer)
conn.Close()
}(conn)
}
}
| 7c723106450951993f1aaf0109008a91b594ef2b | [
"Markdown",
"Go"
] | 12 | Markdown | test987654123/reboot_learnning | bc791a1b4f80b060b2ef528815714e1166d80820 | 7b607d668836289d7c1d289e392754fc505a1109 |
refs/heads/master | <file_sep>'use strict';
const { app, BrowserWindow } = require('electron');
const express = require('express');
const cors = require('cors');
const path = require('path');
const dns = require('dns');
const fs = require('fs');
const api = express();
const port = process.env.PORT || 3000;
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
api.use(cors());
api.get('/api', (req, res) => {
const url = req.query.url != undefined && req.query.url.length > 0 ? req.query.url.replace(/^https?:\/\//i, '') : 'null';
const domain = url != 'null' ? url.split('/')[0] : 'undefined';
dns.lookup(domain, (error, addresses, family) => {
if(error) {
console.log('URL invalid: ' + url);
return res.json({error: 'URL invalid: ' + url});
} else {
console.log('URL: ' + url);
const hash = Math.random().toString(36).substring(2);
console.log('PDF hash: ' + hash);
const target = path.join(__dirname,'pdfs',hash + '.pdf');
console.log('PDF path: ' + target);
app.allowRendererProcessReuse = true;
const window = new BrowserWindow({show : false});
window.loadURL('http://' + url);
const option = {
landscape: req.query.vertical == 'true' ? false : true,
marginsType: 1,
printBackground: true,
printSelectionOnly: false,
pageSize: 'A4',
};
window.webContents.on('did-finish-load', async () => {
await sleep(parseInt(req.query.seconds) > 0 ? parseInt(req.query.seconds) * 1000 : 1000);
window.webContents.printToPDF(option).then(data => {
fs.writeFile(target, data, (error) => {
if (error) throw error;
return res.sendFile(target);
});
}).catch(error => {
console.log('PDF error: ' + error);
return res.json({error: 'PDF error: ' + error});
});
});
};
});
});
api.listen(port, () => {
console.log('Node.js listening on port: ' + port);
}); | 879ca06e7f756cb9c66134dcd43ad913c3dc7703 | [
"JavaScript"
] | 1 | JavaScript | wolfthezelda/website-to-pdf-api | d08db9fd79defc24ff91e42a1e7793d3b69f8c9b | 640648fc32df42efc1fbd0943535562d421b5685 |
refs/heads/master | <file_sep>## State Cleaning
The primary bloat to the state have been generated from the following contracts.
1. Sequentially increasing
* `0x6a0a0fc761c612c340a0e98d33b37a75e5268472`
2. Non sequential (identical contracts)
* [`0x7c20218efc2e07c8fe2532ff860d4a5d8287cb31`](https://etherscan.io/address/0x7c20218efc2e07c8fe2532ff860d4a5d8287cb31)
* [`0x8a2e29e7d66569952ecffae4ba8acb49c1035b6f`](https://etherscan.io/address/0x8a2e29e7d66569952ecffae4ba8acb49c1035b6f)
### `0x6a0a0fc761c612c340a0e98d33b37a75e5268472`
This one generated suicides into sequentially increasing addresses, from
0x0000000000000000000000000000000000000001 -> 0x0000000000000000000000000000000000346b60
So the cleanup from that is pretty trivial.
### `0x7c20218efc2e07c8fe2532ff860d4a5d8287cb31`
These are a bit more tricky, using two sources for seeding and generating destination addresses from these. See [reverse_engineering.md](reverse_engineering.md) for details.
In order to generate the same addresses, we need to two pieces of data from each original transcation:
* `CALLDATA`
* The hash of the previous block (which is not available on-chain any longer, since we've passed 256 blocks)
Also the exploit-contract worked like this:
1. `0x7c20218efc2e07c8fe2532ff860d4a5d8287cb31` created contract `x`.
2. It `CALL`:ed `x` 40 times with an address of a sucide beneficiary. Before each call, generate a new address. During each call, `x` performed suicide to the supplied address.
3. If we have more than 1800 gas, repeat step 2.
One more piece of data that we need is the number of suicides performed, in order to know when to stop our sweep.
## Files in this repo
### Contracts
This repository contains a solidity implementation of a Sweeper contract, with the following signature:
function asm_clean(uint s, uint i);
function sol_clean(uint256 s, uint i);
These should be equivalent, but with `asm_clean` requiring less gas. The first parameter `s` is the initial seed, and the `i` is the number of touches to perform.
### Data files
The files in `/data` are:
* `state_bloat_transactions_original.json` - A file containing some basic data about all transactions into the two attack-contracts listed above.
* `blh` the block hash of the preceding block
* `txhash` the transaction hash
* `state_bloat_transactions.json` - Generated from `state_bloat_transactions_original.json` by using a web3 API to fetch some more data for each transaction:
* `input` - the input to the transactoin
* `gasUsed` - the gas used by the transaction
* `mappings_gas_suicidecount.json` - Generated from `state_bloat_transactions_original.json`, by using a web3 API to perform traces of transcations, and mapping `gasUsed` to number of suicides performed.
* `final_data.json` - Generated from `state_bloat_transactions_original.json` and `mappings_gas_suicidecount.json`. This calculates the `seed` and `iter` values to send into the solidity contract. The json file has the following data points:
* `seed` - Seed value
* `num` - Number of addresses to touch
The file `state_bloat_transactions_original.json` was generated from the Etherchain API, which has been hugely helpful in gathering data. The scripts to create this file is not included in this repository. This file is the _only_ file required to generate the rest of the files.
### Python
The `preprocess_data.py` generates all data based on the `state_bloat_transactions_original.json`. During execution, it saves results to files, and can be aborted/resumed. In this repo, the files are already generated and the script does not need to actually do much work.
If you want to regenerate the data based on `state_bloat_transactions_original.json` from scratch, you need to delete the other json-files and ensure that you have a http-api with `debug` available: `geth --rpc --rpcapi "debug,eth"`
## Live contracts
The `Sweeper.sol` contract was deployed on the main net in [0xad4ceddc9e345ac9f3076bf657ee1e22e382b98de6d351d35c7f8e28e8398021](https://etherscan.io/tx/0xad4ceddc9e345ac9f3076bf657ee1e22e382b98de6d351d35c7f8e28e8398021), and lives on [0xa<KEY>](https://etherscan.io/address/0xa43ebd8939d8328f5858119a3fb65f65c864c6dd)
```javascript
var sweeperAbi = [{"constant":false,"inputs":[{"name":"s","type":"uint256"},{"name":"i","type":"uint256"}],"name":"sol_clean","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"s","type":"uint256"},{"name":"i","type":"uint256"}],"name":"asm_clean","outputs":[],"payable":false,"type":"function"}];
var sweeperContract = web3.eth.contract(sweeperAbi).at("0xa43ebd8939d8328f5858119a3fb65f65c864c6dd");
```
<file_sep>{
"suicides": 0,
"lastOp":{},
"result": function() { return this.suicides },
"step": function(log, db){
if( log.op == 'SUICIDE'){
this.suicides++;
}
},
}<file_sep>#!/usr/bin/env python
import os,sys,locale,json, traceback
import datetime, time
from collections import defaultdict
import logging
import requests
import rlp
from rlp.sedes import big_endian_int, BigEndianInt, Binary
from rlp.utils import decode_hex, encode_hex, ascii_chr, str_to_bytes
from web3 import Web3, RPCProvider
# We need longer timeouts for the debug traces
# Setting it to 5 minutes here
web3rpc = Web3(RPCProvider(host="127.0.0.1", port="8545", connection_timeout=5*60,network_timeout=5*60))
here = os.path.dirname(os.path.abspath(__file__))
#-----------------------------------------------------
# Taken from the pyethereum project
# OBS; Assumes python 2
big_endian_to_int = lambda x: big_endian_int.deserialize(str_to_bytes(x).lstrip(b'\x00'))
int_to_big_endian = lambda x: big_endian_int.serialize(x)
is_numeric = lambda x: isinstance(x, (int, long))
is_string = lambda x: isinstance(x, (str, unicode))
def to_string(value):
return str(value)
def int_to_bytes(value):
if isinstance(value, str):
return value
return int_to_big_endian(value)
def to_string_for_regexp(value):
return str(value)
def bytearray_to_bytestr(value):
return bytes(''.join(chr(c) for c in value))
def parse_int_or_hex(s):
if is_numeric(s):
return s
elif s[:2] in (b'0x', '0x'):
s = to_string(s)
tail = (b'0' if len(s) % 2 else b'') + s[2:]
return big_endian_to_int(decode_hex(tail))
else:
return int(s)
#-----------------------------------------------------
def int_to_hexstring(v):
return "0x"+encode_hex(big_endian_int.serialize(parse_int_or_hex(v)))
def pad(inp):
""" 0-pads a string to 66 width (32 bytes + '0x') """
#0xb2551d22c4e1251431545e50032d6fbfaf93fe0d6c98a4daa44f387bdfe39d83
return inp.ljust(66,"0")
def loadjson(fname):
"""Utility method to load data from a json file
@return None if file is missing"""
try:
with open('%s/data/%s' % (here, fname), 'r') as infile:
return json.loads(infile.read())
except Exception, e:
print(e)
return None
def savejson(fname, obj):
""" Utility method to save an object to a json file"""
fqfn = '%s/data/%s' % (here, fname)
with open(fqfn, 'w+') as outfile:
outfile.write(json.dumps(obj))
print("Wrote file %s" % fqfn)
def getTrace(txHash):
""" Get's the suicide count through the traceTransaction API
Returns either the number of suicides or None
"""
with open('%s/suicide_counter.js' % (here), 'r') as infile:
javascript = infile.read()
# The following javascript tracer can be used to verify that
# we get the beneficiaries right:
#with open('%s/beneficiaries.js' % (here), 'r') as infile:
# javascript = infile.read()
# For tracing the 'heavy' transactions generated during the attack,
# we need to up the timeouts pretty heavily
traceOpts = {
"tracer": javascript,
"timeout": "5m",
}
try:
res = web3rpc._requestManager.request_blocking("debug_traceTransaction", [txHash, traceOpts])
except Exception as e:
traceback.print_exc(file=sys.stdout)
return None
return int(res)
def getTxInputAndGas(txhash):
""" Returns the transaction input data and gas used, as a tuple. This method uses
eth.getTransaction and eth.getTransactionReceipt, which is is a lot faster
than using the debug.traceTransaction"""
try:
tx = web3rpc.eth.getTransaction(txhash)
txreceipt = web3rpc.eth.getTransactionReceipt(txhash)
data = tx['input']
gasUsed = txreceipt['gasUsed']
return (data, gasUsed)
except AttributeError:
return None
def processInputAndGasUsage():
""" This method fetches gasUsed and input data for each transaction,
saving values in the 'state_bloat_transactions.json' file.
"""
transactions = loadjson("state_bloat_transactions.json")
failures = 0
def inputMissing(l):
for el in l:
if not el.has_key('input'):
yield el
for tx in inputMissing(transactions):
d = getTxInputAndGas(tx['txhash'])
if d is None:
print("No data for tx")
failures = failures +1;
continue
(indata, gasUsed) = d
tx['input'] = indata
tx['gasUsed'] = gasUsed
# Save intermediary data
savejson("state_bloat_transactions.json",transactions)
return failures
def processTransactions():
transactions = loadjson("state_bloat_transactions.json")
mappings = loadjson("mappings_gas_suicidecount.json") or {}
failures = 0
def suicideCountMissing(l):
for el in l:
if not mappings.has_key(str(el['gasUsed'])):
yield el
for tx in suicideCountMissing(transactions):
gasUsed = str(tx['gasUsed'])
print("Suicide count for gasUsed=%s not known" % gasUsed)
numSuicides = getTrace(tx['txhash'])
if numSuicides == None:
print("Trace failed")
failures = failures +1
continue
mappings[gasUsed] = numSuicides
savejson("mappings_gas_suicidecount.json", mappings)
h = tx['txhash']
i = tx['input']
sc = mappings[gasUsed]
print("hash %s input %s suicides: %d " % (h,i,sc))
return failures
def outputResult():
"""
Reads the intermediary files
- state_bloat_transactions.json
- mappings_gas_suicidecount.json
These are expected to be 'complete'.
Generates the data points for 'seed' and 'input', and writes
the file 'final_data.json'
"""
transactions = loadjson("state_bloat_transactions.json")
mappings = loadjson("mappings_gas_suicidecount.json")
def numSuicides(tx):
return mappings[str(tx['gasUsed'])]
totalSuicides = 0
final_data = []
for tx in transactions:
totalSuicides = totalSuicides + int(numSuicides(tx))
# input to transaction, right-padded with zeroes to 32 bytes
inp = pad(tx['input'])
# hash of preceding block
h = tx['blh']
# Calculate the seed
# Blockhash(num -1) + input
seed = parse_int_or_hex(h) + parse_int_or_hex(inp)
seed = seed & 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
seed = int_to_hexstring(seed)
print("%s %s %s %d %s" % (tx['txhash'], h,inp, numSuicides(tx), str(seed)))
final_data.append({"seed": seed, "num": numSuicides(tx)})
print("Total suicides: %d" % totalSuicides)
savejson("final_data.json", final_data)
def calculateAddrNr(seedhex, num):
"""
"""
seed = parse_int_or_hex(seedhex)
seed = seed * (num+1) / 0x1000000000000000000000000
addr = seed & 0xffffffffffffffffffffffffffffffffffffffff;
return int_to_hexstring(addr)
def testResult():
""" Tests that the 100th address generated from the seed of txhash
'0x2ca818c26c1e2061206eea43de1eb29095e7071a4e4fe4e5fc6c70f9dd619857'
is indeed the correct one:
'0xd9f816dcca1ad84957832382164530118a416f4b'
see suicide_100_0 at
https://etherscan.io/tx/0x2ca818c26c1e2061206eea43de1eb29095e7071a4e4fe4e5fc6c70f9dd619857#internal
"""
print("Verifying...")
transactions = loadjson("state_bloat_transactions.json")
mappings = loadjson("mappings_gas_suicidecount.json")
def numSuicides(tx):
return mappings[str(tx['gasUsed'])]
totalSuicides = 0
final_data = []
tx = None
for tx in transactions:
if tx['txhash'] == '0x2ca818c26c1e2061206eea43de1eb29095e7071a4e4fe4e5fc6c70f9dd619857':
break
else:
raise Exception("Tx not found")
# input to transaction, right-padded with zeroes to 32 bytes
inp = pad(tx['input'])
# hash of preceding block
h = tx['blh']
# Calculate the seed
# Blockhash(num -1) + input
seed = parse_int_or_hex(h) + parse_int_or_hex(inp)
seed = seed & 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
seed = int_to_hexstring(seed)
addr = calculateAddrNr(seed,100)
assert addr == '0xd9f816dcca1ad84957832382164530118a416f4b'
print("Address %s correct!" % addr )
def main():
# This script writes to 'state_bloat_transactions.json' during script execution.
#
# If no such file exists, it reads from state_bloat_transactions_original.json
# which is expected to contain a list of transaction objects with the following fields
# blh - block hash of the block _preceding_ this transactions block
# txhash - the transaction hash
#
stage_data = loadjson("state_bloat_transactions.json")
if stage_data is None:
stage_data = loadjson("state_bloat_transactions_original.json")
savejson("state_bloat_transactions.json", stage_data)
# Step 1 : get each transaction gasUsed and input data
# Continue until there are no more failures
f = 1
while(f > 0):
f = processInputAndGasUsage()
print("Failures: %d" % f)
# Step 2: get the suicide count for each transaction
# Continue until there are no more failures
f = 1
while f > 0:
f = processTransactions()
# Output it
outputResult()
testResult()
if __name__ == '__main__':
main()
<file_sep>{
suicides: 0,
beneficiaries : [],
result: function() { return this.beneficiaries },
step: function(log, db){
if( log.op == 'SUICIDE'){
this.beneficiaries.push("0x"+log.stack.peek(0).Text(16))
}
},
} | 889721270273629a3cff8d7a2bd7bd1dcfb2e210 | [
"Markdown",
"Python",
"JavaScript"
] | 4 | Markdown | ethereum/statesweep | 9489f3e705cc006abd17ee5ee22e6820a11272a8 | b41869f7b2949b2b3ece3db84d679da1de7cb9a3 |
refs/heads/master | <file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Settings Model
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplating_SettingsModel extends BaseModel
{
public function __construct()
{
parent::__construct();
$settings = $this->getSettings();
foreach($settings as $key => $name) {
$this[$key] = $name;
}
}
protected function getSettings()
{
$settings = array();
foreach($this->attributeNames() as $name) {
if(craft()->config->exists($name, 'componentbasedtemplating')) {
$settings[$name] = craft()->config->get($name, 'componentbasedtemplating');
}
}
return $settings;
}
protected function defineAttributes()
{
$attributes = array(
'components' => array(
'type' => AttributeType::Mixed,
'model' => 'ComponentBasedTemplating_ComponentsSettingsModel'
),
'groups' => array(
'type' => AttributeType::Mixed,
'model' => 'ComponentBasedTemplating_GroupsSettingsModel'
)
);
return $attributes;
}
}<file_sep><?php
/**
* Component-based Templating configuration
*/
return array(
/**
* Individual components
* Set the global variable name and template path
*/
'components' => array(
'name' => 'components', // Default is 'components'
'templatePath' => '_components' // Default is '_components'
),
/**
* Grouped components
* Set the global variable name and template path
*/
'groups' => array(
'name' => 'groups', // Default is 'groups'
'templatePath' => '_groups' // Default is '_groups'
)
);<file_sep># Component-based Templating plugin for Craft CMS
This plugin makes it easy to work in a component-based templating environment
## Overview
Please start by reading [this post](https://medium.com/base-voices/dry-templating-with-twig-and-craft-cms-543292d114aa). Although the solution depicted is different from what this plugin does, it will give you a great overview of the Twig problematic I'm trying to solve.
After publishing the post, some people then made me aware that the solution I provided (using [`macros`](https://twig.sensiolabs.org/doc/2.x/tags/macro.html) to output flexible components) wouldn't work with Craft 3. Indeed, Craft 3 comes with Twig 2 and one of the deprecated features is [related to macros](https://twig.sensiolabs.org/doc/1.x/deprecated.html#macros).
The alternative would be to stop outputting DRY components using `macros` and embrace simple [`includes`](https://twig.sensiolabs.org/doc/2.x/tags/include.html). But the `{% include '_components/some-component' with {} only %}` notation feels unnecessarily complex and weird to me in this context. In comparison, the `macros` notation was `{{ components.someComponent({}) }}`, which made way more sense to me.
The way this plugin works is that it adds a new `components` Global Variables to the Twig environment. You can then use a macro-like notation like `{{ components.artworkCard({}) }}` to grab the `artwork-card.html` component located in the `craft/templates/_components` directory.
On top of `components`, you can also create `groups` using the same logic. Use `{{ groups.artworks }}` and place the `artwork.html` file in the `craft/templates/_groups` directory. Think of `groups` as groups of `components` that you need to output side by side in a template. For this reason, the core of a `group` file will often be made of a `for` loop.
Find working examples in this repo's Wiki.
Compared to `macros`, this plugin brings the following changes:
- makes calls ≈5% slower (when the page isn’t cached)
- the technique will work in both Craft 2 and Craft 3
- no need to do the extra-work of defining macros in the `_macros/components` and `_macros/groups` files
- no need to re-import the `_macros/components` and `_macros/groups` macros in component and groups anymore
Scopes remain the same between both options. It means that components and groups have access to Twig Global Variables but not to variables defined upstream.
## Installation
To install the Component-based Templating plugin, follow these steps:
1. Download the [latest release](https://github.com/pierrestoffe/craft-componentbasedtemplating/releases/latest) & unzip the file
2. Rename the directory into `componentbasedtemplating` if necessary
3. Copy the `componentbasedtemplating` directory into your `craft/plugins` directory
4. Install the plugin in the Craft Control Panel under Settings > Plugins
Component-based Templating works on Craft 2.4.x and Craft 2.5.x.
## Using this plugin
1. Create a component file in your `craft/templates/_components` directory
2. The file name should be the name of your component written in kebab case (eg. `some-component.html`)
3. In the template file where you need to call that component, use `{{ components.someComponent({}) }}` (mind the camel case notation) and pass some parameters inside the curly brackets
4. Back into the component, access the parameters (defined in step 3) simply by using their name (eg. `{{ paramName }}`)
## Roadmap
Some things to do, and ideas for potential features:
* Provide a few components/groups examples
* Adapt for Craft 3
## Credits
Brought to you by [<NAME>](https://pierrestoffe.be)
Kickstarted using [pluginfactory.io](https://pluginfactory.io)
<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Components Settings Model
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplating_GroupsSettingsModel extends BaseModel
{
public function setAttribute($name, $value)
{
parent::setAttribute($name, $value);
}
protected function defineAttributes()
{
$attributes = array(
'name' => array(AttributeType::String, 'default' => 'groups'),
'templatePath' => array(AttributeType::String, 'default' => '_groups')
);
return $attributes;
}
}<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Components Service
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplating_ComponentsService extends BaseApplicationComponent
{
/**
* @param string $method
* @param array $variables
*/
public function __call($method, $variables)
{
$name = craft()->componentBasedTemplating_settings->getComponentsSetting('name');
$template_path = craft()->componentBasedTemplating_settings->getComponentsSetting('templatePath');
echo craft()->componentBasedTemplating->getComponent($method, $variables, $name, $template_path);
}
}<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Groups Service
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplating_GroupsService extends BaseApplicationComponent
{
/**
* @param string $method
* @param array $variables
*/
public function __call($method, $variables)
{
$name = craft()->componentBasedTemplating_settings->getGroupsSetting('name');
$template_path = craft()->componentBasedTemplating_settings->getGroupsSetting('templatePath');
echo craft()->componentBasedTemplating->getGroup($method, $variables, $name, $template_path);
}
}<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Twig Extension
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
use Twig_Extension;
use Twig_Filter_Method;
class ComponentBasedTemplatingTwigExtension extends \Twig_Extension
{
/**
* Set new Twig Global Variables
*/
public function getGlobals()
{
$components_name = craft()->componentBasedTemplating_settings->getComponentsSetting('name');
$groups_name = craft()->componentBasedTemplating_settings->getGroupsSetting('name');
return [
$components_name => craft()->componentBasedTemplating_components,
$groups_name => craft()->componentBasedTemplating_groups,
];
}
}<file_sep># Component-based Templating Changelog
## 1.0.1 -- 2017.09.04
* [Improved] Improved settings model processing speed
* [Improved] Per-value comments in config.php
## 1.0.0 -- 2017.08.04
* [Added] Made the terminology flexible
* [Added] Make the template paths flexible
## 1.0-beta -- 2017.06.04
* Initial release, not meant for production
Brought to you by [<NAME>](https://pierrestoffe.be)
<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Settings Service
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplating_SettingsService extends BaseApplicationComponent
{
public $settings;
public $components_settings;
public $groups_settings;
public function __construct() {
$this->settings = new ComponentBasedTemplating_SettingsModel;
}
public function getComponentsSetting($name)
{
return $this->settings['components'][$name];
}
public function getGroupsSetting($name)
{
return $this->settings['groups'][$name];
}
}<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Translation
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
return array(
'component' => 'composant',
'group' => 'groupe',
'Could not find "{template_name}" {type}.' => 'Impossible de trouver le {type} "{template_name}".',
);
<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* This plugin makes it easy to work in a component-based templating environment
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplatingPlugin extends BasePlugin
{
/**
* @return string
*/
public function getName()
{
return Craft::t('Component-based Templating');
}
/**
* @return string
*/
public function getDescription()
{
return Craft::t('This plugins makes it easy to work in a component-based templating environment');
}
/**
* @return string
*/
public function getDocumentationUrl()
{
return 'https://github.com/pierrestoffe/craft-componentbasedtemplating/blob/master/README.md';
}
/**
* @return string
*/
public function getReleaseFeedUrl()
{
return 'https://raw.githubusercontent.com/pierrestoffe/craft-componentbasedtemplating/master/releases.json';
}
/**
* @return string
*/
public function getVersion()
{
return '1.0.1';
}
/**
* @return string
*/
public function getSchemaVersion()
{
return '1.0.0';
}
/**
* @return string
*/
public function getDeveloper()
{
return '<NAME>';
}
/**
* @return string
*/
public function getDeveloperUrl()
{
return 'https://pierrestoffe.be';
}
/**
* @return bool
*/
public function hasCpSection()
{
return false;
}
/**
* @return Twig_Extension
*/
public function addTwigExtension()
{
Craft::import('plugins.componentbasedtemplating.twigextensions.ComponentBasedTemplatingTwigExtension');
return new ComponentBasedTemplatingTwigExtension();
}
}<file_sep><?php
/**
* Component-based Templating plugin for Craft CMS
*
* Component-based Templating Service
*
* @author <NAME>
* @copyright Copyright (c) 2017 <NAME>
* @link https://pierrestoffe.be
* @package ComponentBasedTemplating
* @since 1.0.0
*/
namespace Craft;
class ComponentBasedTemplatingService extends BaseApplicationComponent
{
/**
* Transform a camelCase string into a dashed string
* @param string $string
* @return string
*/
public function camelCaseToKebab($string)
{
return strtolower(preg_replace('/(?<!^)[A-Z]/', '-$0', $string));
}
/**
* Find the appropriate template and render it with the provided variables
* @param string $method
* @param array $variables
* @param string $name
* @param string $template_path
* @return string
*/
public function getComponent($method, $variables, $name, $template_path)
{
// Set template path
$templates_path = craft()->path->getSiteTemplatesPath();
craft()->path->setTemplatesPath($templates_path);
// Try and find the needed template
$kebab_name = $this->camelCaseToKebab($method);
$template_name = "{$template_path}/{$kebab_name}";
$template_path = craft()->templates->doesTemplateExist($template_name);
// Return and show Exception if template is not defined
if(!$template_path) {
throw new Exception(Craft::t('Could not find "{template_name}" {name}.', array(
'template_name' => $template_name,
'name' => $name
)));
return false;
}
return craft()->templates->render($template_name, $variables[0]);
}
} | 67af404888b1060e5fc66a29f8f83e796654f997 | [
"Markdown",
"PHP"
] | 12 | PHP | pierrestoffe/craft-componentbasedtemplating | 3b3d5a2adaf106ed38e10941941a819a04c7e113 | ab32b921ab60f43c8c5c16479eef58a6b7ce4b1b |
refs/heads/master | <file_sep># Countdown Clock
* What I try to achieve with the **JavaScript**:
* Question: How do timers work?
* The set time for it to run
* It runs for that set amount of time
* Show the amount of time left as countdown progresses
* One way to set up a timer function is the following:
```javascript
function timer(seconds) {
setInterval(function() {
seconds--;
}, 1000);
}
```
However, you can get into issues with this set up because setInterval does not run sometimes. Sometimes if you tab away for a while, setInterval would stop running. In addition, on iOS, when scrolling, all intervals are paused. It might do that because of performance issues as well as to make sure that scrolling goes smoothly.
* **Steps:**
* Figure out how seconds work.
* Figure out how minutes work.
* Figure out how to display time in html.
* Hook up JS to various buttons and input text field.
* Create custom countdown using customForm.
<file_sep>// global variable that lives in window. but you can pop it into an if statement and not have it in the global namespace.
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
/* pass seconds parameter for how many seconds you want the timer to run. */
function timer(seconds) {
// clear any existing timers to make fresh start.
clearInterval(countdown);
/* figure out when timer started. Date.now() gives us current time stamp in milliseconds. */
const now = Date.now();
/* now + number of seconds wish to run timer. now is in ms and seconds is in seconds however. */
const then = now + (seconds * 1000);
/* so that function will immediately run as opposed to a 1 sec (1000 ms) time lag. In other words, shows the current top second immediately, and then runs every 1000 ms thereafter. */
displayTimeLeft(seconds);
displayEndTime(then);
/* show amount of time left to countdown as countdown progresses. It's ok to use setInterval here because if by any chance it doesn't run for a couple of seconds, when setInterval does start running again, it will update the amount of time it skipped. When placing setInterval in value of countdown, we are updating the time left in the countdown. */
countdown = setInterval(() => {
/* Don't use now itself because that was captured when the countdown started running. Date.now() gives current time stamp at any particular second and not the now that was captured at start time. Also want to make sure to convert ms back to seconds. Math.round takes care of any funky rounding errors. If I hadn't added the Math.round, as the setInterval continued, it would have gone into negative numbers because it does not know when to stop itself. Math.round by itself would make no diff in this matter. */
const secondsLeft = Math.round((then - Date.now()) / 1000);
/* check if should stop timer. just returning would not work. It would just stop the function from running, but because of setInterval, the countodwn would still continue but just not display. So what actually has to be done is to store setInterval into its own variable. */
if(secondsLeft < 0) {
// this makes the countdown stop when it reaches 0.
clearInterval(countdown);
return;
}
// display timer
displayTimeLeft(secondsLeft);
}, 1000);
}
/* we want to take into account minutes and seconds. This is the same code as we implemented in the js css clock project. can add hours as well if want to. */
function displayTimeLeft(seconds) {
/* Math.floor because only care about whole minutes */
const minutes = Math.floor(seconds / 60);
/* because we have to take into account remaining seconds as well as minutes. */
const remainderSeconds = seconds % 60;
/* ternary conditional statement adds padded 0 when seconds does below 10 */
const display = `${minutes}:${remainderSeconds < 10 ? '0' : ''}${remainderSeconds}`;
/* update browser tab. This way can display the time in the tab as well instead of the title of the project. */
document.title = display;
timerDisplay.textContent = display;
}
/* display html to match countdown endTime */
function displayEndTime(timestamp) {
/* turn timestamp into date. create new date object. this way can control exactly what you want to display in timestamp. */
const end = new Date(timestamp);
const hour = end.getHours();
const adjustedHour = hour > 12 ? hour - 12 : hour;
const minutes = end.getMinutes();
/* just want to use once so place directly in template string. here we have to account for minutes lower than 10 just as we did with seconds in the value for the display variable. */
endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;
}
function startTimer() {
// turn seconds into a real number. Remember to click button to get results.
const seconds = parseInt(this.dataset.time);
timer(seconds);
}
buttons.forEach(button => button.addEventListener('click', startTimer));
/* can attach name of form directly to document instead of selecting it with querySelector. Same with the name of an input within the form. */
document.customForm.addEventListener('submit', function(e) {
// prevents page reload and setting data over a GET
e.preventDefault();
// 'this' refers to form. that is why proper function is needed. With addition of the mins variable, inputting minutes in the input with name of minutes, works.
const mins = this.minutes.value;
console.log(mins);
// because timer requires seconds. completes the setup for custom minutes.
timer(mins * 60);
// clears out value in the input text field after user hits enter.
this.reset();
});
| b33b3be6bf41d100b77c98a3c0bda19a40b0be24 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | interglobalmedia/countdown-clock | 26510ae0e795b04c91bb13e4611696f632691768 | b904989e70a5bbe8878d28771c29a0399c42b07c |
refs/heads/master | <repo_name>renatas7/contactify-app<file_sep>/src/containers/filter/filter.js
import React, { useState } from 'react';
import { connect } from 'react-redux';
import { actions } from './../../state';
import { Search } from './../../components';
import styles from './filter.module.scss';
import { Paper, FilterDropdown, CheckBox, Button } from './../../components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlusCircle } from '@fortawesome/free-solid-svg-icons';
const Filter = ({ dispatch }) => {
const [active, setActive] = useState(false);
const [filterParam, setFilterParam] = useState('Name');
const [inputValue, setInputValue] = useState('');
const changeDropdownValue = () => {
if (filterParam === 'Name') {
setFilterParam('City');
} else {
setFilterParam('Name');
}
};
const filter = () => {
const data = {
active: active,
filterBy: filterParam,
filterValue: inputValue,
};
dispatch(actions.contacts.setTableFilterAction(data));
};
return (
<div className={styles.container}>
<Paper type="default">
<div className={styles.filterContainer}>
<Search
type="filter"
filterParam={filterParam}
value={inputValue}
onChange={e => setInputValue(e.target.value)}
onKeyPress={event => {
if (event.key === 'Enter') {
filter();
}
}}
/>
<FilterDropdown
value={filterParam}
onChange={() => changeDropdownValue()}
/>
<CheckBox
name="Show active"
label="Show active"
value={filterParam}
checked={active}
onChange={() => setActive(!active)}
/>
<Button type="filter" onClick={filter}>
FILTER
</Button>
</div>
<Button type="add">
<FontAwesomeIcon icon={faPlusCircle} className={styles.plusCircle} />
<span className={styles.buttonText}>ADD NEW CONTRACT</span>
</Button>
</Paper>
</div>
);
};
export default connect()(Filter);
<file_sep>/src/utils/selectors.js
export const selectContactsData = state => state.contactsState.contactsData;
<file_sep>/README.md
# contactify-app
Contactify app is an app in which contacts are rendering from json file. You can click on row in the table and see users info in the card on the left. You can also filter users by name, city and status.
### Prerequisites
Before you start installing things, make sure that you have:
```
"node": ">=10.0.0",
"npm": ">=6.0.0"
```
### Installing
Install dependencies:
```
$ npm install
```
Start the project:
```
$ npm start
```
### Folder structure
App contains 6 folders in src directory:
- **Containers** holds main project blocks which are contained with other smaller components.
- **components** holds smallest components which are reused in all the project.
- **pages** holds project pages. Because it is just one page app it contains just one page in it.
- **state** is responsible for all redux stuff and app logic.
- **style** holds main style guidlines and varables. All other styles are separated inside components
- **utils** holds reusable functions of the project. It also contains redux store setup
### Main Project libraries
- **React** main project library on which all app is based.
- **Redux** for centralizing application's state and logic.
- **Redux-saga** middleware for redux to handle side effect.
- **React router** routing library for react.
### Todo list
- Improve the design;
- Make mobile frendly;
<file_sep>/src/components/logo/logo.js
import React from 'react';
import styles from './logo.module.scss';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserCircle } from '@fortawesome/free-solid-svg-icons';
const Logo = () => {
return (
<div className={styles.container}>
<FontAwesomeIcon icon={faUserCircle} className={styles.icon} />
<h1 className={styles.h1}>CONTACTIFY</h1>
</div>
);
};
export default Logo;
<file_sep>/src/components/index.js
export { default as Header } from './header/header.js';
export { default as Button } from './button/button.js';
export { default as WithSpinner } from './spinner/withSpinner.js';
export { default as Nav } from './nav/nav.js';
export * from './nav/nav.js';
export { default as Logo } from './logo/logo.js';
export { default as Search } from './search/search.js';
export { default as Paper } from './paper/paper.js';
export { default as Dropdown } from './dropdown/dropdown.js';
export { default as FilterDropdown } from './filterDropdown/filterDropdown.js';
export { default as CheckBox } from './checkbox/checkbox.js';
export { default as UserCard } from './userCard/userCard.js';
export { default as Table } from './table/table.js';
export * from './table/table';
export { default as Links } from './footer/links/links.js';
export { default as LastSync } from './footer/lastSync/lastSync.js';
export { default as Help } from './footer/help/help.js';
export {
default as LastContainer,
} from './footer/lastContainer/lastContainer.js';
<file_sep>/src/components/footer/links/links.js
import React from 'react';
import styles from './links.module.scss';
import { NavLink } from 'react-router-dom';
import { Paper, navLinks } from './../..';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCopyright } from '@fortawesome/free-solid-svg-icons';
const Links = () => {
const renderLinks = () =>
navLinks.map(({ name, url }) => (
<li className={styles.item} key={name}>
<NavLink className={styles.links} to={url}>
<span className={styles.label}>{name}</span>
</NavLink>
</li>
));
return (
<div className={styles.container}>
<Paper type="header">
<div className={styles.linksContainer}>
{renderLinks()}
<div className={styles.copyright}>
<FontAwesomeIcon
icon={faCopyright}
className={styles.faCopyright}
/>
<p> {new Date().getFullYear()} Contactify</p>
<div>
<p>About</p>
<p>Privacy</p>
{/*just for now using p before we have real About and Privacy pages
and could replace this paragrphs with nav links */}
</div>
</div>
</div>
</Paper>
</div>
);
};
export default Links;
<file_sep>/src/layout/layout.js
import React from 'react';
import styles from './layout.module.scss';
import { Header } from './../components';
const Layout = () => {
return (
<div className={styles.container}>
<Header />
</div>
);
};
export default Layout;
<file_sep>/src/components/nav/nav.js
import React from 'react';
import { NavLink } from 'react-router-dom';
import styles from './nav.module.scss';
import { config } from './../../api/config';
export const navLinks = [
{
name: config.PAGES.dashboard,
url: config.APP_PATHS.dashboard,
},
{
name: config.PAGES.contacts,
url: config.APP_PATHS.contacts,
},
{
name: config.PAGES.notifications,
url: config.APP_PATHS.notifications,
},
];
const NavFooter = () => {
const renderLinks = () =>
navLinks.map(({ name, url }) => (
<li className={styles.item} key={name}>
<NavLink
className={styles.link}
activeClassName={styles.active}
to={url}
>
<span className={styles.label}>{name.toUpperCase()}</span>
</NavLink>
</li>
));
return (
<div className={styles.container}>
<nav className={styles.nav}>
<ul className={styles.list}>{renderLinks()}</ul>
</nav>
</div>
);
};
export default NavFooter;
<file_sep>/src/components/search/search.js
import React from 'react';
import styles from './search.module.scss';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import PropTypes from 'prop-types';
const Search = ({ type, filterParam, onChange, value, ...rest }) => {
if (type === 'user') {
return (
<div className={styles.searchBoxContainer}>
<input className={styles.searchBox} placeholder="Search"></input>
<button>
<FontAwesomeIcon icon={faSearch} className={styles.searchIcon} />
</button>
</div>
);
} else if (type === 'filter') {
return (
<div className={styles.searchBoxContainer}>
<input
className={styles.searchBox}
placeholder={filterParam}
onChange={onChange}
value={value}
{...rest}
/>
</div>
);
}
};
Search.propTypes = {
type: PropTypes.oneOf(['user', 'filter']),
};
export default Search;
<file_sep>/src/routes.js
import React from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './pages/home/home';
import Dashboard from './pages/dashboard/dashboard';
import Contacts from './pages/contacts/contacts';
import Notifications from './pages/notifications/notifications';
import { config } from './api/config';
import { Header, Footer } from './containers';
const Routes = () => {
return (
<Router>
<Header />
<Switch>
<Route path={'/'} component={Home} exact />
<Route path={config.APP_PATHS.dashboard} component={Dashboard} />
<Route path={config.APP_PATHS.contacts} component={Contacts} />
<Route
path={config.APP_PATHS.notifications}
component={Notifications}
/>
</Switch>
<Footer />
</Router>
);
};
export default Routes;
<file_sep>/src/state/contacts/contactsAction.js
import { constants } from '../constants';
const setUserOnSyncFlagAction = flag => {
return {
type: constants.contacts.SET_ON_SYNC_FLAG,
flag,
};
};
const clearUserStateAction = () => {
return {
type: constants.contacts.CLEAR_USER_STATE,
};
};
const updateDashboardAction = () => {
return {
type: constants.contacts.UPDATE_DASHBOARD_DATA,
};
};
const setTableDataAction = payload => {
return {
type: constants.contacts.SET_TABLE_DATA,
payload,
};
};
const setContactsDataAction = () => {
return {
type: constants.contacts.SET_CONTACTS_DATA,
};
};
const pushContactsDataAction = payload => {
return {
type: constants.contacts.PUSH_CONTACTS_DATA,
payload,
};
};
const setTableFilterAction = payload => {
return {
type: constants.contacts.SET_TABLE_FILTER,
payload,
};
};
const setTableSortingAction = payload => {
return {
type: constants.contacts.SET_TABLE_SORTING,
payload,
};
};
export const userActions = {
clearUserStateAction,
updateDashboardAction,
setUserOnSyncFlagAction,
setTableDataAction,
setContactsDataAction,
pushContactsDataAction,
setTableFilterAction,
setTableSortingAction,
};
<file_sep>/src/pages/notifications/notifications.js
import React from 'react';
import styles from './notifications.module.scss';
const Notifications = () => {
return (
<div className={styles.container}>
<p>Coming soon...</p>
</div>
);
};
export default Notifications;
<file_sep>/src/state/sagas.js
import { constants } from './constants';
import { takeLatest, all, call } from 'redux-saga/effects';
import {
getContactsSaga,
setTableFilterSaga,
getTableSortingSaga,
} from './contacts/ContactsSaga';
function* actionWatcher() {
yield takeLatest(constants.contacts.UPDATE_DASHBOARD_DATA, getContactsSaga);
yield takeLatest(constants.contacts.SET_TABLE_FILTER, setTableFilterSaga);
yield takeLatest(constants.contacts.SET_TABLE_SORTING, getTableSortingSaga);
}
export default function* rootSaga() {
yield all([call(actionWatcher)]);
}
<file_sep>/src/components/userCard/userCard.js
import React from 'react';
import styles from './userCard.module.scss';
import link from './../../assets/images/nopic.png';
import PropTypes from 'prop-types';
const UserCard = ({ name, surname, city, email, phone }) => {
return (
<div className={styles.container}>
<img className={styles.userPic} src={link} alt="User pc" />
<div className={styles.infoContainer}>
<table>
<tbody>
<tr>
<td>Name:</td>
<td>{name}</td>
</tr>
<tr>
<td>Surname:</td>
<td>{surname}</td>
</tr>
<tr>
<td>City:</td>
<td>{city}</td>
</tr>
<tr>
<td>E-mail:</td>
<td>{email}</td>
</tr>
<tr>
<td>Phone:</td>
<td>{phone}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
};
UserCard.propTypes = {
name: PropTypes.string.isRequired,
surname: PropTypes.string.isRequired,
city: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
phone: PropTypes.string.isRequired,
};
export default UserCard;
<file_sep>/src/containers/contactList/contactList.js
import React, { useEffect, useCallback, useState } from 'react';
import { actions } from './../../state/actions';
import { connect } from 'react-redux';
// import { WithSpinner } from '../../components';
import { Paper } from './../../components';
import styles from './contactList.module.scss';
import {
UserCard,
Table,
TableRow,
TableCell,
WithSpinner,
} from './../../components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faEye,
faEyeSlash,
faPencilAlt,
faTrashAlt,
} from '@fortawesome/free-solid-svg-icons';
import PropTypes from 'prop-types';
const ContactList = ({ dispatch, contactsData, loading }) => {
const fetchData = useCallback(() => {
dispatch(actions.contacts.updateDashboardAction());
}, [dispatch]);
useEffect(() => {
fetchData();
}, [dispatch, fetchData]);
const [user, setUser] = useState({
name: '',
surname: '',
city: '',
email: '',
phone: '',
});
const iconActive = <FontAwesomeIcon icon={faEye} />;
const iconInActive = <FontAwesomeIcon icon={faEyeSlash} />;
const iconEdit = <FontAwesomeIcon icon={faPencilAlt} />;
const iconDelete = <FontAwesomeIcon icon={faTrashAlt} />;
const tableHeader = [
{ name: '', backround: '#0085a4' },
{ name: 'Name', backround: '#0085a4', filter: true },
{ name: 'Surname', backround: '#0390ad' },
{ name: 'City', backround: '#0699b8' },
{ name: 'Email', backround: '#0dacc9' },
{ name: 'Phone', backround: '#11b6d3', align: 'right' },
{ name: '', backround: '#13c0dd' },
{ name: '', backround: '#13c0dd' },
];
const textAlign = align => {
return { textALign: align };
};
const renderTable = () =>
contactsData.map(({ id, active, name, surname, city, email, phone }) => (
<TableRow
key={id}
onClick={() => rowClick(id, active, name, surname, city, email, phone)}
>
<TableCell align={'right'}>
{active ? iconActive : iconInActive}
</TableCell>
<TableCell align={'left'}>{name}</TableCell>
<TableCell align={'left'}>{surname}</TableCell>
<TableCell align={'left'}>{city}</TableCell>
<TableCell align={'left'}>{email}</TableCell>
<TableCell align={'right'}>{phone}</TableCell>
<TableCell align={'right'} styles={textAlign('right')}>
{iconEdit}
</TableCell>
<TableCell align={'left'}>{iconDelete}</TableCell>
</TableRow>
));
const rowClick = (id, status, name, surname, city, email, phone) => {
const data = {
id,
status,
name,
surname,
city,
email,
phone,
};
setUser(data);
};
const sorting = sort => {
dispatch(actions.contacts.setTableSortingAction(sort));
};
return (
<div className={styles.container}>
<Paper type="header">
<UserCard
name={user.name}
surname={user.surname}
city={user.city}
email={user.email}
phone={user.phone}
/>
<div className={styles.tableContainer}>
<WithSpinner loading={loading}>
<Table
header={tableHeader}
isEmpty={!contactsData.length}
sorting={sort => sorting(sort)}
>
{renderTable()}
</Table>
</WithSpinner>
</div>
</Paper>
</div>
);
};
const mapStateToProps = state => ({
contactsData: state.contactsState.contactsData,
loading: state.contactsState.isOnSync,
});
ContactList.propTypes = {
dispatch: PropTypes.func.isRequired,
contactsData: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
surname: PropTypes.string.isRequired,
city: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
phone: PropTypes.string.isRequired,
active: PropTypes.bool, //* status active must be required.
//I made it not required, because user with id 6 haven't got active property.
// It seams that is a bug, so need to check it out with backend developer
// why this user with id 6 haven't active property //*
}).isRequired
).isRequired,
};
export default connect(mapStateToProps)(ContactList);
<file_sep>/src/api/api.js
export class Api {
static async updateDashboardDetails() {
const response = await fetch('data/contacts.json');
const data = await response.json();
return data;
}
static async getUsersData() {
const response = await fetch('data/contacts.json');
const data = await response.json();
return data;
}
}
<file_sep>/src/components/checkbox/checkbox.js
import React from 'react';
import styles from './checkbox.module.scss';
import PropTypes from 'prop-types';
const Checkbox = ({ label, name, checked, value, onChange, ...rest }) => (
<div className={styles.checkbox}>
<input
type="checkbox"
checked={checked}
value={value}
onChange={onChange}
{...rest}
/>
<label htmlFor={name} onClick={onChange}>
{label}
</label>
</div>
);
Checkbox.propTypes = {
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
checked: PropTypes.bool.isRequired,
value: PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.number.isRequired,
PropTypes.bool.isRequired,
]).isRequired,
onChange: PropTypes.func.isRequired,
};
export default Checkbox;
<file_sep>/src/state/constants.js
import { ContactsConstants } from './contacts/ContactsConstants';
import { modalsConstants } from './modals/ModalsConstants';
export const constants = {
contacts: ContactsConstants,
modals: modalsConstants,
};
<file_sep>/src/containers/header/header.js
import React from 'react';
import { Nav, Search, Logo, Paper, Dropdown } from './../../components';
import styles from './header.module.scss';
const Header = () => {
return (
<div className={styles.container}>
<Paper type="header">
<div className={styles.leftContainer}>
<Logo />
<div className={styles.navContainer}>
<Nav />
<Search type="user" />
</div>
</div>
<Dropdown />
</Paper>
</div>
);
};
export default Header;
<file_sep>/src/components/paper/paper.js
import React from 'react';
import styles from './paper.module.scss';
import cn from 'classnames';
import PropTypes from 'prop-types';
const Paper = ({ children, type, ...rest }) => {
if (type === 'header') {
return (
<div className={cn(styles.container, styles.margins)}>{children}</div>
);
} else if (type === 'verticalAlign') {
return <div className={cn(styles.container, styles.align)}>{children}</div>;
} else if (type === 'default') {
return (
<div className={cn(styles.container, styles.margins, styles.align)}>
{children}
</div>
);
}
};
Paper.propTypes = {
children: PropTypes.node.isRequired,
type: PropTypes.oneOf(['header', 'verticalAlign', 'default']),
};
export default Paper;
<file_sep>/src/components/dropdown/dropdown.js
import React, { useState } from 'react';
import cn from 'classnames';
import styles from './dropdown.module.scss';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUser, faCaretDown } from '@fortawesome/free-solid-svg-icons';
import { faUsers } from '@fortawesome/free-solid-svg-icons';
import { faComments } from '@fortawesome/free-solid-svg-icons';
import { faWrench } from '@fortawesome/free-solid-svg-icons';
import { faPowerOff } from '@fortawesome/free-solid-svg-icons';
import { Button } from './../../components';
const Dropdown = () => {
const [isOpen, setIsOpen] = useState(false);
return (
<div className={styles.dropdown}>
<Button type="dropdown" onClick={() => setIsOpen(!isOpen)}>
<FontAwesomeIcon icon={faUser} className={styles.faUser} />
<NAME>
<FontAwesomeIcon icon={faCaretDown} className={styles.arrow} />
</Button>
<div className={cn(styles.dropdownContent, isOpen ? styles.show : '')}>
<div>
<FontAwesomeIcon icon={faUsers} className={styles.faUser} />
Groups
</div>
<div>
<FontAwesomeIcon icon={faComments} className={styles.faUser} />
Frequently contacted
</div>
<div>
{' '}
<FontAwesomeIcon icon={faWrench} className={styles.faUser} />
Preferences
</div>
<div>
<FontAwesomeIcon icon={faPowerOff} className={styles.faUser} />
Log out
</div>
</div>
</div>
);
};
export default Dropdown;
<file_sep>/src/components/button/button.js
import React from 'react';
import cn from 'classnames';
import styles from './button.module.scss';
import PropTypes from 'prop-types';
const Button = ({ type, children, ...rest }) => {
if (type === 'dropdown') {
return (
<button
className={cn(styles.dropbtn, styles.dropdownMainStyle)}
{...rest}
>
{children}
</button>
);
} else if (type === 'filter') {
return (
<button className={styles.filterButton} {...rest}>
{' '}
{children}{' '}
</button>
);
} else if (type === 'add') {
return (
<button className={styles.add} {...rest}>
{children}
</button>
);
}
};
Button.propTypes = {
children: PropTypes.node.isRequired,
type: PropTypes.oneOf(['dropdown', 'filter', 'add', 'dark']).isRequired,
};
export default Button;
<file_sep>/src/state/contacts/ContactsReducer.js
import { constants } from '../constants';
const INITIAL_STATE = {
isOnSync: false,
contactsData: [],
};
export const contactsReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case constants.contacts.SET_ON_SYNC_FLAG:
return {
...state,
isOnSync: action.flag,
};
case constants.contacts.SET_TABLE_DATA:
return {
...state,
contactsData: action.payload,
};
default:
return state;
}
};
<file_sep>/src/state/reducers.js
import { combineReducers } from 'redux';
import { contactsReducer } from './contacts/ContactsReducer';
import { modalsReducer } from './modals/ModalsReducer';
export const reducers = combineReducers({
contactsState: contactsReducer,
modalsState: modalsReducer,
});
| dbdd675e8ccdd1819fd9a6ebac83bdd2a9598ebc | [
"JavaScript",
"Markdown"
] | 24 | JavaScript | renatas7/contactify-app | a18afb3617455f4faa49cb3c860688eab4d8ac47 | df06d14f72329dbce5cc6984801a66fd73c4a171 |
refs/heads/master | <repo_name>justinwagg/New_Greenhouse_v4<file_sep>/humidifier.ino
void humidifier(){
//increment total humidifier running time
if(humidOn==true){
hRunTime=hRunTime+(currentMillis-onTime);
onTime=currentMillis;
}
//if humidifier has been on too long, turn off
if(hRunTime>30000){
allowHumid=false;
}
else{allowHumid=true;}
if(h1<50 && allowHumid==true && humidOn==false){
humidControlOn();
}
if(h1>=50 || allowHumid==false){
humidControlOff();
}
}
//reset humidifier run time
BLYNK_WRITE(6){
hRunTime=0;
}
//BLYNK_WRITE(10){
//// if(param.asInt() != hTarget){
//// //EEPROM.update(0,param.asInt());
//// }
//}
<file_sep>/testPrint.ino
void testPrint(){
Serial.println("total h run time= ");
// Serial.println(hRunTime);
//
// Serial.println("hTarget= ");
// Serial.println(hTarget);
// Serial.println("EEPROM(0)= ");
// Serial.println(EEPROM.read(0));
}
<file_sep>/humidControl.ino
void humidControlOn(){
digitalWrite(hPin,HIGH);
onTime=currentMillis;
humidOn=true;
}
void humidControlOff(){
digitalWrite(hPin,LOW);
humidOn=false;
}
<file_sep>/sendUptime.ino
void sendUptime()
{
//Serial.println("sendUptime ran");
h1 = dht.readHumidity();
h2 = dht2.readHumidity();
t = dht.readTemperature(true);
t2 = dht2.readTemperature(true);
hi = dht.computeHeatIndex(t, h1);
hi2 = dht2.computeHeatIndex(t2, h2);
Blynk.virtualWrite(0, h1);
Blynk.virtualWrite(1, h2);
Blynk.virtualWrite(2, t);
Blynk.virtualWrite(3, t2);
Blynk.virtualWrite(4, hi);
Blynk.virtualWrite(5, hi2);
//Blynk.virtualWrite(6,hTarget);
Blynk.virtualWrite(7, allowHumid);
Blynk.virtualWrite(8, (hRunTime / 1000));
Blynk.virtualWrite(9, humidOn);
}
<file_sep>/New_Greenhouse_v4.ino
float h1;
float h2;
float t;
float t2;
float hi;
float hi2;
int test;
int hTarget;
int hPin = 9;
boolean allowHumid = true;
boolean humidOn = false;
boolean hReset = LOW;
boolean connectionOK;
unsigned long onTime;
unsigned long currentMillis;
unsigned long hRunTime;
unsigned long counter[2];
unsigned long total[2] = {
0, 0
}; //total[1] = total run time for the humidifier. it's stored when the humidifier turns off. it's intialized in the setup routine.
#include "DHT.h"
#define BLYNK_PRINT Serial // Comment this out to disable prints and save space
// These are the interrupt and control pins for СС3000
//#define ADAFRUIT_CC3000_IRQ 3
//#define ADAFRUIT_CC3000_VBAT 5
//#define ADAFRUIT_CC3000_CS 10
//#define BLYNK_DEBUG
#define DHTPIN 45
#define DHTPIN2 44
#define DHTTYPE DHT11 // DHT 11
#define W5200_CS 10
#define SDCARD_CS 4
#include <SPI.h>
#include <SimpleTimer.h>
#include <EthernetV2_0.h>
#include <BlynkSimpleEthernetV2_0.h>
//#include <EEPROM.h>
//instantiates
SimpleTimer timerBlynk;
//SimpleTimer timerPrint;
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "v";
IPAddress server_addr(c);
void setup()
{
pinMode(SDCARD_CS,OUTPUT);
digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
Serial.begin(9600);
Blynk.begin(auth);
dht.begin();
timerBlynk.setInterval(1000, sendUptime);
//timerPrint.setInterval(1000, testPrint);
pinMode(hPin, OUTPUT);
digitalWrite(hPin, LOW);
}
void loop()
{
// hTarget=EEPROM.read(0);
currentMillis = millis();
Blynk.run();
timerBlynk.run();
//timerPrint.run();
humidifier();
}
| 3ee7c178dd509347a92b6aa656f2356d84e32dca | [
"C++"
] | 5 | C++ | justinwagg/New_Greenhouse_v4 | becd71276031cac9e1985e6dab2538f8efa51604 | 622765d6cf420637d6b444b4fad1ef2a343315c2 |
refs/heads/master | <file_sep><?php
require_once "business_images.php";
require_once "business.php";
function start(&$model){
return 'startView';
}
function top(&$model){
return 'topView';
}
function description(&$model){
return 'descriptionView';
}
function quiz(&$model){
return 'quizView';
}
function preparing(&$model){
return 'preparingView';
}
function galery(&$model){
$notice1 ='';
$notice2 ='';
if(isset($_POST['remember'])){
foreach($_POST['img'] as $img){
$_SESSION["$img"] = 1;
}
}
showMiniatures($notice1, 'miniatures');
showGalery($notice2, 'galery');
$model['miniatures']=$notice1;
$model['images']=$notice2;
return 'galeryView';
}
function myGalery(&$model){
$notice1 ='';
$notice2 ='';
if(isset($_POST['forget'])){
foreach($_POST['img'] as $img){
unset($_SESSION["$img"] );
}
}
showMiniatures($notice1, 'myMiniatures');
showGalery($notice2, 'myGalery');
$model['miniatures']=$notice1;
$model['images']=$notice2;
return 'myGaleryView';
}
function galeryAdding(&$model){
$notice='';
$error = false;
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$image = $_FILES['zdjecie'];
$image['znak'] = $_POST['znak'];
$image['autor'] = $_POST['autor'];
$image['tytul'] = $_POST['tytul'];
if(isset($_POST['type']) && $_POST['type'] == 'private'){
$priv = $_POST['type'];
$image['priv'] = $_SESSION['login'];
}
else
$priv = false;
checkFile($notice, $error, $image);
if($error == false){
addImage($image, $notice);
addWatermark($image);
addMiniature($image);
saveImageToDb($image, $priv);
}
}
$model['notice'] = $notice;
return 'galeryAddingView';
}
function logout(&$model){
session_destroy();
return 'redirect:startView.php';
}
function logphp(&$model){
if(isset($_SESSION['notice'])){
$model['notice'] = $_SESSION['notice'];
unset($_SESSION['notice']);
}
return 'loginView';
}
function login(&$model){
loginUser($_POST['login'], $_POST['password'], $notice);
if($notice){
$_SESSION['notice'] = $notice;
}
if(isset($_SESSION['id'] ))
return 'redirect:startView.php';
else
return 'redirect:login.php';
}
function register(&$model){
$user = [
'email' =>$_POST['email'],
'login' => $_POST['login'],
'pass' => $_POST['<PASSWORD>'],
'rep_pass' => $_POST['<PASSWORD>'],
];
registerUser($notice, $user);
if($notice)
$_SESSION['notice'] = $notice;
if(isset($_SESSION['id'] ))
return 'redirect:startView.php';
else
return 'redirect:login.php';
}
?><file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<link rel="icon" href="static/images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="static/js/JQuery.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<header>
<h1 id="gora">W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<h3>Co zrobić by wejść na szczyt?</h3>
<p>Kto chciałby zdobyć jakiś szczyt? Na pewno wszyscy, którzy trafili na tą stronę. <br/></p>
<p>Ale jak to osiągnąć?
Należy się do tego odpowiednio przygotować, wtedy sama podróż staje się prostrza i mniej niebezpieczna!
Mapa, jedzenie, odpowiednie ubranie - to tylko najbardziej podstawowe aspekty dobrego przygotowania.
Poniżej znajduje się opis porządnego przygotowania się do wyprawy. Zapraszam do czytania:
</p>
<div id="accordion">
<h4>Planuj trasę</h4>
<div>
<p>
Mapa tyrystyczna, to coś co każdy powinien mieć. Osobiście nie przepadam za elektronicznymi wersjami, a tym bardziej
gdy całkowicie zastępują one papierową wersje. To kwestia gustu, jednak należy się wtedy zaopatrzyć na naładowany sprzęt
elektroniczny.
</p>
<p>
Na szlak najlepiej wyjść wcześnie rano i choć sadyzmem wydaje się wstawanie o strasznej godzinie, kiedy jest jeszcze
ciemno, ma to swoje sensowne uzasadnienie. Po pierwsze: ominiemy innych ludzi. No bo w góry nie idzie się po to,
by się o nich na każdym kroku potykać. Zasada jest prosta – im bardziej popularna trasa, tym wcześniej stawiamy się na jej
starcie. Kiedy leniuchy będą jeszcze przekręcały się z jednego boku na drugi, my będziemy już hen, daleko, w spokoju napawać
się pięknem przyrody. Po drugie: więcej czasu na marsz, to więcej czasu na odpoczynek i wylegiwanie się na trawie
</p>
</div>
<h4>Pogoda</h4>
<div>
<p>
Najlepiej pogodę sprawdzić (w kilku różnych źródłach) wieczorem, przed wyjazdem, a dla pewności jeszcze raz rano na
kamerkach internetowych (a jest ich coraz więcej). Oczywiście, chodzenie po górach w deszczu może być zabawne, ale
równocześnie staje się bardziej niebezpieczne – mokre skały są mało sympatyczne, takoż błotniste ścieżki. Nie mówiąc
już o tym, że w góry idzie się m.in. po to, by podziwiać piękne widoki. Kiedy brodzi się w chmurach jest to średnio
możliwe.
</p>
</div>
<h4>Buciki</h4>
<div>
<p>
Śmiało można zaryzykować teorię, że buty to najważniejszy element górskiego wyposażania. Jeżeli są niewygodne,
to obcierają i człowiek skupia się tylko na tym, że mu źle. Jeżeli przemakają na deszczu, to jest zimno i można złapać
bolesne skurcze, które wcale nie ułatwiają marszu. Jeżeli są za ciężkie, to trudniej oderwać stopy od ziemi i idzie się
o wiele wolniej. Jeżeli nie są ponad kostkę, to o wiele łatwiej ją skręcić i na tym zakończyć wycieczkę. Jeżeli nie są
przystosowane do trudniejszego terenu (twarda podeszwa), to czuć pod stopą każdy kamień, co jest cholernie irytujące.
</p>
</div>
<h4>Plecak</h4>
<div>
<p>
No właśnie: co ze sobą zabrać? Mapę i kompas – żeby zawsze widzieć, w którym miejscu się jest, jak iść dalej lub jak
wrócić. Apteczkę pierwszej pomocy – nigdy nie wiadomo, kiedy będziemy musieli komuś pomóc lub kiedy ktoś będzie musiał
pomóc nam (przezorny zawsze ubezpieczony).
</p>
<p>
Dobra wiadomość dla łasuchów – w górach bezkarnie można objadać się czekoladą, która w kryzysowych momentach doda nam
trochę energii. Oczywiście, nie samymi słodyczami żyje człowiek, dlatego najlepiej zaopatrzyć się jedzenie, które
faktycznie postawi nas na nogi. Kiedy człowiek wpina się na szczyt, to się męczy – a jak się męczy, to się poci. Żeby
się nie odwodnić ZAWSZE należy mieć ze sobą coś do picia, przy czym najlepiej sprawdzi się najzwyklejsza w świecie woda
mineralna a w chłodniejsze dni herbata w termosie, która działa rozgrzewająco.
</p>
</div>
<h4><NAME> bezpieczeństwa</h4>
<div>
<p>
W góry chodzi się po to, żeby zdobywać szczyty, ale też po to, żeby z nich bezpiecznie wrócić – po to, żeby mieć
okazję wejść na kolejne. Góry nie uciekną. Poczekają tydzień, miesiąc a nawet rok. Jeżeli pogoda jest bardzo kiepska,
wyjście na szlak lepiej sobie odpuścić (lub zawrócić z niego, gdy trafimy na załamanie pogody – o ile mamy taką
możliwość). Zwłaszcza wtedy, kiedy dopiero zaczynamy swoją przygodę z trekkingiem i nie mamy zbyt wielkiego doświadczenia
w poruszaniu się po śliskich skałach, czy oblodzonych/błotnistych ścieżkach. Dobrą praktyką jest informowanie bliskich,
gdzie wyruszamy, na jak długo i o której godzinie powinniśmy być z powrotem. Jeżeli przydarzy nam się coś złego, o wiele
łatwiej będzie nas znaleźć. Również z tego powodu powinno znać się swoje aktualne położenie i na bieżąco śledzić na
mapie, gdzie jesteśmy. Wyżej wspominałam o naładowanym telefonie. Warto zapisać sobie w nim numery alarmowe do
GOPR-u/TOPR-u: 985 lub +48 601 100 300.
</p>
</div>
</div>
<a href="http://tpn.pl/" target="_blank"><img id="nrTopr" class="link" src="static/images/other/goprNr.jpg" alt="numer telefonu ratunkowego w górach" /></a>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<link rel="icon" href="static/images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
</head>
<body>
<div id="container">
<header>
<h1>W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<h3>
galeria
</h3>
<table class="galery">
<tr>
<td>
<ul id="galeria">
<?= $images
?>
</ul>
</td>
<td class="galeryRight">
<form method="post" >
<input type="submit" name="remember" value="Zapamiętaj wybrane"/>
<div id="miniatury">
<table id="listaMiniatur">
<?= $miniatures ?>
</table>
</div>
</form>
</td>
</tr>
</table>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep>var odp=[0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0 ,0, 0, 0, 0, 0];
function changeColor(el1, id2) {
var id1 = el1.id;
document.getElementById(id1).style.background = "lightGreen";
document.getElementById(id2).style.background = "lightGray";
odp[id1-1] = 1;
odp[id2-1] = -1;
}
function sprawdz() {
var punkty = 0;
if (odp[0] == 1) punkty++;
if (odp[2] == 1) punkty++;
if (odp[4] == 1) punkty++;
if (odp[6] == 1) punkty++;
if (odp[8] == 1) punkty++;
if (odp[11] == 1) punkty++;
if (odp[12] == 1) punkty++;
if (odp[15] == 1) punkty++;
dodajElement(punkty);
}
function dodajElement(ptk) {
usunElement();
var p = document.createElement('div');
var tekst = document.createTextNode('Brawo, twój wynik to: ' + ptk + '/8 ptk ');
p.style.backgroundColor = 'yellow';
p.style.paddingLeft = "10px";
p.style.fontSize = "18px";
p.style.margin = "10px";
p.style.marginLeft = "30%";
p.style.marginRight = '30%';
p.style.padding = "10px";
p.id = "wynik";
p.appendChild(tekst);
document.getElementById('sect').appendChild(p);
}
function usunElement() {
var usun = document.getElementById('wynik');
if (usun)
usun.parentNode.removeChild(usun);
}
<file_sep>db.addUser( {user:"wai_web",
pwd: "<PASSWORD>",
roles:["readWrite", "dbAdmin"]})
<file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<link rel="icon" href="static/images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
<script src="static/js/JavaScript.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<header>
<h1 id="gora">W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section id="sect">
<h3>Czas na QUIZ!</h3>
<noscript>
Quiz jest niedostępy. Wyłączona obsługa JavaScript w przeglądarce.
</noscript>
<h5 id="h5">Zasady gry:</h5>
<p>
Poniżej znajduje się 6 zdjęć pewnych szczytów. Twoim zadaniem jest wskazanie poprawnej nazwy góry.
</p>
<table class="bezkrawedzi">
<tr>
<td>
<img src="static/images/other/quiz/giewont.jpg" alt="1" />
<label id="1" onclick="changeColor(this, 2)">Giewont</label>
<label class="rightLabel" id="2" onclick="changeColor(this, 1)">Rysy</label>
</td>
<td>
<img src="static/images/other/quiz/dolinahocholowska.jpg" alt="2" />
<label id="3" onclick="changeColor(this, 4)"><NAME></label>
<label class="rightLabel" id="4" onclick="changeColor(this, 3)"><NAME></label>
</td>
</tr>
<tr>
<td>
<img src="static/images/other/quiz/dolinaRybiegoPotoku.jpg" alt="3" />
<label id="5" onclick="changeColor(this, 6)"><NAME></label>
<label class="rightLabel" id="6" onclick="changeColor(this, 5)"><NAME></label>
</td>
<td>
<img src="static/images/other/quiz/gerlach.jpg" alt="4" />
<label id="7" onclick="changeColor(this, 8)">Gerlach</label>
<label class="rightLabel" id="8" onclick="changeColor(this, 7)">Giewont</label>
</td>
</tr>
<tr>
<td>
<img src="static/images/other/quiz/koscielec.jpg" alt="5" />
<label id="9" onclick="changeColor(this, 10)">Kościelec</label>
<label class="rightLabel" id="10" onclick="changeColor(this, 9)">Świnica</label>
</td>
<td>
<img src="static/images/other/quiz/krzyzne.jpg" alt="6" />
<label id="11" onclick="changeColor(this, 12)">przełęcz Zawrat</label>
<label class="rightLabel" id="12" onclick="changeColor(this, 11)">przełęcz Krzyżne</label>
</td>
</tr>
<tr>
<td>
<img src="static/images/other/quiz/mnich.jpg" alt="7" />
<label id="13" onclick="changeColor(this, 14)">Mnich</label>
<label class="rightLabel" id="14" onclick="changeColor(this, 13)"><NAME></label>
</td>
<td>
<img src="static/images/other/quiz/rysy.jpg" alt="8" />
<label id="15" onclick="changeColor(this, 16)">Krywań</label>
<label class="rightLabel" id="16" onclick="changeColor(this, 15)">Rysy</label>
</td>
</tr>
</table>
<label id="spr" onclick="sprawdz()">SPRAWDŹ</label>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<link rel="icon" href="static/images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
</head>
<body>
<div id="container">
<header>
<h1>W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<?php nowLog();?>
<h2>Tatry</h2>
<img class="cytat" src="static/images/other/cyt.jpg" alt="cytat"/>
<p>
Myślę, że Tatry nie trzeba nikomu przedstawiać. Turystów w tych okolicach nigdy nie brakuje.
Wszyscy na pewno kojarzą Tatry z: Zakopanym - a dokładnie Krupówki, Giewont i <NAME>.
Są to najbardziej popularne miejsca na Podhalu. Na dowód wstawiam te zdięcia:
</p>
<img class="toLeft" src="static/images/other/GiewontKolejka.jpg" alt="kolejka na Giewont"/>
<img src="static/images/other/tlumyMorskieOko.jpg" alt="tłumy nad Morskim Oku"/>
<img src="static/images/other/krupowki.jpg" alt="tłumy na Krupówkach"/>
<p>
No ale przecież nic dziwnego, że to jest tak oblegane. W końcu tu jest pięknie!!
<br/>
</p>
<img src="static/images/other/KrupowkiNoca.jpg" alt="Krupówki nocą"/>
<img src="static/images/other/giewont.jpg" alt="Widok na Giewont"/>
<img src="static/images/other/morskieOko.jpg" alt="Morskie Oko z góry"/>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep><?php
$routing = [
'/' => 'start',
'/startView.php' => 'start',
'/galeria.php' => 'galery',
'/galeryView.php' => 'galery',
'/galeryFormView.php' => 'galeryAdding',
'/register' => 'register',
'/login' => 'login',
'/login.php' => 'logphp',
'/loginView.php' => 'logphp',
'/logout' => 'logout',
'/topView.php' => 'top',
'/descriptionView.php' => 'description',
'/quizView.php' => 'quiz',
'/preparingView.php' => 'preparing',
'/myGaleryView.php' => 'myGalery',
];
?><file_sep><?php
function showMiniatures(&$model, $type){
$dir = __DIR__.'/web/static/images';
if ( file_exists( $dir ) == false ) {
$model = 'Directory \''.$dir.'\' not found!';
}
else {
$dir_contents = scandir( $dir );
$number = 1;
$db = getDb();
foreach ( $dir_contents as $file ) {
if(substr($file, strlen($file)-6,6) == '_m.jpg' || substr($file, strlen($file)-6,6) == '_m.png'){
$name = substr($file,0, strlen($file)-6).'.'.takeExtension($file);
$query = ['name' => $name,];
$images = $db->images->findOne($query);
$id = $images['_id'];
if(($type == 'myMiniatures' && isset($_SESSION["$id"])) || $type == 'miniatures'){
$checked ='';
if(!isset($images['priv']) || ( isset($_SESSION["login"]) && $images['priv'] == $_SESSION["login"])){
if(isset($_SESSION["$id"]) && $type == 'miniatures'){
$checked = ' checked ';
}
$author = '';
$title = '';
if(isset($images['author']))
$text = '</br>'.$images['author'].'<br/>';
else
$text = '</br></br>';
if(isset($images['author']))
$text = $text.$images['title'];
if(isset($images['priv']))
$text = '</br>(zdjecie prywatne)'.$text;
$model = $model.'<tr><td class="check"><input type="checkbox" name="img[]" value="'.$images['_id'].'"'.$checked.'/></td><td><a href="#image'.$number.'"><img src="static/images/'.$file.'" alt="zdjęcie'.$number.'" /></a></p>'.$text.'</td></tr>';
$number++;
}
}
}
}
}
}
function showGalery(&$model, $type){
$dir = __DIR__.'/web/static/images';
if ( file_exists( $dir ) == false ) {
$model = 'Directory \''.$dir.'\' not found!';
}
else {
$dir_contents = scandir( $dir );
$number = 1;
$db = getDb();
foreach ( $dir_contents as $file ) {
if(substr($file, strlen($file)-6,6) == '_z.jpg' || substr($file, strlen($file)-6,6) == '_z.png'){
$name = substr($file,0, strlen($file)-6).'.'.takeExtension($file);
$query = ['name' => $name,];
$images = $db->images->findOne($query);
$id = $images['_id'];
if(($type == 'myGalery' && isset($_SESSION["$id"])) || $type == 'galery'){
if(!isset($images['priv']) || ( isset($_SESSION['login']) && $images['priv'] == $_SESSION['login'])){
$model = $model.'<li id="image'.$number.'"><img src="static/images/'.$file.'" alt="zdjęcie'.$number.'"/></li>';
$number++;
}
}
}
}
}
}
function checkFile(&$notice, &$error, $image){
if($image['type'] != 'image/png' && $image['type'] != 'image/jpeg'){
$notice = $notice."<br/>zdjęcie ma zły format";
$error = true;
}
if($image['size'] > 1048576){
$notice = $notice."<br/>zdjęcie ma za duży rozmiar";
$error = true;
}
}
function addImage(&$image, &$notice){
$dir = __DIR__."/web/static/images/";
$image['newName'] = $image['name'];
$db = getDb();
$image['shortName'] = substr($image['name'], 0, strlen($image['name'])-4);
$image['extension'] = takeExtension($image['name']);
$image['name'] = $image['shortName'].'.'.$image['extension'];
$image['newName'] = $image['shortName'].'.'.$image['extension'];
for($j = 1; $db -> images -> findOne(['name' => $image['newName']]); $j++){
$image['newName'] = $image['shortName'].$j.'.'.$image['extension'];
}
$target = $dir.$image['newName'];
if(move_uploaded_file($image['tmp_name'], $target))
$notice = "<br/>zdjęcie ".$image['name']." przesłano prawidłowo";
$image['name'] = $image['newName'];
$image['shortName'] = substr($image['name'], 0, strlen($image['name'])-4);
}
function addMiniature($image){
$dir = __DIR__."/web/static/images/";
list($width,$height) = getimagesize($dir.$image['name']);
$miniature = imagecreatetruecolor(200, 125);
if($image['extension'] == 'png')
$src = imagecreatefrompng($dir.$image['name']);
else
$src = imagecreatefromjpeg($dir.$image['name']);
imagecopyresized ($miniature, $src , 0 ,0 , 0 , 0 , 200 , 125 , $width , $height );
if($image['extension'] == 'png')
imagepng($miniature, $dir.$image['shortName'].'_m.'.$image['extension']);
else
imagejpeg($miniature, $dir.$image['shortName'].'_m.'.$image['extension']);
imagedestroy($src);
imagedestroy($miniature);
move_uploaded_file($miniature['tmp_name'], $dir.$image['shortName'].'_m.'.$image['extension']);
}
function addWatermark($image){
$dir = __DIR__."/web/static/images/";
list($width,$height) = getimagesize($dir.$image['name']);
$target = $dir.$image['name'];
$imageProperties = imagecreatetruecolor($width, $height);
if($image['extension'] == 'jpg')
$targetLayer = imagecreatefromjpeg($target);
else
$targetLayer = imagecreatefrompng($target);
imagecopyresampled($imageProperties, $targetLayer, 0, 0, 0, 0, $width, $height, $width, $height);
$watermarkColor = imagecolorallocate($imageProperties, 191,191,191);
imagestring($imageProperties, 5, 100, $height - 60, $image['znak'], $watermarkColor);
imagecopymerge($imageProperties, $targetLayer, 0, 0, 0, 0, $width, $height, 20);
if($image['extension'] == 'png')
imagepng($imageProperties, $dir.$image['shortName'].'_z.'.$image['extension']);
else
imagejpeg($imageProperties, $dir.$image['shortName'].'_z.'.$image['extension']);
imagedestroy($targetLayer);
imagedestroy($imageProperties);
move_uploaded_file($imageProperties['tmp_name'], $dir.$image['shortName'].'_z.'.$image['extension']);
}
function saveImageToDb(&$img, $priv){
$db = getDb();
$image = [
'name'=> $img['name'],
'title' => $img['tytul'],
'author'=>$img['autor'],
];
if(isset($img['priv']))
$image['priv'] = $_SESSION['login'];
$db -> images -> insert($image);
}
function takeExtension($name){
if(strtolower(substr($name, strlen($name)- 3,3)) == 'png')
return 'png';
else
return 'jpg';
}
?><file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<link rel="icon" href="static/images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
</head>
<body>
<div id="container">
<header>
<h1>W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<h3>Top 5 najwyższych szczytów</h3>
<p>
Jeżeli zastanawiałeś się kiedyś, jakie szczyty w Tatrach są najwyższe to dobrze trafiłeś!!
<br /> Poniżej masz wszytstko wypisane w przejżystej tabeli.
Wypisałam tylko te szczyty, ktore leżą w Polsce lub na granicy polsko-słowackiej. Cociaż tak naprawdę największy wieszchołek całkowicie
położony w Polsce to Kozi Wierch mający zaledwie 2291m n. p. m.. Tak więc praktycznie wszystkie wypisane góry leżą na granicy.
<br />
W kolumnie "dostępność" napisałam czy zwykly turysta może wejść na ten szczyt - czyli czy prowadzi tam jakiś oznakowany szlak.
Na resztęszczytów "brak szlaku" często wchodzą taternicy.
</p>
<table>
<caption>top 10 szczytów w Tatrach polskich (włącznie ze szczytami granicznymi)</caption>
<tr>
<th>nr</th>
<th>polska nazwa</th>
<th>słowacka nazwa</th>
<th>wysokość n.p.m.</th>
<th>dostępność</th>
<th>pierwsze wejście (rok)</th>
</tr>
<tr>
<td>1</td>
<td> Rysy</td>
<td>Rysy</td>
<td>2499 m</td>
<td>dostępny</td>
<td>1840</td>
</tr>
<tr class="parzysta">
<td>2</td>
<td> <NAME></td>
<td>Veľký Mengusovský štít</td>
<td> 2438 m</td>
<td>dostępny</td>
<td>1877</td>
</tr>
<tr>
<td>3</td>
<td> <NAME></td>
<td><NAME>, <NAME></td>
<td> 2430 m</td>
<td>brak szlaku</td>
<td>1905</td>
</tr>
<tr class="parzysta">
<td>4</td>
<td> <NAME> </td>
<td><NAME>ský štít</td>
<td> 2410 m</td>
<td>dostępny</td>
<td>1903</td>
</tr>
<tr>
<td>5</td>
<td> <NAME> </td>
<td><NAME>ovský štít</td>
<td> 2393 m</td>
<td>brak szlaku</td>
<td>1903</td>
</tr>
<tr class="parzysta">
<td>6</td>
<td><NAME></td>
<td>Hincova veža</td>
<td>2377 m</td>
<td>brak szlaku</td>
<td>1903</td>
</tr>
<tr>
<td>7</td>
<td> Cubryna </td>
<td>Čubrina</td>
<td>2376 m </td>
<td>brak szlaku</td>
<td>1884</td>
</tr>
<tr class="parzysta">
<td>8</td>
<td> <NAME> </td>
<td>Volia veža</td>
<td> 2373 m</td>
<td>dostępny</td>
<td>1905</td>
</tr>
<tr>
<td>9</td>
<td> <NAME> </td>
<td>Žabia veža</td>
<td> 2335 m</td>
<td>dostępny</td>
<td>1905</td>
</tr>
<tr class="parzysta">
<td>10</td>
<td>Świnica </td>
<td>Svinica</td>
<td>2301 m</td>
<td>dostępny</td>
<td>1867</td>
</tr>
</table>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<link rel="icon" href="images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
</head>
<body>
<div id="container">
<header>
<h1>W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<h3>
logowanie
</h3>
<div class="toLeft logowanie">
<h2>logowanie</h2>
<form name="logowanie" action="login" method="post">
<p><?php if(isset($notice['login'])) echo $notice['login']; ?></p></br>
<label>Login: <input type="text" name="login" required/></label></br></br>
<label>Hasło: <input type="password" name="password" required /></label></br></br>
<input name="zaloguj" value="zaloguj" type="submit">
</form>
</div>
<div class="toLeft logowanie">
<h2>rejestracja</h2>
<form name="rejestracja" action="register" method="post">
<label>Adres e-mail: <input type="text" name="email" required/></label></br>
<p><?php if(isset($notice['email'])) echo $notice['email'];
else echo '</br>'; ?></p></br>
<label>Login: <input type="text" name="login" required/></label></br>
<p><?php if(isset($notice['log'])) echo $notice['log'];
else echo '</br>';?></p></br>
<label>Hasło: <input type="password" name="password" required /></label></br></br>
<label>Powtórz hasło: <input type="password" name="repetition_password" required /></label></br>
<p><?php if(isset($notice['pass'])) echo $notice['pass'];
else echo '</br>';?></p></br>
<input name="zarejestruj" value="zarejestruj" type="submit">
</form>
</div>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep>db.addUser( {user:"admin",
pwd: "<PASSWORD>",
roles:["userAdminAnyDatabase"]})
<file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<link rel="icon" href="static/images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
</head>
<body>
<div id="container">
<header>
<h1 id="gora">W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<h4>Opis Tatr</h4>
<p>
Tatry są najwyższym masywem górskim w Karpatach Zachodnich. Ogólnie, całe Tatry
zajmują powierzchnię 740 km2, a w granicach Polski znajduje się zaledwie 174 km 2.
Długa i skomplikowana historia geologiczna doprowadziła do ogromnej różnorodności
skał oraz skomplikowanej tektoniki tego regionu. Najwyższą część - <NAME>,
budują najstarsze skały: granitoidy, skały metamorficzne. Skały osadowe budują północny
skłon Tatr. Są to serie wierchowe oraz Tatry Reglowe.
</p>
<p>Tatry dzielą się na dwie główne części: <NAME> i <NAME>.</p>
<p>
<NAME> ciągną się od Siwego Wierchu i Doliny Suchego Potoku na zachodzie,
po przełęcz Liliową i Zawory na wschodzie. Główny grzbiet Tatr Zachodnich ciągnie się
równoleżnikowo, wzdłuż krystalicznego trzonu i tylko pomiędzy Tomanowem i Liliowem
skręca ku północy, na zbudowane z fałdów serii wierchowej Czerwone Wierchy, Goryczkowe
Czuby, Kasprowy. Najwyższe szczyty Tatr Zachodnich biegną w południowych odgałęzieniach
głównego grzbietu. Są to: Bystra (2248 m), Raczkowa Czuba albo Jakubina (2189 m).
Na granicy państwa najwyższymi wzniesieniami są: Starorobociański (2176 m),
Błyszcz (2158 m), Jarząbczy (2137 m), Kamienista (2126 m) i Krzesanica (2122 m)
w grupie Czerwonych Wierchów. Po polskiej stronie Tatr Zachodnich znajdują się
następujące doliny: Chochołowska z Jarząbczą i Starobociańską, Kościeliska z Tomanową
i Miętusią, Małej Łąki, Bystrej z Kasprową i Kondratową. Ponadto kilka mniejszych dolin
rozwinęło się w serii reglowej: Lejowa, Za Bramką, Strążyska, Białego i Olczyska.
Rzeźba Tatr Zachodnich ma przeważnie charakter erozyjny i krasowy; tylko w tych
czterech wyżej wymienionych dolinach, w ich wyższych częściach występują formy glacjalne.
</p>
<p>
W wapiennych częściach gór występują liczne jaskinie. Najdłuższa z nich dochodzi do
6 km długości, a najgłębsza do 772 m głębokości (Jaskinia Wielka Śnieżna w Dolinie Małej
Łąki). Północna część Tatr Zachodnich jest niższa do 1300-1500 m.n.p.m. Są to Regle.
</p>
<a href="#gora"><img class="strzalka" src="static/images/other/strzalka1.jpg" alt="up" /></a>
<h4>Rysy</h4>
<p>
Nazwa szczytu pochodzi od pożłobionych zboczy kompleksu Niżnych Rysów, Żabiego Szczytu
Wyżniego i Żabiego Mnicha, które swoimi kształtami mogą budzić skojarzenia, jakoby góra
była silnie porysowana.
</p>
<p>
Wejście od strony polskiej jest dobrze ubezpieczone (360 metrów łańcuchów), wymaga jednak
przygotowania turystycznego i kondycyjnego. Od Morskiego Oka deniwelacja wynosi 1104 metry.
Od Czarnego Stawu średnie nachylenie szlaku wynosi aż 30 stopni. Szlak wiedzie przez miejsca
zacienione, co powoduje spadki temperatury oraz duże prawdopodobieństwo zalegania płatów śniegu.
Od czasu otwarcia polskiego szlaku na Rysy zginęło na nim ponad 50 osób.
</p>
<p>
Szczyt swoją popularność zawdzięcza niezrównanej panoramie: przy dobrej pogodzie można podziwiać
widoki w promieniu do 100 km. Z wierzchołka można rozróżnić 80 szczytów tatrzańskich i mniej więcej
50 szczytów w innych grupach górskich, podziwiać 13 większych jezior tatrzańskich
</p>
<p>
Chata pod Rysami jest najwyżej położonym tego typu obiektem w Tatrach – wysokość 2250 m
brzmi naprawdę imponująco. Chata czynna jest w sezonie letnim i nie prowadzi do niej żadna
droga dojazdowa, toteż zaopatrzenie we wszelkie produkty odbywa się za życzliwością turystów
lub tatrzańskich tragarzy. Jeśli turysta do Chatki pod Rysami przyniesie od 5 do 10 kg prowiantu,
zostanie uraczony herbatą z sokiem malinowym. Energia elektryczna pochodzi z baterii słonecznych,
a w wodę schronisko zaopatruje się z pobliskiego strumyka lub topniejącego śniegu. Schronisko
dysponuje salą do spania na poddaszu oraz salą jadalną i bufetem na parterze.
</p>
<a href="#gora"><img class="strzalka" src="static/images/other/strzalka1.jpg" alt="up" /></a>
<h4>Morskie Oko</h4>
<p>
Jednym z najchętniej odwiedzanych miejsc w okolicach Zakopanego jest Morskie Oko. To największe
jezioro w Tatrach leży w Dolinie Rybiego Potoku w odległości około 25 km od Zakopanego. Samochodem
lub busem można dojechać do Palenicy Białczańskiej, pozostałe 8 km trzeba pokonać pieszo lub dorożką
(zimą saniami). Miejsce to zawdzięcza swoją popularność niesamowitym widokom, jakie rozciągają się
na <NAME> i szczy<NAME>. Nad <NAME> znajduje się też schronisko górskie.
</p>
<p>
Samo jezioro jest pochodzenia polodowcowego i ma powierzchnię 35h a największa głębokość to 51m.
Woda jest bardzo przejrzysta, widoczność sięga 12m w głąb. Dawniej nazywane Rybim Stawem ze względu
na naturalne zarybienie jeziora, co jest zjawiskiem rzadkim w jeziorach tatrzańskich – żyją w nim
głównie pstrągi. Zimą w okresie od listopada do kwietnia jezioro jest zamarznięte i można po nim
spacerować – oczywiście czas jest umowny i zależy od temperatur panujących wokół.
</p>
<p>
Na morenie zamykającej jezioro od północy stoi schronisko PTTK. Położone na wysokości 1405 m n.p.m.
należy do najstarszych i najpiękniejszych schronisk tatrzańskich. Nazwane zostało imieniem Stanisława
Staszica, który w roku 1805 badał jezioro. Obok, przy końcu drogi, po lewej stronie znajduje się stare
schronisko, które pierwotnie było wozownią (1890). Obydwa budynki zostały uznane za zabytkowe.
Schronisko stanowi punkt wyjściowy do wycieczek na Rysy, Mięguszowiecką Przełęcz pod Chłopkiem
i Szpiglasową Przełęcz. Powyżej Morskiego Oka, w kierunku południowym znajduje się drugie duże jezioro
w Dolinie Rybiego Potoku, Czarny Staw pod Rysami (Czarny Staw nad Morskim Okiem).
</p>
<a href="#gora"><img class="strzalka" src="static/images/other/strzalka1.jpg" alt="up" /></a>
<h4><NAME> </h4>
<p>
Nazwa <NAME> pochodzi od leżącej u podnóży szczytu <NAME>, a ta z kolei
według podań ludowych od imienia lub przezwiska jej właściciela – górala Kaspra. Zbudowany
jest ze skał krystalicznych, mimo położenia w młodszej części Tatr zbudowanej ze skał osadowych.
</p>
<p>
Strome stoki (niemal ściany) opadają tylko do Doliny Kasprowej. Znajduje się w nich kilka
żlebów, z których najbardziej znany jest Żleb pod Palcem. Z wszystkich pozostałych stron
szczyt Kasprowego Wierchu dostępny jest bez problemu.
</p>
<p>
Tuż poniżej wydłużonego wierzchołka Kasprowego Wierchu, na wysokości 1959 m n.p.m. stoi budynek,
w którym znajduje się bar, restauracja, kiosk, poczekalnia dla czekających na zjazd kolejką,
przechowalnia nart oraz zimowa stacja TOPR. Od budynku do Suchej Przełęczy prowadzi brukowany
kamieniem spacerowy chodnik o długości ok. 200 m.
</p>
<p>
Trasa na Kasprowy Wierch z Kuźnic należy do jednych z najłatwiejszych w polskich Tatrach.
Jest monotonna i chwilami wręcz nudna, wszelako polecam ją z uwagi na brak dużego zatłoczenia
szczególnie w okresie zimowym (duża część ludzi po prostu wjeżdża kolejką na szczyt). Ponadto
stanowi wspaniałe miejsce do treningu dla biegaczy.
</p>
<a href="#gora"><img class="strzalka" src="static/images/other/strzalka1.jpg" alt="up" /></a>
<h4>Giewont</h4>
<p>
Giewont, <NAME>, symbol Zakopanego. Jest równie piękny, co niebezpieczny (zginęło na nim
najwięcej osób w Tatrach), jednak fakt ten odstrasza tylko część turystów. Reszta zmierza w wiadomym
kierunku, żeby tylko stanąć na wierzchołku góry i dotknąć krzyża.
</p>
<p>
Jego główny wierzchołek, <NAME>, jest często uznawany za najwyższy szczyt w Tatrach Zachodnich
położony w całości na terenie Polski; wyższa jest jednak <NAME> w pobliżu Czerwonych Wierchów.
</p>
<p>
Ponad szczytem Giewontu góruje krzyż o wysokości piętnastu metrów. Przy dobrej widoczności jest on
widziany z najodleglejszych zakątków Zakopanego. To dar od mieszkańców Zakopanego ufundowany w 1900
rocznicę narodzin Jezusa Chrystusa – postawiono go w sierpniu 1901 roku.
</p>
<h5>Legenda o Śpiącym Rycerzu</h5>
<p>
Niektórzy nie mają wątpliwości – Giewont to nikt inny, jak <NAME>, który czuwa nie tylko nad
Zakopanem, ale i nad całą Polską i z pewnością zbudzi się, gdy ta znajdzie się w niebezpieczeństwie.
Co o Giewoncie mówi legenda?
</p>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="pl">
<head>
<title>Tatry</title>
<meta name="description" content="Strona poświęcona Tatrom. Jest poświęcona dla wszystkich, którzy chcą się czegoś dowiedzieć o naszych pięknych górach." />
<meta name="keywords" content="góra, góry, Tatry, wycieczki, turystyka, szczyty, zdięcia górskie, schroniska"/>
<meta charset="UTF-8" />
<meta name="author" content="<NAME>"/>
<link rel="icon" href="images/other/favicon.gif" type="image/x-icon"/>
<link rel="stylesheet" href="static/css/style.css" type="text/css" />
</head>
<body>
<div id="container">
<header>
<h1>W górach jest wszystko co kocham</h1>
<h3>wszystko co jest związane z Tatrami</h3>
</header>
<nav>
<ol class="menu">
<li><a href="startView.php"><img src="static/images/other/home.png" alt="Start" /></a></li>
<li>
GALERIA
<ul>
<li><a href="galeryView.php">GALERIA</a></li>
<li><a href="galeryFormView.php">PRZESLIJ</a></li>
<li><a href="myGaleryView.php">MOJE</a></li>
</ul>
</li>
<li>
SZCZYTY
<ul>
<li><a href="topView.php">TOP 10</a></li>
<li><a href="descriptionView.php">OPISY</a></li>
</ul>
</li>
<li><a href="preparingView.php">PRZYGOTOWANIE</a></li>
</ol>
<p id="log">
<?php logButton() ?>
</p>
</nav>
<section>
<h3>
galeria - przesyłanie zdjęć
</h3>
<div id="form">
<form method="post" enctype="multipart/form-data">
<label>
<span>Zdjęcie:</span>
<input type="file" name="zdjecie" required/>
</label>
<br/><br/>
<label>
<span>Znak wodny:</span>
<input type="text" name="znak" required/>
</label>
<br/><br/>
<label>
<span>Tytuł:</span>
<input type="text" name="tytul" />
</label>
<br/><br/>
<label>
<span>Autor:</span>
<input type="text" name="autor" <?php if(isset($_SESSION['id'])) echo 'value="'.$_SESSION['login'].'"';?>/>
</label>
<br/><br/>
<?php if(isset($_SESSION['id'])){
echo '<label>
<input type="radio" name="type" value="public" checked />
<span> zdjęcie publiczne</span>
</label>
<br/>
<label>
<input type="radio" name="type" value="private" />
<span> zdjęcie prywatne</span>
</label>
<br/><br/>';
}
?>
<input type="submit" name="id" value="przeslij" >
</form>
</div>
<?=
$notice;
?>
</section>
<footer>
<NAME>
</footer>
</div>
</body>
</html>
<file_sep><?php
function getDb(){
$mongo = new MongoClient(
"mongodb://localhost:27017/",
['username' => 'wai_web',
'password' => '<PASSWORD>',
'db' => 'wai',
]);
$db = $mongo->wai;
return $db;
}
function logButton(){
if(!isset($_SESSION['id'] )){
echo '<a href="login.php">ZALOGUJ</a>';
}
else {
echo '<a href="logout">WYLOGUJ</a>';
}
}
function nowLog(){
if(isset($_SESSION['nowLogin'])){
echo '<p>Zostałeś poprawnie zalogowany jako '.$_SESSION['login'].'</p>';
unset($_SESSION['nowLogin']);
}
}
function takeUserPass($login){
$db = getDb();
if($user = $db -> users -> findOne(['login' => $login]))
return $user['password'];
else
return false;
}
function loginUser($login, $pass, &$notice){
$db = getDb();
$dbPass = takeUserPass($login);
if(!$dbPass){
$notice['login']='błędny login lub hasło';
}
else if(!password_verify($pass, $dbPass)){
$notice['login'] = 'błędny login lub hasło';
}
else{
$user = $db -> users ->findOne(['login' => $login]);
session_regenerate_id();
$_SESSION['id'] = $user['_id'];
$_SESSION['login']=$login;
$_SESSION['nowLogin'] = 1;
}
}
function registerUser(&$notice, $user){
$register = true;
if(strpos($user['email'], '@') <= 0){
$register = false;
$notice['email'] = 'niepoprawny e-mail</br>';
}
if($user['pass'] != $user['rep_pass']){
$register = false;
$notice['pass'] = '<PASSWORD></br>';
}
if(takeUserPass($user['login'])){
$register = false;
$notice['log'] = 'nazwa uzytkownika jest juz zajeta</br>';
}
if($register){
$hash = password_hash($user['pass'], PASSWORD_DEFAULT);
$newUser = [
'email' => $user['email'],
'login' => $user['login'],
'password' => $hash,
];
$db = getDb();
$db -> users -> insert($newUser);
loginUser($user['login'], $user['pass'], $notice);
}
}
?> | 3093de9b5ec6e4feb57029b9f82de60f320b8bfa | [
"JavaScript",
"PHP"
] | 15 | PHP | EwelinaR/Gory_strona_www | 669e9e6a2835b4d37072f80fb9d2827caedbf809 | 9a3045e248948565d24057ecd52a10e007bb026c |
refs/heads/master | <file_sep>module Api
class BaseController < ApplicationController
rescue_from ActionController::RoutingError, :with => :render_404
def error(status = 500, message="Server Error")
render json: {success: false, code: status, message: message, payload: {}}, status: status
end
def success(data=nil, message="SUCCESS")
data = JSON.parse render_to_string if data.nil?
render json: {success: true, code: 200 , message: message, payload: data}, status: '200'
end
def render_404
error(404, 404, "Unknown API method")
end
end
end<file_sep>namespace :real_estates do
desc "import real estates from csv file"
task :import, [:country_code, :filename] => :environment do |t, args|
filename = args.filname.present? ? args.filename : 'Sacramentorealestatetransactions.csv'
country_code = args.country_code.present? ? args.country_code : 'US'
csv_path = "#{Rails.root.join('public','csv')}/#{filename}"
importer = RealEstatesImporter.new(country_code)
reader = CSV.read(csv_path)
reader.shift
reader.each_with_index do |x, i|
importer.add_new_real_estate(x)
printf("\r[%-25s] #{i+1}/#{reader.count} ", "=" * ((i+1.0)/reader.count*25) )
end
end
end
<file_sep>attributes *RealEstate.column_names
node(:location) {|i| i.location}<file_sep>class State < ActiveRecord::Base
belongs_to :country
has_many :cities, dependent: :nullify
validates :country, presence: true
validates :name, presence: true
validates :name, uniqueness: { case_sensitive: false, scope: :country_id }
end<file_sep>to boot it up do the follow steps
1- You need to have `docker` and `docker-compose` utitlies install on your machine.
2- Open your terminal
3- `docker-compose up` - building images and launching container will fire up.
4- open a new terminal window
5- `sudo docker exec -it estateme_web_1 /bin/bash`
6- `bundle exec rake db:drop db:create db:migrate`
7- run the following rake task in order to populate data `bundle exec rake real_estates:import` this rake task takes two optional args the country_code and the csv filename. if you don't provide it will use the default which is US and the file you provide.
8- you can run the test with `bundle exec rspec` I relied on data we have populated so you need to run the same rake task mentioned above in the test env before starting the tests. A better approach is to rely on Factory_bot.
9- For api crud operations I have only created index and show
10- the apis are paginated with default per page = 20 even the search api is paginated.
11- there is extra admin area to display data
7- all set you can now test the app by visiting the following url `localhost:3000`<file_sep>require 'rails_helper'
RSpec.describe Country, type: :model do
let(:country) {Country.first}
describe "Country" do
it "must have name" do
country.name = nil
expect{country.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
it "must have alpha2" do
country.alpha2 = nil
expect{country.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end<file_sep>require 'rails_helper'
RSpec.describe State, type: :model do
let(:state) {State.first}
describe "State" do
it "must have country" do
state.country_id = nil
expect{state.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
it "must have name" do
state.name = nil
expect{state.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end<file_sep>module Api::V1
class RealEstatesController < Api::BaseController
def index
@real_estates = paginate RealEstate.all
success()
end
def show
@real_estate = RealEstate.where(id: params[:id]).first
@real_estate.present? ? success() : error(404, "record no found!")
end
def search
options = {price_from: params[:price_from], price_to: params[:price_to], space_from: params[:space_from], space_to: params[:space_to], page: params[:page]}
@real_estates = RealEstate.search(params[:query], options)
success()
end
end
end<file_sep>class Admin::RealEstatesController < ApplicationController
def index
@real_estates = RealEstate.search(params)
end
end<file_sep>require 'rails_helper'
RSpec.describe RealEstate, type: :model do
let(:real_estate) {RealEstate.first}
describe "RealEstate" do
it "expect real estate to have a location" do
expect(real_estate.location).to be_a(String)
end
it "search with result" do
expect(RealEstate.search).to be_instance_of(Elasticsearch::Model::Response::Records)
expect(RealEstate.search('condo')).to be_instance_of(Elasticsearch::Model::Response::Records)
end
it "must have type" do
real_estate.estate_type = nil
expect{real_estate.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
it "must have city" do
real_estate.city_id = nil
expect{real_estate.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
it "must have street" do
real_estate.street = nil
expect{real_estate.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end<file_sep>require 'rails_helper'
RSpec.describe City, type: :model do
let(:city) {City.first}
describe "City" do
it "must have state" do
city.state_id = nil
expect{city.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
it "must have name" do
city.name = nil
expect{city.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end<file_sep>class Country < ActiveRecord::Base
has_many :states, dependent: :nullify
validates :name, presence: true
validates :name, uniqueness: { case_sensitive: false }
validates :alpha2, presence: true
validates :alpha2, uniqueness: { case_sensitive: false }
def self.get(country_code)
country = where(alpha2: country_code).first
if country.blank?
c = ISO3166::Country.find_country_by_alpha2(country_code)
if c.present?
country = create(name: c.data['name'], alpha2: c.data['alpha2'])
end
end
country
end
end<file_sep>class RealEstatesImporter
HEADERS = ['street', 'city', 'zip', 'state', 'beds', 'baths', 'sq_ft', 'estate_type', 'sale_date', 'price', 'latitude', 'longitude']
def initialize(country_code)
get_country(country_code)
end
def add_new_real_estate(data)
if @country.present?
@hash = HEADERS.zip(data).to_h
get_state(@hash['state'])
if @state.present?
get_city(@hash['city'])
if @city.present?
@real_estate = RealEstate.new(@hash.except('city', 'state'))
@real_estate.city_id = @city.id
@real_estate.name = @real_estate.street
@real_estate.save
end
end
end
end
def estate
@real_estate
end
private
def get_country(country_code)
@country = Country.where(alpha2: country_code).first
if @country.blank?
c = ISO3166::Country.find_country_by_alpha2(country_code)
if c.present?
@country = Country.create(name: c.data['name'], alpha2: c.data['alpha2'])
end
end
end
def get_state(state_code)
unless @state.present? && @state.alpha2 == state_code
@state = State.where(alpha2: state_code, country_id: @country.id).first
if @state.blank?
s = ISO3166::Country.find_country_by_alpha2(@country.alpha2).states[state_code]
if s.present?
@state = State.create(name: s["name"], country_id: @country.id, alpha2: state_code)
end
end
end
end
def get_city(city_name)
unless @city.present? && @city.name == city_name
@city = City.where(name: city_name, state_id: @state.id).first
if @city.blank?
@city = City.create(name: city_name, state_id: @state.id)
end
end
end
end
#street city zip state beds baths sq__ft type sale_date price latitude longitude
#3526 HIGH ST SACRAMENTO 95838 CA 2 1 836 Residential Wed May 21 00:00:00 EDT 2008 59222 38.631913 -121.434879<file_sep>require 'rails_helper'
RSpec.describe Api::V1::RealEstatesController , type: :controller do
describe "GET #index" do
subject {get :index, format: :json}
it "renders successfully" do
expect(response.code.to_i).to eq(200)
end
end
describe "GET #show" do
subject {get :show, id: real_estate.id, format: :json}
let(:real_estate) {RealEstate.first}
it "successful" do
expect(response.code.to_i).to eq(200)
end
end
describe "GET #search" do
subject {get :search, format: :json}
it "renders successfully" do
expect(response.code.to_i).to eq(200)
end
end
end<file_sep>class CreateAll < ActiveRecord::Migration
def change
create_table :real_estates do |t|
t.string :name
t.string :estate_type
t.string :street, default: ""
t.string :zip, default: ""
t.float :latitude, default: 0.0
t.float :longitude, default: 0.0
t.float :sq_ft, default: 0.0
t.float :price, default: 0.0
t.datetime :sale_date
t.integer :baths
t.integer :beds
t.integer :city_id, default: 0
t.timestamps null: false
end
add_index :real_estates, [:city_id]
create_table :countries do |t|
t.string :name
t.string :alpha2
t.timestamps null: false
end
create_table :states do |t|
t.string :name
t.string :alpha2
t.integer :country_id
t.timestamps null: false
end
add_index :states, [:country_id]
create_table :cities do |t|
t.string :name
t.integer :state_id
t.timestamps null: false
end
add_index :cities, [:state_id]
end
end
<file_sep>class City < ActiveRecord::Base
belongs_to :state
has_many :real_estates
validates :name, presence: true
validates :name, uniqueness: { case_sensitive: false, scope: :state_id }
validates :state, presence: true
end<file_sep>version: '3.1'
services:
db:
image: postgres
elasticsearch:
image: elasticsearch:alpine
ports:
- "9200:9200"
- "9300:9300"
volumes:
- elasticsearch:/usr/share/elasticsearch/data
web:
build: .
volumes:
- .:/estate_me
ports:
- "3000:3000"
depends_on:
- db
- elasticsearch
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
elasticsearch:<file_sep>class FloatRangeGenerator
PRICE = 'price'
SPACE = 'space'
def initialize(from, to, type=FloatRangeGenerator::PRICE)
@from = from.to_f
@to = to.to_f
@type = type
end
def generate
validate_from_float
validate_to_float
end
def get_range
{from: @from, to: @to}
end
def from
@from
end
def to
@to
end
private
def validate_from_float
@from = @from > 0.0 ? @from : 0.0
end
def validate_to_float
unless @to > @from
if @type == FloatRangeGenerator::PRICE
@to = @from + 10000
else
@to = @from + 50
end
end
end
end<file_sep>source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.4'
gem 'rake', '~> 12.0.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'rabl', '~> 0.11.6'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'pry-rails', '~> 0.3.4' #enhanced ruby console
gem 'kaminari', '~> 0.16.3' #used for backend paginations
gem 'api-pagination', '~> 4.1.1' #api pagination
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'materialize-sass', '~> 0.98.2' #materialize css based on material design
gem 'geocoder', '~> 1.4', '>= 1.4.4'
gem 'countries', '~> 1.1.0' #get all the countries codes and names
gem 'dotenv-rails', '~> 2.0'
gem 'web-console', '~> 2.0', group: :development
group :development, :test do
gem 'rspec-rails', '~> 3.5'
gem 'pry-byebug', '~> 3.4', '>= 3.4.2'
gem 'spring'
end
group :test do
gem 'factory_girl_rails'
gem 'shoulda-matchers', '~> 3.1', '>= 3.1.2'
gem 'cucumber-rails', '~> 1.4', '>= 1.4.3'
gem 'selenium-webdriver', '~> 3.13'
gem 'guard-rspec'
gem 'database_cleaner', '~> 1.5', '>= 1.5.3'
end<file_sep>node(false) { partial('api/v1/real_estates/shared/real_estate', :object => @real_estate) }
<file_sep>collection @real_estates
extends 'api/v1/real_estates/shared/real_estate'<file_sep>require 'elasticsearch/model'
class RealEstate < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
belongs_to :city
validates :city, presence: true
validates :street, presence: true
validates :estate_type, presence: true
geocoded_by :geo_location
after_validation :geocode
################elastic search methods#######################
settings index: {number_of_shards: 1,
analysis: {
analyzer: {
string_lowercase: {tokenizer: 'standard', filter: ['lowercase', 'asciifolding'] }
}
}
} do
mapping dynamic: false do
indexes :estate_type, type: :text, analyzer: 'string_lowercase'
indexes :price, type: :float
indexes :sq_ft, type: :float
end
end
# def self.search(query=nil, options={})
# options ||= {}
# return [] if query.blank? && options.blank?
# search_definition = {
# query: {
# bool: {
# must: [],
# filter: []
# }
# }
# }
# unless options.blank?
# search_definition[:from] = 0
# search_definition[:size] = ELASTICSEARCH_MAX_RESULTS
# end
# # query
# if query.present?
# search_definition[:query][:bool][:must] << {
# multi_match: {
# query: query,
# fields: %w(estate_type),
# operator: 'or'
# }
# }
# end
# search_definition[:query][:bool][:filter] << {
# range: { price: {
# gte: 89921.0,
# lte: 89921.0
# }
# }
# }
# __elasticsearch__.search(search_definition)
# end
def self.search(options={})
options ||= {}
search_definition = {
query: {
dis_max: {
tie_breaker: 0.7,
boost: 1.2,
queries: []
}
}
}
if options[:query].present?
search_definition[:query][:dis_max][:queries] << {match: {estate_type: options[:query]}}
end
if options[:price_from].present?
price_range = FloatRangeGenerator.new(options[:price_from], options[:price_to])
price_range.generate
search_definition[:query][:dis_max][:queries] << {range: {price: {gte: price_range.from, lte: price_range.to}}}
end
if options[:space_from].present?
space_range = FloatRangeGenerator.new(options[:space_from], options[:space_to], FloatRangeGenerator::SPACE)
space_range.generate
search_definition[:query][:dis_max][:queries] << {range: {sq_ft: {gte: space_range.from, lte: space_range.to}}}
end
search_definition[:query][:dis_max][:queries].present? ? __elasticsearch__.search(search_definition).page(options[:page]).records : [] rescue []
end
############################################################
def geo_location
if self.latitude.blank? || self.longitude.blank?
self.location
end
end
def location
city_name = self.city.name rescue ''
state_name = self.city.state.name rescue ''
country_name = self.city.state.country.name rescue ''
"#{self.street}, #{self.zip}, #{city_name}, #{state_name}, #{country_name}"
end
end | f45573fba65277ec72097baaa582166c591fad7b | [
"RDoc",
"Ruby",
"YAML"
] | 22 | Ruby | moustafasallam/estate_me | da25f60631077844b0cdf6fd842af16606e09c7b | a329e218ee6872c923e2c5a3cf51eb71fdee4718 |
refs/heads/master | <repo_name>rakamochy/controler-aktifitas<file_sep>/Akt.php
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Akt extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library(array('PHPExcel','PHPExcel/IOFactory'));
if($this->session->userdata('masuk')==TRUE){
$this->url = $this->session->userdata('url');
$this->client = new nusoap_client($this->url,true);
$this->proxy = $this->client->getProxy();
$this->token = $this->session->userdata('gettoken');
}
else{
redirect('gettoken_jyn/logout');
}
}
function listmhs(){
$table = 'mahasiswa';
$datacari = $this->input->post('cari',true);
if(empty($datacari)){
$filter= '';
}
else{
$filter = "nipd ilike '%".$datacari."%' OR nm_pd ilike '%".$datacari."%'";
}
//$limit = 2;
//$filter = "nm_pd ilike '%novi%'";
$order = 'nipd desc';
//$offset = 0;
$totaldata = $this->proxy->GetCountRecordset($this->token,$table,$filter);
$config['base_url'] = site_url('mahasiswa/listmhs');
$config['total_rows'] = $totaldata['result'];
$config['per_page'] = $per_page = 10;
$config['uri_segment'] = 3;
$config['uri_segment']=3;
$config['first_link']='Awal';
$config['last_link']='Akhir';
$config['next_link']='Next → ';
$config['prev_link']='← Prev';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$result = $this->proxy->GetListMahasiswa($this->token,$filter,$order,$per_page,$page);
$data['paging'] = $this->pagination->create_links();
$data['cari']=$datacari;
$data['result'] = $result ;
$data['total'] = $totaldata;
$x['isi'] = $this->load->view('mahasiswa/listdata',$data,true);
$this->load->view('template',$x);
}
function import_updatedata(){
$d['file_url']= base_url().'asset/dist/file/import_akt.xlsx';
$x['isi'] = $this->load->view('akt/forminputupdate',$d,true);
$this->load->view('template',$x);
}
function import_insertdata(){
$d['file_url']= base_url().'asset/dist/file/import_akt.xlsx';
$x['isi'] = $this->load->view('akt/forminputinsert',$d,true);
$this->load->view('template',$x);
}
function insertdata(){
$this->benchmark->mark('mulai');
$tabel1 = 'aktivitas_mahasiswa';
$tabel2 = 'anggota_aktivitas';
$error_file = '';
$sukses_count = 0;
$error_count = 0;
$update_count = 0;
$sukses_msg = array();
$error_msg = array();
$update_msg = array();
$fileName = $_FILES['import']['name'];
$config['upload_path'] = './asset/upload/'; //buat folder dengan nama assets di root folder
$config['file_name'] = $fileName;
$config['allowed_types'] = 'xls|xlsx|csv';
$config['max_size'] = 10000;
$this->load->library('upload');
$this->upload->initialize($config);
if(! $this->upload->do_upload('import') ){
$error_file = $this->upload->display_errors();
$link = site_url('akt/import_insertdata');
echo "<script>
window.alert('$error_file'); location.href=('$link');
</script>";
}
else{
$media = $this->upload->data();
$inputFileName = './asset/upload/'.$media['file_name'];
try {
$inputFileType = IOFactory::identify($inputFileName);
$objReader = IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++){ // Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
//Sesuaikan sama nama kolom tabel di database
$sem = $rowData[0][1];
$jenis_akt = $rowData[0][2];
$judul = $rowData[0][3];
$lokasi = $rowData[0][4];
$no_sk = $rowData[0][5];
$tgl_sk = $rowData[0][6];
$ket_akt = $rowData[0][7];
$kodeprodi = $rowData[0][8];
$jenis_anggota = $rowData[0][9];
$nim = $rowData[0][10];
$nama_pd = $rowData[0][11];
$jns_peran_mhs = $rowData[0][12];
$idsp = $this->session->userdata('idsp');
//Filter Prodi
$filter_sms = "id_sp='".$this->session->userdata('idsp')."' and kode_prodi ilike '%".$kodeprodi."%'";
$temp_sms = $this->proxy->GetRecord($this->token,'sms',$filter_sms);
if($temp_sms['result']){
$id_sms = $temp_sms['result']['id_sms'];
}
else $id_sms ='';
$record['id_smt'] = $sem;
$record['judul_akt_mhs'] = $judul;
$record['lokasi_kegiatan'] = $lokasi;
$record['sk_tugas'] = $no_sk;
$record['tgl_sk_tugas'] = $tgl_sk;
$record['ket_akt'] = $ket_akt;
$record['a_komunal'] = $jenis_anggota;
$record['id_jns_akt_mhs'] = $jenis_akt;
$record['id_sms'] = $id_sms;
$data = $record;
$insert_data= $this->proxy->InsertRecord($this->token,$tabel1,json_encode($data));
if($insert_data['result']){
if($insert_data['result']['error_desc']==NULL){
$id_pd = $insert_data['result']['id_akt_mhs'];
$filter_sms = "id_sp='".$this->session->userdata('idsp')."' and kode_prodi ilike '%".$kodeprodi."%'";
$temp_sms = $this->proxy->GetRecord($this->token,'sms',$filter_sms);
if($temp_sms['result']){
$id_sms = $temp_sms['result']['id_sms'];
}
//filter Mahasiswa PT
$filter_mhspt = "nipd ilike '%".$nim."%'";
$temp_mhspt = $this->proxy->GetRecord($this->token,'mahasiswa_pt',$filter_mhspt);
if($temp_mhspt['result']){
$id_reg_pd = $temp_mhspt['result']['id_reg_pd'];
$id_pd = $temp_mhspt['result']['id_pd'];
}else $id_reg_pd='';
//Filter Mahasiswa
$filtermhs = "id_pd='".$id_pd."'";
$tempmhs = $this->proxy->GetRecord($this->token,'mahasiswa',$filtermhs);
if($tempmhs['result']){
$nm_pd = $tempmhs['result']['nm_pd'];
}else $id_reg_pd='';
//$record['id_ang_akt_mhs'] = '1';
$record_pt['id_reg_pd'] = $id_reg_pd;
$record_pt['id_akt_mhs'] = $id_pd;
$record_pt['nm_pd'] = $nama_pd;
$record_pt['nipd'] = $nim;
$record_pt['jns_peran_mhs'] = $jns_peran_mhs;
$data_pt = $record_pt;
$insert_pt = $this->proxy->InsertRecord($this->token,$tabel2,json_encode($data_pt));
//var_dump($insert_pt);
if($insert_pt['result']['error_desc']==NULL){
++$sukses_count;
$sukses_msg[] = 'Data "'.$rowData[0][11].' / '.$judul.'" berhasil di tambahkan <br>';
}
else{
++$error_count;
$error_msg[] = "Error pada data ( '".$jenis_akt." / ".$judul.") : '".$insert_data['result']['error_desc']."' <br>";
}
}
else{
++$error_count;
$error_msg[] = "Error pada data ".$nm_pd." - ".$insert_pt['result']['error_desc'];
}
}
}
}
$this->benchmark->mark('selesai');
if($sukses_count!=0){
$d['sukses_jml'] = $sukses_count." Data berhasil ditambahkan, detail :<br>";
$d['sukses_msg'] = $sukses_msg;
}
if($error_count != 0){
$d['error_jml'] = $error_count." Data gagal di tambahkan,detail : <br>" ;
$d['error_msg'] = $error_msg;
}
unlink('./asset/upload/'.$fileName);
$d['eksekusi_waktu'] = $this->benchmark->elapsed_time('mulai', 'selesai')." Detik";
$x['isi'] = $this->load->view('akt/pesaninsert',$d,true);
$this->load->view('template',$x);
}
}
?>
| 8319237ddcdbc15db9801430c0970fbb33a5923a | [
"PHP"
] | 1 | PHP | rakamochy/controler-aktifitas | 2bb6e51b4e50cb9d35fbbd88411042e3a340cc91 | 8f5b278147576271b9663d6a144b2546c1850420 |
refs/heads/master | <file_sep>package org.deeplearning4j.examples.recurrent.seq2seq;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.*;
import org.deeplearning4j.nn.conf.graph.rnn.DuplicateToTimeSeriesVertex;
import org.deeplearning4j.nn.conf.graph.rnn.LastTimeStepVertex;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.api.MultiDataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import java.util.ArrayList;
import java.lang.*;
/**
* Created by susaneraly on 3/27/16.
*/
public class Seq2seq {
public static final int seed = 1234;
public static final int vectorSize = 300;
public static final int vacabSize = 43981;
public static final int batchSize = 128;
public static final int nEpochs = 50;
public static final int nIterations = 1;
public static final int hiddenSize = 500;
public static void main(String[] args) throws Exception {
//Training data iterator
//CustomSequenceIterator iterator = new CustomSequenceIterator(seed, batchSize, totalBatches, NUM_DIGITS,timeSteps);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT).iterations(1)
.updater(Updater.RMSPROP)
.regularization(true).l2(0.000005)
.weightInit(WeightInit.XAVIER)
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue).gradientNormalizationThreshold(1.0)
.learningRate(0.5)
.seed(seed)
.list()
.layer(0, new GravesLSTM.Builder().nIn(vectorSize).nOut(hiddenSize)
.activation("softsign").build())
.layer(1, new GravesLSTM.Builder().nIn(hiddenSize).nOut(hiddenSize).activation("softsign").build())
.layer(2, new GravesLSTM.Builder().nIn(hiddenSize).nOut(hiddenSize).activation("softsign").build())
.layer(3, new GravesLSTM.Builder().nIn(hiddenSize).nOut(hiddenSize).activation("softsign").build())
.layer(4, new GravesLSTM.Builder().nIn(hiddenSize).nOut(hiddenSize).activation("softsign").build())
.layer(5, new GravesLSTM.Builder().nIn(hiddenSize).nOut(hiddenSize).activation("softsign").build())
.layer(6, new RnnOutputLayer.Builder().activation("softmax")
.lossFunction(LossFunctions.LossFunction.MCXENT).nIn(hiddenSize).nOut(vacabSize).build())
.pretrain(false).backprop(true)
.build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
}
}
<file_sep>package org.deeplearning4j.examples.nlp.paragraphvectors;
import org.canova.api.util.ClassPathResource;
import org.deeplearning4j.models.paragraphvectors.ParagraphVectors;
import org.deeplearning4j.models.word2vec.wordstore.inmemory.InMemoryLookupCache;
import org.deeplearning4j.text.documentiterator.LabelsSource;
import org.deeplearning4j.text.sentenceiterator.BasicLineIterator;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizer.preprocessor.CommonPreprocessor;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This is example code for dl4j ParagraphVectors implementation. In this example we build distributed representation of all sentences present in training corpus.
* However, you still use it for training on labelled documents, using sets of LabelledDocument and LabelAwareIterator implementation.
*
* *************************************************************************************************
* PLEASE NOTE: THIS EXAMPLE REQUIRES DL4J/ND4J VERSIONS >= rc3.8 TO COMPILE SUCCESSFULLY
* *************************************************************************************************
*
* @author <EMAIL>
*/
public class TalkToMe {
private static final Logger log = LoggerFactory.getLogger(ParagraphVectorsTextExample.class);
public static void main(String[] args) throws Exception {
ClassPathResource resource = new ClassPathResource("/question.txt");
File file = resource.getFile();
SentenceIterator iter = new BasicLineIterator(file);
InMemoryLookupCache cache = new InMemoryLookupCache();
TokenizerFactory t = new DefaultTokenizerFactory();
t.setTokenPreProcessor(new CommonPreprocessor());
/*
if you don't have LabelAwareIterator handy, you can use synchronized labels generator
it will be used to label each document/sequence/line with it's own label.
But if you have LabelAwareIterator ready, you can can provide it, for your in-house labels
*/
LabelsSource source = new LabelsSource("DOC_");
ParagraphVectors vec = new ParagraphVectors.Builder()
.trainWordVectors(true)
.batchSize(100)
.minWordFrequency(3)
.iterations(5)
.epochs(20)
.layerSize(150)
.learningRate(0.025)
.labelsSource(source)
.windowSize(5)
.iterate(iter)
.trainWordVectors(false)
.vocabCache(cache)
.tokenizerFactory(t)
.sampling(0)
.workers(5)
.build();
vec.fit();
// double similarity1 = vec.similarity("DOC_9835", "DOC_12492");
// log.info("9836/12493 ('This is my house .'/'This is my world .') similarity: " + similarity1);
//
// double similarity2 = vec.similarity("DOC_3720", "DOC_16392");
// log.info("3721/16393 ('This is my way .'/'This is my work .') similarity: " + similarity2);
//
// double similarity3 = vec.similarity("DOC_6347", "DOC_3720");
// log.info("6348/3721 ('This is my case .'/'This is my way .') similarity: " + similarity3);
//
// // likelihood in this case should be significantly lower
// double similarityX = vec.similarity("DOC_3720", "DOC_9852");
// log.info("3721/9853 ('This is my way .'/'We now have one .') similarity: " + similarityX +
// "(should be significantly lower)");
ArrayList<Double> similarity = new ArrayList<Double>();
for(int i=0;i<65498;++i){
similarity.add(vec.similarity("DOC_1","DOC_"+i));
}
double maxSim = 0.0;
int index = 0;
for(int i = 0 ; i < 65498; ++i){
if( similarity.get(i)> maxSim ){
maxSim = similarity.get(i);
index = i;
}
}
System.out.println(vec.similarityToLabel("DOC_1","DOC_1"));
System.out.println(index);
Scanner sc = new Scanner(System.in);
String input;
System.out.println(vec.inferVector("what is ai"));
System.out.println(vec.inferVector("what is dog"));
System.out.println(vec.inferVector("DOC_9835"));
System.out.println(vec.inferVector("i like you"));
System.out.println(vec.inferVector("i hate you"));
while(true){
input = sc.nextLine();
System.out.println(vec.predictSeveral(input,10));
System.out.println("*****************");
// System.out.println(vec.nearestLabels(input,10));
}
}
}
<file_sep>DL4J Release 0.4 Examples
=========================
Repository of Deeplearning4J neural net examples:
- MLP Neural Nets
- Convolutional Neural Nets
- Recurrent Neural Nets
- TSNE
- Word2Vec & GloVe
- Anomaly Detection
---
## Documentation
For more information, check out [deeplearning4j.org](http://deeplearning4j.org/) and its [JavaDoc](http://deeplearning4j.org/doc/).
If you notice issues, please log them, and if you want to contribute, submit a pull request. Input is welcome here.
| 60f6eaeb346560f3ea83b62dd1fbbf5da0101dfe | [
"Markdown",
"Java"
] | 3 | Java | fangpin/dl4j-examples | 0a2249b9766f3ba0f925cdb19211e833ecc01bfb | e9d9ed7d785e5f6fd57d8055b8a5448b31195edc |
refs/heads/master | <file_sep>const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'ICLEAR')) {
async function purge() {
message.delete();
if (!message.member.roles.find("name", "bot-commander")) {
message.channel.send("Tu n'as pas la permission !");
message.delete(5000);
return;
}
if (isNaN(args[0])) {
message.channel.send('Usage: ' + prefix + 'clear <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages trouvés, deleting...');
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
if(msg.startsWith(prefix + 'IMOTD')){
bot.user.setActivity(args[0]);
}
if(msg.startsWith(prefix + 'IHELP')){
var embed = new Discord.RichEmbed()
.setDescription('Help commandes: \n !ihelp \n !iclear !')
message.channel.sendEmbed(embed);
}
});
bot.on('ready', () => {
console.log('Bot started.');
});
bot.login('<KEY>');
| 7d74180deb3e9f149c34f9b886faea5687d08a27 | [
"JavaScript"
] | 1 | JavaScript | LolpopYT/InfinityBot | e8ebcfd36795ffea767aa29a097167a999f142f8 | 60d9e105d3a41600a71aec199a594afa7b1cb789 |
refs/heads/main | <repo_name>erfsfj-github/repository<file_sep>/common-reuse/common-utils/src/main/java/com/gcase/utils/encrypt/aes/v1/AesUtil.java
package com.gcase.utils.encrypt.aes.v1;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
/**
* <p>
*
* <p>
*
* @creator bicheng.deng
* @createTime 2021/2/1
*/
public class AesUtil {
static final String ALGORITHM = "AES";
public static Charset CHARSET = Charset.forName("UTF-8");
public static String AES_LOGIN_KEY = "myKey";
public static SecretKey generateKey(String aesKey) { // 生成密钥
KeyGenerator kgen = null;
SecureRandom random=null;
SecretKeySpec sks = null;
try {
kgen = KeyGenerator.getInstance(ALGORITHM);
random = SecureRandom.getInstance("SHA1PRNG","SUN");
random.setSeed(aesKey.getBytes());
kgen.init(128,random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
sks = new SecretKeySpec(enCodeFormat, ALGORITHM);
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
e.printStackTrace();
}
return sks;
}
public static byte[] encrypt(String content, String aesKey) { // 加密
return aes(content.getBytes(CHARSET), Cipher.ENCRYPT_MODE, generateKey(aesKey));
}
public static String decrypt(byte[] contentArray, String aesKey) { // 解密
byte[] result = aes(contentArray,Cipher.DECRYPT_MODE,generateKey(aesKey));
return new String(result,CHARSET);
}
private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey){
Cipher cipher = null;
byte[] result = null;
try {
cipher = Cipher.getInstance(ALGORITHM);
cipher.init(mode, secretKey);
result = cipher.doFinal(contentArray);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String content = "111111";
String aesKey = "myKey";
long timeStart = System.currentTimeMillis();
byte[] encryptResult = encrypt(content, aesKey);
long timeEnd = System.currentTimeMillis();
System.out.println("加密后的结果为:" + new String(encryptResult,CHARSET));
String decryptResult = decrypt(encryptResult,aesKey);
System.out.println("解密后的结果为:" + decryptResult);
System.out.println("加密用时:" + (timeEnd - timeStart));
}
}
<file_sep>/common-reuse/README.md
# 一、项目结构
```
.
├── common-utils 公共组件
│ └── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── gcase
│ │ ├── feat 功能
│ │ ├── middleware 中间件
│ │ ├── model 数据模型
│ │ └── utils 工具类
│ └── resources classpath
│
├── rpc-consumer rpc消费者
└── rpc-service rpc发布者
├── rpc-annotation-provider rpc发布者注解式实现
├── rpc-api rpc服务暴露接口
└── rpc-provider rpc发布者普通实现
```
# 二、项目规范
## 2.1 模块结构定义
### 1. 功能包
目录结构:feat / <功能定义> / <实现方式> / <实现版本> / <具体实现>
### 2. 中间件包
目录结构:middleware / <中间件定义> / <实现方式> / <实现版本> / <具体实现>
### 3. 数据模型包
目录结构:model / <场景定义> / <实现版本> / <模型 | 状态码>
### 4. 工具类
目录结构:utils / <工具定义> / <实现方式> / <实现版本> / <具体实现>
## 2.2 信息补充描述
- 方法的必要注释
- 一个实现版本所需要的环境配置以及依赖说明
- 原则上一个实现版本对应实现一个案例<file_sep>/common-reuse/common-utils/src/main/java/com/gcase/utils/encrypt/aes/v2/EncryptUtil.java
package com.gcase.utils.encrypt.aes.v2;
import org.springframework.util.StringUtils;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* <p>
* 前端解密
* <p>
*
* @creator bicheng.deng
* @createTime 2021/2/1
*/
public class EncryptUtil {
public static String AES_FRONT_KEY = "<KEY>";
/**
* AES解密
* @param encryptStr 密文
* @param decryptKey 秘钥,必须为16个字符组成
* @return 明文
* @throws Exception
*/
public static String aesDecrypt(String encryptStr, String decryptKey) {
if (StringUtils.isEmpty(encryptStr) || StringUtils.isEmpty(decryptKey)) {
return null;
}
byte[] encryptByte = Base64.getDecoder().decode(encryptStr);
Cipher cipher = null;
byte[] decryptBytes = null;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
decryptBytes = cipher.doFinal(encryptByte);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return new String(decryptBytes);
}
/**
* AES加密
* @param content 明文
* @param encryptKey 秘钥,必须为16个字符组成
* @return 密文
* @throws Exception
*/
public static String aesEncrypt(String content, String encryptKey) throws Exception {
if (StringUtils.isEmpty(content) || StringUtils.isEmpty(encryptKey)) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptStr);
}
// 测试加密与解密
public static void main(String[] args) {
try {
String secretKey = "<KEY>";
String content = "111111";
String s1 = aesEncrypt(content, secretKey);
System.out.println(s1);
String s = aesDecrypt(s1, secretKey);
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/common-reuse/rpc-service/rpc-provider/src/main/java/com/gcase/App.java
package com.gcase;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//创建服务
OrderServiceImpl orderService = new OrderServiceImpl();
RpcProxyServer rpcProxyServer = new RpcProxyServer();
//发布服务
rpcProxyServer.publisher(orderService,8008);
}
}
<file_sep>/common-reuse/rpc-consumer/src/main/resources/application.properties
remote.host=localhost
remote.port=8008
spring.application.name=user-service
server.port=8080<file_sep>/common-reuse/rpc-consumer/src/main/java/com/gcase/annotation/ReferenceInvokeProxy.java
package com.gcase.annotation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
//2
@Component
public class ReferenceInvokeProxy implements BeanPostProcessor {
@Autowired
RemoteInvocationHandler invocationHandler;
//spring容器初始化之前找到加了自定义注解需要被注入的属性
//代理这个属性的方法
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Field[] fields=bean.getClass().getDeclaredFields();
for(Field field:fields){
if(field.isAnnotationPresent(CusReference.class)){
field.setAccessible(true);
//针对这个加了CusReference注解的字段,设置为一个代理的值
Object proxy= Proxy.newProxyInstance(field.getType().getClassLoader(),new Class<?>[]{field.getType()},invocationHandler);
try {
field.set(bean,proxy); //相当于针对加了CusReference的注解,设置了一个代理,这个代理的实现是invocationHandler
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return bean;
}
}<file_sep>/common-reuse/common-utils/src/main/java/com/gcase/feat/interceptors/authentication/WebMvcConfig.java
package com.gcase.feat.interceptors.authentication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* <p>
* 拦截器注册
* <p>
*
* @creator bicheng.deng
* @createTime 2021/1/27
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public AuthInterceptor getAuthInterceptor(){
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getAuthInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/login");
}
}
<file_sep>/README.md
# repository
公共仓库
<file_sep>/common-reuse/rpc-consumer/src/main/java/com/gcase/normal/App.java
package com.gcase.normal;
import com.gcase.IOrderService;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//Rpc客户端请求代理对象
RpcProxyClient rpcProxyClient = new RpcProxyClient();
//客户端调用远程服务
IOrderService orderService = rpcProxyClient.clientProxy(IOrderService.class,"localhost",8008);
String s = orderService.helloWorld();
System.out.println(s);
orderService.orderById("id");
}
}
<file_sep>/common-reuse/rpc-service/rpc-annotation-provider/src/main/java/com/gcase/OrderServiceImpl.java
package com.gcase;
//3、发布服务的实现类
@CusRemoteService
public class OrderServiceImpl implements IOrderService {
@Override
public String helloWorld() {
System.out.println("Hello World");
return "返回值";
}
@Override
public String orderById(String id) {
return "orderById > ";
}
}
<file_sep>/common-reuse/common-utils/src/main/java/com/gcase/utils/http/HttpKey.java
package com.gcase.utils.http;
/**
* <p>
* Http相关常量
* <p>
*
* @creator bicheng.deng
* @createTime 2021/2/1
*/
public class HttpKey {
public static final String USER_TOKEN = "User-Token";
public static final String USER_KEY = "User-Key";
}
<file_sep>/common-reuse/rpc-service/rpc-api/src/main/java/com/gcase/IOrderService.java
package com.gcase;
//1、暴露接口
public interface IOrderService {
String helloWorld();
String orderById(String id);
}
| b7a8e8d46c2c8cb71bf0764068b12044a32fba97 | [
"Markdown",
"Java",
"INI"
] | 12 | Java | erfsfj-github/repository | 6be28c0c1536a95366ca05d43fe200300f821069 | 219e9b1df8beb156cadb1c311e9df258d3d1fcf0 |
refs/heads/master | <repo_name>itnug987/Freshokartz<file_sep>/app/src/main/java/com/freshokartz2/ProductsPrime.java
package com.freshokartz2;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.freshokartz2.Cart.cart_items;
import com.freshokartz2.Product.ProductList;
import com.freshokartz2.Product.Result;
import com.github.aakira.expandablelayout.ExpandableRelativeLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
//Class for products individual description
public class ProductsPrime extends AppCompatActivity {
TextView product_name, test;
Button check, addtoCart, buynow;
EditText incre;
boolean invalidQuantity=false;
boolean checkOfUnknown;
TextView checks;
Spinner spinner, pickup;
int k;
String value = "";
double finalValue;
SessionManagement session;
ImageView plus, minus, cross;
ExpandableRelativeLayout expa;
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(CartApi.DJANGO_SITE)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
CartApi cartApi = retrofit.create(CartApi.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String id = intent.getStringExtra("skId");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products_prime);
//pickup = findViewById(R.id.pickup);
Toolbar toolbar = findViewById(R.id.toolbar);
String[] grams = new String[]{
"Kg",
"g"
};
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Product Details");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addtoCart = findViewById(R.id.addtocat);
buynow = findViewById(R.id.buynow);
cross = findViewById(R.id.cross);
checks = findViewById(R.id.checks);
incre = findViewById(R.id.incre);
plus = findViewById(R.id.plus);
minus = findViewById(R.id.minus);
expa = findViewById(R.id.expa);
check = findViewById(R.id.check);
plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = incre.getText().toString();
try {
finalValue = Double.parseDouble(value);
double gra = (int) finalValue;
if (!checkOfUnknown) {
finalValue = gra;
}
finalValue = finalValue + 0.250;
incre.setText(String.valueOf(finalValue));
checkOfUnknown = true;
} catch (Exception e) {
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = incre.getText().toString();
try {
finalValue = Double.parseDouble(value);
double gra = (int) finalValue;
if (!checkOfUnknown) {
finalValue = gra;
finalValue = finalValue + 0.250;
}
finalValue = finalValue - 0.250;
if (finalValue > 0) {
incre.setText(String.valueOf(finalValue));
}
checkOfUnknown = true;
} catch (Exception e) {
}
}
});
getProductsDescription(id);
}
private void getProductsDescription(String id) {
Call<ProductList> result = CatApi.getService().getProductsDescription(id);
result.enqueue(new Callback<ProductList>() {
@Override
public void onResponse(Call<ProductList> call, Response<ProductList> response) {
final ProductList productList = response.body();
final List<Result> main = productList.getResults();
TextView prod;
final TextView price, descript;
ImageView pic;
String pil;
Button cart;
prod = findViewById(R.id.product_name);
pic = findViewById(R.id.product_image);
price = findViewById(R.id.price);
descript = findViewById(R.id.description);
//cart = findViewById(R.id.cart);
// finalValue = Integer.valueOf(incre.getText().toString());
// k = Integer.valueOf(incre.getText().toString());
Log.i("proname", main.get(0).getProductName());
incre.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
expa.collapse();
cross.setImageResource(R.drawable.ic_action_rigth);
try {
double gtr = Double.parseDouble(s.toString());
if (gtr > Double.valueOf(main.get(0).getMaximumSaleQuantity())) {
s.replace(0, s.length(), "0");
Toast.makeText(getApplicationContext(), "Maximum sale quantity exceeded", Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
}
try {
double krt = Double.parseDouble(s.toString());
String numberD = String.valueOf(krt);
numberD = numberD.substring(numberD.indexOf("."));
System.out.println(numberD);
Log.i("numbers", numberD);
if (!numberD.equals(".5") && !numberD.equals(".25") && !numberD.equals(".75") && !numberD.equals(".0") ) {
Log.i("nbeers", numberD);
incre.setError("Write quantity like 0.25,1, 1.5, 1.75 ");
checkOfUnknown = false;
invalidQuantity=true;
}
else {
invalidQuantity=false;
incre.setError(null);
}
} catch (Exception e) {
}
}
});
addtoCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (addtoCart.getText().equals("Add to Cart")) {
double gtr = Double.parseDouble(incre.getText().toString());
// Intent intent1 = getIntent();
// int cart_id = intent1.getIntExtra("cart_id", 40);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
get_cart_id(token, productList.getResults().get(0).getSku(), gtr);
addtoCart.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient));
addtoCart.setText("Update the Cart");
}
else if(addtoCart.getText().equals("Update the Cart")){
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
get_cart_id(token, productList.getResults().get(0).getSku(), 0.01);
addtoCart.setBackgroundColor(Color.parseColor("#30978E"));
addtoCart.setText("Add to Cart");
}
}
});
Log.i("pronam", main.get(0).getDescription());
String name = main.get(0).getProductName();
prod.setText(name);
price.setText("Price: Rs." + main.get(0).getPrice().toString());
check.setOnClickListener(new View.OnClickListener() {
double trt;
@Override
public void onClick(View v) {
String gr = incre.getText().toString();
if (gr.matches("")) {
expa.toggle();
checks.setText("Specify Quantity");
cross.setImageResource(R.drawable.ic_action_name);
return;
}
trt = Double.parseDouble(incre.getText().toString());
String sValue = (String) String.format("%.2f", trt);
trt = Double.parseDouble(sValue);
if (!expa.isExpanded()) {
if (invalidQuantity==false) {
expa.expand();
checks.setText("Rs. " + String.valueOf(trt * main.get(0).getPrice()));
cross.setImageResource(R.drawable.ic_action_name);
}
else if (invalidQuantity){
expa.expand();
checks.setText("Invalid Quantity");
cross.setImageResource(R.drawable.ic_action_name);
}
} else if (expa.isExpanded()) {
expa.collapse();
cross.setImageResource(R.drawable.ic_action_rigth);
}
}
});
// updateUI();
// price.setText(main.get(0).getPrice().toString());
// descript.setText(main.get(0).getDescription());
String url = "http://13.233.247.56/" + (String) main.get(0).getProductImage();
Glide.with(getApplicationContext())
.load(url)
//.apply(new RequestOptions().override(140, 140))
.into(pic);
buynow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gintent = new Intent(getApplicationContext(), Buynow_order.class);
gintent.putExtra("skId",main.get(0).getSku());
getApplicationContext().startActivity(gintent); }
});
}
@Override
public void onFailure(Call<ProductList> call, Throwable t) {
}
});
// @@@@@@ On buynow button clicked @@@@@@
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
private void addToCart(int cart_id, String sku, Double quantity_ordered){
CartItem cartItem = new CartItem(sku,quantity_ordered);
List<CartItem> cart = new ArrayList<CartItem>();
cart.add(cartItem);
CartOrder cartOrder = new CartOrder(cart);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Call<CartOrder> call = cartApi.addtocart(cart_id, TokenRequest, cartOrder);
call.enqueue(new Callback<CartOrder>() {
@Override
public void onResponse(Call<CartOrder> call, Response<CartOrder> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Toast.makeText(ProductsPrime.this, "Added to cart", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<CartOrder> call, Throwable t) {
}
});
}
private void get_cart_id(String token, final String sku, final Double quantity_ordered ){
String TokenRequest = "Token "+ token;
Call<cart_items> result = cartApi.getDetail(TokenRequest);
result.enqueue(new Callback<cart_items>() {
@Override
public void onResponse(Call<cart_items> call, Response<cart_items> response) {
cart_items items = response.body();
int cart_id = items.getResults().get(0).getCart_id();
addToCart(cart_id, sku,quantity_ordered);
}
@Override
public void onFailure(Call<cart_items> call, Throwable t) {
}
});
}
public void delete_cart_item(final String sku, final Double quantity_ordered ){
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Call<cart_items> result = cartApi.getDetail(TokenRequest);
result.enqueue(new Callback<cart_items>() {
@Override
public void onResponse(Call<cart_items> call, Response<cart_items> response) {
cart_items items = response.body();
int cart_id = items.getResults().get(0).getCart_id();
delete(cart_id, sku,quantity_ordered);
}
@Override
public void onFailure(Call<cart_items> call, Throwable t) {
}
});
}
public void delete(int cart_id, String sku, Double quantity_ordered){
CartItem cartItem = new CartItem(sku,quantity_ordered);
List<CartItem> cart = new ArrayList<CartItem>();
cart.add(cartItem);
CartOrder cartOrder = new CartOrder(cart);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Call<CartOrder> call = cartApi.addtocart(cart_id, TokenRequest, cartOrder);
call.enqueue(new Callback<CartOrder>() {
@Override
public void onResponse(Call<CartOrder> call, Response<CartOrder> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Toast.makeText(ProductsPrime.this, "Deleted from cart", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<CartOrder> call, Throwable t) {
}
});
}
}
<file_sep>/app/src/main/java/com/freshokartz2/Buynow_order.java
package com.freshokartz2;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.freshokartz2.Cart.Result;
import com.freshokartz2.Cart.cart_items;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Buynow_order extends AppCompatActivity {
TextView expectedDate;
RecyclerView recyclerView;
Button place_order;
TextView amount, total_amount;
AlertDialog.Builder alertBuilder;
SessionManagement session;
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(CartApi.DJANGO_SITE)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
CartApi cartApi = retrofit.create(CartApi.class);
SessionManagement sessionManagement;
BpSales_Order sales_orderApi = retrofit.create(BpSales_Order.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buynow_order);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Order Details");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycle_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
sessionManagement = new SessionManagement(getApplicationContext());
HashMap<String, String> user = sessionManagement.getUserDetails();
final String token = user.get(SessionManagement.KEY_TOKEN);
getProductsCat(token);
place_order = findViewById(R.id.place_order);
place_order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add_bp_sales_order(token);
}
});
amount = findViewById(R.id.total_amount);
total_amount = findViewById(R.id.total_amount_payable);
expectedDate = findViewById(R.id.expected);
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
//String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
expectedDate.setText("Expected delivery date : "+tomorrowAsString);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
if (item_id == android.R.id.home) {
super.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void getProductsCat(String token){
String TokenRequest = "Token "+ token;
Call<cart_items> result = cartApi.getDetail(TokenRequest);
result.enqueue(new Callback<cart_items>() {
@Override
public void onResponse(Call<cart_items> call, Response<cart_items> response) {
cart_items items = response.body();
if(items.getCount()>0) {
List<Result> main = items.getResults();
amount.setText(String.valueOf(items.getResults().get(0).getOrder_amount()));
total_amount.setText(String.valueOf(items.getResults().get(0).getOrder_amount()));
recyclerView.setAdapter(new CartItemsAdapter(Buynow_order.this, items.getResults().get(0).getOrder_items()));
}
}
@Override
public void onFailure(Call<cart_items> call, Throwable t) {
}
});
}
private void add_bp_sales_order(String token){
String TokenRequest = "Token "+ token;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
String tomorrowAsString = dateFormat.format(tomorrow);
List<CartItem> cartItems= new ArrayList<>();
SalesOrderResponseBody salesOrderResponseBody = new SalesOrderResponseBody(tomorrowAsString, "cash_on_delivery",1,1,null,"free_shipping",0.00, "android_app", cartItems);
Call<SalesOrderResponseBody> call = sales_orderApi.add_bp_sales_order(TokenRequest,salesOrderResponseBody);
call.enqueue(new Callback<SalesOrderResponseBody>() {
@Override
public void onResponse(Call<SalesOrderResponseBody> call, Response<SalesOrderResponseBody> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Toast.makeText(Buynow_order.this, "Order is placed", Toast.LENGTH_SHORT).show();
alertBuilder = new AlertDialog.Builder(Buynow_order.this);
alertBuilder.setMessage(" Your order is placed. Keep Shopping. ")
.setCancelable(false)
.setPositiveButton("Return to Shopping", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
create_new_cart();
Intent i = new Intent(Buynow_order.this, ActivityMain.class);
startActivity(i);
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.setTitle("Order placed");
alertDialog.show();
//Intent i = new Intent(Buynow_order.this, ActivityMain.class);
//startActivity(i);
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<SalesOrderResponseBody> call, Throwable t) {
}
});
}
private void create_new_cart(){
List<CartItem> cart = new ArrayList<CartItem>();
CartOrder cartOrder = new CartOrder(cart);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Call<CartOrder> call = cartApi.new_addtocart(TokenRequest, cartOrder);
call.enqueue(new Callback<CartOrder>() {
@Override
public void onResponse(Call<CartOrder> call, Response<CartOrder> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Toast.makeText(Buynow_order.this, "New cart is created", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<CartOrder> call, Throwable t) {
}
});
}
}
<file_sep>/app/src/main/java/com/freshokartz2/adapter/Adapter_past_order_items.java
package com.freshokartz2.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.freshokartz2.Order_Items;
import com.freshokartz2.R;
import java.util.List;
public class Adapter_past_order_items extends RecyclerView.Adapter<Adapter_past_order_items.ViewHolder> {
private Context ctx;
private List<Order_Items> items ;
public Adapter_past_order_items(Context ctx, List<Order_Items> items) {
this.ctx = ctx;
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(ctx);
View v = inflater.inflate(R.layout.past_order_item, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
final Order_Items c = items.get(position);
viewHolder.title.setText(c.getProduct_name());
viewHolder.price.setText(c.getPrice().toString());
viewHolder.quantity_ordered.setText(c.getQuantity_ordered().toString());
}
@Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView title;
public TextView quantity_ordered;
public TextView price;
public ViewHolder(View v) {
super(v);
title = v.findViewById(R.id.title);
quantity_ordered = v.findViewById(R.id.quantity_ordered);
price = v.findViewById(R.id.price);
}
}
}
<file_sep>/app/src/main/java/com/freshokartz2/LoginApi.java
package com.freshokartz2;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface LoginApi {
String DJANGO_SITE = "http://172.16.31.10/";
@POST("bp-login/")
Call<Bptoken> login(@Body Login login);
@GET("api/v1/businesspartners/bpauthtoken/")
Call<BpResponseBody> getDetail(@Header("Authorization") String djangoToken);
}
<file_sep>/app/src/main/java/com/freshokartz2/CartItemsAdapter.java
package com.freshokartz2;
import com.freshokartz2.Cart.cart_items;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.balysv.materialripple.MaterialRippleLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class CartItemsAdapter extends RecyclerView.Adapter<CartItemsAdapter.ViewHolder> {
Context ctx;
private List<Order_Items> items;
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(CartApi.DJANGO_SITE)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
CartApi cartApi = retrofit.create(CartApi.class);
public CartItemsAdapter(Context ctx, List<Order_Items> items) {
this.ctx = ctx;
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(ctx);
View v = inflater.inflate(R.layout.cart_item, parent, false);
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
final Order_Items c = items.get(position);
viewHolder.title.setText(c.getProduct_name());
viewHolder.price.setText(c.getPrice().toString());
viewHolder.quantity_ordered.setText(c.getQuantity_ordered().toString());
viewHolder.edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String skId = items.get(position).getSku();
Intent gintent = new Intent(ctx, ProductsPrime.class);
gintent.putExtra("skId",skId);
ctx.startActivity(gintent);
}
});
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
delete_cart_item(c.getSku(), c.getQuantity_ordered());
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView title;
public TextView price;
public TextView quantity_ordered;
public MaterialRippleLayout lyt_parent;
public Button edit, delete;
public ViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.title);
quantity_ordered = (TextView) v.findViewById(R.id.quantity_ordered);
price = (TextView) v.findViewById(R.id.price);
lyt_parent = (MaterialRippleLayout) v.findViewById(R.id.lyt_parent);
edit = v.findViewById(R.id.edit);
delete = v.findViewById(R.id.delete);
}
}
public void delete_cart_item(final String sku, final Double quantity_ordered ){
SessionManagement session = new SessionManagement(ctx);
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Call<cart_items> result = cartApi.getDetail(TokenRequest);
result.enqueue(new Callback<cart_items>() {
@Override
public void onResponse(Call<cart_items> call, Response<cart_items> response) {
cart_items items = response.body();
int cart_id = items.getResults().get(0).getCart_id();
delete(cart_id, sku,quantity_ordered);
}
@Override
public void onFailure(Call<cart_items> call, Throwable t) {
}
});
}
public void delete(int cart_id, String sku, Double quantity_ordered){
CartItem cartItem = new CartItem(sku,0.01);
List<CartItem> cart = new ArrayList<CartItem>();
cart.add(cartItem);
CartOrder cartOrder = new CartOrder(cart);
SessionManagement session = new SessionManagement(ctx);
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Call<CartOrder> call = cartApi.addtocart(cart_id, TokenRequest, cartOrder);
call.enqueue(new Callback<CartOrder>() {
@Override
public void onResponse(Call<CartOrder> call, Response<CartOrder> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Toast.makeText(ctx, "Deleted from cart", Toast.LENGTH_SHORT).show();
Intent i = new Intent(ctx, Buynow_order.class);
ctx.startActivity(i);
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<CartOrder> call, Throwable t) {
}
});
}
}<file_sep>/app/src/main/java/com/freshokartz2/CartApi.java
package com.freshokartz2;
import com.freshokartz2.Cart.cart_items;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface CartApi {
String DJANGO_SITE = "http://172.16.31.10/";
@GET("api/v1/cart/current/")
Call<cart_items> getDetail(@Header("Authorization") String djangoToken);
@PATCH("api/v1/cart/{cart_id}/")
Call<CartOrder> addtocart(@Path("cart_id") int cart_id, @Header("Authorization") String djangoToken, @Body CartOrder cartOrder);
@POST("api/v1/cart/")
Call<CartOrder> new_addtocart(@Header("Authorization") String djangoToken,@Body CartOrder cartOrder);
}
<file_sep>/app/src/main/java/com/freshokartz2/adapter/CatAdapter.java
package com.freshokartz2.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.freshokartz2.Category.Result;
import com.freshokartz2.ProductsShow;
import com.freshokartz2.R;
import java.util.List;
public class CatAdapter extends RecyclerView.Adapter<CatAdapter.CatAdapterViewHolder>{
String[] data;
private Context context;
private List<Result> items;
public CatAdapter(Context context, List<Result> items) {
this.context = context;
this.items = items;
}
@NonNull
@Override
public CatAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.category_items, viewGroup, false);
return new CatAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CatAdapterViewHolder catAdapterViewHolder, final int i) {
Result result = items.get(i);
catAdapterViewHolder.textView.setText(result.getName());
String url = (String) result.getCategoryImage();
Glide.with(context)
.load(url)
//.apply(new RequestOptions().override(140, 140))
.into(catAdapterViewHolder.category_image);
catAdapterViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = items.get(i).getCategoryTreeId();
Log.i("yourta", String.valueOf(id));
Intent intent = new Intent(context, ProductsShow.class);
intent.putExtra("refId", id);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public class CatAdapterViewHolder extends RecyclerView.ViewHolder{
TextView textView;
ImageView category_image;
public CatAdapterViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.catName);
category_image = itemView.findViewById(R.id.category_image);
}
}
}
<file_sep>/app/src/main/java/com/freshokartz2/SalesOrderResponseBody.java
package com.freshokartz2;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class SalesOrderResponseBody {
@SerializedName("expected_delivery_date")
@Expose
private String expected_delivery_date;
@SerializedName("payment_method")
@Expose
private String payment_method;
@SerializedName("billing_address")
@Expose
private Integer billing_address;
@SerializedName("shipping_address")
@Expose
private Integer shipping_address;
@SerializedName("coupon_code")
@Expose
private String coupon_code;
@SerializedName("shipping_method")
@Expose
private String shipping_method;
@SerializedName("shipping_fee")
@Expose
private Double shipping_fee;
@SerializedName("order_type")
@Expose
private String order_type;
@SerializedName("order_items")
@Expose
private List<CartItem> cartItems = null;
public SalesOrderResponseBody(String expected_delivery_date, String payment_method, Integer billing_address, Integer shipping_address, String coupon_code, String shipping_method, Double shipping_fee, String order_type, List<CartItem> cartItems) {
this.expected_delivery_date = expected_delivery_date;
this.payment_method = payment_method;
this.billing_address = billing_address;
this.shipping_address = shipping_address;
this.coupon_code = coupon_code;
this.shipping_method = shipping_method;
this.shipping_fee = shipping_fee;
this.order_type = order_type;
this.cartItems = cartItems;
}
public String getExpected_delivery_date() {
return expected_delivery_date;
}
public void setExpected_delivery_date(String expected_delivery_date) {
this.expected_delivery_date = expected_delivery_date;
}
public String getPayment_method() {
return payment_method;
}
public void setPayment_method(String payment_method) {
this.payment_method = payment_method;
}
public Integer getBilling_address() {
return billing_address;
}
public void setBilling_address(Integer billing_address) {
this.billing_address = billing_address;
}
public Integer getShipping_address() {
return shipping_address;
}
public void setShipping_address(Integer shipping_address) {
this.shipping_address = shipping_address;
}
public String getCoupon_code() {
return coupon_code;
}
public void setCoupon_code(String coupon_code) {
this.coupon_code = coupon_code;
}
public String getShipping_method() {
return shipping_method;
}
public void setShipping_method(String shipping_method) {
this.shipping_method = shipping_method;
}
public Double getShipping_fee() {
return shipping_fee;
}
public void setShipping_fee(Double shipping_fee) {
this.shipping_fee = shipping_fee;
}
public String getOrder_type() {
return order_type;
}
public void setOrder_type(String order_type) {
this.order_type = order_type;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
}
<file_sep>/app/src/main/java/com/freshokartz2/ActivityOrderHistory.java
package com.freshokartz2;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.freshokartz2.BpSalesOrder.Result;
import com.freshokartz2.BpSalesOrder.SalesOrder;
import com.freshokartz2.adapter.AdapterOrderHistory;
import com.freshokartz2.utils.Tools;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ActivityOrderHistory extends AppCompatActivity {
private View parent_view;
private RecyclerView recyclerView;
private AdapterOrderHistory adapter;
SessionManagement session;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BpSales_Order.DJANGO_SITE)
.addConverterFactory(GsonConverterFactory.create())
.build();
BpSales_Order sales_orderApi = retrofit.create(BpSales_Order.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_history);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
initToolbar();
iniComponent();
getOrderHistoryDetails(token);
}
private void iniComponent() {
parent_view = findViewById(android.R.id.content);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void initToolbar() {
ActionBar actionBar;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.title_activity_history);
Tools.systemBarLolipop(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
if (item_id == android.R.id.home) {
super.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
private void getOrderHistoryDetails(String token){
String Token_request = "Token " + token;
Call<SalesOrder> result = sales_orderApi.getOrderHistory(Token_request);
result.enqueue(new Callback<SalesOrder>() {
@Override
public void onResponse(Call<SalesOrder> call, Response<SalesOrder> response) {
SalesOrder salesOrder = response.body();
// Toast.makeText(ActivityOrderHistory.this, salesOrder.getCount(), Toast.LENGTH_SHORT).show();
List<Result> main = salesOrder.getResults();
recyclerView.setAdapter(new AdapterOrderHistory(ActivityOrderHistory.this, salesOrder.getResults()));
View lyt_no_item = (View) findViewById(R.id.lyt_no_item);
if (main.size() == 0) {
lyt_no_item.setVisibility(View.VISIBLE);
} else {
lyt_no_item.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call<SalesOrder> call, Throwable t) {
}
});
}
}
<file_sep>/app/src/main/java/com/freshokartz2/AddressApi.java
package com.freshokartz2;
import com.freshokartz2.Country.CountryList;
import com.freshokartz2.State.StateList;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface AddressApi {
String DJANGO_SITE = "http://172.16.17.32/";
@POST("api/v1/bp/addresses/")
Call<AddressDetail> add_address(@Header("Authorization") String DjangoToken, @Body AddressDetail addressDetail);
@GET("api/v1/state/")
Call<StateList> getState();
@GET("api/v1/country/")
Call<CountryList> getCountry();
}
<file_sep>/app/src/main/java/com/freshokartz2/ActivityProfile.java
package com.freshokartz2;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.freshokartz2.utils.Tools;
import java.util.HashMap;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ActivityProfile extends AppCompatActivity {
TextView name, email, mobile_number, area, outstanding_balance, organization, gender, dateOfBirth, gstin;
Button add_address;
SessionManagement session;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ProfileApi.DJANGO_SITE)
.addConverterFactory(GsonConverterFactory.create())
.build();
ProfileApi profileApi = retrofit.create(ProfileApi.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
getProfileDetails(token);
add_address = findViewById(R.id.add_address);
add_address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(ActivityProfile.this, ActivityAddAddress.class);
startActivity(i);
}
});
initToolbar();
}
private void initToolbar() {
ActionBar actionBar;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("Profile");
Tools.systemBarLolipop(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
if (item_id == android.R.id.home) {
super.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void getProfileDetails(String token) {
String Token_request = "Token " + token;
Call<BpResponseBody> call = profileApi.getDetail(Token_request);
call.enqueue(new Callback<BpResponseBody>() {
@Override
public void onResponse(Call<BpResponseBody> call, Response<BpResponseBody> response) {
BpResponseBody finalResponseBody = response.body();
name = findViewById(R.id.name);
email = findViewById(R.id.email);
mobile_number = findViewById(R.id.mobile_number);
organization = findViewById(R.id.organization);
gender = findViewById(R.id.gender);
area =findViewById(R.id.area);
dateOfBirth = findViewById(R.id.dateOfBirth);
gstin = findViewById(R.id.gstin);
outstanding_balance = findViewById(R.id.outstanding_balance);
name.setText(finalResponseBody.getFirstName());
email.setText(finalResponseBody.getEmail());
mobile_number.setText(finalResponseBody.getMobileNumber());
organization.setText(finalResponseBody.getOrganizationName());
area.setText(finalResponseBody.getArea().getArea());
gender.setText(finalResponseBody.getGender());
outstanding_balance.setText(finalResponseBody.getOutstanding_balance());
dateOfBirth.setText(finalResponseBody.getDate_of_birth());
gstin.setText(finalResponseBody.getGSTIN());
Log.i("tuy", "hghyjv");
Toast.makeText(ActivityProfile.this, "Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<BpResponseBody> call, Throwable t) {
Toast.makeText(ActivityProfile.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
}
}
<file_sep>/app/src/main/java/com/freshokartz2/ProfileApi.java
package com.freshokartz2;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
public interface ProfileApi {
String DJANGO_SITE = "http://192.168.127.12/";
@GET("api/v1/businesspartners/")
Call<BpResponseBody> getDetail(@Header("Authorization") String djangoToken);
}
<file_sep>/app/src/main/java/com/freshokartz2/SalesOrderAdapter.java
package com.freshokartz2;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import com.github.aakira.expandablelayout.ExpandableRelativeLayout;
import java.util.List;
public class SalesOrderAdapter extends RecyclerView.Adapter<SalesOrderAdapter.ProAdapterViewHolder> {
private Context context;
private List<Order_Items> items;
public SalesOrderAdapter(Context context, List<Order_Items> items) {
this.context = context;
this.items = items;
}
@NonNull
@Override
public ProAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.order_item, viewGroup, false);
return new ProAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ProAdapterViewHolder proAdapterViewHolder, final int i) {
Order_Items result = items.get(i);
proAdapterViewHolder.textView.setText(result.getSku());
proAdapterViewHolder.price.setText(String.valueOf("Rs. " + result.getPrice()));
// proAdapterViewHolder.incre.setText(order_items.get(i).getQuantity_ordered());
//String url = "http://172.16.58.3/" + (String) result.getProductImage();
/* Glide.with(context)
.load(url)
//.apply(new RequestOptions().override(140, 140))
.into(proAdapterViewHolder.imageView);
Log.i("pred","csdfsf");
*/
}
@Override
public int getItemCount() {
return items.size();
}
public class ProAdapterViewHolder extends RecyclerView.ViewHolder {
ExpandableRelativeLayout relativeLayout;
boolean invalidQuantity=false;
boolean checkOfUnknown;
TextView textView, price;
double finalValue;
ImageView imageView, plus, minus, dropd;
EditText incre;
Button buyNow;
Spinner spinner;
public ProAdapterViewHolder(@NonNull View itemView) {
super(itemView);
relativeLayout = itemView.findViewById(R.id.out);
textView = itemView.findViewById(R.id.text);
incre = itemView.findViewById(R.id.incre);
incre.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
double gtr = Double.parseDouble(s.toString());
if (gtr > 10) {
s.replace(0, s.length(), "10");
}
} catch (NumberFormatException e) {
}
try {
double krt = Double.parseDouble(s.toString());
String numberD = String.valueOf(krt);
numberD = numberD.substring(numberD.indexOf("."));
System.out.println(numberD);
Log.i("numbers", numberD);
if (!numberD.equals(".5") && !numberD.equals(".25") && !numberD.equals(".75") && !numberD.equals(".0") ) {
Log.i("nbeers", numberD);
incre.setError("Write quantity like 0.25,1, 1.5, 1.75 ",null);
buyNow.setEnabled(false);
}
else {
buyNow.setEnabled(true);
//invalidQuantity=false;
incre.setError(null);
}
} catch (Exception e) {
}
}
});
plus = itemView.findViewById(R.id.plus);
minus = itemView.findViewById(R.id.minus);
price = itemView.findViewById(R.id.price);
imageView = itemView.findViewById(R.id.img_product);
spinner = itemView.findViewById(R.id.spin);
String[] items = new String[]{"Kg"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(itemView.getContext(), android.R.layout.simple_spinner_dropdown_item, items);
spinner.setAdapter(adapter);
plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = incre.getText().toString();
try {
finalValue = Double.parseDouble(value);
double gra = (int) finalValue;
if (!checkOfUnknown) {
finalValue = gra;
}
finalValue = finalValue + 0.250;
incre.setText(String.valueOf(finalValue));
checkOfUnknown = true;
} catch (Exception e) {
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = incre.getText().toString();
try {
finalValue = Double.parseDouble(value);
double gra = (int) finalValue;
if (!checkOfUnknown) {
finalValue = gra;
finalValue = finalValue + 0.250;
}
finalValue = finalValue - 0.250;
if (finalValue > 0) {
incre.setText(String.valueOf(finalValue));
}
checkOfUnknown = true;
} catch (Exception e) {
}
}
});
// plus.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// String value = incre.getText().toString();
// finalValue = Integer.parseInt(value);
// finalValue++;
// incre.setText(String.valueOf(finalValue));
// }
// });
//
// minus.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// String value = incre.getText().toString();
// finalValue = Integer.parseInt(value);
// finalValue--;
// if (finalValue > 0)
// incre.setText(String.valueOf(finalValue));
// }
// });
}
}
}
<file_sep>/app/src/main/java/com/freshokartz2/LoginAndRegistration.java
package com.freshokartz2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginAndRegistration extends AppCompatActivity {
private Button register;
private EditText email, password;
private Button button_login;
private ImageButton backhome;
private String token;
private SharedPreferences mPreferences;
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(LoginApi.DJANGO_SITE)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
LoginApi loginApi = retrofit.create(LoginApi.class);
CartApi cartApi = retrofit.create(CartApi.class);
SessionManagement session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_and_registration);
email = findViewById(R.id.email);
password =findViewById(R.id.password);
session = new SessionManagement(getApplicationContext());
button_login = findViewById(R.id.login);
button_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
}
});
register = findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(LoginAndRegistration.this, Registration.class);
startActivity(i);
}
});
backhome = findViewById(R.id.backhome);
backhome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i =new Intent(LoginAndRegistration.this, ActivityMain.class);
startActivity(i);
}
});
}
private void login() {
Login login = new Login(email.getText().toString() , password.getText().toString());
Call<Bptoken> call = loginApi.login(login);
call.enqueue(new Callback<Bptoken>() {
@Override
public void onResponse(Call<Bptoken> call, Response<Bptoken> response) {
Log.i("ghjk", "ghjk");
if (response.isSuccessful()) {
Log.i("vvpo", "vvpo");
if (response.body() != null) {
token = response.body().getToken();
Toast.makeText(getApplicationContext(), token, Toast.LENGTH_SHORT).show();
showPost(token);
Toast.makeText(LoginAndRegistration.this, "12345", Toast.LENGTH_SHORT).show();
Log.i("sperer", "gyjvhj");
session.createLoginSession(token);
if(session.isFirstTime()){
create_new_cart();
Intent i = new Intent(LoginAndRegistration.this, ActivityMain.class);
startActivity(i);
}
else {
Intent i = new Intent(LoginAndRegistration.this, ActivityMain.class);
startActivity(i);
}
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<Bptoken> call, Throwable t) {
Toast.makeText(LoginAndRegistration.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void showPost(String token) {
String Token_request = "Token " + token;
Call<BpResponseBody> call = loginApi.getDetail(Token_request);
call.enqueue(new Callback<BpResponseBody>() {
@Override
public void onResponse(Call<BpResponseBody> call, Response<BpResponseBody> response) {
BpResponseBody finalResponseBody = response.body();
Log.i("tuy", "hghyjv");
Toast.makeText(LoginAndRegistration.this, "Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<BpResponseBody> call, Throwable t) {
Toast.makeText(LoginAndRegistration.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
}
private void create_new_cart(){
List<CartItem> cart = new ArrayList<CartItem>();
CartOrder cartOrder = new CartOrder(cart);
session = new SessionManagement(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManagement.KEY_TOKEN);
String TokenRequest = "Token "+ token;
Log.d(token, TokenRequest);
Call<CartOrder> call = cartApi.new_addtocart(TokenRequest, cartOrder);
call.enqueue(new Callback<CartOrder>() {
@Override
public void onResponse(Call<CartOrder> call, Response<CartOrder> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Toast.makeText(LoginAndRegistration.this, "New cart is created", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("fail", "fail");
}
}
@Override
public void onFailure(Call<CartOrder> call, Throwable t) {
}
});
}
}
<file_sep>/app/src/main/java/com/freshokartz2/Product/OrderItem.java
package com.freshokartz2.Product;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class OrderItem {
@SerializedName("sku")
@Expose
private String sku;
@SerializedName("quantity_ordered")
@Expose
private Double quantityOrdered;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public Double getQuantityOrdered() {
return quantityOrdered;
}
public void setQuantityOrdered(Double quantityOrdered) {
this.quantityOrdered = quantityOrdered;
}
}
<file_sep>/app/src/main/java/com/freshokartz2/AddressDetail.java
package com.freshokartz2;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AddressDetail {
@SerializedName("name")
@Expose
private String name;
@SerializedName("nickname")
@Expose
private String nickname;
@SerializedName("house_flat_shop_number")
@Expose
private String house_flat_shop_number;
@SerializedName("detail_address")
@Expose
private String detail_address;
@SerializedName("area")
@Expose
private int area;
@SerializedName("city")
@Expose
private int city;
@SerializedName("state")
@Expose
private int state;
@SerializedName("country")
@Expose
private int country;
@SerializedName("pincode")
@Expose
private String pincode;
@SerializedName("contact_number")
@Expose
private String contact_number;
@SerializedName("is_default_billing")
@Expose
private Boolean is_default_billing;
@SerializedName("is_default_shipping")
@Expose
private Boolean is_default_shipping;
public AddressDetail(String name, String nickname, String house_flat_shop_number, String detail_address, int area, int city, int state, int country, String pincode, String contact_number, Boolean is_default_billing, Boolean is_default_shipping) {
this.name = name;
this.nickname = nickname;
this.house_flat_shop_number = house_flat_shop_number;
this.detail_address = detail_address;
this.area = area;
this.city = city;
this.state = state;
this.country = country;
this.pincode = pincode;
this.contact_number = contact_number;
this.is_default_billing = is_default_billing;
this.is_default_shipping = is_default_shipping;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getHouse_flat_shop_number() {
return house_flat_shop_number;
}
public void setHouse_flat_shop_number(String house_flat_shop_number) {
this.house_flat_shop_number = house_flat_shop_number;
}
public String getDetail_address() {
return detail_address;
}
public void setDetail_address(String detail_address) {
this.detail_address = detail_address;
}
public int getArea() {
return area;
}
public void setArea(int area) {
this.area = area;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public int getCountry() {
return country;
}
public void setCountry(int country) {
this.country = country;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getContact_number() {
return contact_number;
}
public void setContact_number(String contact_number) {
this.contact_number = contact_number;
}
public Boolean getIs_default_billing() {
return is_default_billing;
}
public void setIs_default_billing(Boolean is_default_billing) {
this.is_default_billing = is_default_billing;
}
public Boolean getIs_default_shipping() {
return is_default_shipping;
}
public void setIs_default_shipping(Boolean is_default_shipping) {
this.is_default_shipping = is_default_shipping;
}
}
<file_sep>/app/src/main/java/com/freshokartz2/CatApi.java
package com.freshokartz2;
import com.freshokartz2.Area.AreaList;
import com.freshokartz2.Category.PostList;
import com.freshokartz2.City.CityList;
import com.freshokartz2.Product.OrderInfo;
import com.freshokartz2.Product.ProductList;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Path;
public class CatApi {
private static final String url = "http://13.233.247.56/api/v1/";
public static PostService postService = null;
public static PostService getService() {
if (postService == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url).addConverterFactory(GsonConverterFactory.create())
.build();
postService = retrofit.create(PostService.class);
}
return postService;
}
public interface PostService {
// @GET("categorytrees/")
// Call<PostList> getPostList();
//
// @GET("products/")
// Call<ProductList> getProductList();
@GET("categorytrees/")
Call<PostList> getPostList();
// @GET("products/")
// Call<ProductList> getProductList();
@GET("products/{id}/")
Call<ProductList> getProductsDescription(@Path("id") String id);
@GET("/api/v1/products/product_by_category_id/{id}/")
Call<ProductList> getProductsByCateGory_Guest(@Path("id") int id);
@GET("/api/v1/products/product_by_category_id/{id}/")
Call<ProductList> getProductsByCateGory_Registered(@Path("id") int id, @Header("Authorization") String djangoToken);
@GET("city/")
Call<CityList> getCity();
@GET("area/")
Call<AreaList> getArea();
@POST("bp/sales_order/")
Call<OrderInfo> placeOrder(@Header("Authorization") String djangoToken
,@Body OrderInfo orderInfo);
}
}
| 75f45ce18e0ae2e6aa711c3147b5c3a9dac2076b | [
"Java"
] | 17 | Java | itnug987/Freshokartz | 4bcc61ae8ef61738350b9f4500a92f74dbd81b6a | 5cf0b989219da58334c54b3f0568e8e81e650e34 |
refs/heads/master | <repo_name>pitershaoxia/coupon-alibaba<file_sep>/alibaba-coupon-settlement/src/main/java/com/alibaba/coupon/module/service/RuleExecutor.java
package com.alibaba.coupon.module.service;
import com.alibaba.coupon.module.enums.RuleFlagEnums;
import com.simple.coupon.domain.dto.SettlementInfoDTO;
/**
* 优惠券模板规则处理器接口定义
*/
public interface RuleExecutor {
/**
* 规则类型标记
*
* @return
*/
RuleFlagEnums ruleConfig();
/**
* 优惠券规则计算
*
* @param dto
* @return
*/
SettlementInfoDTO computeRule(SettlementInfoDTO dto);
}
<file_sep>/alibaba-coupon-tempalte/src/main/java/com/alibaba/coupon/module/service/TemplateService.java
package com.alibaba.coupon.module.service;
import com.alibaba.coupon.domain.vo.TempalteRequestVo;
import com.simple.coupon.domain.dto.CouponTemplateDTO;
import com.simple.coupon.domain.vo.RespVo;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Map;
public interface TemplateService {
ResponseEntity<RespVo<?>> buildTemplate(TempalteRequestVo requestVo);
ResponseEntity<RespVo<?>> queryTemplateInfo(Integer id);
ResponseEntity<RespVo<?>> findAllUsableTemplate();
Map<Integer, CouponTemplateDTO> findIds2TemplateDTO(List<Integer> ids);
}
<file_sep>/alibaba-coupon-tempalte/src/main/java/com/alibaba/coupon/domain/entity/CouponTemplate.java
package com.alibaba.coupon.domain.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.simple.coupon.domain.enums.CouponCategoryEnums;
import com.simple.coupon.domain.enums.DistributionEnums;
import com.simple.coupon.domain.enums.ProductLineEnums;
import com.simple.coupon.domain.vo.TemplateRuleVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "coupon_template")
public class CouponTemplate implements Serializable {
private static final long serialVersionUID = 1904841585003729701L;
/**
* 自增主键
*/
@Id
@GeneratedValue(generator = "JDBC")
private Integer id;
/**
* 是否是可用状态; true: 可用, false: 不可用
*/
private Boolean available;
/**
* 是否过期; true: 是, false: 否
*/
private Boolean expired;
/**
* 优惠券名称
*/
private String name;
/**
* 优惠券 logo
*/
private String logo;
/**
* 优惠券描述
*/
private String intro;
/**
* 优惠券分类
*/
private CouponCategoryEnums category;
/**
* 产品线
*/
@Column(name = "product_line")
private ProductLineEnums product_line;
/**
* 优惠券总数
*/
@Column(name = "coupon_count")
private Integer count;
/**
* 创建时间
*/
@Column(name = "create_time")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 创建用户
*/
@Column(name = "user_id")
private Long userId;
/**
* 优惠券模板的编码
*/
@Column(name = "template_key")
private String templateKey;
/**
* 目标用户
*/
private DistributionEnums target;
/**
* 优惠券规则: TemplateRule 的 json 表示
*/
private TemplateRuleVo rule;
}<file_sep>/alibaba-coupon-settlement/src/main/java/com/alibaba/coupon/module/enums/RuleFlagEnums.java
package com.alibaba.coupon.module.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @Auther Piter_Liu
* @Description <h1>规则类型枚举定义</h1>
* @Date 2020/9/25
*/
@Getter
@AllArgsConstructor
@SuppressWarnings("all")
public enum RuleFlagEnums {
MANJIAN("满减券的计算规则"),
ZHEKOU("折扣券的计算规则"),
LIJIAN("立减券的计算规则"),
MANJIAN_ZHEKOU("满减券+折扣券的计算规则");
/**
* 规则描述
*/
private String description;
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/module/dao/CouponMapper.java
package com.alibaba.coupon.module.dao;
import com.alibaba.coupon.domain.entity.Coupon;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface CouponMapper extends Mapper<Coupon> {
List<Coupon> findAllByUserIdAndStatus(@Param("userId") Long userId, @Param("code") Integer code);
int insertUserGetCoupon(@Param("cp") Coupon coupon);
}<file_sep>/README.md
# coupon-alibaba
springcloud-alibaba 微服务优惠券项目
tool | version
-----------|-----------
kafka | 2.11-2.4
mysql | 5.7x
redis | 3.2
cloud-version | Greenwich.SR3
alibaba-version | 2.1.0.RELEASE
项目介绍
---
- 优惠券模板服务 <br>
假设根据运营人员设定的条件去构造优惠券模板,这里优惠券必须有数量的限制并且用于分发的优惠券必须有对应的优惠券码,优惠券设定了18位,要求1:不可以重复,2:有一定的识别性
- 优惠券分发服务 <br>
根据用户id和优惠券状态查找用户优惠券记录,而优惠券的状态分三类:可用的、已使用的、过期的(未被使用),除了获取用户的优惠券之外,还有延迟的过期处理策略<br>
这里根据优惠券的领取限制,还得对比当前用户所拥有的优惠券,判断是否可以进行领取
- 优惠券结算模块服务 <br>
根据优惠券类型结算优惠券,要求1:优惠券是分类的,不同类的优惠券有不同的计算方法。2:不同类的优惠券可以组合,所以也需要有不同的计算方法
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/domain/enums/CouponStatusEnums.java
package com.alibaba.coupon.domain.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Objects;
import java.util.stream.Stream;
/**
* 优惠券状态枚举类
*/
@Getter
@AllArgsConstructor
public enum CouponStatusEnums {
USABLE("可用的", 1),
USED("已使用的", 2),
EXPIRED("过期的(未被使用的)", 3);
/**
* 优惠券状态描述
*/
private String description;
/**
* 优惠券状态编码
*/
private Integer code;
/**
* 根据code获取到 CouponStatus
*
* @return
*/
public static CouponStatusEnums getCouponStatusByCode(Integer code) {
Objects.requireNonNull(code);
return Stream.of(values())
.filter(b -> b.code.equals(code))
.findAny()
.orElseThrow(() -> new IllegalArgumentException(code + "not exists"));
}
}
<file_sep>/alibaba-coupon-settlement/src/main/java/com/alibaba/coupon/SettlementApplication.java
package com.alibaba.coupon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Description:
* @Author: LiuPing
* @Time: 2020/9/14 0014 -- 14:12
*/
@SpringBootApplication
public class SettlementApplication {
public static void main(String[] args) {
SpringApplication.run(SettlementApplication.class,args);
}
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/module/feign/TemplateFeignClient.java
package com.alibaba.coupon.module.feign;
import com.alibaba.coupon.module.feign.hystix.TemplateFeignClientHystrix;
import com.simple.coupon.domain.dto.CouponTemplateDTO;
import com.simple.coupon.domain.vo.RespVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
/**
* 优惠券模板微服务 feign 接口的定义
*/
@FeignClient(value = "nacos-client-coupon-template", fallback = TemplateFeignClientHystrix.class)
public interface TemplateFeignClient {
/**
* 查询所有可用的优惠券模板
*
* @return
*/
@GetMapping("/coupon-template/template/sdk/all")
RespVo<List<CouponTemplateDTO>> findAllUsableTemplate();
/**
* 获取模板ids 到 CouponTemplateDTO 的映射
*
* @return
*/
@GetMapping("/coupon-template/template/sdk/infos")
Map<Integer, CouponTemplateDTO> findIds2TemplateDTO(@RequestParam("ids") List<Integer> ids);
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/domain/dto/CouponKafkaMessageDTO.java
package com.alibaba.coupon.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @Description: <h1>优惠券 kafka 消息对象定义</h1>
* @Author: LiuPing
* @Time: 2020/8/6 0006 -- 17:24
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponKafkaMessageDTO {
/**
* 优惠券状态
*/
private Integer status;
/**
* coupon 的主键
*/
private List<Integer> ids;
}
<file_sep>/alibaba-coupon-tempalte/src/main/java/com/alibaba/coupon/module/service/impl/AsyncServiceImpl.java
package com.alibaba.coupon.module.service.impl;
import com.alibaba.coupon.domain.entity.CouponTemplate;
import com.alibaba.coupon.module.dao.CouponTemplateMapper;
import com.alibaba.coupon.module.service.MyAsyncService;
import com.google.common.base.Stopwatch;
import com.simple.coupon.common.constant.CacheConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @Description: <h2>异步服务操作</h2>
* @Author: LiuPing
* @Time: 2020/9/17 0017 -- 14:12
*/
@Slf4j
@Service
@SuppressWarnings("all")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AsyncServiceImpl implements MyAsyncService {
private final CouponTemplateMapper templateMapper;
/**
* 注入 Redis 模板类
*/
private final StringRedisTemplate redisTemplate;
@Async("getAsyncExecutor")
@Override
public void asyncBuildCouponByTemplate(CouponTemplate template) {
// 执行时间监听器
Stopwatch stopwatch = Stopwatch.createStarted();
// 构造优惠券码
Set<String> couponCodes = buildCouponCode(template);
String redisKey = String.format("%s%s", CacheConstant.RedisPrefix_COUPON_TEMPLATE, template.getId().toString());
Long count = redisTemplate.opsForList().rightPushAll(redisKey, couponCodes); // 写入redis中
log.debug("【存入redis中的优惠券码数据量count】= {}", count);
template.setAvailable(true); // 标识模板可用
templateMapper.updateAvailable(template); // 更新最新状态
stopwatch.stop();
log.info("【Construct CouponCode By Template Cost】 = {}ms", stopwatch.elapsed(TimeUnit.MICROSECONDS));
// todo 发送短信或邮件通知优惠券模板可用了
log.debug("CouponTemplate({}) is available", template.getId());
}
/**
* <h2>构造优惠券码</h2>
* 规则:
* 优惠券码(对应于每一种优惠券,18位)
* 前四位:产品线(1)+优惠券分类(001)
* 中间六位:日期随机(190805)
* 后八位:0-9 随机数生成
*
* @return
*/
private Set<String> buildCouponCode(CouponTemplate template) {
// 执行监听器
Stopwatch stopwatch = Stopwatch.createStarted();
// 使用set数据结构避免出现重复数据
Set<String> codeSet = new HashSet<>(template.getCount());
String prefix4 = template.getProduct_line().getCode() + template.getCategory().getCode() + "";
String date = new SimpleDateFormat("yyMMdd").format(template.getCreateTime());
for (Integer i = 0; i < template.getCount(); i++) {
codeSet.add(prefix4 + buildCounponCodeSuffix14(date));
}
stopwatch.stop();
log.debug("【redis的优惠券码创建耗时】= {}ms", stopwatch.elapsed(TimeUnit.MICROSECONDS));
return codeSet;
}
/**
* 构造后14位
*
* @return
*/
private String buildCounponCodeSuffix14(String date) {
char[] bases = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
List<Character> chars = date.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
Collections.shuffle(chars); // 将输入的list进行排序打乱并返回
// 生成日期的随机数6位
String midfix6 = chars.stream()
.map(Objects::toString)
.collect(Collectors.joining());
// 生成后8位
String suffix8 = RandomStringUtils.random(1, bases) // 在base范围中随机选一个数
+ RandomStringUtils.randomNumeric(7); // 在0-9中随机生成7个数
return midfix6 + suffix8;
}
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/module/feign/hystix/TemplateFeignClientHystrix.java
package com.alibaba.coupon.module.feign.hystix;
import com.alibaba.coupon.module.feign.TemplateFeignClient;
import com.simple.coupon.domain.dto.CouponTemplateDTO;
import com.simple.coupon.domain.vo.RespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @Auther Piter_Liu
* @Description <h1>优惠券模板feign 接口的熔断降级策略</h1>
* @Date 2020/8/8
*/
@Slf4j
@Component
public class TemplateFeignClientHystrix implements TemplateFeignClient {
/**
* <h2>查询所有可用的优惠券模板</h2>
*/
@Override
public RespVo<List<CouponTemplateDTO>> findAllUsableTemplate() {
log.error("【eureka-client-coupon-template 服务实例】 findAllUsableTemplate " +
"request error");
// 出现熔断,返回空数据
return new RespVo<>(
-1,
"[eureka-client-coupon-template] request error",
Collections.emptyList()
);
}
/**
* <h2>获取模板ids 到 CouponTemplateDTO 的映射</h2>
*/
@Override
public Map<Integer, CouponTemplateDTO> findIds2TemplateDTO(List<Integer> ids) {
log.error("【eureka-client-coupon-template 服务实例】findIds2TemplateDTO " +
"request error");
// return new RespVo<>(
// -1,
// "[eureka-client-coupon-template] request error",
// Collections.emptyMap()
// );
return Collections.emptyMap();
}
}
<file_sep>/alibaba-coupon-tempalte/src/main/java/com/alibaba/coupon/domain/vo/CouponTemplateVo.java
package com.alibaba.coupon.domain.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponTemplateVo {
/**
* 自增主键
*/
private Integer id;
/**
* 是否是可用状态; true: 可用, false: 不可用
*/
private Boolean available;
/**
* 是否过期; true: 是, false: 否
*/
private Boolean expired;
/**
* 优惠券名称
*/
private String name;
/**
* 优惠券 logo
*/
private String logo;
/**
* 优惠券描述
*/
private String intro;
/**
* 优惠券分类
*/
private String category;
/**
* 产品线
*/
private String productLine;
/**
* 优惠券总数
*/
private Integer count;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 创建用户
*/
private Long userId;
/**
* 优惠券模板的编码
*/
private String templateKey;
/**
* 目标用户
*/
private String target;
/**
* 优惠券规则: TemplateRule 的 json 表示
*/
private String rule;
}<file_sep>/alibaba-coupon-tempalte/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>coupon</artifactId>
<groupId>com.alibaba</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>alibaba-coupon-tempalte</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!-- 引入 redis 的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- apache 提供的一些工具类 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>alibaba-coupon-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- tk mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<!-- myabtis的分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<!-- Actuator 对微服务端点进行管理和配置监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 引入nacos服务注册发现组件 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- 引入sentinel熔断器 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- 引入feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- 引入feign的连接池 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 指定该Main Class为全局的唯一入口 -->
<mainClass>com.alibaba.coupon.TemplateApplication</mainClass>
<!--<layout>ZIP</layout>-->
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project><file_sep>/alibaba-coupon-tempalte/src/main/java/com/alibaba/coupon/domain/vo/TempalteRequestVo.java
package com.alibaba.coupon.domain.vo;
import com.simple.coupon.domain.enums.CouponCategoryEnums;
import com.simple.coupon.domain.enums.DistributionEnums;
import com.simple.coupon.domain.enums.ProductLineEnums;
import com.simple.coupon.domain.vo.TemplateRuleVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* @Auther Piter_Liu
* @Description 优惠券模板参数接收对象
* @Date 2020/9/16
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TempalteRequestVo {
/**
* 优惠券名称
*/
private String name;
/**
* 优惠券 logo
*/
private String logo;
/**
* 优惠券描述
*/
private String desc;
/**
* 优惠券分类
*/
private Integer category;
/**
* 产品线
*/
private Integer productLine;
/**
* 总数
*/
private Integer count;
/**
* 创建用户
*/
private Long userId;
/**
* 目标用户
*/
private Integer target;
/**
* 优惠券规则
*/
private TemplateRuleVo rule;
/**
* 简单的参数校验
*/
public boolean validate() {
boolean stringValid = StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(logo)
&& StringUtils.isNotEmpty(desc);
boolean enumValid = (null != CouponCategoryEnums.getCouponByCode(category))
&& (null != ProductLineEnums.getProductLineEnumsByCode(productLine))
&& (null != DistributionEnums.getDistributionByCode(target));
boolean numValid = count > 0 && userId > 0;
return stringValid && enumValid && numValid && rule.validate();
}
}
<file_sep>/alibaba-coupon-common/src/main/java/com/simple/coupon/domain/vo/RespVo.java
package com.simple.coupon.domain.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Description:
* @Author: LiuPing
* @Time: 2020/9/14 0014 -- 16:34
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RespVo<T> implements Serializable {
private static final long serialVersionUID = -7395558874666977196L;
private Integer code;
private String msg;
private T data;
public RespVo(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public RespVo(T data) {
this.code = 200;
this.data = data;
this.msg = "";
}
}
<file_sep>/alibaba-coupon-settlement/src/main/java/com/alibaba/coupon/module/controller/SettlementController.java
package com.alibaba.coupon.module.controller;
import com.alibaba.coupon.module.service.ExecuteManager;
import com.alibaba.fastjson.JSON;
import com.simple.coupon.domain.dto.SettlementInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: 结算服务 -- 测试ok
* @Author: LiuPing
* @Time: 2020/9/25 0025 -- 17:03
*/
@Slf4j
@RestController
@RequestMapping("/coupon-settlement")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SettlementController {
private final ExecuteManager executeManager;
@PostMapping("/settlement/compute")
public SettlementInfoDTO computeGoods(@RequestBody SettlementInfoDTO infoDTO) {
log.debug("SettlementInfoDTO 传入参数 = {}", JSON.toJSONString(infoDTO));
SettlementInfoDTO settlementInfoDTO = executeManager.computeRule(infoDTO);
System.out.println(settlementInfoDTO);
return settlementInfoDTO;
}
}
<file_sep>/alibaba-coupon-common/src/main/java/com/simple/coupon/common/constant/CacheConstant.java
package com.simple.coupon.common.constant;
/**
* @Auther Piter_Liu
* @Description <h1>常量定义</h1>
* @Date 2020/8/4
*/
public class CacheConstant {
/**
* kafka 消息的topic
*/
public static final String TOPIC = "simple_user_coupon_op";
// Redis key 前缀定义 coupon_template_code: 其实已经分组了,后面那串是多余了
/** 优惠券码 key 前缀 */
public static final String RedisPrefix_COUPON_TEMPLATE = "coupon_template_code:";
/** 用户当前所有可用的优惠券 key 前缀 */
public static final String RedisPrefix_USER_COUPON_USEABLE = "user_coupon_usable:";
/** 用户当前所有已使用的优惠券 key 前缀 */
public static final String RedisPrefix_USER_COUPON_USED = "user_coupon_used:";
/** 用户当前所有已过期的优惠券 key 前缀 */
public static final String RedisPrefix_USER_COUPON_EXPIRED = "user_coupon_expired:";
}
<file_sep>/sql/imooc_coupon_data.sql
/*
Navicat Premium Data Transfer
Source Server : 本地MySQL
Source Server Type : MySQL
Source Server Version : 50728
Source Host : localhost:3306
Source Schema : imooc_coupon_data
Target Server Type : MySQL
Target Server Version : 50728
File Encoding : 65001
Date: 04/03/2021 15:26:53
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for coupon
-- ----------------------------
DROP TABLE IF EXISTS `coupon`;
CREATE TABLE `coupon` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`template_id` int(11) NOT NULL DEFAULT 0 COMMENT '关联优惠券模板的主键',
`user_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '领取用户',
`coupon_code` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券码',
`assign_time` datetime(0) NOT NULL DEFAULT '0000-01-01 00:00:00' COMMENT '领取时间',
`status` int(11) NOT NULL DEFAULT 0 COMMENT '优惠券的状态(1-可用,2-已使用,3-过期)',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_template_id`(`template_id`) USING BTREE,
INDEX `idx_user_id`(`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '优惠券(用户领取的记录)' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of coupon
-- ----------------------------
INSERT INTO `coupon` VALUES (1, 17, 118, '100192000469204207', '2020-09-11 10:29:31', 1);
INSERT INTO `coupon` VALUES (10, 17, 118, '100109204042073816', '2020-09-11 10:54:14', 1);
INSERT INTO `coupon` VALUES (11, 17, 116, '100102040990549920', '2020-09-11 11:24:19', 1);
INSERT INTO `coupon` VALUES (12, 17, 116, '100192000469204207', '2020-09-11 11:27:50', 1);
INSERT INTO `coupon` VALUES (13, 17, 116, '100149200096589597', '2020-09-11 11:38:23', 1);
INSERT INTO `coupon` VALUES (14, 17, 116, '100102004915972990', '2020-09-30 15:30:04', 1);
INSERT INTO `coupon` VALUES (15, 17, 116, '100102090499932339', '2020-09-30 15:31:42', 1);
INSERT INTO `coupon` VALUES (16, 17, 116, '100190002475556452', '2020-09-30 15:35:49', 1);
INSERT INTO `coupon` VALUES (17, 17, 4396, '100140209073263306', '2020-09-30 15:36:44', 1);
INSERT INTO `coupon` VALUES (18, 17, 4396, '100109040255884180', '2020-09-30 16:04:46', 1);
-- ----------------------------
-- Table structure for coupon_path
-- ----------------------------
DROP TABLE IF EXISTS `coupon_path`;
CREATE TABLE `coupon_path` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '路径ID, 自增主键',
`path_pattern` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '路径模式 ',
`http_method` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT 'http请求类型',
`path_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '路径描述',
`service_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '服务名',
`op_mode` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '操作类型, READ/WRITE',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_path_pattern`(`path_pattern`) USING BTREE,
INDEX `idx_servivce_name`(`service_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '路径信息表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of coupon_path
-- ----------------------------
INSERT INTO `coupon_path` VALUES (10, '/coupon-template/template/build', 'POST', 'buildTemplate', 'eureka-client-coupon-template', 'WRITE');
INSERT INTO `coupon_path` VALUES (11, '/coupon-template/template/info', 'GET', 'info', 'eureka-client-coupon-template', 'READ');
-- ----------------------------
-- Table structure for coupon_role
-- ----------------------------
DROP TABLE IF EXISTS `coupon_role`;
CREATE TABLE `coupon_role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '角色ID, 自增主键',
`role_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '角色名称',
`role_tag` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '角色TAG标识',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户角色表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of coupon_role
-- ----------------------------
INSERT INTO `coupon_role` VALUES (1, '管理员', 'ADMIN');
INSERT INTO `coupon_role` VALUES (2, '超级管理员', 'SUPER_ADMIN');
INSERT INTO `coupon_role` VALUES (3, '普通用户', 'CUSTOMER');
-- ----------------------------
-- Table structure for coupon_role_path_mapping
-- ----------------------------
DROP TABLE IF EXISTS `coupon_role_path_mapping`;
CREATE TABLE `coupon_role_path_mapping` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`role_id` int(11) NOT NULL DEFAULT 0 COMMENT '角色ID',
`path_id` int(11) NOT NULL DEFAULT 0 COMMENT '路径ID',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_role_id`(`role_id`) USING BTREE,
INDEX `idx_path_id`(`path_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '角色路径映射表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of coupon_role_path_mapping
-- ----------------------------
INSERT INTO `coupon_role_path_mapping` VALUES (1, 1, 10);
INSERT INTO `coupon_role_path_mapping` VALUES (2, 1, 11);
INSERT INTO `coupon_role_path_mapping` VALUES (3, 3, 11);
-- ----------------------------
-- Table structure for coupon_template
-- ----------------------------
DROP TABLE IF EXISTS `coupon_template`;
CREATE TABLE `coupon_template` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`available` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是可用状态; true: 可用, false: 不可用',
`expired` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否过期; true: 是, false: 否',
`name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券名称',
`logo` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券 logo',
`intro` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券描述',
`category` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券分类',
`product_line` int(11) NOT NULL DEFAULT 0 COMMENT '产品线',
`coupon_count` int(11) NOT NULL DEFAULT 0 COMMENT '优惠券总数',
`create_time` datetime(0) NOT NULL DEFAULT '0000-01-01 00:00:00' COMMENT '创建时间',
`user_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '创建用户',
`template_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券模板的编码',
`target` int(11) NOT NULL DEFAULT 0 COMMENT '目标用户',
`rule` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '优惠券规则: TemplateRule 的 json 表示',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `name`(`name`) USING BTREE,
INDEX `idx_category`(`category`) USING BTREE,
INDEX `idx_user_id`(`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 18 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '优惠券模板表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of coupon_template
-- ----------------------------
INSERT INTO `coupon_template` VALUES (12, 1, 1, '优惠券01', 'http://www.imooc.com', '这是第一张优惠券', '001', 1, 1000, '2020-08-19 11:47:06', 10001, '100120200819', 1, '{\"discount\":{\"base\":199,\"quota\":20},\"expiration\":{\"deadline\":1568082612129,\"gap\":1,\"period\":1},\"limitation\":1,\"usage\":{\"city\":\"深圳市\",\"goodsType\":\"[1,3]\",\"province\":\"广东省\"},\"weight\":\"[]\"}');
INSERT INTO `coupon_template` VALUES (13, 1, 1, '优惠券02', 'http://www.imooc.com', '这是第二张优惠券', '002', 1, 1000, '2020-08-19 11:49:31', 10001, '100220200819', 1, '{\"discount\":{\"base\":1,\"quota\":85},\"expiration\":{\"deadline\":1568082612129,\"gap\":1,\"period\":1},\"limitation\":1,\"usage\":{\"city\":\"桐城市\",\"goodsType\":\"[1,3]\",\"province\":\"安徽省\"},\"weight\":\"[\\\"1001201909060001\\\"]\"}');
INSERT INTO `coupon_template` VALUES (14, 1, 1, '优惠券03', 'http://www.imooc.com', '这是第三张优惠券', '003', 1, 1000, '2020-08-19 11:49:53', 10001, '100320200819', 1, '{\"discount\":{\"base\":1,\"quota\":5},\"expiration\":{\"deadline\":1568082612129,\"gap\":1,\"period\":1},\"limitation\":1,\"usage\":{\"city\":\"桐城市\",\"goodsType\":\"[1,3]\",\"province\":\"安徽省\"},\"weight\":\"[]\"}');
INSERT INTO `coupon_template` VALUES (17, 1, 0, 'nike篮球鞋专用券', 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1029818041,1523383330&fm=26&gp=0.jpg', 'k8篮球鞋', '001', 1, 1000, '2020-09-04 16:45:40', 9527, '100120200904', 1, '{\"discount\":{\"base\":799,\"quota\":60},\"expiration\":{\"deadline\":1630684800000,\"gap\":0,\"period\":1},\"limitation\":100,\"usage\":{\"city\":\"深圳市\",\"goodsType\":\"[1,4]\",\"province\":\"广东省\"},\"weight\":\"[\\\"\\\"]\"}');
-- ----------------------------
-- Table structure for coupon_user
-- ----------------------------
DROP TABLE IF EXISTS `coupon_user`;
CREATE TABLE `coupon_user` (
`id` int(200) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for coupon_user_role_mapping
-- ----------------------------
DROP TABLE IF EXISTS `coupon_user_role_mapping`;
CREATE TABLE `coupon_user_role_mapping` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`user_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '用户ID',
`role_id` int(11) NOT NULL DEFAULT 0 COMMENT '角色ID',
PRIMARY KEY (`id`) USING BTREE,
INDEX `key_role_id`(`role_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户角色关系映射表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of coupon_user_role_mapping
-- ----------------------------
INSERT INTO `coupon_user_role_mapping` VALUES (1, 15, 1);
INSERT INTO `coupon_user_role_mapping` VALUES (2, 16, 3);
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/alibaba-coupon-settlement/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>coupon</artifactId>
<groupId>com.alibaba</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>alibaba-coupon-settlement</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- apache 提供的一些工具类 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>alibaba-coupon-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Actuator 对微服务端点进行管理和配置监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 引入nacos服务注册发现组件 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
</dependencies>
</project><file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/domain/dto/CouponClassifyDTO.java
package com.alibaba.coupon.domain.dto;
import com.alibaba.coupon.domain.entity.Coupon;
import com.alibaba.coupon.domain.enums.CouponStatusEnums;
import com.simple.coupon.domain.enums.PeriodTypeEnums;
import com.simple.coupon.domain.vo.TemplateRuleVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.time.DateUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Description: 用户优惠券分类,根据优惠券状态
* @Author: LiuPing
* @Time: 2020/9/23 0023 -- 14:51
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponClassifyDTO {
/**
* 可使用的
*/
private List<Coupon> usableList;
/**
* 已使用的
*/
private List<Coupon> usedList;
/**
* 已过期的
*/
private List<Coupon> expireList;
/**
* 对当前的优惠券进行分类
*
* @return
*/
@SuppressWarnings("all")
public static CouponClassifyDTO classify(List<Coupon> coupons) {
List<Coupon> usableList = new ArrayList<>(coupons.size());
List<Coupon> usedList = new ArrayList<>(coupons.size());
List<Coupon> expireList = new ArrayList<>(coupons.size());
// 优惠券本身的过期策略是延时的
coupons.forEach(
c -> {
// 判断优惠券是否过期
Boolean isTimeExpire; // true -- 过期
long curTime = new Date().getTime();
TemplateRuleVo.Expiration ex = c.getTemplateSDK().getRule().getExpiration();
if (PeriodTypeEnums.REGULAR.getCode().equals(ex.getPeriod())) {
// 如果是固定日期,只要判断一下当前的优惠券deadline 是否小于当前世界
isTimeExpire = ex.getDeadline() <= curTime;
} else {
// 变动日期
isTimeExpire = DateUtils.addDays(
c.getAssignTime(), // 用户领取优惠券的时间
ex.getGap() // 时间间隔
).getTime() <= curTime; // 对时间操作后与当前世界进行判断
}
if (CouponStatusEnums.USED == c.getStatus()) {
usedList.add(c);
} else if (CouponStatusEnums.EXPIRED == c.getStatus()) {
expireList.add(c);
} else {
usableList.add(c);
}
}
);
return CouponClassifyDTO.builder()
.usableList(usableList)
.usedList(usedList)
.expireList(expireList)
.build();
}
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/domain/converter/CouponStatusConverter.java
package com.alibaba.coupon.domain.converter;
import com.alibaba.coupon.domain.enums.CouponStatusEnums;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @Description: 优惠券状态类型转换器
* @Author: LiuPing
* @Time: 2020/9/23 0023 -- 14:23
*/
@MappedTypes(CouponStatusEnums.class)
public class CouponStatusConverter implements TypeHandler<CouponStatusEnums> {
ObjectMapper objectMapper = new ObjectMapper();
@Override
public void setParameter(PreparedStatement preparedStatement, int index, CouponStatusEnums couponStatusEnums, JdbcType jdbcType) throws SQLException {
try {
String value = objectMapper.writeValueAsString(couponStatusEnums.getCode());
preparedStatement.setInt(index, Integer.parseInt(value));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Override
public CouponStatusEnums getResult(ResultSet resultSet, String param) throws SQLException {
int code = resultSet.getInt(param);
return parseInteger2CouponStatusEnums(code);
}
private CouponStatusEnums parseInteger2CouponStatusEnums(Integer code) {
if (code == null) {
return null;
}
return CouponStatusEnums.getCouponStatusByCode(code);
}
@Override
public CouponStatusEnums getResult(ResultSet resultSet, int index) throws SQLException {
int code = resultSet.getInt(index);
return parseInteger2CouponStatusEnums(code);
}
@Override
public CouponStatusEnums getResult(CallableStatement callableStatement, int index) throws SQLException {
int code = callableStatement.getInt(index);
return parseInteger2CouponStatusEnums(code);
}
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/module/controller/MainController.java
package com.alibaba.coupon.module.controller;
import com.alibaba.coupon.domain.dto.AcquireTemplateRequestDTO;
import com.alibaba.coupon.module.service.DistributeService;
import com.alibaba.fastjson.JSON;
import com.simple.coupon.domain.dto.SettlementInfoDTO;
import com.simple.coupon.domain.vo.RespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* @Description:
* @Author: LiuPing
* @Time: 2020/9/23 0023 -- 15:56
*/
@Slf4j
@RestController
@RequestMapping("/coupon-distribution")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MainController {
private final DistributeService distributeService;
/**
* 根据用户id和优惠券状态查询用户的优惠券记录
*
* @return
*/
@GetMapping("/coupons")
public ResponseEntity<RespVo<?>> findCouponByStatus(@RequestParam("userId") Long userId,
@RequestParam("status") Integer status) {
log.debug("Find Coupons By Status:{}, {}", userId, status);
return ResponseEntity.ok(new RespVo<>(distributeService.findCouponByStatus(userId, status)));
}
/**
* 根据用户id 查询当前可以领取的优惠券模板
*
* @return
*/
@GetMapping("/template")
public ResponseEntity<RespVo<?>> findAvailableTemplate(@RequestParam("userId") Long userId) {
log.debug("Find Available Template: {}", userId);
return distributeService.findAvailableTemplate(userId);
}
/**
* 用户领取优惠券
*
* @return
*/
@PostMapping("/acquire/template")
public ResponseEntity<RespVo<?>> acquireTemplate(@RequestBody AcquireTemplateRequestDTO requestDTO) {
log.debug("Acquire Template : {}", JSON.toJSONString(requestDTO));
return distributeService.acquireTemplate(requestDTO);
}
/**
* 结算(核销)优惠券 -- (未测试)
*
* @return
*/
@PostMapping("/settlement")
public SettlementInfoDTO settlement(@RequestBody SettlementInfoDTO infoDTO) {
log.debug("settlement 传入参数内容 = {}", JSON.toJSONString(infoDTO));
return distributeService.settlement(infoDTO);
}
}
<file_sep>/alibaba-coupon-tempalte/src/main/java/com/alibaba/coupon/config/GlobalExceptionHandler.java
package com.alibaba.coupon.config;
import com.simple.coupon.common.base.ErrorTip;
import com.simple.coupon.common.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Description: 全局异常类处理器
* @Author: LiuPing
* @Time: 2020/9/17 0017 -- 16:55
*/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<ErrorTip> handlerCustomException(MyException e) {
log.warn("发送MyException异常", e);
// return ResponseEntity.status(e.getCode()).body(new ErrorTip(e.getCode(),e.getMessage()));
// 如果要设置返回的header再修改
return ResponseEntity.status(e.getCode()).body(
ErrorTip.builder()
.message(e.getMessage())
.code(e.getCode())
.build());
}
}
<file_sep>/alibaba-coupon-distribution/src/main/java/com/alibaba/coupon/module/service/KafkaService.java
package com.alibaba.coupon.module.service;
public interface KafkaService {
}
<file_sep>/alibaba-coupon-settlement/src/test/java/com/alibaba/coupon/SettlementTest.java
package com.alibaba.coupon;
import com.alibaba.coupon.module.service.ExecuteManager;
import com.alibaba.fastjson.JSON;
import com.simple.coupon.domain.dto.CouponTemplateDTO;
import com.simple.coupon.domain.dto.GoodsInfoDTO;
import com.simple.coupon.domain.dto.SettlementInfoDTO;
import com.simple.coupon.domain.enums.CouponCategoryEnums;
import com.simple.coupon.domain.enums.GoodsTypeEnums;
import com.simple.coupon.domain.vo.TemplateRuleVo;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.Collections;
/**
* @Description:
* @Author: LiuPing
* @Time: 2020/9/30 0030 -- 10:19
*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class SettlementTest {
@Autowired
private ExecuteManager manager;
private Long fakeUserId = 20001L;
@Test
public void test() {
// 满减优惠券结算测试
log.info("ManJian Coupon Executor Test");
SettlementInfoDTO manjianInfo = fakeManJianCouponSettlement();
SettlementInfoDTO result = manager.computeRule(manjianInfo);
log.info("manjianInfo = {}", JSON.toJSONString(manjianInfo));
log.info("result = {}", JSON.toJSONString(result));
log.info("{}", result.getCost());
log.info("{}", result.getCouponAndTemplateInfos().size());
log.info("{}", result.getCouponAndTemplateInfos());
// 折扣优惠券结算测试
// log.info("ZheKou Coupon Executor Test");
// SettlementInfoDTO zhekouInfo = fakeZheKouCouponSettlement();
// SettlementInfoDTO result = manager.computeRule(zhekouInfo);
// log.info("{}", result.getCost());
// log.info("{}", result.getCouponAndTemplateInfos().size());
// log.info("{}", result.getCouponAndTemplateInfos());
// 立减优惠券结算测试
// log.info("LiJian Coupon Executor Test");
// SettlementInfoDTO lijianInfo = fakeLiJianCouponSettlement();
// SettlementInfoDTO result = manager.computeRule(lijianInfo);
// log.info("{}", result.getCost());
// log.info("{}", result.getCouponAndTemplateInfos().size());
// log.info("{}", result.getCouponAndTemplateInfos());
// 满减折扣优惠券结算测试
// log.info("ManJian ZheKou Coupon Executor Test");
// SettlementInfoDTO manjianZheKouInfo = fakeManJianAndZheKouCouponSettlement();
// SettlementInfoDTO result = manager.computeRule(manjianZheKouInfo);
// log.info("{}", result.getCost());
// log.info("{}", result.getCouponAndTemplateInfos().size());
// log.info("{}", result.getCouponAndTemplateInfos());
}
/**
* 满减优惠券测试
*
* @return
*/
private SettlementInfoDTO fakeManJianCouponSettlement() {
SettlementInfoDTO info = new SettlementInfoDTO();
info.setUserId(fakeUserId);
info.setEmploy(false);
info.setCost(0.0);
GoodsInfoDTO GoodsInfoDTO01 = new GoodsInfoDTO();
GoodsInfoDTO01.setCount(2);
GoodsInfoDTO01.setPrice(10.88);
GoodsInfoDTO01.setType(GoodsTypeEnums.WENYU.getCode());
GoodsInfoDTO GoodsInfoDTO02 = new GoodsInfoDTO();
// 达到满减标准
GoodsInfoDTO02.setCount(10);
// 没有达到满减标准
// GoodsInfoDTO02.setCount(5);
GoodsInfoDTO02.setPrice(20.88);
GoodsInfoDTO02.setType(GoodsTypeEnums.WENYU.getCode());
info.setGoodsInfos(Arrays.asList(GoodsInfoDTO01, GoodsInfoDTO02));
SettlementInfoDTO.CouponAndTemplateDTO ctInfo =
new SettlementInfoDTO.CouponAndTemplateDTO();
ctInfo.setId(1);
CouponTemplateDTO templateSDK = new CouponTemplateDTO();
templateSDK.setId(1);
templateSDK.setCategory(CouponCategoryEnums.MANJIAN.getCode() + "");
templateSDK.setKey("100120190801");
TemplateRuleVo rule = new TemplateRuleVo();
rule.setDiscount(new TemplateRuleVo.Discount(20, 199));
rule.setUsage(new TemplateRuleVo.Usage("广州省", "深圳市",
JSON.toJSONString(Arrays.asList( // 这里优惠券类型必须包含设置type
GoodsTypeEnums.WENYU.getCode(),
GoodsTypeEnums.JIAJU.getCode()
))));
templateSDK.setRule(rule);
ctInfo.setTemplate(templateSDK);
info.setCouponAndTemplateInfos(Collections.singletonList(ctInfo));
System.out.println("传入参数:" + JSON.toJSON(info));
return info;
}
/**
* 折扣优惠券测试
*
* @return
*/
private SettlementInfoDTO fakeZheKouCouponSettlement() {
SettlementInfoDTO info = new SettlementInfoDTO();
info.setUserId(fakeUserId);
info.setEmploy(false);
info.setCost(0.0);
GoodsInfoDTO GoodsInfoDTO01 = new GoodsInfoDTO();
GoodsInfoDTO01.setCount(2);
GoodsInfoDTO01.setPrice(10.88);
GoodsInfoDTO01.setType(GoodsTypeEnums.WENYU.getCode());
GoodsInfoDTO GoodsInfoDTO02 = new GoodsInfoDTO();
GoodsInfoDTO02.setCount(10);
GoodsInfoDTO02.setPrice(20.88);
GoodsInfoDTO02.setType(GoodsTypeEnums.WENYU.getCode());
info.setGoodsInfos(Arrays.asList(GoodsInfoDTO01, GoodsInfoDTO02));
SettlementInfoDTO.CouponAndTemplateDTO ctInfo =
new SettlementInfoDTO.CouponAndTemplateDTO();
ctInfo.setId(1);
CouponTemplateDTO templateSDK = new CouponTemplateDTO();
templateSDK.setId(2);
templateSDK.setCategory(CouponCategoryEnums.ZHEKOU.getCode() + "");
templateSDK.setKey("100220190712");
// 设置 TemplateRule
TemplateRuleVo rule = new TemplateRuleVo();
rule.setDiscount(new TemplateRuleVo.Discount(85, 1));
rule.setUsage(new TemplateRuleVo.Usage("安徽省", "桐城市",
JSON.toJSONString(Arrays.asList(
GoodsTypeEnums.WENYU.getCode(),
GoodsTypeEnums.JIAJU.getCode()
))));
// 优惠券类不匹配
// rule.setUsage(new TemplateRuleVo.Usage("安徽省", "桐城市",
// JSON.toJSONString(Arrays.asList(
// GoodsTypeEnums.SHENGXIAN.getCode(),
// GoodsTypeEnums.JIAJU.getCode()
// ))));
templateSDK.setRule(rule);
ctInfo.setTemplate(templateSDK);
info.setCouponAndTemplateInfos(Collections.singletonList(ctInfo));
System.out.println("传入参数:" + JSON.toJSON(info));
return info;
}
/**
* 立减优惠券测试
*
* @return
*/
private SettlementInfoDTO fakeLiJianCouponSettlement() {
SettlementInfoDTO info = new SettlementInfoDTO();
info.setUserId(fakeUserId);
info.setEmploy(false);
info.setCost(0.0);
GoodsInfoDTO GoodsInfoDTO01 = new GoodsInfoDTO();
GoodsInfoDTO01.setCount(2);
GoodsInfoDTO01.setPrice(10.88);
GoodsInfoDTO01.setType(GoodsTypeEnums.WENYU.getCode());
GoodsInfoDTO GoodsInfoDTO02 = new GoodsInfoDTO();
GoodsInfoDTO02.setCount(10);
GoodsInfoDTO02.setPrice(20.88);
GoodsInfoDTO02.setType(GoodsTypeEnums.WENYU.getCode());
info.setGoodsInfos(Arrays.asList(GoodsInfoDTO01, GoodsInfoDTO02));
SettlementInfoDTO.CouponAndTemplateDTO ctInfo =
new SettlementInfoDTO.CouponAndTemplateDTO();
ctInfo.setId(1);
CouponTemplateDTO templateSDK = new CouponTemplateDTO();
templateSDK.setId(3);
templateSDK.setCategory(CouponCategoryEnums.LIJIAN.getCode() + "");
templateSDK.setKey("200320190712");
TemplateRuleVo rule = new TemplateRuleVo();
rule.setDiscount(new TemplateRuleVo.Discount(5, 1));
rule.setUsage(new TemplateRuleVo.Usage("安徽省", "桐城市",
JSON.toJSONString(Arrays.asList(
GoodsTypeEnums.WENYU.getCode(),
GoodsTypeEnums.JIAJU.getCode()
))));
templateSDK.setRule(rule);
ctInfo.setTemplate(templateSDK);
info.setCouponAndTemplateInfos(Collections.singletonList(ctInfo));
System.out.println("传入参数:" + JSON.toJSON(info));
return info;
}
/**
* 满减+折扣优惠券
*
* @return
*/
private SettlementInfoDTO fakeManJianAndZheKouCouponSettlement() {
SettlementInfoDTO info = new SettlementInfoDTO();
info.setUserId(fakeUserId);
info.setEmploy(false);
info.setCost(0.0);
GoodsInfoDTO GoodsInfoDTO01 = new GoodsInfoDTO();
GoodsInfoDTO01.setCount(2);
GoodsInfoDTO01.setPrice(10.88);
GoodsInfoDTO01.setType(GoodsTypeEnums.WENYU.getCode());
GoodsInfoDTO GoodsInfoDTO02 = new GoodsInfoDTO();
GoodsInfoDTO02.setCount(10);
GoodsInfoDTO02.setPrice(20.88);
GoodsInfoDTO02.setType(GoodsTypeEnums.WENYU.getCode());
info.setGoodsInfos(Arrays.asList(GoodsInfoDTO01, GoodsInfoDTO02));
// 满减优惠券
SettlementInfoDTO.CouponAndTemplateDTO manjianInfo =
new SettlementInfoDTO.CouponAndTemplateDTO();
manjianInfo.setId(1);
CouponTemplateDTO manjianTemplate = new CouponTemplateDTO();
manjianTemplate.setId(1);
manjianTemplate.setCategory(CouponCategoryEnums.MANJIAN.getCode() + "");
// key 必须得符合规则
manjianTemplate.setKey("100120190712");
TemplateRuleVo manjianRule = new TemplateRuleVo();
manjianRule.setDiscount(new TemplateRuleVo.Discount(20, 199));
manjianRule.setUsage(new TemplateRuleVo.Usage("安徽省", "桐城市",
JSON.toJSONString(Arrays.asList(
GoodsTypeEnums.WENYU.getCode(),
GoodsTypeEnums.JIAJU.getCode()
))));
manjianRule.setWeight(JSON.toJSONString(Collections.emptyList()));
manjianTemplate.setRule(manjianRule);
manjianInfo.setTemplate(manjianTemplate);
// 折扣优惠券
SettlementInfoDTO.CouponAndTemplateDTO zhekouInfo =
new SettlementInfoDTO.CouponAndTemplateDTO();
zhekouInfo.setId(1);
CouponTemplateDTO zhekouTemplate = new CouponTemplateDTO();
zhekouTemplate.setId(2);
zhekouTemplate.setCategory(CouponCategoryEnums.ZHEKOU.getCode() + "");
zhekouTemplate.setKey("100220190712");
TemplateRuleVo zhekouRule = new TemplateRuleVo();
zhekouRule.setDiscount(new TemplateRuleVo.Discount(85, 1));
zhekouRule.setUsage(new TemplateRuleVo.Usage("安徽省", "桐城市",
JSON.toJSONString(Arrays.asList(
GoodsTypeEnums.WENYU.getCode(),
GoodsTypeEnums.JIAJU.getCode()
))));
zhekouRule.setWeight(JSON.toJSONString(
Collections.singletonList("1001201907120001")
));
zhekouTemplate.setRule(zhekouRule);
zhekouInfo.setTemplate(zhekouTemplate);
info.setCouponAndTemplateInfos(Arrays.asList(
manjianInfo, zhekouInfo
));
System.out.println("传入参数:" + JSON.toJSON(info));
return info;
}
}
<file_sep>/alibaba-coupon-settlement/src/main/java/com/alibaba/coupon/module/service/impl/ManJianZheKouExecutor.java
package com.alibaba.coupon.module.service.impl;
import com.alibaba.coupon.module.enums.RuleFlagEnums;
import com.alibaba.coupon.module.service.MyAbstractExecutorService;
import com.alibaba.coupon.module.service.RuleExecutor;
import com.alibaba.fastjson.JSON;
import com.simple.coupon.domain.dto.GoodsInfoDTO;
import com.simple.coupon.domain.dto.SettlementInfoDTO;
import com.simple.coupon.domain.enums.CouponCategoryEnums;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Description: 满减 + 折扣优惠券结算规则执行器
* @Author: LiuPing
* @Time: 2020/9/29 0029 -- 17:08
*/
@Slf4j
@Component
@SuppressWarnings("all")
public class ManJianZheKouExecutor extends MyAbstractExecutorService implements RuleExecutor {
/**
* 规则类型标记
*
* @return
*/
@Override
public RuleFlagEnums ruleConfig() {
return RuleFlagEnums.MANJIAN_ZHEKOU;
}
/**
* 校验商品类型与优惠券是否匹配
* 需要注意:
* 1、这里实现的满减 + 折扣优惠券的校验
* 2、如果想要使用多类优惠券,则必须要所有的商品类型都包含在内,即差集为空
*
* @param dto
* @return
*/
@Override
protected boolean isGoodsTypeSatisfy(SettlementInfoDTO settlement) {
log.debug("校验满减和折扣优惠券是否匹配满足条件");
List<Integer> goodsTypeList = settlement.getGoodsInfos().stream()
.map(GoodsInfoDTO::getType)
.collect(Collectors.toList());
List<Integer> templateGoodsType = new ArrayList<>();
settlement.getCouponAndTemplateInfos().forEach(
c -> {
templateGoodsType.addAll(JSON.parseObject(
c.getTemplate().getRule().getUsage().getGoodsType(),
List.class
));
}
);
// 如果想要使用多种优惠券叠加,则必须要所有商品的类型都包含在内,即差集为空,
return CollectionUtils.isEmpty(
CollectionUtils.subtract(goodsTypeList, templateGoodsType) // A - B 为null A的集合比B小
);
}
/**
* 优惠券规则的计算
*
* @param dto 包含了选择的优惠券
* @return
*/
@Override
public SettlementInfoDTO computeRule(SettlementInfoDTO dto) {
double goodsSum = retain2Decimals(goodsCostSum(dto.getGoodsInfos()));
// 商品类型的校验
SettlementInfoDTO statisfy = processGoodsTypeNotStatisfy(dto, goodsSum);
if (statisfy != null) {
log.debug("满减优惠券和折扣优惠券模板不匹配当前的商品类型");
return statisfy;
}
SettlementInfoDTO.CouponAndTemplateDTO manjian = null;
SettlementInfoDTO.CouponAndTemplateDTO zhekou = null;
for (SettlementInfoDTO.CouponAndTemplateDTO ct : dto.getCouponAndTemplateInfos()) {
if (CouponCategoryEnums.getCouponByCode(Integer.valueOf(ct.getTemplate().getCategory())) == CouponCategoryEnums.MANJIAN) {
manjian = ct;
} else {
zhekou = ct;
}
}
assert null != manjian;
assert null != zhekou;
// 当前的折扣优惠券和满减券如果不能共用(一起使用),则清空优惠券,返回商品原价
if (!isTemplateCanShared(manjian, zhekou)) {
log.debug("当前的满减券和折扣券不能被一起使用");
dto.setCost(goodsSum);
dto.setCouponAndTemplateInfos(Collections.emptyList());
return dto;
}
List<SettlementInfoDTO.CouponAndTemplateDTO> ctInfos = new ArrayList<>();
double manjianBase = manjian.getTemplate().getRule().getDiscount().getBase();
double manjianQuota = manjian.getTemplate().getRule().getDiscount().getQuota();
// 最终价格
double tatgetSum = goodsSum;
// 先计算满减
if (tatgetSum >= manjianBase) {
tatgetSum -= manjianQuota;
ctInfos.add(manjian);
}
// 再计算折扣
double zhekouQuota = zhekou.getTemplate().getRule().getDiscount().getQuota();
tatgetSum *= zhekouQuota * 1.0 / 100;
ctInfos.add(zhekou);
dto.setCost(retain2Decimals(
tatgetSum > minCost() ? tatgetSum : minCost()
));
dto.setCouponAndTemplateInfos(ctInfos);
log.info("使用满减券和折扣券后的商品总价cost = {} To {}", goodsSum, dto.getCost());
return dto;
}
private boolean isTemplateCanShared(SettlementInfoDTO.CouponAndTemplateDTO manJian, SettlementInfoDTO.CouponAndTemplateDTO zheKou) {
// 优惠券编码的id4位
String manjianKey = manJian.getTemplate().getKey()
+ String.format("%04d", manJian.getTemplate().getId());
String zhekouKey = zheKou.getTemplate().getKey()
+ String.format("%04d", zheKou.getTemplate().getId());
List<String> allSharedKeysForManjian = new ArrayList<>();
allSharedKeysForManjian.add(manjianKey);
allSharedKeysForManjian.addAll(JSON.parseObject(
manJian.getTemplate().getRule().getWeight(),
List.class
));
List<String> allSharedKeysForZhekou = new ArrayList<>();
allSharedKeysForZhekou.add(zhekouKey);
allSharedKeysForZhekou.addAll(JSON.parseObject(
zheKou.getTemplate().getRule().getWeight(),
List.class
));
return CollectionUtils.isSubCollection(
Arrays.asList(manjianKey, zhekouKey), allSharedKeysForManjian)
|| CollectionUtils.isSubCollection(
Arrays.asList(manjianKey, zhekouKey), allSharedKeysForZhekou);
}
}
| b9062c1b2a8f192255016833adf0f3fb989d9d47 | [
"Markdown",
"Java",
"Maven POM",
"SQL"
] | 27 | Java | pitershaoxia/coupon-alibaba | 44dc2d37c56e412075cbc8aa243c49c48f5970cb | 57e3d7f22025c92a0fef891bec90182907dbb2ac |
refs/heads/master | <repo_name>Alen0206/rabbitmq-demo<file_sep>/src/main/java/com/ljq/rabbitmqhello/receiver/Receiver3.java
package com.ljq.rabbitmqhello.receiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author: lujinqi
* @date: 2018/8/19 13:53
*/
@Component
@Slf4j
@RabbitListener(queues = "fanout.C")
public class Receiver3 {
@RabbitHandler
public void process(String hello){
log.info("Receiver C {}",hello);
}
}
| 8b7c0df16afe848f266b6483a6b763db42310021 | [
"Java"
] | 1 | Java | Alen0206/rabbitmq-demo | 756d59bc8154c5b04da94c9287425a555f685bec | fcce87ad7543832c0940f3152844ddf362e8f165 |
refs/heads/master | <file_sep>require('sinatra')
require('sinatra/contrib/all')
require_relative('../models/book.rb')
also_reload('../models/*')
get '/catalogue/books' do # BOOK
@books = Book.all()
erb(:all_index)
end
get '/catalogue/new-book' do # BOOK
erb(:book_new)
end
get '/catalogue/:id/edit-book' do # BOOK
@book = Book.find(params['id'])
erb(:book_edit)
end
post '/catalogue/create-book' do # BOOK
@book = Book.new(params)
@book.save()
redirect to '/catalogue/books'
end
post '/catalogue/:id/update-book' do # BOOK
Book.new(params).update()
redirect to '/catalogue/books'
end
post '/catalogue/:id/delete-book' do # BOOK
book = Book.find(params['id'])
book.delete()
redirect to '/catalogue/books'
end
<file_sep>DROP TABLE IF EXISTS piece_locations;
DROP TABLE IF EXISTS pieces;
DROP TABLE IF EXISTS books;
CREATE TABLE pieces (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
suite VARCHAR(255),
movement INT,
catalogue_name VARCHAR(255),
opus INT,
work_number INT,
composer VARCHAR(255)
);
CREATE TABLE books (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
edition VARCHAR(255)
);
CREATE TABLE piece_locations (
id SERIAL PRIMARY KEY,
book_id INT REFERENCES books(id) ON DELETE CASCADE,
piece_id INT REFERENCES pieces(id) ON DELETE CASCADE
);
<file_sep>require('sinatra')
require('sinatra/contrib/all')
require_relative('../models/piece.rb')
also_reload('../models/*')
get '/catalogue/pieces' do # PIECE
@pieces = Piece.all()
erb(:piece_index)
end
get '/catalogue/new-piece' do # PIECE
erb(:piece_new)
end
get '/catalogue/:id/edit-piece' do # PIECE
@piece = Piece.find(params['id'])
erb(:piece_edit)
end
post '/catalogue/create-piece' do # PIECE
@piece = Piece.new(params)
@piece.save()
redirect to '/catalogue/pieces'
end
post '/catalogue/:id/update-piece' do # PIECE
Piece.new(params).update()
redirect to '/catalogue/pieces'
end
post '/catalogue/:id/delete-piece' do # PIECE
piece = Piece.find(params['id'])
piece.delete()
redirect to '/catalogue/pieces'
end
<file_sep>require('sinatra')
require('sinatra/contrib/all')
require_relative('controllers/pieces_controller.rb')
require_relative('controllers/piece_locations_controller.rb')
require_relative('controllers/books_controller.rb')
also_reload('../models/*')
get '/' do
erb(:homepage)
end
<file_sep>require('pg')
require_relative('../db/sql_runner.rb')
require_relative('piece.rb')
require_relative('book.rb')
class PieceLocation
attr_reader :id
attr_accessor :book_id, :piece_id
def initialize(options)
@id = options['id'].to_i if options['id']
@book_id = options['book_id'].to_i
@piece_id = options['piece_id'].to_i
end
def save()
if PieceLocation.find(@book_id, @piece_id).nil?
sql = "INSERT INTO piece_locations
(book_id, piece_id)
VALUES
($1, $2)
RETURNING id"
values = [@book_id, @piece_id]
piece_location_hash = SqlRunner.run(sql, values).first()
@id = piece_location_hash['id'].to_i
end
end
def delete()
sql = "DELETE FROM piece_locations WHERE piece_locations.id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def self.find(bk_id, pc_id)
sql = "SELECT * FROM piece_locations
WHERE (piece_locations.book_id, piece_locations.piece_id)
= ($1, $2)"
values = [bk_id, pc_id]
found_relationship = SqlRunner.run(sql, values).first()
return found_relationship.nil? != true ? PieceLocation.new(found_relationship) : nil
end
def self.delete_all()
sql = "DELETE FROM piece_locations"
SqlRunner.run(sql)
end
end
<file_sep>require('pg')
require_relative('../db/sql_runner.rb')
require_relative('piece.rb')
require_relative('piece_location.rb')
class Piece
attr_reader :id
attr_accessor :name, :suite, :movement, :catalogue_name, :opus, :work_number, :composer
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
@suite = options['suite']
@movement = options['movement'].to_i
@catalogue_name = options['catalogue_name']
@opus = options['opus'].to_i
@work_number = options['work_number'].to_i
@composer = options['composer']
end
def save()
make_valid_numbers()
sql = "INSERT INTO pieces
(name,
suite,
movement,
catalogue_name,
opus,
work_number,
composer)
VALUES
($1, $2, $3, $4, $5, $6, $7)
RETURNING id"
values = [@name,
@suite,
@movement,
@catalogue_name,
@opus,
@work_number,
@composer]
piece_hash = SqlRunner.run(sql, values).first()
@id = piece_hash['id'].to_i
end
def update()
make_valid_numbers()
sql = "UPDATE pieces SET
(name, suite, movement, catalogue_name, opus, work_number, composer)
=
($1, $2, $3, $4, $5, $6, $7)
WHERE id = $8"
values = [@name, @suite, @movement, @catalogue_name, @opus, @work_number, @composer, @id]
SqlRunner.run(sql, values)
end
def delete()
sql = "DELETE FROM pieces WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def filled_fields()
return filled_field = {
'suite' => (@suite != '') ? true : false,
'movement' => (@movement != 0) ? true : false,
'catalogue_name' => (@catalogue_name != '') ? true : false,
'opus' => (@opus != 0) ? true : false,
'work_number' => (@work_number != 0) ? true : false,
}
end
def self.find(id)
sql = "SELECT * FROM pieces
WHERE pieces.id = $1"
values = [id]
found_piece = SqlRunner.run(sql, values).first()
return Piece.new(found_piece)
end
def self.all()
sql = "SELECT * FROM pieces"
pieces = SqlRunner.run(sql)
return pieces.map { |piece| Piece.new(piece)}
end
def self.delete_all()
sql = "DELETE FROM pieces"
SqlRunner.run(sql)
end
def all_books()
sql = "SELECT * FROM pieces
INNER JOIN piece_locations ON pieces.id = piece_locations.piece_id
INNER JOIN books ON books.id = piece_locations.book_id
WHERE pieces.id = $1"
values = [@id]
books = SqlRunner.run(sql, values)
return books.map { |book| Book.new(book) }
end
def make_valid_numbers()
if @movement < 1
@movement = 0
end
if @opus < 1
@opus = 0
end
if @work_number < 1
@work_number = 0
end
end
end
<file_sep>require('sinatra')
require('sinatra/contrib/all')
require_relative('../models/piece_location.rb')
require_relative('../models/book.rb')
require_relative('../models/piece.rb')
also_reload('../models/*')
get '/catalogue/new-piece-location' do # PIECE LOCATION
@all_pieces = Piece.all()
@all_books = Book.all()
erb(:piece_location_new)
end
post '/catalogue/create-piece-location' do # PIECE LOCATION
@piece_location = PieceLocation.new(params)
@piece_location.save()
redirect to '/catalogue/books'
end
post '/catalogue/:book_id/:piece_id/delete-piece-location' do # PIECE LOCATION
relationship = PieceLocation.find(params['book_id'], params['piece_id'])
relationship.delete()
redirect to '/catalogue/books'
end
<file_sep>### Sheet Music Catalogue
A relational database which allows the user to keep track of their books of sheet music and the pieces inside of them. A book of sheet music may contain many pieces, and a piece may appear in many books of sheet music.
#### MVP
The app should allow the user to:
x x create and edit their books of sheet music.
x x create and edit the pieces of music they own.
x x associate certain pieces with certain books of sheet music.
x x see a list of all the books of sheet music they own, and their contents.
x x see the contents of a specific book they own.
x x see all of the locations of a specific piece (e.g. a Chopin Nocturne may be found in both a compilation of Chopin Nocturnes and an exam syllabus book, so it would show both of them).
#### Possible Extensions
- The database could be restructured with a Composers table to allow the user to see which pieces they own by a particular composer.
- The Composers table could contain what musical period a composer was from (e.g. the Baroque period, the Classical period, the Romantic period, etc.), and then show the user the composition of their library by style, and the user's "favourite composer" (e.g. the composer who composed the most music in their library).
- Composer information could be displayed on different pages with the composer's picture, their date of birth and death, and their list of compositions.
#### Other Considerations
I realise I could use ISBN as a primary key in the Books table. However, I have opted not to implement this at present, as the likelihood of inputting the number incorrectly is high.
<file_sep># Sheet Music Catalogue
Repository link: https://github.com/RootSeven/Sheet_Music_Catalogue
Sheet Music Catalogue is a relational database with a browser-based front-end that you can use to store the details of books of sheet music and their contents. It was coded in Ruby, and uses Sinatra to run in a browser. The database was created using PostgreSQL, and the views were created using HTML and CSS.
## Using the App
To use this app, you must create a database called sheet_music_catalogue and run the SQL file. On Mac, you may do this by navigating to the Sheet_Music_Catalogue folder and using the commands:
__createdb sheet_music_catalogue__<br>
__psql -d sheet_music_catalogue -f db/sheet_music_catalogue.sql__
To install, download this repository and run the file __app.rb__ using Ruby. Then open the app in a browser window.
## Functionality
With this app, you can:
- Add Books to your collection, storing their Name and Edition
- Add Pieces to your collection, storing their Name, Composer, Suite, Movement, Opus and Number
- Add Pieces to Books in your collection
- View the contents of each Book in your collection
- View which Books a specific Piece in your collection may be found in
## Guide
Use the navigation bar at the top of the page to navigate this app.
## Home
Found on the Navigation Bar at the top of the page. Home contains an explanation of how to use the app.
## Full Catalogue
Found on the Navigation Bar at the top of the page. This page allows you to view you collection by Book, with the Book's contents below.
## All Pieces in Catalogue
Found on the Navigation Bar at the top of the page. This page allows you to view your collection by Piece, with the Books the Piece appears in below.
## Books
### Add New Book
Found on the Navigation Bar at the top of the page. This form allows you to add a new Book. Type in the Book's Name and Edition, and press the Submit button. You will be redirected to the Full Catalogue page.
### Edit Book
Below a Book's details on the Full Catalogue is an Edit Book button. Click this to open a form which you can use to edit the details of a Book. Click Update Book and you will be redirected to the Full Catalogue page, with the Book's details updated.
### Delete Book
Below the Edit Book button is the Delete Book button. Click this button to delete the Book from your collection. Any Pieces which were in this Book will now no longer have this Book in their list of Books they appear in.
## Pieces
### Create New Piece
Found on the Navigation Bar at the top of the page. This form allows you to add a new Piece, including the details for:
- Piece Name
- Composer
- Suite
- Movement
- Catalogue Prefix (e.g. Op., BWV etc.)
- Opus
- and Number.
Suite, Movement, Catalogue Prefix, Opus and Number may be left blank if these do not have any values. Click the Create New Piece button. You will be redirected to the All Pieces in Catalogue page.
### Edit Piece
Below a Piece's details in the All Pieces in Catalogue page is an Edit Piece button. Click this to edit the details of the piece.
### Delete Piece
Below the Edit Piece button is the Delete Piece button. Click this to delete a piece from your collection.
## Relating Pieces with Books
Found on the Navigation Bar at the top of the page. The piece will no longer be found in any Books it was in on the Full Catalogue page.
### Add Piece to Book
Found on the Navigation Bar at the top of the page. Choose the Book and Piece you want to relate, and click Add Piece to Book. The Piece will now be listed in the Book's contents on the Full Catalogue page, and the Book will now be listed as one of the Piece's locations on the All Pieces in Catalogue page.
<file_sep>require_relative('../models/book.rb')
require_relative('../models/piece.rb')
require_relative('../models/piece_location.rb')
PieceLocation.delete_all
Piece.delete_all
Book.delete_all
# Pieces
piece1 = Piece.new({
'name' => '<NAME>',
'suite' => 'Children\'s Corner',
'movement' => 1,
'catalogue_name' => 'L.',
'opus' => 113,
'work_number' => 0,
'composer' => '<NAME>',
})
piece2 = Piece.new({
'name' => '<NAME>',
'suite' => 'Children\'s Corner',
'movement' => 2,
'catalogue_name' => 'L.',
'opus' => 113,
'work_number' => 0,
'composer' => '<NAME>',
})
piece3 = Piece.new({
'name' => 'Adriana',
'suite' => 'Valses venezolanos',
'movement' => 7,
'catalogue_name' => '',
'opus' => 0,
'work_number' => 0,
'composer' => '<NAME>',
})
piece4 = Piece.new({
'name' => '<NAME>',
'suite' => '',
'movement' => 0,
'catalogue_name' => '',
'opus' => 0,
'work_number' => 0,
'composer' => '<NAME>',
})
piece5 = Piece.new({
'name' => 'Gigue',
'suite' => 'French Suite No.5 in G',
'movement' => 7,
'catalogue_name' => 'BWV',
'opus' => 816,
'work_number' => 0,
'composer' => '<NAME>',
})
piece6 = Piece.new({
'name' => 'Rondo',
'suite' => 'Sonata in E',
'movement' => 3,
'catalogue_name' => 'Op.',
'opus' => 14,
'work_number' => 1,
'composer' => '<NAME>',
})
piece1.save()
piece2.save()
piece3.save()
piece4.save()
piece5.save()
piece6.save()
# Books
book1 = Book.new({
'name' => 'ABRSM Grade 8 Piano Exam Pieces 2017 & 2018',
'edition' => 'ABRSM'
})
book2 = Book.new({
'name' => 'Children\'s Corner: Little Suite for Piano',
'edition' => 'Urtext'
})
book3 = Book.new({
'name' => 'Je te veux: valse chantee pour chant & piano',
'edition' => 'Salabert Editions'
})
book1.save()
book2.save()
book3.save()
# Piece Locations
piece_location1 = PieceLocation.new({
'book_id' => book1.id,
'piece_id' => piece1.id,
})
piece_location2 = PieceLocation.new({
'book_id' => book2.id,
'piece_id' => piece1.id,
})
piece_location3 = PieceLocation.new({
'book_id' => book2.id,
'piece_id' => piece2.id,
})
piece_location4 = PieceLocation.new({
'book_id' => book1.id,
'piece_id' => piece3.id
})
piece_location5 = PieceLocation.new({
'book_id' => book3.id,
'piece_id' => piece4.id
})
piece_location6 = PieceLocation.new({
'book_id' => book1.id,
'piece_id' => piece5.id
})
piece_location1.save()
piece_location2.save()
piece_location3.save()
piece_location4.save()
piece_location5.save()
piece_location6.save()
<file_sep>require('pg')
require_relative('../db/sql_runner.rb')
require_relative('book.rb')
require_relative('piece_location.rb')
class Book
attr_reader :id
attr_accessor :name, :edition
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
@edition = options['edition']
end
def save()
sql = "INSERT INTO books
(name, edition)
VALUES
($1, $2)
RETURNING id"
values = [@name, @edition]
book_hash = SqlRunner.run(sql, values).first()
@id = book_hash['id'].to_i
end
def update()
sql = "UPDATE books SET (name, edition) = ($1, $2)
WHERE id = $3"
values = [@name, @edition, @id]
SqlRunner.run(sql, values)
end
def delete()
sql = "DELETE FROM books WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def all_pieces()
sql = "SELECT * FROM books
INNER JOIN piece_locations ON books.id = piece_locations.book_id
INNER JOIN pieces ON piece_locations.piece_id = pieces.id
WHERE books.id = $1"
values = [@id]
pieces = SqlRunner.run(sql, values)
return pieces.map { |piece| Piece.new(piece)}
end
def self.find(id)
sql = "SELECT * FROM books
WHERE books.id = $1"
values = [id]
found_book = SqlRunner.run(sql, values).first()
return Book.new(found_book)
end
def self.all()
sql = "SELECT * FROM books"
books = SqlRunner.run(sql)
return books.map { |book| Book.new(book)}
end
def self.delete_all()
sql = "DELETE FROM books"
SqlRunner.run(sql)
end
end
| 987a2b47a8d2270acfc7ef0d4aa190953bde38ae | [
"Markdown",
"SQL",
"Ruby"
] | 11 | Ruby | RootSeven/Sheet_Music_Catalogue | 5342a4399a33a30b17667cf73e32682e2c1e8617 | 64c6d2ef80e82958cbda8fc32c564fc9066b6067 |
refs/heads/master | <repo_name>awinlei/ganttplus<file_sep>/plus_gantt/app/controllers/plusgantt_controller.rb
class PlusganttController < ApplicationController
menu_item :plusgantt
before_filter :find_optional_project
rescue_from Query::StatementInvalid, :with => :query_statement_invalid
helper :plusgantt
helper :issues
helper :projects
helper :queries
include QueriesHelper
helper :sort
include SortHelper
include Redmine::Export::PDF
include Plusgantt::PlusganttHelper
def show
@plusgantt = PlusganttChart.new(params)
@plusgantt.project = @project
retrieve_query
@query.group_by = nil
@plusgantt.query = @query if @query.valid?
basename = (@project ? "#{@project.identifier}-" : '') + 'plusgantt'
respond_to do |format|
format.html { render :action => "show", :layout => !request.xhr? }
format.png { send_data(@plusgantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @plusgantt.respond_to?('to_image')
format.pdf { send_data(@plusgantt.to_pdf, :type => 'application/pdf', :filename => "#{basename}.pdf") }
end
end
end
<file_sep>/plus_gantt/config/routes.rb
# Plugin's routes
# See: http://guides.rubyonrails.org/routing.html
get '/projects/:project_id/issues/plusgantt', :to => 'plusgantt#show', :as => 'project_plusgantt'
get '/issues/plusgantt', :to => 'plusgantt#show'
get 'plusgantt', :to => 'plusgantt#show'<file_sep>/plus_gantt/lib/plusgantt_hook_listener.rb
module Plusgantt
class Utils
def initialize()
end
def get_hollydays_between(earlier_date, later_date)
hollydays = 0
Rails.logger.info("get_hollydays_between: " + Plusgantt.get_hollydays.to_s)
if Plusgantt.get_hollydays
hollydays += Plusgantt.get_hollydays.count{|d| (earlier_date <= d.to_date && d.to_date <= later_date)}
end
return hollydays
end
def calc_days_between_date(earlier_date, later_date)
days_diff = (later_date - earlier_date).to_i
weekdays = 0
if days_diff >= 7
whole_weeks = (days_diff/7).to_i
later_date -= whole_weeks*7
weekdays += whole_weeks*5
end
if later_date >= earlier_date
dates_between = earlier_date..(later_date)
weekdays += dates_between.count{|d| ![0,6].include?(d.wday)}
end
return weekdays
end
def calc_weekenddays_between_date(earlier_date, later_date)
Rails.logger.info("----------------calc_weekenddays_between_date start----------------------------")
days_diff = (later_date - earlier_date).to_i
weekenddays = 0
if days_diff >= 7
whole_weeks = (days_diff/7).to_i
Rails.logger.info("whole_weeks: " + whole_weeks.to_s)
later_date -= whole_weeks*7
Rails.logger.info("new later_date: " + later_date.to_s)
weekenddays += whole_weeks*2
Rails.logger.info("3 - weekenddays: " + weekenddays.to_s)
end
if later_date >= earlier_date
dates_between = earlier_date..(later_date)
weekenddays += dates_between.count{|d| ![1,2,3,4,5].include?(d.wday)}
Rails.logger.info("4 - weekenddays: " + weekenddays.to_s)
end
Rails.logger.info("5 - weekenddays: " + weekenddays.to_s)
return weekenddays
Rails.logger.info("----------------calc_weekenddays_between_date end----------------------------")
end
def get_asignacion(issue)
if issue.custom_value_for(CustomField.find_by_name('asignacion')) &&
issue.custom_value_for(CustomField.find_by_name('asignacion')).value.to_d > 0
return issue.custom_value_for(CustomField.find_by_name('asignacion')).value.to_d
end
if issue.assigned_to && issue.assigned_to.custom_value_for(CustomField.find_by_name('asignacion')) &&
issue.assigned_to.custom_value_for(CustomField.find_by_name('asignacion')).value.to_d > 0
return issue.assigned_to.custom_value_for(CustomField.find_by_name('asignacion')).value.to_d
end
if issue.project.custom_value_for(CustomField.find_by_name('asignacion')) &&
issue.project.custom_value_for(CustomField.find_by_name('asignacion')).value.to_d > 0
return issue.project.custom_value_for(CustomField.find_by_name('asignacion')).value.to_d
end
return Plusgantt.hour_by_day
end
def update_issue_end_date(issue)
#Validate start_date
issue.start_date = cal_start_date(issue.start_date)
Rails.logger.info("----------------controller_issues_edit_after_save----------------------------")
Rails.logger.info("start date modified to: " + issue.start_date.to_s)
Rails.logger.info("----------------controller_issues_edit_after_save----------------------------")
#calculate end date.
hour_by_day = get_asignacion(issue)
days = (issue.estimated_hours / hour_by_day).ceil
if days <= 1
issue.due_date = issue.start_date
else
end_date = issue.start_date + days.to_i - 1
Rails.logger.info("----------------controller_issues_edit_after_save----------------------------")
Rails.logger.info("days: " + days.to_s)
Rails.logger.info("----------------controller_issues_edit_after_save----------------------------")
issue.due_date = cal_end_date(issue.start_date, end_date)
end
end
def cal_start_date(start_date)
if start_date.wday == 6
start_date = (start_date + 2).to_date
else
if start_date.wday == 0
start_date = (start_date + 1).to_date
end
end
hollydays = get_hollydays_between(start_date, start_date)
if hollydays.to_i > 0
return cal_start_date((start_date + hollydays).to_date)
else
return start_date.to_date
end
end
def cal_end_date(start_date, end_date)
Rails.logger.info("----------------cal_end_date start----------------------------")
Rails.logger.info("start_date: " + start_date.to_s)
Rails.logger.info("end_date: " + end_date.to_s)
weekenddays = calc_weekenddays_between_date(start_date, end_date)
if weekenddays == 0
Rails.logger.info("1 - weekenddays: " + weekenddays.to_s)
hollydays = get_hollydays_between(start_date, end_date)
Rails.logger.info("Hollydays: " + hollydays.to_s)
if hollydays.to_i > 0
start_date = (end_date + 1).to_date
end_date = (end_date + hollydays.to_i).to_date
weekenddays = calc_weekenddays_between_date(start_date, end_date)
if weekenddays == 0
hollydays = get_hollydays_between(end_date, end_date)
Rails.logger.info("Hollydays: " + hollydays.to_s)
if hollydays.to_i > 0
end_date = (end_date + hollydays.to_i).to_date
return cal_end_date(end_date, end_date)
else
return end_date.to_date
end
else
if end_date.wday == 6
Rails.logger.info("DIA SABADO")
return cal_end_date((end_date + 2).to_date, (end_date + 2 + (weekenddays - 1)).to_date)
else
if end_date.wday == 0
Rails.logger.info("DIA DOMINGO")
return cal_end_date((end_date + 1).to_date, (end_date + 1 + (weekenddays - 1)).to_date)
else
Rails.logger.info("DIA:" + end_date.wday.to_s)
return cal_end_date(end_date, (end_date + weekenddays).to_date)
end
end
end
end;
return end_date.to_date
else
hollydays = get_hollydays_between(start_date, end_date)
Rails.logger.info("Hollydays: " + hollydays.to_s)
if hollydays.to_i > 0
weekenddays += calc_weekenddays_between_date( (end_date + 1).to_date, (end_date + hollydays.to_i).to_date)
end_date = (end_date + hollydays.to_i).to_date
end
if end_date.wday == 6
Rails.logger.info("DIA SABADO")
return cal_end_date((end_date + 2).to_date, (end_date + 2 + (weekenddays - 1)).to_date)
else
if end_date.wday == 0
Rails.logger.info("DIA DOMINGO")
return cal_end_date((end_date + 1).to_date, (end_date + 1 + (weekenddays - 1)).to_date)
else
Rails.logger.info("DIA:" + end_date.wday.to_s)
return cal_end_date(end_date, (end_date + weekenddays).to_date)
end
end
end
Rails.logger.info("----------------cal_end_date end----------------------------")
end
end
class PlusganttHookListener < Redmine::Hook::ViewListener
render_on :view_issues_sidebar_issues_bottom, :partial => "plusgantt/issues_sidebar"
def controller_issues_new_after_save(context={})
update_issue_end_date(context, true)
end
def controller_issues_edit_after_save(context={})
update_issue_end_date(context, true)
end
def controller_issues_bulk_edit_before_save(context={})
update_issue_end_date(context, false)
end
def update_issue_end_date(context={}, save)
if Plusgantt.calculate_end_date
@utils = Utils.new()
issue = context[:issue]
if issue.start_date && issue.estimated_hours && issue.leaf?
@utils.update_issue_end_date(issue)
if save
if issue.save
Rails.logger.info("Issue updated")
else
raise ActiveRecord::Rollback
end
end
end
end
end
end
end<file_sep>/plus_gantt/init.rb
require_dependency 'plusgantt_hook_listener'
require 'issue_patch'
Redmine::Plugin.register :plus_gantt do
name 'Gantt Plus plugin'
author '<NAME>'
description 'This is a plugin for Redmine wich render a project gantt adding a control date in order to visualize the expected ratio'
version '0.0.1'
url ''
author_url 'https://www.linkedin.com/in/lucioferrero/'
menu :project_menu, :plusgantt, {:controller => 'plusgantt', :action => 'show' }, :caption => :label_plusgantt, :after => :gantt, :param => :project_id
project_module :plusgantt do
permission :view_plusgantt, {:plusgantt => [:show]}
end
settings :default => {'empty' => true}, :partial => 'settings/plusgantt/general'
end
ActionDispatch::Callbacks.to_prepare do
require 'plus_gantt'
end<file_sep>/plus_gantt/README.rdoc
= plus_gantt
Description goes here
<file_sep>/plus_gantt/lib/issue_patch.rb
require_dependency 'issue'
module IssuePatch
def self.included(base) # :nodoc:
base.send(:extend, ClassMethods)
base.send(:include, InstanceMethods)
base.class_eval do
alias_method :reschedule_on, :reschedule_on_with_patch
end
end
module ClassMethods
end
module InstanceMethods
include Plusgantt
def reschedule_on_with_patch(date)
Rails.logger.info("----------------reschedule_on_with_patch start----------------------------")
if Plusgantt.calculate_end_date
Rails.logger.info("date: " + date.to_s)
if @utils.nil?
Rails.logger.info("----------------reschedule_on_with_patch initialize----------------------------")
@utils = Utils.new()
end
@utils.get_hollydays_between(date, date)
Rails.logger.info("issue: " + self.to_s)
self.start_date = date
if self.start_date && self.estimated_hours && self.leaf?
@utils.update_issue_end_date(self)
end
else
self.reschedule_on(date)
end
Rails.logger.info("----------------reschedule_on_with_patch end----------------------------")
end
end
end
Rails.configuration.to_prepare do
#unless Issue.included_modules.include? IssuePatch
Issue.send(:include, IssuePatch)
#end
end<file_sep>/plus_gantt/lib/plus_gantt.rb
require 'plusgantt/helpers/plusgantt'
module Plusgantt
HOURS_BY_DAY = 8.0
VALID_HOURS_BY_DAY = [4.0, 8.0, 12.0, 16.0]
CALCULATE_END_DATE = false
class << self
def calculate_end_date
if Setting.plugin_plus_gantt['calculate_end_date'].nil?
CALCULATE_END_DATE
else
if Setting.plugin_plus_gantt['calculate_end_date'] == '1'
true
else
false
end
end
end
def hour_by_day
if Setting.plugin_plus_gantt['hour_by_day']
by_settigns = Setting.plugin_plus_gantt['hour_by_day'].to_d
if VALID_HOURS_BY_DAY.include?(by_settigns)
by_settigns
else
HOURS_BY_DAY
end
else
HOURS_BY_DAY
end
end
def hollydays
if Setting.plugin_plus_gantt['hollydays']
Setting.plugin_plus_gantt['hollydays']
else
""
end
end
def get_hollydays
if Setting.plugin_plus_gantt['hollydays']
Setting.plugin_plus_gantt['hollydays'].split(",").sort
else
[]
end
end
def get_hollydays_js
if Setting.plugin_plus_gantt['hollydays']
Setting.plugin_plus_gantt['hollydays'].split(",").sort.to_json
else
[]
end
end
end
end<file_sep>/plus_gantt/assets/javascripts/plusgantt.js
/* Redmine - project management software
Copyright (C) 2006-2016 <NAME> */
var draw_gantt = null;
var draw_top;
var draw_right;
var draw_left;
var rels_stroke_width = 2;
function setDrawArea() {
draw_top = $("#gantt_draw_area").position().top;
draw_right = $("#gantt_draw_area").width();
draw_left = $("#gantt_area").scrollLeft();
}
function getRelationsArray() {
var arr = new Array();
$.each($('div.task_todo[data-rels]'), function(index_div, element) {
var element_id = $(element).attr("id");
if (element_id != null) {
var issue_id = element_id.replace("task-todo-issue-", "");
var data_rels = $(element).data("rels");
for (rel_type_key in data_rels) {
$.each(data_rels[rel_type_key], function(index_issue, element_issue) {
arr.push({issue_from: issue_id, issue_to: element_issue,
rel_type: rel_type_key});
});
}
}
});
return arr;
}
function drawRelations() {
var arr = getRelationsArray();
$.each(arr, function(index_issue, element_issue) {
var issue_from = $("#task-todo-issue-" + element_issue["issue_from"]);
var issue_to = $("#task-todo-issue-" + element_issue["issue_to"]);
if (issue_from.size() == 0 || issue_to.size() == 0) {
return;
}
var issue_height = issue_from.height();
var issue_from_top = issue_from.position().top + (issue_height / 2) - draw_top;
var issue_from_right = issue_from.position().left + issue_from.width();
var issue_to_top = issue_to.position().top + (issue_height / 2) - draw_top;
var issue_to_left = issue_to.position().left;
var color = issue_relation_type[element_issue["rel_type"]]["color"];
var landscape_margin = issue_relation_type[element_issue["rel_type"]]["landscape_margin"];
var issue_from_right_rel = issue_from_right + landscape_margin;
var issue_to_left_rel = issue_to_left - landscape_margin;
draw_gantt.path(["M", issue_from_right + draw_left, issue_from_top,
"L", issue_from_right_rel + draw_left, issue_from_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
if (issue_from_right_rel < issue_to_left_rel) {
draw_gantt.path(["M", issue_from_right_rel + draw_left, issue_from_top,
"L", issue_from_right_rel + draw_left, issue_to_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
draw_gantt.path(["M", issue_from_right_rel + draw_left, issue_to_top,
"L", issue_to_left + draw_left, issue_to_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
} else {
var issue_middle_top = issue_to_top +
(issue_height *
((issue_from_top > issue_to_top) ? 1 : -1));
draw_gantt.path(["M", issue_from_right_rel + draw_left, issue_from_top,
"L", issue_from_right_rel + draw_left, issue_middle_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
draw_gantt.path(["M", issue_from_right_rel + draw_left, issue_middle_top,
"L", issue_to_left_rel + draw_left, issue_middle_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
draw_gantt.path(["M", issue_to_left_rel + draw_left, issue_middle_top,
"L", issue_to_left_rel + draw_left, issue_to_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
draw_gantt.path(["M", issue_to_left_rel + draw_left, issue_to_top,
"L", issue_to_left + draw_left, issue_to_top])
.attr({stroke: color,
"stroke-width": rels_stroke_width
});
}
draw_gantt.path(["M", issue_to_left + draw_left, issue_to_top,
"l", -4 * rels_stroke_width, -2 * rels_stroke_width,
"l", 0, 4 * rels_stroke_width, "z"])
.attr({stroke: "none",
fill: color,
"stroke-linecap": "butt",
"stroke-linejoin": "miter"
});
});
}
function getProgressLinesArray() {
var arr = new Array();
var today_left = $('#control_date').position().left;
arr.push({left: today_left, top: 0});
$.each($('div.issue-subject, div.version-name'), function(index, element) {
var t = $(element).position().top - draw_top ;
var h = ($(element).height() / 9);
var element_top_upper = t - h;
var element_top_center = t + (h * 3);
var element_top_lower = t + (h * 8);
var issue_closed = $(element).children('span').hasClass('issue-closed');
var version_closed = $(element).children('span').hasClass('version-closed');
if (issue_closed || version_closed) {
arr.push({left: today_left, top: element_top_center});
} else {
var issue_done = $("#task-done-" + $(element).attr("id"));
var is_behind_start = $(element).children('span').hasClass('behind-start-date');
var is_over_end = $(element).children('span').hasClass('over-end-date');
if (is_over_end) {
arr.push({left: draw_right, top: element_top_upper, is_right_edge: true});
arr.push({left: draw_right, top: element_top_lower, is_right_edge: true, none_stroke: true});
} else if (issue_done.size() > 0) {
var done_left = issue_done.first().position().left +
issue_done.first().width();
arr.push({left: done_left, top: element_top_center});
} else if (is_behind_start) {
arr.push({left: 0 , top: element_top_upper, is_left_edge: true});
arr.push({left: 0 , top: element_top_lower, is_left_edge: true, none_stroke: true});
} else {
var todo_left = today_left;
var issue_todo = $("#task-todo-" + $(element).attr("id"));
if (issue_todo.size() > 0){
todo_left = issue_todo.first().position().left;
}
arr.push({left: Math.min(today_left, todo_left), top: element_top_center});
}
}
});
return arr;
}
function drawGanttProgressLines() {
var arr = getProgressLinesArray();
var color = $("#control_date")
.css("border-left-color");
var i;
for(i = 1 ; i < arr.length ; i++) {
if (!("none_stroke" in arr[i]) &&
(!("is_right_edge" in arr[i - 1] && "is_right_edge" in arr[i]) &&
!("is_left_edge" in arr[i - 1] && "is_left_edge" in arr[i]))
) {
var x1 = (arr[i - 1].left == 0) ? 0 : arr[i - 1].left + draw_left;
var x2 = (arr[i].left == 0) ? 0 : arr[i].left + draw_left;
draw_gantt.path(["M", x1, arr[i - 1].top,
"L", x2, arr[i].top])
.attr({stroke: color, "stroke-width": 2});
}
}
}
function drawGanttHandler() {
var folder = document.getElementById('gantt_draw_area');
if(draw_gantt != null)
draw_gantt.clear();
else
draw_gantt = Raphael(folder);
setDrawArea();
if ($("#draw_progress_line").prop('checked'))
drawGanttProgressLines();
if ($("#draw_relations").prop('checked'))
drawRelations();
}
| 0d3ddb4f3b521d60f9eaba09a32915814052820d | [
"JavaScript",
"RDoc",
"Ruby"
] | 8 | Ruby | awinlei/ganttplus | f19a4cb13091d1152a3f3e8d1d4d74e3e6d76958 | 5c5cf97e5a9fcd0a2b2d97eb0606dbf884cbf2f5 |
refs/heads/master | <repo_name>anam1999/laravel_aplikasitower<file_sep>/app/Tower.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tower extends Model
{
//
//mendaftarkan atribut yang ada didalam fillable untuk di simpan saat melakukan input
protected $fillable = [
'nama_tower', 'alamat', 'rt', 'rw', 'id_kec', 'id_desa', 'koor_lat', 'koor_leng',
'tinggi','tanggal_imb', 'id_provider1', 'id_provider2', 'id_provider3', 'ket_pemilik', 'akhir_sewa', 'nama_pemilik_tower','nama_pemilik_lahan',
'id_jenis_tower','id_foto','id_user'
];
//Relasi database dari tabel tower ke desa
public function desa(){
return $this->belongsTo('App\Desa','id_desa','id_desa');
}
//Relasi database dari tabel tower ke foto
public function foto(){
return $this->belongsTo('App\Foto','id_foto','id');
}
//Relasi database dari tabel tower ke kecamatan
public function kecamatan(){
return $this->belongsTo('App\Kecamatan','id_kec','id_kecamatan');
}
//Relasi database dari tabel tower ke jenis tower
public function jenis(){
return $this->belongsTo('App\Jenis_Tower','id_jenis_tower','id');
}
}
<file_sep>/app/Foto.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Foto extends Model
{
//
//mendaftarkan atribut yang ada didalam fillable untuk di simpan saat melakukan input
protected $fillable = [
'foto'
];
//membuat fungsi tower
public function tower(){
//membuat relasi one to many ke model Tower
return $this->hasMany('App\Tower','id');
}
}
<file_sep>/app/Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//
//Relasi database dari tabel role ke user
protected function user(){
//membuat relasi one to many ke model User
return $this->hasMany('App\User');
}
}
<file_sep>/data_tower.sql
-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 16, 2020 at 03:47 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `data_tower`
--
-- --------------------------------------------------------
--
-- Table structure for table `desas`
--
CREATE TABLE `desas` (
`id` int(10) UNSIGNED NOT NULL,
`id_desa` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`desa` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_kec` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `desas`
--
INSERT INTO `desas` (`id`, `id_desa`, `desa`, `id_kec`, `created_at`, `updated_at`) VALUES
(2, '35.09.01.2001', 'Padomasan', '35.09.01', NULL, NULL),
(3, '35.09.01.2002', 'Keting', '35.09.01', NULL, NULL),
(4, '35.09.01.2003', 'Jombang', '35.09.01', NULL, NULL),
(5, '35.09.01.2004', 'Ngampelrejo', '35.09.01', NULL, NULL),
(6, '35.09.01.2005', 'Wringinagung', '35.09.01', NULL, NULL),
(7, '35.09.02.2001', 'Cakru', '35.09.02', NULL, NULL),
(8, '35.09.02.2002', 'Paseban', '35.09.02', NULL, NULL),
(9, '35.09.02.2003', 'Kraton', '35.09.02', NULL, NULL),
(10, '35.09.02.2004', 'Kencong', '35.09.02', NULL, NULL),
(11, '35.09.02.2005', ' Wonorejo', '35.09.02', NULL, NULL),
(12, '35.09.03.2001', 'Jamintoro', '35.09.03', NULL, NULL),
(13, '35.09.03.2002', 'Jatiroto', '35.09.03', NULL, NULL),
(14, '35.09.03.2003', 'Kaliglagah', '35.09.03', NULL, NULL),
(15, '35.09.03.2004', 'Jambesari', '35.09.03', NULL, NULL),
(16, '35.09.03.2005', 'Yosorati', '35.09.03', NULL, NULL),
(17, '35.09.03.2006', ' Sumberagung', '35.09.03', NULL, NULL),
(18, '35.09.03.2007', 'Gelang', '35.09.03', NULL, NULL),
(19, '35.09.03.2008', 'Rowotengah', '35.09.03', NULL, NULL),
(20, '35.09.03.2009', 'Pringgowirawan', '35.09.03', NULL, NULL),
(21, '35.09.03.2010', 'Karangbayat', '35.09.03', NULL, NULL),
(22, '35.09.04.2001', 'Kepanjen', '35.09.04', NULL, NULL),
(23, '35.09.04.2002', 'Mayangan', '35.09.04', NULL, NULL),
(24, '35.09.04.2003', 'Gumukmas', '35.09.04', NULL, NULL),
(25, '35.09.04.2004', ' Menambu', '35.09.04', NULL, NULL),
(26, '35.09.04.2005', 'Tembokrejo', '35.09.04', NULL, NULL),
(27, '35.09.04.2006', 'Purwoasri', '35.09.04', NULL, NULL),
(28, '35.09.04.2007', 'Bagorejo', '35.09.04', NULL, NULL),
(29, '35.09.05.2001', 'Sukoreno', '35.09.05', NULL, NULL),
(30, '35.09.05.2002', 'Sidorejo', '35.09.05', NULL, NULL),
(31, '35.09.05.2003', 'Gunungsari', '35.09.05', NULL, NULL),
(32, '35.09.05.2004', 'Gadingrejo', '35.09.05', NULL, NULL),
(33, '35.09.05.2005', 'Umbulrejo', '35.09.05', NULL, NULL),
(34, '35.09.05.2006', 'Umbulsari', '35.09.05', NULL, NULL),
(35, '35.09.05.2007', 'Tanjungsari', '35.09.05', NULL, NULL),
(36, '35.09.05.2008', 'Tegalwangi', '35.09.05', NULL, NULL),
(37, '35.09.05.2009', 'Paleran', '35.09.05', NULL, NULL),
(38, '35.09.06.2001', 'Tanggulkulon', '35.09.06', NULL, NULL),
(39, '35.09.06.2002', 'Tanggulwetan', '35.09.06', NULL, NULL),
(40, '35.09.06.2003', 'Patemon', '35.09.06', NULL, NULL),
(41, '35.09.06.2004', 'Darungan', '35.09.06', NULL, NULL),
(42, '35.09.06.2005', ' Manggisan', '35.09.06', NULL, NULL),
(43, '35.09.06.2006', 'Selodakon', '35.09.06', NULL, NULL),
(44, '35.09.06.2007', '<NAME>', '35.09.06', NULL, NULL),
(45, '35.09.06.2008', ' Klatakan', '35.09.06', NULL, NULL),
(46, '35.09.07.2001', 'Pondokjoyo', '35.09.07', NULL, NULL),
(47, '35.09.07.2002', 'Pondokdalem', '35.09.07', NULL, NULL),
(48, '35.09.07.2003', 'Rejoagung', '35.09.07', NULL, NULL),
(49, '35.09.07.2004', 'Semboro', '35.09.07', NULL, NULL),
(50, '35.09.07.2005', 'Sidomekar', '35.09.07', NULL, NULL),
(51, '35.09.07.2006', 'Sidomulyo', '35.09.07', NULL, NULL),
(52, '35.09.08.2001', 'Mlokorejo', '35.09.08', NULL, NULL),
(53, '35.09.08.2002', 'Mojomulyo', '35.09.08', NULL, NULL),
(54, '35.09.08.2003', 'Mojosari', '35.09.08', NULL, NULL),
(55, '35.09.08.2004', 'Pugerkulon', '35.09.08', NULL, NULL),
(56, '35.09.08.2005', 'Wringintelu', '35.09.08', NULL, NULL),
(57, '35.09.08.2006', 'Kasiyan', '35.09.08', NULL, NULL),
(58, '35.09.08.2007', ' Bagon', '35.09.08', NULL, NULL),
(59, '35.09.08.2008', ' <NAME>', '35.09.08', NULL, NULL),
(60, '35.09.08.2009', 'Wonosari', '35.09.08', NULL, NULL),
(61, '35.09.08.2010', 'Jambearum', '35.09.08', NULL, NULL),
(62, '35.09.08.2011', 'Grenden', '35.09.08', NULL, NULL),
(63, '35.09.08.2012', 'Pugerwetan', '35.09.08', NULL, NULL),
(64, '35.09.08.2013', 'Lampeji', '35.09.08', NULL, NULL),
(65, '35.09.08.2014', 'Kawangrejo', '35.09.08', NULL, NULL),
(66, '35.09.08.2015', '<NAME>', '35.09.08', NULL, NULL),
(67, '35.09.09.2001', 'Curahkalong', '35.09.09', NULL, NULL),
(68, '35.09.09.2002', 'Gambirono', '35.09.09', NULL, NULL),
(69, '35.09.09.2003', ' Bangsalsari', '35.09.09', NULL, NULL),
(70, '35.09.09.2004', 'Tugusari', '35.09.09', NULL, NULL),
(71, '35.09.09.2005', 'Karangsono', '35.09.09', NULL, NULL),
(72, '35.09.09.2006', 'Sukorejo', '35.09.09', NULL, NULL),
(73, '35.09.09.2007', ' Langkap', '35.09.09', NULL, NULL),
(74, '35.09.09.2008', 'Tisnogambar', '35.09.09', NULL, NULL),
(75, '35.09.09.2009', ' Petung', '35.09.09', NULL, NULL),
(76, '35.09.09.2010', ' Banjarsari', '35.09.09', NULL, NULL),
(77, '35.09.09.2011', 'Badean', '35.09.09', NULL, NULL),
(78, '35.09.09.2012', 'Bedadung', '35.09.09', NULL, NULL),
(79, '35.09.09.2013', 'Patemon', '35.09.09', NULL, NULL),
(80, '35.09.10.2001', 'Karangduren', '35.09.10', NULL, NULL),
(81, '35.09.10.2002', ' <NAME>', '35.09.10', NULL, NULL),
(82, '35.09.10.2003', ' Tutul', '35.09.10', NULL, NULL),
(83, '35.09.10.2004', ' Balungkulon', '35.09.10', NULL, NULL),
(84, '35.09.10.2005', 'Balunglor', '35.09.10', NULL, NULL),
(85, '35.09.10.2006', 'Balungkidul', '35.09.10', NULL, NULL),
(86, '35.09.10.2007', 'Curahlele', '35.09.10', NULL, NULL),
(87, '35.09.10.2008', 'Gumelar', '35.09.10', NULL, NULL),
(88, '35.09.11.2001', 'Lojejer', '35.09.11', NULL, NULL),
(89, '35.09.11.2002', 'Ampel', '35.09.11', NULL, NULL),
(90, '35.09.11.2003', 'Tamansari', '35.09.11', NULL, NULL),
(91, '35.09.11.2004', 'Dukuhdempok', '35.09.11', NULL, NULL),
(92, '35.09.11.2005', ' Glundengan', '35.09.11', NULL, NULL),
(93, '35.09.11.2006', 'Tanjungrejo', '35.09.11', NULL, NULL),
(94, '35.09.11.2007', 'Kesilir', '35.09.11', NULL, NULL),
(95, '35.09.12.2001', 'Tegalsari', '35.09.12', NULL, NULL),
(96, '35.09.12.2002', 'Sabrang', '35.09.12', NULL, NULL),
(97, '35.09.12.2003', 'Sumberejo', '35.09.12', NULL, NULL),
(98, '35.09.12.2004', 'Ambulu', '35.09.12', NULL, NULL),
(99, '35.09.12.2005', 'Karanganyar', '35.09.12', NULL, NULL),
(100, '35.09.12.2006', 'Andongsari', '35.09.12', NULL, NULL),
(101, '35.09.12.2007', ' Pontang', '35.09.12', NULL, NULL),
(102, '35.09.13.2001', 'Nogosari', '35.09.13', NULL, NULL),
(103, '35.09.13.2002', 'Curahmalang', '35.09.13', NULL, NULL),
(104, '35.09.13.2003', 'Rowotamtu', '35.09.13', NULL, NULL),
(105, '35.09.13.2004', 'Kaliwining', '35.09.13', NULL, NULL),
(106, '35.09.13.2005', 'Pecoro', '35.09.13', NULL, NULL),
(107, '35.09.13.2006', 'Rambipuji', '35.09.13', NULL, NULL),
(108, '35.09.13.2007', 'Gugut', '35.09.13', NULL, NULL),
(109, '35.09.13.2008', 'Rambigundam', '35.09.13', NULL, NULL),
(110, '35.09.14.2001', 'Pakis', '35.09.14', NULL, NULL),
(111, '35.09.14.2002', '<NAME>', '35.09.14', NULL, NULL),
(112, '35.09.14.2003', 'Panti', '35.09.14', NULL, NULL),
(113, '35.09.14.2004', 'Glagahwero', '35.09.14', NULL, NULL),
(114, '35.09.14.2005', 'Suci', '35.09.14', NULL, NULL),
(115, '35.09.14.2006', ' Kemiri', '35.09.14', NULL, NULL),
(116, '35.09.14.2007', 'Serut', '35.09.14', NULL, NULL),
(117, '35.09.14.2008', 'Glagahwetan', '35.09.14', NULL, NULL),
(118, '35.09.15.2001', 'Jubung', '35.09.15', NULL, NULL),
(119, '35.09.15.2002', 'Dukuhmencek', '35.09.15', NULL, NULL),
(120, '35.09.15.2003', 'Sukorambi', '35.09.15', NULL, NULL),
(121, '35.09.15.2004', 'Karangpring', '35.09.15', NULL, NULL),
(122, '35.09.15.2005', 'Klungkung', '35.09.15', NULL, NULL),
(123, '35.09.16.2001', 'Kemuningsarikidul', '35.09.16', NULL, NULL),
(124, '35.09.16.2002', 'Wonojati', '35.09.16', NULL, NULL),
(125, '35.09.16.2003', 'Jenggawah', '35.09.16', NULL, NULL),
(126, '35.09.16.2004', 'Kertonegoro', '35.09.16', NULL, NULL),
(127, '35.09.16.2005', 'Sruni', '35.09.16', NULL, NULL),
(128, '35.09.16.2006', 'Jatisari', '35.09.16', NULL, NULL),
(129, '35.09.16.2007', 'Jatimulyo', '35.09.16', NULL, NULL),
(130, '35.09.16.2008', 'Cangkring', '35.09.16', NULL, NULL),
(131, '35.09.17.2001', 'Sukamakmur', '35.09.17', NULL, NULL),
(132, '35.09.17.2002', 'Mangaran', '35.09.17', NULL, NULL),
(133, '35.09.17.2003', 'Pancakarya', '35.09.17', NULL, NULL),
(134, '35.09.17.2004', 'Ajung', '35.09.17', NULL, NULL),
(135, '35.09.17.2005', 'Klompangan', '35.09.17', NULL, NULL),
(136, '35.09.17.2006', 'Wirowongso', '35.09.17', NULL, NULL),
(137, '35.09.17.2007', ' Rowoindah', '35.09.17', NULL, NULL),
(138, '35.09.18.2001', 'Sidodadi', '35.09.18', NULL, NULL),
(139, '35.09.18.2002', 'Tempurejo', '35.09.18', NULL, NULL),
(140, '35.09.18.2003', 'Andongrejo', '35.09.18', NULL, NULL),
(141, '35.09.18.2004', 'Pondokrejo', '35.09.18', NULL, NULL),
(142, '35.09.18.2005', 'Wonoasri', '35.09.18', NULL, NULL),
(143, '35.09.18.2006', 'Curahnongko\n', '35.09.18', NULL, NULL),
(144, '35.09.18.2007', 'Curahtakir', '35.09.18', NULL, NULL),
(145, '35.09.18.2008', 'Sanenrejo\n', '35.09.18', NULL, NULL),
(146, '35.09.19.1001', 'Mangli', '35.09.19', NULL, NULL),
(147, '35.09.19.1002', 'Sempusari', '35.09.19', NULL, NULL),
(148, '35.09.19.1003', 'Kebonagung', '35.09.19', NULL, NULL),
(149, '35.09.19.1004', 'Kaliwates', '35.09.19', NULL, NULL),
(150, '35.09.19.1005', 'Jemberkidul', '35.09.19', NULL, NULL),
(151, '35.09.19.1006', 'Kepatihan', '35.09.19', NULL, NULL),
(152, '35.09.19.1007', 'Tegalbesar', '35.09.19', NULL, NULL),
(153, '35.09.20.1001', 'Banjarsengon', '35.09.20', NULL, NULL),
(154, '35.09.20.1002', 'Jumerto', '35.09.20', NULL, NULL),
(155, '35.09.20.1003', 'Gebang', '35.09.20', NULL, NULL),
(156, '35.09.20.1004', 'Slawu', '35.09.20', NULL, NULL),
(157, '35.09.20.1005', 'Bintoro', '35.09.20', NULL, NULL),
(158, '35.09.20.1006', 'Jemberlor', '35.09.20', NULL, NULL),
(159, '35.09.20.1007', 'Patrang', '35.09.20', NULL, NULL),
(160, '35.09.20.1008', 'Baratan', '35.09.20', NULL, NULL),
(161, '35.09.21.1001', 'Kebonsari', '35.09.21', NULL, NULL),
(162, '35.09.21.1002', 'Sumbersari', '35.09.21', NULL, NULL),
(163, '35.09.21.1003', ' Kranjingan', '35.09.21', NULL, NULL),
(164, '35.09.21.1004', 'Karangrejo', '35.09.21', NULL, NULL),
(165, '35.09.21.1005', 'Tegalgede', '35.09.21', NULL, NULL),
(166, '35.09.21.1006', 'Wirolegi', '35.09.21', NULL, NULL),
(167, '35.09.21.1007', 'Antirogo', '35.09.21', NULL, NULL),
(168, '35.09.22.2001', 'Kemuninglor', '35.09.22', NULL, NULL),
(169, '35.09.22.2002', 'Darsono', '35.09.22', NULL, NULL),
(170, '35.09.22.2003', 'Arjasa', '35.09.22', NULL, NULL),
(171, '35.09.22.2004', 'Candijati', '35.09.22', NULL, NULL),
(172, '35.09.22.2005', 'Biting', '35.09.22', NULL, NULL),
(173, '35.09.22.2006', 'Kamal', '35.09.22', NULL, NULL),
(174, '35.09.23.2001', 'Lengkong', '35.09.23', NULL, NULL),
(175, '35.09.23.2002', 'Kawangrejo', '35.09.23', NULL, NULL),
(176, '35.09.23.2003', 'Tamansari', '35.09.23', NULL, NULL),
(177, '35.09.23.2004', 'Mumbulsari', '35.09.23', NULL, NULL),
(178, '35.09.23.2005', 'Suco', '35.09.23', NULL, NULL),
(179, '35.09.23.2006', 'Lampeji', '35.09.23', NULL, NULL),
(180, '35.09.23.2007', '<NAME>', '35.09.23', NULL, NULL),
(181, '35.09.23.2008', 'Bagon', '35.09.23', NULL, NULL),
(182, '35.09.23.2009', 'Jambearum', '35.09.23', NULL, NULL),
(183, '35.09.23.2010', 'Kasiyan', '35.09.23', NULL, NULL),
(184, '35.09.23.2011', '<NAME>', '35.09.23', NULL, NULL),
(185, '35.09.23.2012', 'Mojokerto', '35.09.23', NULL, NULL),
(186, '35.09.23.2013', 'Wonosari', '35.09.23', NULL, NULL),
(187, '35.09.23.2014', '<NAME>', '35.09.23', NULL, NULL),
(188, '35.09.24.2001', 'Patemon', '35.09.24', NULL, NULL),
(189, '35.09.24.2002', 'Bedadung', '35.09.24', NULL, NULL),
(190, '35.09.24.2003', 'Sumberpinang', '35.09.24', NULL, NULL),
(191, '35.09.24.2004', 'Subo', '35.09.24', NULL, NULL),
(192, '35.09.24.2005', 'Kertosari', '35.09.24', NULL, NULL),
(193, '35.09.24.2006', 'Jatian', '35.09.24', NULL, NULL),
(194, '35.09.24.2007', 'Pakusari', '35.09.24', NULL, NULL),
(195, '35.09.25.2001', 'Sucopangepok', '35.09.25', NULL, NULL),
(196, '35.09.25.2002', 'Panduman', '35.09.25', NULL, NULL),
(197, '35.09.25.2003', 'Sukojember', '35.09.25', NULL, NULL),
(198, '35.09.25.2004', 'Jelbuk', '35.09.25', NULL, NULL),
(199, '35.09.25.2005', 'Sukowiryo', '35.09.25', NULL, NULL),
(200, '35.09.25.2006', 'Sugerkidul', '35.09.25', NULL, NULL),
(201, '35.09.26.2001', ' Mrawan', '35.09.26', NULL, NULL),
(202, '35.09.26.2002', 'Mayang', '35.09.26', NULL, NULL),
(203, '35.09.26.2003', 'Seputih', '35.09.26', NULL, NULL),
(204, '35.09.26.2004', 'Tegalwaru', '35.09.26', NULL, NULL),
(205, '35.09.26.2005', 'Tegalrejo', '35.09.26', NULL, NULL),
(206, '35.09.26.2006', 'Sumberkejayan', '35.09.26', NULL, NULL),
(207, '35.09.26.2007', ' Sidomukti', '35.09.26', NULL, NULL),
(208, '35.09.27.2001', 'Gumuksari', '35.09.27', NULL, NULL),
(209, '35.09.27.2002', 'Sukoreno', '35.09.27', NULL, NULL),
(210, '35.09.27.2003', 'Patempuran', '35.09.27', NULL, NULL),
(211, '35.09.27.2004', 'Sumberkalong', '35.09.27', NULL, NULL),
(212, '35.09.27.2005', 'Sumberjeruk', '35.09.27', NULL, NULL),
(213, '35.09.27.2006', 'Glagahwero', '35.09.27', NULL, NULL),
(214, '35.09.27.2007', 'Kalisat', '35.09.27', NULL, NULL),
(215, '35.09.27.2008', 'Ajung', '35.09.27', NULL, NULL),
(216, '35.09.27.2009', 'Plalangan', '35.09.27', NULL, NULL),
(217, '35.09.27.2010', 'Gambiran', '35.09.27', NULL, NULL),
(218, '35.09.27.2011', 'Sumberketempa', '35.09.27', NULL, NULL),
(219, '35.09.27.2012', 'Sebanen', '35.09.27', NULL, NULL),
(220, '35.09.28.2001', 'Lembengan', '35.09.28', NULL, NULL),
(221, '35.09.28.2002', 'Suren', '35.09.28', NULL, NULL),
(222, '35.09.28.2003', 'Karangpaiton', '35.09.28', NULL, NULL),
(223, '35.09.28.2004', 'Sumberanget', '35.09.28', NULL, NULL),
(224, '35.09.28.2005', 'Sukogidri', '35.09.28', NULL, NULL),
(225, '35.09.28.2006', 'Ledokombo', '35.09.28', NULL, NULL),
(226, '35.09.28.2007', 'Sumberlesung', '35.09.28', NULL, NULL),
(227, '35.09.28.2008', 'Sumbersalak', '35.09.28', NULL, NULL),
(228, '35.09.28.2009', 'Slateng', '35.09.28', NULL, NULL),
(229, '35.09.28.2010', 'Sumberbulus', '35.09.28', NULL, NULL),
(230, '35.09.29.2001', 'Sumberwringin', '35.09.29', NULL, NULL),
(231, '35.09.29.2002', 'Sukokerto', '35.09.29', NULL, NULL),
(232, '35.09.29.2003', 'Sumberwaru', '35.09.29', NULL, NULL),
(233, '35.09.29.2004', 'Sukowono', '35.09.29', NULL, NULL),
(234, '35.09.29.2005', 'Baletbaru', '35.09.29', NULL, NULL),
(235, '35.09.29.2006', 'Sukorejo', '35.09.29', NULL, NULL),
(236, '35.09.29.2007', 'Sukosari', '35.09.29', NULL, NULL),
(237, '35.09.29.2008', 'Arjasa', '35.09.29', NULL, NULL),
(238, '35.09.29.2009', 'Sumberdanti', '35.09.29', NULL, NULL),
(239, '35.09.29.2010', 'Pocangan', '35.09.29', NULL, NULL),
(240, '35.09.29.2011', ' Dawuhanmangli', '35.09.29', NULL, NULL),
(241, '35.09.29.2012', 'Mojogemi', '35.09.29', NULL, NULL),
(242, '35.09.30.2001', 'Sempolan', '35.09.30', NULL, NULL),
(243, '35.09.30.2002', 'Harjomulyo', '35.09.30', NULL, NULL),
(244, '35.09.30.2003', 'Karangharjo', '35.09.30', NULL, NULL),
(245, '35.09.30.2004', 'Silo', '35.09.30', NULL, NULL),
(246, '35.09.30.2005', 'Pace', '35.09.30', NULL, NULL),
(247, '35.09.30.2006', 'Mulyorejo', '35.09.30', NULL, NULL),
(248, '35.09.30.2007', 'Sumberjati', '35.09.30', NULL, NULL),
(249, '35.09.30.2008', 'Garahan', '35.09.30', NULL, NULL),
(250, '35.09.30.2009', 'Sidomulyo', '35.09.30', NULL, NULL),
(251, '35.09.31.2001', 'Plerean', '35.09.31', NULL, NULL),
(252, '35.09.31.2002', 'Sumberpakem', '35.09.31', NULL, NULL),
(253, '35.09.31.2003', 'Pringgondani', '35.09.31', NULL, NULL),
(254, '35.09.31.2004', 'Randuagung', '35.09.31', NULL, NULL),
(255, '35.09.31.2005', 'Cumedak', '35.09.31', NULL, NULL),
(256, '35.09.31.2006', 'Sumberjambe', '35.09.31', NULL, NULL),
(257, '35.09.31.2007', 'Gunungmalang', '35.09.31', NULL, NULL),
(258, '35.09.31.2008', 'Jambearum', '35.09.31', NULL, NULL),
(259, '35.09.31.2009', 'Rowosari', '35.09.31', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `fotos`
--
CREATE TABLE `fotos` (
`id` bigint(20) UNSIGNED NOT NULL,
`foto` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `fotos`
--
INSERT INTO `fotos` (`id`, `foto`, `created_at`, `updated_at`) VALUES
(1, '1563508684409074-PDETI8-256.jpg', '2019-07-18 20:58:04', '2019-07-18 20:58:04'),
(2, '1563508722409074-PDETI8-256.jpg', '2019-07-18 20:58:42', '2019-07-18 20:58:42'),
(3, '1563711857library.png', '2019-07-21 05:24:17', '2019-07-21 05:24:17'),
(4, '156371196557088144_1027933214068866_3570791210953998336_n.jpg', '2019-07-21 05:26:05', '2019-07-21 05:26:05'),
(5, '1563715949Screenshot_2019-07-21-19-45-55-132_com.instagram.android.png', '2019-07-21 06:32:29', '2019-07-21 06:32:29'),
(6, '1563935763kelebihan dan kelemahan honda beat.png', '2019-07-23 19:36:03', '2019-07-23 19:36:03');
-- --------------------------------------------------------
--
-- Table structure for table `jenis__towers`
--
CREATE TABLE `jenis__towers` (
`id` bigint(20) UNSIGNED NOT NULL,
`nama_tower` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `jenis__towers`
--
INSERT INTO `jenis__towers` (`id`, `nama_tower`, `created_at`, `updated_at`) VALUES
(1, 'BTS', NULL, NULL),
(2, 'Radio', NULL, NULL),
(3, 'CCTV', NULL, NULL),
(4, 'Lain-Lain', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `kecamatans`
--
CREATE TABLE `kecamatans` (
`id` int(10) UNSIGNED NOT NULL,
`id_kecamatan` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`kecamatan` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `kecamatans`
--
INSERT INTO `kecamatans` (`id`, `id_kecamatan`, `kecamatan`, `created_at`, `updated_at`) VALUES
(2, '35.09.01', 'Jombang', NULL, NULL),
(3, '35.09.02', 'Kencong', NULL, NULL),
(4, '35.09.03', 'Sumberbaru', NULL, NULL),
(5, '35.09.04', 'Gumukmas', NULL, NULL),
(6, '35.09.05', 'Umbulsari', NULL, NULL),
(7, '35.09.06', 'Tanggul', NULL, NULL),
(8, '35.09.07', 'Semboro', NULL, NULL),
(9, '35.09.08', 'Puger', NULL, NULL),
(10, '35.09.09', 'Bangsalsari', NULL, NULL),
(11, '35.09.10', 'Balung', NULL, NULL),
(12, '35.09.11', 'Wuluhan', NULL, NULL),
(13, '35.09.12', 'Ambulu', NULL, NULL),
(14, '35.09.13', 'Rambipuji', NULL, NULL),
(15, '35.09.14', 'Panti', NULL, NULL),
(16, '35.09.15', 'Sukorambi', NULL, NULL),
(17, '35.09.16', 'Jenggawah', NULL, NULL),
(18, '35.09.17', 'Ajung', NULL, NULL),
(19, '35.09.18', 'Tempurejo', NULL, NULL),
(20, '35.09.19', 'Kaliwates', NULL, NULL),
(21, '35.09.20', 'Patrang', NULL, NULL),
(22, '35.09.21', 'Sumbersari', NULL, NULL),
(23, '35.09.22', 'Arjasa', NULL, NULL),
(24, '35.09.23', 'Mumbulsari', NULL, NULL),
(25, '35.09.24', 'Pakusari', NULL, NULL),
(26, '35.09.25', 'Jelbuk', NULL, NULL),
(27, '35.09.26', 'Mayang', NULL, NULL),
(28, '35.09.27', 'Kalisat', NULL, NULL),
(29, '35.09.28', 'Ledokombo', NULL, NULL),
(30, '35.09.29', 'Sukowono', NULL, NULL),
(31, '35.09.30', 'Silo', NULL, NULL),
(32, '35.09.31', 'Sumberjambe', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2019_07_03_014937_create_towers_table', 1),
(4, '2019_07_03_020551_create_fotos_table', 1),
(5, '2019_07_03_020652_create_roles_table', 1),
(6, '2019_07_03_020739_create_desas_table', 1),
(7, '2019_07_03_020819_create_kecamatans_table', 1),
(8, '2019_07_03_020929_create_jenis__towers_table', 1),
(9, '2019_07_03_021026_create_providers_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `providers`
--
CREATE TABLE `providers` (
`id` bigint(20) UNSIGNED NOT NULL,
`nama_provider` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `providers`
--
INSERT INTO `providers` (`id`, `nama_provider`, `created_at`, `updated_at`) VALUES
(1, 'Telkomsel', NULL, NULL),
(2, 'Indosat', NULL, NULL),
(3, 'XL', NULL, NULL),
(4, 'Axis', NULL, NULL),
(5, 'Smartfren', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `roles`
--
CREATE TABLE `roles` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `roles`
--
INSERT INTO `roles` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'admin', NULL, NULL),
(2, 'user', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `towers`
--
CREATE TABLE `towers` (
`id` bigint(20) UNSIGNED NOT NULL,
`nama_tower` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`alamat` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`rt` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`rw` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_kec` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_desa` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`koor_lat` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`koor_leng` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`tinggi` int(11) NOT NULL,
`nama_pemilik_tower` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`tanggal_imb` date NOT NULL,
`id_provider1` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_provider2` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`id_provider3` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`ket_pemilik` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`akhir_sewa` date NOT NULL,
`nama_pemilik_lahan` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_jenis_tower` int(11) NOT NULL,
`id_foto` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`id_user` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `towers`
--
INSERT INTO `towers` (`id`, `nama_tower`, `alamat`, `rt`, `rw`, `id_kec`, `id_desa`, `koor_lat`, `koor_leng`, `tinggi`, `nama_pemilik_tower`, `tanggal_imb`, `id_provider1`, `id_provider2`, `id_provider3`, `ket_pemilik`, `akhir_sewa`, `nama_pemilik_lahan`, `id_jenis_tower`, `id_foto`, `id_user`, `created_at`, `updated_at`) VALUES
(1, '<NAME>', 'Jember', '1', '1', '35.09.19', '35.09.19.1006', '-8.1723181', '113.70211429999999', 25, '', '2019-07-19', '1', '', '', 'Kominfo', '2019-07-19', 'Kominfo', 1, '2', NULL, '2019-07-18 20:58:42', '2019-07-18 20:58:42'),
(2, 'Kos', 'Jember', '1', '1', '35.09.21', '35.09.21.1001', '-8.1924373', '113.70376809999999', 25, '', '2019-07-21', '1', '', '', 'sewa', '2019-07-21', 'admin', 1, '4', NULL, '2019-07-21 05:26:05', '2019-07-21 05:26:05'),
(4, '<NAME>', 'Jember', '1', '1', '35.09.04', '35.09.04.2002', '-8.1722932', '113.7021115', 20, 'admin', '2019-07-24', '2', '3', '4', 'Sewa Telkom', '2019-07-24', 'Admin', 2, '2', NULL, '2019-07-23 19:30:49', '2019-07-23 19:30:49'),
(5, 'angga', 'aaaa', '1', '1', '35.09.23', '35.09.23.2010', '-8.287816549424495', '113.75051120830085', 1, '1', '2019-07-24', '1', '1', '1', '1', '2019-07-24', '1', 1, '6', NULL, '2019-07-23 19:36:03', '2019-07-23 19:36:03');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`role_id` int(11) DEFAULT NULL,
`nama` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`username` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `role_id`, `nama`, `username`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(2, 1, 'angga dwi', 'angga', '$2y$10$bu/rEJXLdvtsratXezZyDuk2oExSVLtZJTOpvXCRk<PASSWORD>/iRSczxC', NULL, '2019-07-18 20:41:54', '2019-07-18 20:41:54'),
(3, 2, 'khoirul anam', 'anam', '$2y$10$nwJ6jQioUUG4d2C2Cstm6.jXV5I5ma2e4FCtNXBXVpN4ekl8ljA1m', NULL, '2019-07-22 19:00:28', '2019-07-22 19:00:28'),
(5, 2, 'Ang<NAME>', 'angga1', '$2y$10$uCyWS4ka69Hw5fNUtVvIh.pVqNB478c9vhz8BsQcqlh6hnuPuOssG', NULL, '2019-07-25 20:04:12', '2019-07-25 20:04:12');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `desas`
--
ALTER TABLE `desas`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `desas_id_desa_unique` (`id_desa`);
--
-- Indexes for table `fotos`
--
ALTER TABLE `fotos`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `jenis__towers`
--
ALTER TABLE `jenis__towers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `kecamatans`
--
ALTER TABLE `kecamatans`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `kecamatans_id_unique` (`id`),
ADD UNIQUE KEY `kecamatans_id_kecamatan_unique` (`id_kecamatan`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indexes for table `providers`
--
ALTER TABLE `providers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `roles`
--
ALTER TABLE `roles`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `towers`
--
ALTER TABLE `towers`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `koor_lat` (`koor_lat`,`koor_leng`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `desas`
--
ALTER TABLE `desas`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=260;
--
-- AUTO_INCREMENT for table `fotos`
--
ALTER TABLE `fotos`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `jenis__towers`
--
ALTER TABLE `jenis__towers`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `kecamatans`
--
ALTER TABLE `kecamatans`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `providers`
--
ALTER TABLE `providers`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `roles`
--
ALTER TABLE `roles`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `towers`
--
ALTER TABLE `towers`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/app/Http/Controllers/TowersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tower;
use App\Desa;
use App\Kecamatan;
use App\Provider;
use App\Jenis_Tower;
use App\Foto;
use PDF;
use Alert;
class TowersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
//membuat fungsi index untuk halaman index data tower.
public function index()
{
//mengambil tabel desa dari database.
$data_desa = Desa::all();
//mengambil tabel kecamatan dari database dan disortir urut dari abjad paling atas.
$kecamatan = Kecamatan::orderBy('kecamatan', 'ASC')->get();
//menampilkan data duplikasi hanya muncul 1 kali.
$data_kec = Tower::distinct()->get(['id_kec']);
//mengambil tabel tower dari database.
$towers = Tower::all();
//menghitung data pada tabel tower berdasarkan id kecamatan dan id jenis tower.
$radio = Tower::where('id_kec','35.09.01')->where('id_jenis_tower','1')->count();
//menampilkan halaman hasil data tower.
return view('hasil', compact('towers','data_kec','data_desa','kecamatan','radio'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
//membuat funngsi create untuk halaman Tambah Tower
public function create()
{
//mengambil tabel desa dari database.
$data_desa = Desa::all();
//mengambil tabel kecamatan dari database dan disortir urut dari abjad paling atas.
$data_kec = Kecamatan::orderBy('kecamatan', 'ASC')->get();
//mengambil tabel provider dari database.
$data_provider = Provider::all();
//mengambil tabel jenis tower dari database.
$data_jenis_tower = Jenis_Tower::all();
//mengambil tabel tower dari database.
$towers = Tower::all();
//menampilkan halaman tambah data tower.
return view('tambah', compact('towers','data_kec','data_desa','data_provider','data_jenis_tower'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
//membuat fungsi store untuk input data tower
public function store(Request $request)
{
//
//membuat validasi pada semua input harus diisi.
$this->validate($request,[
'nama_tower' => 'required',
'alamat' => 'required',
'rt' => 'required',
'rw' => 'required',
'id_kec' => 'required',
'id_desa' => 'required',
'koor_lat' => 'required|unique:towers,koor_lat',
'koor_leng' => 'required|unique:towers,koor_leng',
'tinggi' => 'required',
'tanggal_imb' => 'required',
'id_provider1' => 'required',
'ket_pemilik' => 'required',
'akhir_sewa' => 'required',
'nama_pemilik_tower' => 'required',
'nama_pemilik_lahan' => 'required',
'id_jenis_tower' => 'required',
]);
//mengambil data dari inputan dan disimpan ke database.
$input = $request->all();
//jika mengirim file dengan id foto
if($file = $request->file('id_foto')){
//menggunakan nama dari file yang di di upload dengan original(tanoa duplikat).
$name = time(). $file->getClientOriginalName();
//memindah file ke folder images yang dibuat.
$file->move('images',$name);
//menggunakan variabel foto mengambil dari model Foto
$photo = Foto::create(['foto'=>$name]);
//menggunakan variabel input untuk mengambil id foto disimpan ke tabel tower.
$input['id_foto'] = $photo->id;
}
//menyimpan variabet input ke tabel Tower.
Tower::create($input);
//jika berhasil maka akan menampilkan alert sukses dan diarahkan ke tampilan halaman tambah.
Alert::success("Berhasil");
return redirect('/tower/create');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//membuat fungsi show untuk menampilkan halaman hasil dari input data tower.
public function show($id)
{
//menampilakn tabel tower dengan mengambil id kecamtan.
$towers = Tower::where('id_kec',$id)->get();
//menampilakn tabel desa dengan sortir menggunakan abjad paling atas.
$data = Desa::orderBy('desa','ASC')->where('id_kec',$id)->get();
//menampilkan tabel kecamatan dengan id kecamatan.
$kecamatan = Kecamatan::where('id_kecamatan',$id)->get();
//menampilkan halaman data tower.
return view('data',compact('data','towers','id','kecamatan'));
//return $towers;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//membuat fungsi edit untuk melakukan edit data tower.
public function edit($id)
{
//menampilkan tabel tower berdasarkan id desa
$towers = Tower::where('id_desa',$id)->get();
//menampilkan halaman edit
return view('edit',compact('towers'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
//membuat fungsi update untuk melakukan update data tower.
public function update(Request $request, $id)
{
//menampilkan tabel tower
$tower = Tower::findOrFail($id);
//validasi pada semua inputan harus diisi.
$this->validate($request,[
'nama_tower' => 'required',
'alamat' => 'required',
'rt' => 'required',
'rw' => 'required',
'id_kec' => 'required',
'id_desa' => 'required',
'koor_lat' => 'required',
'koor_leng' => 'required',
'tinggi' => 'required',
'tanggal_imb' => 'required',
'id_provider1' => 'required',
'ket_pemilik' => 'required',
'akhir_sewa' => 'required',
'nama_pemilik_tower' => 'required',
'nama_pemilik_lahan' => 'required',
'id_jenis_tower' => 'required',
//validasi inputan harus diisi dengan type file yang ditentukan.
'id_foto' => 'required|image|mimes:jpg,png,gif,jpeg,svg',
]);
//mengirim inputan dan disimpan kedalam database.
$input = $request->all();
//jika mengirim file dengan id foto
if($file = $request->file('id_foto')){
//menggunakan nama dari file yang di di upload dengan original(tanoa duplikat).
$name = time().$file->getClientOriginalName();
//memindah file ke folder images yang dibuat.
$file->move('images',$name);
//menggunakan variabel foto dan mengambil dari model Foto
$photo = Foto::create(['foto'=>$name]);
//menggunakan variabel input untuk mengambil id foto disimpan ke tabel tower.
$input['id_foto'] = $photo->id;
}
//melakukan update pada data tower
$tower->update($input);
//menmpilkan berhasil dengan alert sukses dan kembali ke halaman terkahir kali di akses.
Alert::success("Berhasil");
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//membuat fungsi destroy untuk melakukan hapus data tower.
public function destroy($id)
{
//mencari data dari tabel tower
$towers = Tower::findOrFail($id);
//melakukan aksi delete pada data tower
$towers->delete();
//menampilkan berhasil dengan alert sukses dan menampilkan halaman terakhir di akses.
Alert::success("Berhasil");
return redirect()->back();
}
//membuat fungsi desa untuk menampilkan list data desa
public function desa(Request $request){
//menampilkan tabel desa dengan dari id kecamatan.
$desa = Desa::where('id_kec',$request->id)->get();
//mengembalikan data dalam bentuk json.
return response()->json($desa);
}
//membuat fungsi prosesEdit untuk melakukan proses edit data tower.
public function prosesEdit($id){
//mengambil tabel desa dari database .
$data_desa = Desa::all();
//mencari tabel tower dari database.
$towers = Tower::findOrFail($id);
//mengambil data dari tabel desa di database.
$data_desa = Desa::all();
//mengambil tabel kecamatan dari database dan disortir urut dari abjad paling atas.
$data_kec = Kecamatan::orderBy('kecamatan', 'ASC')->get();
//mengambil tabel provider dari database .
$data_provider = Provider::all();
//mengambil tabel jenis tower dari database.
$data_jenis_tower = Jenis_Tower::all();
//menampilkan halaman update data tower.
return view('update', compact('towers','data_kec','data_desa','data_provider','data_jenis_tower'));
}
// public function lihatuser($id){
// $data_user =User::all();
// return view('user',compact('data_user'));
// }
public function cetak(){
$towers = Tower::all();
return view('cetak',compact('towers'));
}
public function cetakpdf(){
$towers = Tower::all();
$pdf = PDF::loadview('cetakpdf',compact('towers'));
return $pdf->stream();
}
}
<file_sep>/app/Desa.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Desa extends Model
{
//Relasi database dari tabel desa ke kecamatan
//fungsi kecamatan untuk menampilkan data kecamatan
public function kecamatan(){
//id_kecamatan sebagai foreign key pada tabel Desa
return $this->belongsTo('App\Kecamatan','id_kec','id_kecamatan');
}
//fungsi tower menampilkan data tower
public function tower(){
//membuat relasi one to many ke model tower.
return $this->hasMany('App\Tower');
}
}
<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
//variabel tabel untuk user
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
//mennyimpan data saat melakukan input
protected $fillable = [
'username', 'password', 'role_id', 'nama',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//Relasi database dari tabel user kerole
public function role(){
//role_id sebagai foreign key pada tabel User
return $this->belongsTo('App\Role','role_id');
}
//membuat fungsi isAdmin untuk admin
public function isAdmin(){
//jika role_name=admin maka benar
if($this->role->name == 'admin'){
return true;
}
return false;
}
//membuat fungsi isUser untuk user
public function isUser(){
//jika role_name=user maka benar
if($this->role->name == 'user'){
return true;
}
return false;
}
}
<file_sep>/app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tower;
use App\Desa;
use App\Kecamatan;
use App\Provider;
use App\Jenis_Tower;
use App\Foto;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
//membuat fungsi index untuk halaman index data tower.
public function index()
{
//mengambil tabel desa dari database .
$data_desa = Desa::all();
//mengambil tabel kecamatan dari database dan disortir urut dari abjad paling atas.
$kecamatan = Kecamatan::orderBy('kecamatan', 'ASC')->get();
//menampilkan data duplikasi hanya muncul 1 kali.
$data_kec = Tower::distinct()->get(['id_kec']);
//mengambil tabel tower dari database.
$towers = Tower::all();
//menghitung data pada tabel tower berdasarkan id kecamatan dan id jenis tower.
$radio = Tower::where('id_kec','35.09.01')->where('id_jenis_tower','1')->count();
//manmpilkan halaman user
return view('user', compact('towers','data_kec','data_desa','kecamatan','radio'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//membuat fungsi show untuk halaman hasil data tower.
public function show($id)
{
//menampilkan data tabel tower dengan id kecamatan.
$towers = Tower::where('id_kec',$id)->get();
//menampilak tabel desa dengan sortir abjad paling atas.
$data = Desa::orderBy('desa','ASC')->where('id_kec',$id)->get();
//menampilkan tabel kecamatan dengan id kecamatan.
$kecamatan = Kecamatan::where('id_kecamatan',$id)->get();
//menampilkan halaman data2
return view('data2',compact('data','towers','id','kecamatan'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//membuat fungsi edit untuk melihat detail data tower.
public function edit($id)
{
//menampilkan tabel tower dengan id desa
$towers = Tower::where('id_desa',$id)->get();
//menampilkan halaman detail.
return view('detail',compact('towers'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
use Alert;
class AuthController extends Controller
{
//
//membuat fungsi getLogin untuk menampilkan halaman Login.
public function getLogin(){
return view('login');
}
//membuat fungsi postLogin untuk melakukan proses autentikasi login.
public function postLogin(Request $request){
//proses pengecekan username dan password dari database pada saat login.
if(auth()->attempt(['username' => $request->username, 'password' => $request->password])){
//jika akun memiliki role_id=1, maka sebagai admin kemudian menuju ke halaman admin.
if(auth()->user()->role_id == 1){
return redirect()->route('tower.index');
//jika akun memiliki role_id=2, maka sebagai user kemudian menuju ke halaman user.
}
else if(auth()->user()->role_id == 2){
return redirect()->route('users.index');
}
}
//jika tidak ada akun, maka akan menampilkan halaman login.
Alert::error('Akun Tidak Ada');
return redirect()->route('halaman_login');
}
//membuat fungsi getDaftar untuk menampilkan halaman Daftar.
public function getDaftar(){
return view('daftar');
}
//membuat fungsi postLogin untuk melakukan proses autentikasi pada saat Daftar.
public function postDaftar(Request $request){
//validasi jika username, nama, passsword harud di isi.
$this->validate($request,[
'username' => 'required|unique:users,username',
'nama' => 'required',
'password' => '<PASSWORD>',
]);
//mengambil data dari inputan dan disimpan ke dalam database.
User::create([
'username'=> $request->username,
'nama'=> $request->nama,
'role_id'=> $request->role_id,
'password' => <PASSWORD>($request->password)
]);
//jika berhasil maka akan menampilakn alert sukses dan tetap dihalaman daftar.
Alert::success("Berhasil");
return redirect()->back();
}
//membuat fungsi logout untuk proses logout saat sudah login.
public function logout(){
//jika logout maka akan diarahkan ke halaman login..
auth()->logout();
return redirect()->route('halaman_login');
}
public function lihatuser(){
$users = User::all();
return view('lihatuser',compact('users'));
}
public function updateuser($id){
$users = User::findOrFail($id);;
return view('updateuser',compact('users'));
}
public function prosesupdate(Request $request, $id){
//validasi jika username, nama, passsword harud di isi.
$users = User::findOrFail($id);
$this->validate($request,[
'username' => 'required',
'nama' => 'required',
]);
if (trim($request->password) == ''){
$input = $request->except('password');
}else{
$input = $request->all();
$input['password'] = <PASSWORD>($request->password);
}
$users->update($input);
//jika berhasil maka akan menampilakn alert sukses dan tetap dihalaman daftar.
Alert::success("Berhasil");
return redirect('lihat');
}
public function hapususer($id){
$users =User::findOrFail($id);
$users->delete();
Alert::success("Berhasil");
return redirect()->back();
}
public function search(Request $request){
$cari = $request->get('search');
$users = User::where('nama','LIKE','%'.$cari.'%')->paginate(10);
return view('lihatuser', compact('users'));
}
}
<file_sep>/database/migrations/2019_07_03_014937_create_towers_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTowersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//Membuat Tabel towers
Schema::create('towers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nama_tower');
$table->string('alamat');
$table->string('rt');
$table->string('rw');
$table->string('id_kec');
$table->string('id_desa');
$table->string('koor_lat');
$table->string('koor_leng');
$table->integer('tinggi');
$table->date('tanggal_imb');
$table->integer('id_provider');
$table->string('ket_pemilik');
$table->date('akhir_sewa');
$table->string('nama_pemilik');
$table->integer('id_jenis_tower');
$table->string('id_foto');
$table->string('id_user');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('towers');
}
}
<file_sep>/routes/web.php
<?php
use App\Http\Middleware\UserAuth;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Melihat router dengan php artisan route:list
Route::get('/', function(){
return view('home');
})->middleware('guest');
//Routes untuk akses TowesController
Route::resource('tower','TowersController')->middleware(['admin','auth']);
Route::resource('users','UsersController')->middleware(['user','auth']);
Route::get('/delete/{id}','TowersController@destroy')->middleware(['admin','auth'])->name('delete');
Route::get('/hapus/{id}','AuthController@hapususer')->name('hapus');
Route::get('/desa','TowersController@desa')->middleware(['admin','auth']);
Route::get('/update/{id}','TowersController@prosesEdit')->middleware(['admin','auth'])->name('update');
Route::get('/updateuser/{id}','AuthController@updateuser')->name('updateuser');
Route::put('/prosesupdateuser/{id}','AuthController@prosesupdate')->name('prosesupdateuser');
Route::get('/login','AuthController@getLogin')->middleware('guest')->name('halaman_login');
Route::post('/login','AuthController@postLogin')->middleware('guest')->name('login');
Route::get('/daftar','AuthController@getDaftar')->middleware(['admin','auth'])->name('halaman_daftar');
Route::post('/daftar','AuthController@postDaftar')->middleware(['admin','auth'])->name('daftar');
Route::get('/lihat','AuthController@lihatuser')->name('lihat');
Route::get('/logout','AuthController@logout')->middleware('admin')->name('logout');
Route::get('/logout-user','AuthController@logout')->middleware('user')->name('logout-user');
Route::get('cariuser','AuthController@search')->name('cariuser');
Route::get('/cetak','TowersController@cetak');
Route::get('/cetakpdf', 'TowersController@cetakpdf')->name('pdf');
<file_sep>/app/Kecamatan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Kecamatan extends Model
{
//
//Relasi database dari tabel kecamatan ke desa
public function desa(){
//membuat relasi one to many ke model Desa.
return $this->hasMany('App\Desa','id_kecamatan','id_kec');
}
}
| 92edbbc298d5117101dd73ceac41786c2784f231 | [
"SQL",
"PHP"
] | 12 | PHP | anam1999/laravel_aplikasitower | aacc5a2a9c40436a5606a4d5ff664ed4523e8598 | ea255d941dbeb3ea4f7b6f52e78da3547921fa5d |
refs/heads/master | <repo_name>TheProjecter/twitterm<file_sep>/experiments/httpclient/Rakefile
# Fix for FileList
class Rake::FileList
def exclude_fl(file_list)
file_list.to_a.each { |file|
self.exclude(file)
}
end
end
require 'rake/clean'
title = 'example'
task :default => [title]
@libs = ['netclient']
# The modules we're working with
mods = FileList.new('*.ml')
mods.exclude("#{title}.ml")
mod_names = mods.ext
mod_objs = mods.ext('.ml')
mod_ints = mods.ext('.cmi')
CLOBBER.include(title, '*.mli')
CLEAN.include('*.cmo', '*.cml', '*.o', '*.out', '*.cmi', '*.cmx')
def build_cmd
"ocamlfind ocamlopt -warn-error A -package #{@libs.join(",")} -linkpkg "
end
desc "Compiles the program into a native executable"
file title => mod_objs + [ "#{title}.ml" ] + mod_ints do |t|
impls = t.prerequisites.to_a - mod_ints
sh build_cmd + "-o #{t.name} #{impls.join(" ")}"
end
rule '.cmx' => '.ml' do |t|
my_mods = FileList.new('*.cmx')
my_mods.exclude_fl(t.prerequisites)
sh build_cmd + "-c -o #{t.name} #{t.prerequisites.join(" ")} " + my_mods.to_s
end
rule '.cmi' => '.mli' do |t|
#my_mods = FileList.new('*.cmi')
#my_mods.exclude_fl(t.prerequisites)
sh build_cmd + "-c #{t.prerequisites.join(" ")} " #+ my_mods.to_s
end
rule '.mli' => '.ml' do |t|
sh build_cmd + "-i #{t.source} > #{t.name}"
end
| 50ab6df168cd1959b2dbce863f8a8653dc87f37c | [
"Ruby"
] | 1 | Ruby | TheProjecter/twitterm | 670ed0c821a05f9b65409011dc88b06fd9f79885 | 439fb4b43614da772813f8ebad6f41d9a66e9ae4 |
refs/heads/main | <repo_name>HaiTrieuNg/MovieTheaterSeatingChallenge<file_sep>/input.java
public class input {
private String o;
private String n;
public input (String orderNumber, String numberOfSeats) {
this.o = orderNumber;
this.n = numberOfSeats;
}
public String getOrderNumber () {
return this.o;
}
public String getNumberOfSeats () {
return this.n;
}
}
<file_sep>/seat.java
import java.util.*;
public class seat {
private String state;
private int index;
public seat(int index)
/**
* Constructor
*/
{
this.state = "s";
this.index = index;
}
public String getState()
/**
* return the state of the seat
*/
{
return this.state;
}
public int getIndex()
/**
* return the position of the seat in a row
*/
{
return this.index;
}
public void setTaken()
/**
* set the seat as taken
*/
{
this.state = "X";
}
public void setBuffered()
/**
* set the seat as buffer seat
*/
{
this.state = "B";
}
}
<file_sep>/findSeat.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class findSeat {
private grid g;
public findSeat() {
g = new grid();
}
public grid getGrid ()
/**
* return the grid
*/
{
return this.g;
}
public void writeOutput (String s)
/**
* create and write to output file
*/
{
try {
File myObj = new File("output.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(
new FileWriter("output.txt", true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.write(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String choosenSeats(String orderNum, Integer n)
/**
* Chose random row and seats from the list of available ways to make n consecutive seats
* call writeOutput to write result to output file
*/
{
Map<Integer, ArrayList<ArrayList<Integer>>> allOptions = new TreeMap<Integer, ArrayList<ArrayList<Integer>>>(g.allRowsOptions(n));
if(allOptions.size() > 0) {
//chose random numbers
int chosenRowIndex = (int) (Math.random() * (allOptions.keySet().size()-1 - 0 + 1) + 0);
//get the value from hashmap
int chosenRow = (int) allOptions.keySet().toArray()[chosenRowIndex];
int chosenSeatsIndex = (int) (Math.random() * (allOptions.get(chosenRow).size()-1 - 0 + 1) + 0);
ArrayList<Integer> chosenSeat = allOptions.get(chosenRow).get(chosenSeatsIndex);
g.setBufferedSeats (chosenRow, chosenSeat.get(0), n);
g.setTakenSeats (chosenRow, chosenSeat.get(0), n);
String s = orderNum + " ";
int m = chosenRow + 65;
Character charRow = (char)m;
String stringRow = Character.toString(charRow);
for(int i = 0 ; i<n; i++) {
int actualSeatNum = chosenSeat.get(i) + 1;
s = s + stringRow + actualSeatNum + ",";
}
if (s.endsWith(",")) {
s = s.substring(0, s.length() - 1);
}
s += "\n";
writeOutput (s);
return s;
}
else {
return ("There is no available consecutive numbers of seats that ensure safety.");
}
}
}
<file_sep>/README.md
# MovieTheaterSeatingChallenge
My first thought was to fill the seats rows by rows
<br>pros: the theater can fill the most seat possible
<br>cons: unrealistic since in real life, users get to chose their seat. Therefore, the seat chosen will be random.
<br><br>
The thought of implement a program that simulate realistic behavior lead me to decide to work on a more complicated implementation - filling the seats randomly.
<br>pros: this is the situation in real life
<br>cons: the theater won't be as full. There might be empty seats.
<br><br>
To run the program on command line:
<br>
-cd to the program directory
<br>
-type: javac main.java
<br>
-type: java main "directory to your input file"
<br>
exp: java main "input.txt"
<br>
If you have issue with Java version and enviroment variables, this link might be helpful:
<br>
https://webdeasy.de/en/error-a-jni-error-has-occured-how-to-fix-this-java-error/
<br><br>
s : available seats
<br>
X : taken seat (unavailable)
<br>
B : buffer seats (unavailable)
<br><br>
- Assumed that input file acts as user. Since real users don't chose the seats row by row, the program implemented random seat chosing behavior.
- Users that buy multiple tickets tend to sit together. The program assumed that each for each reservation, everyone seat next to each other on consecutive seats.
- Everytime seats are taken, the 3 seats on the right and 3 seats on the left of the party will become buffers to ensure safety.
- Since the seats are chosen randomly for each reservation to illustrate real customer behavior, many times there are more than 3 buffers between 2 customers. Even so, no one should seat between them to ensure safety.
- Rows from A to J
- Seats from 1 to 20
- Output file will be created as the program done executes in the same directory as the source code.
- Multiple runs will be written to the same output file once it created after the first time.
- Input file can be from any directory, doesn't have to be in the same file as the source code.
<br><br>
Under is an example of how the grid and output file looks like after running the program with input file :<br>
R001 2
<br>
R002 4
<br>
R003 4
<br>
R004 3
<br>
.png)
.png)
<file_sep>/grid.java
import java.util.ArrayList;
import java.util.HashMap;
public class grid {
private row[] grid;
public grid()
/**
* Constructor
*/
{
this.grid = new row[10];
for(int i = 0 ; i<10 ; i++) {
grid[i] = new row(i);
}
}
public void print_grid ()
/**
* print the grid
*/
{
for (int i = 0 ; i< grid.length; i++) {
for (int j = 0 ; j< grid[0].getLength(); j++) {
System.out.print(grid[i].getSeatState(j));
}
System.out.print("\n");
}
}
public row getRow (int index)
/**
* return the row at index
*/
{
return this.grid[index];
}
public HashMap<Integer, ArrayList<ArrayList<Integer>>> allRowsOptions (int n)
/**
* Return all of the possible ways to make n consecutive seats in the whole grid
*/
{
HashMap<Integer,ArrayList<ArrayList<Integer>>> rowsOptions = new HashMap<>();
for(int i = 0 ; i<10 ; i++) {
ArrayList<ArrayList<Integer>> availableAtRow = new ArrayList<ArrayList<Integer>>();
availableAtRow = grid[i].nConsecutiveWays(n);
if(availableAtRow.size() != 0) {
rowsOptions.put(i,(availableAtRow));
}
}
return rowsOptions;
}
public void setTakenSeats (int rowIndex, int start, int n)
/**
* set n seats as taken
*/
{
for(int i = 0 ; i< n ; i++)
grid[rowIndex].setTakenState(start+i);
}
public void setBufferedSeats (int rowIndex, int start, int n)
/**
* set 3 seats before and 3 seat after the party as buffered
*/
{
for(int i = 0 ; i < 3; i++) {
if(start + n + i < 20)
grid[rowIndex].setBufferedState(start + n + i);
if(start - (i+1) >= 0)
grid[rowIndex].setBufferedState(start - (i+1));
}
}
}
<file_sep>/row.java
import java.util.ArrayList;
public class row {
private seat[] row;
private int rowIndex;
public row(int rowIndex)
/**
* Constructor
*/
{
this.row = new seat[20];
this.rowIndex = rowIndex;
for(int i = 0 ; i<20 ; i++) {
row[i] = new seat(i);
}
}
public int getLength()
/**
* return numbers of seat in row (should be 20)
*/
{
return row.length;
}
public seat getSeat (int index)
/**
* return the specific seat in the row
*/
{
return this.row[index];
}
public String getSeatState(int index)
/**
* return the state of a specific seat in the row
*/
{
return row[index].getState();
}
public ArrayList<Integer> openSeats()
/**
* return a list of all open seats in the row
*/
{
ArrayList<Integer> openList = new ArrayList<Integer>();
for (seat s : this.row) {
if (s.getState() == "s") {
openList .add(s.getIndex());
}
}
return openList;
}
public void setTakenState(int index)
/**
* set a seat in the row as taken
*/
{
row[index].setTaken();
}
public void setBufferedState(int index)
/**
* set a seat in the row as buffer
*/
{
row[index].setBuffered();
}
public ArrayList<ArrayList<Integer>> nConsecutiveWays (int n)
/**
* return a list of ways to make n consecutive seats from the available seats in the row
*/
{
ArrayList<ArrayList<Integer>> consecutiveWays = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> openSeats = this.openSeats();
if(openSeats.size() >= n) {
for (int i = 0 ; i < openSeats.size(); i++) {
int start =i;
boolean notConsecutive = false;
if(i + n < openSeats.size() + 1) {
for(int j = start + 1 ; j < i + n ; j++) {
if(openSeats.get(start) + 1 != openSeats.get(j)) {
notConsecutive = true;
break;
}
else
start = start + 1;
}
if (!notConsecutive) {
ArrayList<Integer> consecutiveSeats = new ArrayList<Integer>();
for(int k = 0; k<n ; k++)
consecutiveSeats.add(openSeats.get(i+k));
consecutiveWays.add(consecutiveSeats);
}
}
}
}
return consecutiveWays;
}
}
| 5c11cfc1eb2219c6ff6a764a68bdc3a2d2f593c0 | [
"Markdown",
"Java"
] | 6 | Java | HaiTrieuNg/MovieTheaterSeatingChallenge | 0bb19c35a06f0c6c6fa634d7862aa971618867d6 | dae12ad532c3f46d0d8d45b32a2f767029b39b38 |
refs/heads/master | <file_sep><?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('getTotalAttack','ApiController@getTotalAttack');
Route::get('getTotalCountry','ApiController@getTotalCountry');
Route::get('getTotalMalwareAttack','ApiController@getTotalMalware');
Route::get('getUniqueAttack','ApiController@getUniqueAttack');
Route::get('countryList','ApiController@countryList');
Route::get('topCountry','ApiController@topCountry');
Route::get('topFiveCountry','ApiController@topFiveCountry');
Route::get('topFivePort','ApiController@topFivePort');
Route::get('topFiveMalware','ApiController@topFiveMalware');
Route::get('instituteCount','ApiController@instituteCount');
Route::get('sensorList','SensorController@sensorList');
Route::get('getIPSensor/{sensorId}','SensorController@ipAttackedList');
Route::get('getPortSensor/{sensorId}','SensorController@PortAttackedList');
Route::get('getMalwareSensor/{sensorIP}', 'SensorController@malwareAttackedList');
Route::get('getPICSensor/{sensorID}', 'SensorController@picSensorDetail');<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
function __construct()
{
$this->apiKey = config('app.api-key') ;
$this->host = config('app.api-url') ;
}
public function userList()
{
$userList = $this->host . 'users/list/' . 10 . '/' . 10 . '/' . Session::get('sessionKey') . '/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$userList);
$userListResp = $res->getBody();
$userListResp = json_decode($userListResp);
return response()->json(['total' => $userListResp] , 200);
}
public function storeUser() {
$rules = array(
'name' => 'required',
'telp' => 'required|numeric',
'email' => 'required|email',
'password' => '<PASSWORD>',
'confirmPassword' => '<PASSWORD>'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator);
} else {
$encodedEmail = base64_encode(Input::get('email'));
$encodedPassword = base64_encode(Input::get('pass'));
$url = $this->host . "users/add/" . Session::get('sessionKey') . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client;
$client->setDefaultOption('verify', false);
$req = $client->createRequest('POST', $url);
$req->setHeader('Content-Type', 'application/x-www-form-urlencoded');
$postBody = $req->getBody();
$postBody->setField('name', Input::get('name'));
$postBody->setField('telp', Input::get('telp'));
$postBody->setField('encodedEmail', $encodedEmail);
$postBody->setField('encodedPassword', $encodedPassword);
$postBody->setField('instituteId', Input::get('institute'));
$postBody->setField('roleId', Input::get('role'));
try {
$resp = $client->send($req);
if($resp){
Session::flash('success', 'Successfully created User!');
return Redirect::to('userList');
}
}
catch (\GuzzleHttp\Exception\ClientException $e){
echo($e);
}
// $user = new User();
// $user->user_name = Input::get('name');
// $user->user_telp = Input::get('telp');
// $user->user_email = Input::get('email');
// $user->user_pass = <PASSWORD>(Input::get('pass'));
// $user->institute_id = Input::get('institute');
// $user->role_id = Input::get('role');
// $user->user_last_activity = new \DateTime;
// $user->user_last_update = new \DateTime;
// $user->user_creation_time = new \DateTime;
// $user->timestamps = false;
// $user->save();
// Session::flash('success', 'Successfully created User!');
// return Redirect::to('userList');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class InstitutionController extends Controller
{
function __construct()
{
$this->apiKey = config('app.api-key') ;
$this->host = config('app.api-url') ;
}
public function instituteCount()
{
$institute = $this->host . '/institutes/instituteCount/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$institute);
$instituteResp = $res->getBody();
$instituteResp = json_decode($instituteResp);
return response()->json(['total' => $instituteResp] , 200);
}
public function storeInstitute() {
$rules = array(
'name' => 'required',
'address' => 'required',
'category' => 'required',
'province' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator);
} else {
$institute = new Institute();
$institute->institute_name = Input::get('name');
$institute->institute_address = Input::get('address');
$institute->category_id = Input::get('category');
$institute->institute_province = Input::get('province');
$institute->timestamps = false;
$institute->save();
Session::flash('success', 'Successfully created Institution!');
return Redirect::to('institutionList');
}
}
}
<file_sep>$(document).ready(function() {
$('#roleTable').on('click', '.role-table-td', function() {
var state = $(this).parent().hasClass('highlighted-tr');
$('.highlighted-tr').removeClass('highlighted-tr');
if (!state) {
$(this).parent().addClass('highlighted-tr');
}
});
$.ajax({
type: "GET",
url: "getRoles",
cache: false,
dataType: 'json',
beforeSend: function() {
$("#roleTable").css('display', 'none');
$("#roleList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#roleList").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#roleTable').removeAttr('style');
$('table#roleTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#roleTable > tbody:last').append('<tr><td class="role-table-td" style="cursor: pointer" onclick="getRoleDetail(\'' + data.role_id + '\')">' + data.role_name + '</td></tr>');
//<td style="cursor: pointer" onclick="categoryDelete(\'' + data.category_id + '\')"><a href="#detail-modal" data-toggle="modal"><i class="fa fa-trash-o"></i></a></td>
});
}
});
});
function categoryDelete(id) {
document.getElementById("b").innerHTML = 'Are you sure?</br></br><table width="400" style="text-align: center;"><td><button type="button" onclick="del(\'' + id + '\')"><i class="fa fa-thumbs-o-up fa-3x"></i></button></td><td><button type="button" data-dismiss="modal"><i class="fa fa-thumbs-o-down fa-3x"></i></button></td></table>';
}
function del(id) {
$.ajax({
type: "GET",
url: "deleteCategory/" + id,
cache: false,
beforeSend: function() {
// $("#b").css('display', 'none');
$("#b").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#b").html('');
}, //Hide spinner
success: function() {
$("#b").append('Success!');
location.reload();
}
});
}
function getRoleDetail(roleId) {
$('#roleDetailSpan').removeAttr('style');
$.ajax({
type: "GET",
url: "getRoleUsers/" + roleId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#roleUserTable").css('display', 'none');
$("#roleUserDiv").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#roleUserDiv").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#roleUserTable').removeAttr('style');
$('table#roleUserTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#roleUserTable > tbody:last').append('<tr><td>' + data.user_name + '</td></tr>');
});
}
});
}
<file_sep>$(document).ready(function () {
//27 Mei 2015
//menu responsive
//
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$('#nongol').click(function (e) {
//$("#sidebar").slideToggle();
$("#nav-accordion").slideToggle();
});
//collapse sidebar function
// $("#sidebar").hover(function () {
// $("#sidebar").css("margin-left", "0px");
// $("#main-content").css("margin-left", "210px");
// document.getElementById("main-content").style.WebkitTransition = "all 0.5s";
// document.getElementById("sidebar").style.WebkitTransition = "all 0.5s";
// document.getElementById("main-content").style.MozTransition = "all 0.5s";
// document.getElementById("sidebar").style.MozTransition = "all 0.5s";
// }, function () {
// $("#sidebar").css("margin-left", "-150px");
// $("#main-content").css("margin-left", "60px");
// });
$('#addChart').click(function (e) {
//show menuChart
$("#menuChart").slideDown(500);
});
$("#new-chart").sortable({
items: '.sortable',
placeholder: "dashed-placeholder",
forcePlaceholderSize: true,
tolerance: "pointer"
})
$("#new-chart").sortable("disable");
$("#editWidget").click(function (e) {
$("#editWidget").hide();
$("#saveWidget").show();
$("#new-chart-button").show();
$(".closeWidget").show();
$("#new-chart").sortable("enable")
})
$("#saveWidget").click(function (e) {
$("#editWidget").show();
$("#saveWidget").hide();
$("#new-chart-button").hide();
$(".closeWidget").hide();
$("#new-chart").sortable("disable");
var jsonArray = [];
$('.chart').each(function (index) {
var obj = {
position: index,
divId: $(this).attr('id'),
type: $(this).attr('type'),
selectedData: $(this).attr('dataSelected')
}
jsonArray.push(obj);
})
var jsonString = JSON.stringify(jsonArray);
console.log(jsonString);
// alert(jsonString);
$.ajax({
type: "POST",
contentType: 'application/x-www-form-urlencoded',
url: "saveConfigJson",
dataType: "json",
data: {configuration: jsonString},
success: function () {
alert("success")
},
});
})
var configData = [];
var widgetCount = 1;
$.ajax({
type: "GET",
dataType: 'json',
url: "getConfigJson",
data: "",
cache: false,
success: function (msg) {
$.each(msg, function (i, data) {
configData = JSON.parse(data.configuration);
$.each(configData, function (j, conf) {
if (conf.type == 'pie' && conf.selectedData == 'topCountry') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFiveCountry(conf.type, conf.divId)
}
else if (conf.type == 'donut' && conf.selectedData == 'topCountry') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFiveCountry(conf.type, conf.divId)
}
else if (conf.type == 'pie' && conf.selectedData == 'topPort') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFivePort(conf.type, conf.divId)
}
else if (conf.type == 'donut' && conf.selectedData == 'topPort') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFivePort(conf.type, conf.divId)
}
else if (conf.type == 'pie' && conf.selectedData == 'topMalware') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFiveMalware(conf.type, conf.divId)
}
else if (conf.type == 'donut' && conf.selectedData == 'topMalware') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFiveMalware(conf.type, conf.divId)
}
else if (conf.type == 'table' && conf.selectedData == 'topCountry') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFiveCountry(conf.type, conf.divId)
}
else if (conf.type == 'table' && conf.selectedData == 'topPort') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFivePort(conf.type, conf.divId)
}
else if (conf.type == 'table' && conf.selectedData == 'topMalware') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
topFiveMalware(conf.type, conf.divId)
}
else if (conf.type == 'table' && conf.selectedData == 'liveticker') {
autoAppendChart(conf.type, conf.selectedData, conf.divId);
livetickerTable(conf.divId)
}
else if(conf.type == 'map' && conf.selectedData == 'indoMap'){
autoAppendChart(conf.type, conf.selectedData, conf.divId);
indonesiaMap(conf.divId)
}
else if(conf.type == 'map' && conf.selectedData == 'worldMap'){
autoAppendChart(conf.type, conf.selectedData, conf.divId);
worldMap(conf.divId)
}
widgetCount++;
})
})
}
})
// var jsonArray2 = [{position: 0, divId: 'widget-1', type: 'pie', selectedData: 'topCountry'},
// {'position': 1, divId: 'widget-3', 'type': 'donut', 'selectedData': 'topCountry'},
// {'position': 2, divId: 'widget-2', 'type': 'pie', 'selectedData': 'topCountry'}];
// $.each(jsonArray2, function (i, data) {
// if (data.type == 'pie' && data.selectedData == 'topCountry') {
// autoAppendChart(data.type, data.selectedData, data.divId);
// topFiveCountry(data.type, data.divId)
//
// }
//
// else if (data.type == 'donut' && data.selectedData == 'topCountry') {
// autoAppendChart(data.type, data.selectedData, data.divId);
// topFiveCountry(data.type, data.divId)
// }
// })
function autoAppendChart(type, selectedData, divId) {
if (type == 'pie' || type == 'donut') {
if(selectedData == 'topCountry'){
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Negara Terpopuler</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='" + divId + "' class='chart' style='height: 300px;' type='" + type + "' dataSelected='" + selectedData + "'></div></div>" +
"</div></div>");
}
else if(selectedData == 'topPort'){
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='" + divId + "' class='chart' style='height: 300px;' type='" + type + "' dataSelected='" + selectedData + "'></div></div>" +
"</div></div>");
}
else if(selectedData == 'topMalware'){
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Malware Terpopuler</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='" + divId + "' class='chart' style='height: 300px;' type='" + type + "' dataSelected='" + selectedData + "'></div></div>" +
"</div></div>");
}
}
else if (type == 'table') {
if (selectedData == 'topCountry') {
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Negara Terpopuler</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-" + divId + "'></div><div id='" + divId + "' class='chart' style='height: 300px' type='" + type + "' dataSelected='" + selectedData + "'>" +
"<table class='table'><thead><tr><th>Rank</th><th>Country</th><th>Attack Count</th></tr></thead>" +
"<tbody id='topCountryTable-" + divId + "'></tbody>" +
"</table></div></div>" +
"</div></div>");
}
else if (selectedData == 'topMalware') {
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Malware Terpopuler</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-" + divId + "'></div><div id='" + divId + "' class='chart' style='height: 300px' type='" + type + "' dataSelected='" + selectedData + "'>" +
"<table class='table'><thead><tr><th>Rank</th><th>Malware</th><th>Attack Count</th></tr></thead>" +
"<tbody id='topCountryTable-" + divId + "'></tbody>" +
"</table></div></div>" +
"</div></div>");
}
else if (selectedData == 'topPort') {
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-" + divId + "'></div><div id='" + divId + "' class='chart' style='height: 300px' type='" + type + "' dataSelected='" + selectedData + "'>" +
"<table class='table'><thead><tr><th>Rank</th><th>Service</th><th>Attack Count</th></tr></thead>" +
"<tbody id='topCountryTable-" + divId + "'></tbody>" +
"</table></div></div>" +
"</div></div>");
}
else if (selectedData == 'liveticker') {
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Live Ticker</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-" + divId + "'><div id='" + divId + "' class='chart' style='height: 300px' type='" + type + "' dataSelected='" + selectedData + "'>" +
"<table id='liveTickerTable-" + divId + "' class='table'><thead><tr><th style='text-align: center'>Time</th><th style='text-align: center'>Country</th><th style='text-align: center'>Port</th></tr></thead>" +
"<tbody></tbody>" +
"</table></div></div></div></div>");
}
}
else if(type == "map"){
if(selectedData == 'indoMap'){
$("#new-chart").append("<div class='col-md-12 sortable' style='float:left'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Peta Serangan Indonesia</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='" + divId + "' class='chart' style='height: 300px' type='"+type+"' dataSelected='"+selectedData+"'></div></div></div></div>");
}
else if(selectedData == 'worldMap'){
$("#new-chart").append("<div class='col-md-12 sortable' style='float:left'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Peta Serangan Dunia</h3><div class='box-tool closeWidget' style='display:none'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='" + divId + "' class='chart' style='height: 300px' type='"+type+"' dataSelected='"+selectedData+"'></div></div></div></div>");
}
}
}
function topFiveCountry(type, divId) {
if (type == 'pie') { // Pie Chart Top Country
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
var topAttackerPie = []
$("#" + divId).html('');
$.each(msg, function (i, dataChart) {
topAttackerPie[i] = {label: dataChart.countryName, data: dataChart.count}
})
piegraph("#" + divId, topAttackerPie)
}
});
}
else if (type == 'donut') { // Donut Chart Top Country
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
var topAttacker = []
$("#" + divId).html('');
$.each(msg, function (i, data) {
topAttacker[i] = {label: data.countryName, value: data.count, labelColor: "#FFFFFF"}
})
donutgraph(divId, topAttacker)
}
});
}
else if (type == 'table') { // Table Top Country
var rank = 1;
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#" + divId).hide();
$("#widget-loading-" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#" + divId).show();
$("#widget-loading-" + divId).html("")
$.each(msg, function (i, data) {
$("#topCountryTable-" + divId).append('<tr><td>' + rank + '</td><td>' + data.countryName + '</td><td>' + data.count + '</td></tr>')
rank++;
})
}
});
}
}
function topFivePort(type, divId) {
if (type == 'pie') { // Pie Chart Top Port
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
var topPortPie = []
$("#" + divId).html('');
$.each(msg, function (i, dataChart) {
topPortPie[i] = {label: dataChart.service + " ("+dataChart.portDestination+")", data: dataChart.countPort}
})
piegraph("#" + divId, topPortPie)
}
});
}
else if (type == 'donut') { // Donut Chart Top Port
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
var topPort = []
$("#" + divId).html('');
$.each(msg, function (i, data) {
topPort[i] = {label: data.service + " ("+data.portDestination+")", value: data.countPort, labelColor: "#FFFFFF"}
})
donutgraph(divId, topPort)
}
});
}
else if (type == 'table') { // Table Top Port
var rank = 1;
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#" + divId).hide();
$("#widget-loading-" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#" + divId).show();
$("#widget-loading-" + divId).html("")
$.each(msg, function (i, data) {
$("#topCountryTable-" + divId).append('<tr><td>' + rank + '</td><td>' + data.service + '</td><td>' + data.countPort + '</td></tr>')
rank++;
})
}
});
}
}
function topFiveMalware(type, divId) {
if (type == 'pie') { // Pie Chart Top Malware
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveMalware",
data: "",
beforeSend: function () {
$("#" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
var topMalwarePie = []
$("#" + divId).html('');
$.each(msg, function (i, dataChart) {
topMalwarePie[i] = {label: dataChart.virustotalscan_result, data: dataChart.count}
})
piegraph("#" + divId, topMalwarePie)
}
});
}
else if (type == 'donut') { // Donut Chart Top Malware
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveMalware",
data: "",
beforeSend: function () {
$("#" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
var topMalware = []
$("#" + divId).html('');
$.each(msg, function (i, data) {
topMalware[i] = {label: data.virustotalscan_result, value: data.count, labelColor: "#FFFFFF"}
})
donutgraph(divId, topMalware)
}
});
}
else if (type == 'table') { // Table Top Malware
var rank = 1;
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveMalware",
data: "",
beforeSend: function () {
$("#" + divId).hide();
$("#widget-loading-" + divId).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#" + divId).show();
$("#widget-loading-" + divId).html("")
$.each(msg, function (i, data) {
$("#topCountryTable-" + divId).append('<tr><td>' + rank + '</td><td>' + data.virustotalscan_result + '</td><td>' + data.count + '</td></tr>')
rank++;
})
}
});
}
}
function livetickerTable(divId) {
var connection;
connection = new WebSocket('wss://webservice-beta.honeynet.id/websocket/liveTicker');
connection.onopen = function () {
$('table#liveTickerTable-' + divId + ' > tbody:last').empty();
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (msg) {
var isi = JSON.parse(msg.data);
console.log(isi);
var sourceCountry = isi.sourceCountryName;
var portDest = isi.destinationPort;
var myDate = new Date(isi.timestamp);
var hour;
var minute;
var second;
if (myDate.getHours() < 10) {
hour = "0" + myDate.getHours();
}
else {
hour = myDate.getHours();
}
if (myDate.getMinutes() < 10) {
minute = "0" + myDate.getMinutes();
}
else {
minute = myDate.getMinutes();
}
if (myDate.getSeconds() < 10) {
second = "0" + myDate.getSeconds();
}
else {
second = myDate.getSeconds();
}
if (sourceCountry == "UNKNOWN") {
}
else {
$('table#liveTickerTable-' + divId).prepend('<tr style="text-align: center"><td>' + hour + ":" + minute + ":" + second + '</td><td>' + sourceCountry + '</td><td>' + portDest + '</td></tr>')
var rowCount = $('table#liveTickerTable-' + divId + ' tr').length;
if (rowCount > 4) {
$('table#liveTickerTable-' + divId + ' tr:last').remove;
}
}
}
}
// var donutI = 0;
// var pieJ = 0;
// var lineK = 0;
// var barL = 0;
// var areaM = 0;
var indoMap, worldMap;
// var iMap = 0;
// var wMap = 0;
function piegraph(classname, graphData) {
$.plot($(classname), graphData, {
series: {
pie: {
show: true,
}
},
});
}
function donutgraph(classname, graphData) {
Morris.Donut({
element: classname,
data: graphData,
colors: ["#ADEBFF", "#00FF00", "#FF6666"]
});
}
$("#dataChart").hide();
$("#dataTable").hide();
$("#dataMap").hide();
$("#dataLabel").hide()
var valueType;
$("#tipeChart").change(function () {
valueType = $("#tipeChart option:selected").val()
$("#dataLabel").show()
if (valueType == 'pie' || valueType == 'donut') {
$("#dataChart").show();
$("#dataTable").hide();
$("#dataMap").hide();
}
else if (valueType == 'table') {
$("#dataTable").show();
$("#dataChart").hide();
$("#dataMap").hide();
}
else if (valueType == 'map') {
$("#dataMap").show();
$("#dataChart").hide();
$("#dataTable").hide();
}
})
$("#confirm-chart").click(function (e) {
var graphData = [];
var lineGraphData = [];
var donutData = []
var series = Math.floor(Math.random() * 10) + 1;
for (var i = 0; i < series; i++) {
donutData[i] = {
label: "Series" + (i + 1),
value: Math.floor((Math.random()) * 100) + 1,
labelColor: "#FFFFFF"
}
graphData[i] = {
label: "Series" + (i + 1),
data: Math.floor((Math.random() - 1) * 100) + 1
}
lineGraphData[i] = [i, Math.floor(Math.random() * 100) + 1]
}
var chartValue = $("#dataChart option:selected").val();
var tableValue = $("#dataTable option:selected").val();
var mapValue = $("#dataMap option:selected").val();
if (chartValue == 'top' && valueType == 'pie') { // Top Country Pie
widgetCount++;
if ($("#widget-"+widgetCount).length == 0) {
var topAttackerPie = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Top Attacker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='pie' dataSelected='topCountry'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topAttackerPie[i] = {label: data.countryName, data: data.count}
})
piegraph("#widget-" + widgetCount, topAttackerPie)
$("#new-chart-button").show();
}
});
}
else{
widgetCount++;
if ($("#widget-"+widgetCount).length == 0) {
var topAttackerPie = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Top Attacker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='pie' dataSelected='topCountry'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topAttackerPie[i] = {label: data.countryName, data: data.count}
})
piegraph("#widget-" + widgetCount, topAttackerPie)
$("#new-chart-button").show();
}
});
}
else {
widgetCount++;
var topAttackerPie = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Top Attacker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='pie' dataSelected='topCountry'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topAttackerPie[i] = {label: data.countryName, data: data.count}
})
piegraph("#widget-" + widgetCount, topAttackerPie)
$("#new-chart-button").show();
}
});
}
}
}
else if (chartValue == 'top' && valueType == 'donut') { // Top Country Donut
widgetCount++;
if ($("#widget-"+widgetCount).length == 0) {
var topAttacker = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Top Attacker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='donut' dataSelected='topCountry'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topAttacker[i] = {label: data.countryName, value: data.count, labelColor: "#FFFFFF"}
})
donutgraph("widget-" + +widgetCount, topAttacker)
$("#new-chart-button").show();
}
});
}
else {
widgetCount++;
var topAttacker = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Top Attacker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='donut' dataSelected='topCountry'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topAttacker[i] = {label: data.countryName, value: data.count, labelColor: "#FFFFFF"}
})
donutgraph("widget-" + +widgetCount, topAttacker)
$("#new-chart-button").show();
}
});
}
}
else if (chartValue == 'port' && valueType == 'pie') { // Top Port Pie
widgetCount++;
if ($("#widget-"+widgetCount).length == 0) {
var topPortPie = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='pie' dataSelected='topPort'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topPortPie[i] = {label: data.service + " ("+data.portDestination+")", data: data.countPort}
})
piegraph("#widget-" + widgetCount, topPortPie)
$("#new-chart-button").show();
}
});
}
else {
widgetCount++;
var topPortPie = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='pie' dataSelected='topPort'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topPortPie[i] = {label: data.service + " ("+data.portDestination+")", data: data.countPort}
})
piegraph("#widget-" + widgetCount, topPortPie)
$("#new-chart-button").show();
}
});
}
}
else if (chartValue == 'port' && valueType == 'donut') { // Top Port Donut
widgetCount++;
if ($("#widget-"+widgetCount).length == 0) {
var topPort = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='donut' dataSelected='topPort'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topPort[i] = {label: data.service + " ("+data.portDestination+")", value: data.countPort, labelColor: "#FFFFFF"}
})
donutgraph("widget-" + +widgetCount, topPort)
$("#new-chart-button").show();
}
});
}
else {
widgetCount++;
var topPort = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='donut' dataSelected='topPort'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topPort[i] = {label: data.service + " ("+data.portDestination+")", value: data.countPort, labelColor: "#FFFFFF"}
})
donutgraph("widget-" + +widgetCount, topPort)
$("#new-chart-button").show();
}
});
}
}
else if (chartValue == 'malware' && valueType == 'pie') { // Top Malware Pie
widgetCount++;
var topMalwarePie = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Captured Malware</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='pie' dataSelected='topMalware'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveMalware",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
console.log(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topMalwarePie[i] = {label: data.virustotalscan_result, data: data.count}
})
piegraph("#widget-" + widgetCount, topMalwarePie)
$("#new-chart-button").show();
}
});
}
else if (chartValue == 'malware' && valueType == 'donut') { // Top Malware Donut
widgetCount++;
var topMalware = [];
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Captured Malware</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px;' type='donut' dataSelected='topMalware'></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveMalware",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).html('');
$.each(msg, function (i, data) {
topMalware[i] = {label: data.virustotalscan_result, value: data.count, labelColor: "#FFFFFF"}
})
donutgraph("widget-" + +widgetCount, topMalware)
$("#new-chart-button").show();
}
});
}
else if (tableValue == 'top' && valueType == 'table') { // Top Country Table
widgetCount++;
var rank = 1;
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Top Attacker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-widget-" + widgetCount + "'></div><div id='widget-" + widgetCount + "' class='chart' style='height: 300px' type='table' dataSelected='topCountry'>" +
"<table class='table'><thead><tr><th>Rank</th><th>Country</th><th>Attack Count</th></tr></thead>" +
"<tbody id='topCountryTable-widget-" + widgetCount + "'></tbody>" +
"</table></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveCountry",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).hide();
$("#widget-loading-widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).show();
$("#widget-loading-widget-" + widgetCount).html("")
$.each(msg, function (i, data) {
$("#topCountryTable-widget-" + widgetCount).append('<tr><td>' + rank + '</td><td>' + data.countryName + '</td><td>' + data.count + '</td></tr>')
rank++;
})
$("#new-chart-button").show();
}
});
}
else if (tableValue == 'port' && valueType == 'table') { // Top Port Table
widgetCount++;
var rank = 1;
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Port Terpopuler</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-widget-" + widgetCount + "'></div><div id='widget-" + widgetCount + "' class='chart' style='height: 300px' type='table' dataSelected='topCountry'>" +
"<table class='table'><thead><tr><th>Rank</th><th>Service</th><th>Attack Count</th></tr></thead>" +
"<tbody id='topCountryTable-widget-" + widgetCount + "'></tbody>" +
"</table></div></div>" +
"</div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFivePort",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).hide();
$("#widget-loading-widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).show();
$("#widget-loading-widget-" + widgetCount).html("")
$.each(msg, function (i, data) {
$("#topCountryTable-widget-" + widgetCount).append('<tr><td>' + rank + '</td><td>' + data.service + '</td><td>' + data.countPort + '</td></tr>')
rank++;
})
$("#new-chart-button").show();
}
});
}
else if (tableValue == 'malware' && valueType == 'table') { // Top Malware Table
widgetCount++;
var rank = 1
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Captured Malware</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-widget-" + widgetCount + "'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px' type='table' dataSelected='topMalware'>" +
"<table class='table'><thead><tr><th>Rank</th><th>Malware Name</th><th>Count</th></tr></thead>" +
"<tbody id='topMalwareTable-widget-" + widgetCount + "'></tbody>" +
"</table></div></div></div></div>");
$.ajax({
type: "GET",
dataType: 'json',
url: "topFiveMalware",
data: "",
beforeSend: function () {
$("#widget-" + widgetCount).hide()
$("#widget-loading-widget-" + widgetCount).html("<center><img src='public/assets/img/ajax-loader.gif'></center>")
$("#new-chart-button").hide();
},
error: function (e) {
alert(e);
},
cache: false,
success: function (msg) {
$("#widget-" + widgetCount).show()
$("#widget-loading-widget-" + widgetCount).html("")
$.each(msg, function (i, data) {
$("#topMalwareTable").append("<tr><td>" + rank + "</td><td>" + data.virustotalscan_result + "</td><td>" + data.count + "</td></tr>")
rank++;
})
$("#new-chart-button").show();
}
});
}
else if (tableValue == 'liveticker' && valueType == 'table') {
widgetCount++;
var connection;
$("#new-chart").append("<div class='col-md-6 sortable'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Live Ticker</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content' style='height: 320px'><div id='widget-loading-widget-" + widgetCount + "'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px' type='table' dataSelected='liveticker'>" +
"<table id='liveTickerTable-widget-" + widgetCount + "' class='table'><thead><tr><th style='text-align: center'>Time</th><th style='text-align: center'>Country</th><th style='text-align: center'>Port</th></tr></thead>" +
"<tbody></tbody>" +
"</table></div></div></div></div>");
connection = new WebSocket('wss://webservice-beta.honeynet.id/websocket/liveTicker');
connection.onopen = function () {
$('table#liveTickerTable-widget-' + widgetCount + ' > tbody:last').empty();
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (msg) {
var isi = JSON.parse(msg.data);
console.log(isi);
var sourceCountry = isi.sourceCountryName;
var portDest = isi.destinationPort;
var myDate = new Date(isi.timestamp);
var hour;
var minute;
var second;
if (myDate.getHours() < 10) {
hour = "0" + myDate.getHours();
}
else {
hour = myDate.getHours();
}
if (myDate.getMinutes() < 10) {
minute = "0" + myDate.getMinutes();
}
else {
minute = myDate.getMinutes();
}
if (myDate.getSeconds() < 10) {
second = "0" + myDate.getSeconds();
}
else {
second = myDate.getSeconds();
}
if (sourceCountry == "UNKNOWN") {
}
else {
$('table#liveTickerTable-widget-' + widgetCount).prepend('<tr style="text-align: center"><td>' + hour + ":" + minute + ":" + second + '</td><td>' + sourceCountry + '</td><td>' + portDest + '</td></tr>')
var rowCount = $('table#liveTickerTable-widget-' + widgetCount + ' tr').length;
if (rowCount > 4) {
$('table#liveTickerTable-widget-' + widgetCount + ' tr:last').remove;
}
}
}
}
else if (mapValue == 'indoMap' && valueType == 'map') {
widgetCount++;
$("#new-chart").append("<div class='col-md-12 sortable' style='float:left'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> Indonesia Map</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-loading-widget-" + widgetCount + "'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px' type='map' dataSelected='indoMap'></div></div></div></div></div>");
indonesiaMap("widget-" + widgetCount);
}
else if (mapValue == 'worldMap' && valueType == 'map') {
widgetCount++;
$("#new-chart").append("<div class='col-md-12 sortable' style='float:left'>" +
"<div class='box'>" +
"<div class='box-title'><h3><i class='fa fa-bar-chart-o'></i> World Map</h3><div class='box-tool'> <a data-action='close' class='close' href='#'><i class='fa fa-times'></i></a> </div></div>" +
"<div class='box-content'><div id='widget-loading-widget-" + widgetCount + "'><div id='widget-" + widgetCount + "' class='chart' style='height: 300px' type='map' dataSelected='worldMap'></div></div></div></div></div>");
worldMap("widget-" + widgetCount);
}
})
function worldMap(divId) {
$.ajax({
type: "GET",
dataType: 'json',
url: 'loadWorldMap',
data: "",
cache: false,
beforeSend: function () {
$("#" + divId).html('<center class="loading-ajax"><img src="public/assets/img/ajax-loader.gif"></center>');
},
success: function (msg) {
console.log(msg);
$("#" + divId).html('');
$("#" + divId).vectorMap({
backgroundColor: 'transparent',
// zoomButtons: false,
// zoomOnScroll: false,
map: 'world_mill_en',
markerStyle: {
initial: {
fill: '#FF0000',
stroke: '#383f47'
}
},
focusOn: {
x: 0.5,
y: 0.5,
scale: 0.5
},
series: {
regions: [{
// scale: ['#99B2FF', '#0047B2'],
scale: ['#FFFFFF', '#0047B2'],
normalizeFunction: 'linear',
values: msg,
min: 0,
max: 1000000,
legend: {
vertical: true
}
}, {
legend: {
horizontal: true,
cssClass: 'jvectormap-legend-icons',
}
}]
},
// onMarkerTipShow: function (e, el, code) {
// el.html(el.html() + ' (Attack Hit - ' + msg[code] + ')');
// },
onRegionTipShow: function (e, el, code) {
if (typeof msg[code] === 'undefined') {
el.html(el.html() + '<br>Jumlah Serangan: 0)');
}
else {
el.html(el.html() + '<br>Jumlah Serangan: ' + numberWithCommas(msg[code]));
}
},
// onRegionLabelShow: function (e, el, code) {
// el.html(el.html() + ' (Attack Hit - ' + msg[code] + ')');
// },
});
}});
}
function indonesiaMap(divId) {
$.ajax({
type: "GET",
dataType: 'json',
url: "loadIndonesiaMap",
data: "",
cache: false,
beforeSend: function () {
$("#" + divId).html('<center class="loading-ajax"><img src="public/assets/img/ajax-loader.gif" /></center>');
},
success: function (msg) {
console.log(msg);
$("#" + divId).html('');
$('#' + divId).vectorMap({
backgroundColor: 'transparent',
// zoomButtons: false,
// zoomOnScroll: false,
map: 'id_mill_en',
focusOn: {
x: 0.5,
y: 0.5,
scale: 0.5
},
series: {
regions: [{
// scale: ['#99B2FF', '#0047B2'],
scale: ['#FFFFFF', '#0047B2'],
normalizeFunction: 'linear',
values: msg,
min: 0,
max: 1000000,
legend: {
vertical: true
}
}, {
legend: {
horizontal: true,
cssClass: 'jvectormap-legend-icons',
title: 'Business type'
}
}]
},
onRegionLabelShow: function (e, el, code) {
el.html(el.html() + ' (Attack Hit - ' + msg[code] + ')');
},
onRegionTipShow: function (e, el, code) {
if (typeof msg[code] === 'undefined') {
el.html(el.html() + '<br>Jumlah Serangan: 0)');
}
else {
el.html(el.html() + '<br>Jumlah Serangan: ' + numberWithCommas(msg[code]));
}
},
});
}});
}
/*
$("#draggable").draggable({
connectToSortable: "#new-chart",
revert: "invalid",
cursor: "move",
drag: function (event, ui) {
alert("hi");
},
start: function (event, ui) {
alert("hello");
}
});
*/
//coba baru, pake clone
/*$("#new-chart").sortable({
start: function( event, ui ) {
clone = $(ui.item[0].outerHTML).clone();
},
placeholder: {
element: function(clone, ui) {
return $('<div class="new-chart">'+clone[0].innerHTML+'</div>');
},
update: function() {
return;
}
}
});*/
$(document).on("click", ".close",function () {
if ($(this).data('action') == undefined) {
alert("apabae");
return;
}
var action = $(this).data('action');
var btn = $(this);
switch (action) {
case 'close':
$(this).parents('.box').fadeOut(500, function () {
$(this).parent().remove();
})
break;
}
e.preventDefault();
});
})<file_sep>function getIP(ipaddress, offset, limit) {
//var country_new = country;
$.ajax({
type: "GET",
url: "searchIP/" + ipaddress + "/" + offset + "/" + limit,
cache: false,
beforeSend: function() {
$("#resultSearch").removeAttr('style');
$("#loading-search").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#ipFoundTable").css('display', 'none');
$("#ipFoundTableOuter").css('display', 'none');
$("#not-found").css('display', 'none');
$("#ip-searched").html(ipaddress)
},
complete: function() {
$("#loading-search").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
// $("#loading-search").html('');
if (msg.length != 0) {
$('#ipFoundTableOuter').removeAttr('style');
$('#ipFoundTable').removeAttr('style');
$('table#ipFoundTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#ipFoundTable > tbody:last').append('<tr ><td class="ip-table-td" style="cursor: pointer" onclick="getIPDetail(\'' + data.remote_host + '\', 20, 0)"> <a href=# data-toggle="modal" data-target="#ip-detail-modal">' + data.remote_host + '</a></td><td class="right-aligned">' + numberWithCommas(data.count) + '</td></tr>');
});
if (msg.length >= limit)
$('table#ipFoundTable > tbody:last').append('<tr class="load-more-tr"><td colspan="2"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalIP(\'' + ipaddress + '\', ' + limit + ', ' + (offset + limit) + ')">Load More</button></td></tr>');
}
else {
$("#not-found").removeAttr('style');
$("#not-found").html("<center><b><h3>No IP found</h3></b><center>");
}
}
});
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function getAdditionalIP(ipaddress, limit, offset) {
$.ajax({
type: "GET",
url: "searchIP/" + ipaddress + "/" + offset + "/" + limit,
cache: false,
beforeSend: function() {
$('.load-more-tr').css('display', 'none');
$("table#ipFoundTable > tbody:last").append('<center class="load-other"><img style="margin-left: 90px;" src="public/assets/img/ajax-loader-1.gif" /></center>');
},
complete: function() {
$(".load-other").css('display', 'none');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$.each(msg, function(i, data) {
$('table#ipFoundTable > tbody:last').append('<tr ><td class="ip-table-td" style="cursor: pointer" onclick="getIPDetail(\'' + data.remote_host + '\',20,0)"> <a href=# data-toggle="modal" data-target="#ip-detail-modal">' + data.remote_host + '</a></td><td class="right-aligned">' + numberWithCommas(data.count) + '</td></tr>');
});
if(msg.length >= limit)
$('table#ipFoundTable > tbody:last').append('<tr class="load-more-tr"><td colspan="2"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalIP(\'' + ipaddress + '\', ' + limit + ', ' + (offset + limit) + ')">Load More</button></td></tr>');
}
});
}
function getIPDetail(ipaddress, detailLimit, detailOffset) {
$('#ipDetailSpan').removeAttr('style');
$("#ipDetailTitle").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#ipDetail").html('');
$.get('ipDetail/' + ipaddress, function(data) {
$("#ipDetailTitle").html('');
var json = JSON.parse(data);
$.each(json.rawdata, function(i, parsed){
$('#ipDetail').append(parsed + "<br>");
})
});
$.ajax({
type: "GET",
url: "getPortAttack/" + ipaddress + "/" + detailLimit + "/" + detailOffset,
cache: false,
beforeSend: function() {
$("#PortList").css('display', 'none');
$("#port-load-bar").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#port-load-bar").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$("#PortList").removeAttr('style');
$('table#PortList > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#PortList > tbody:last').append('<tr><td>' + data.attackedPort + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td></tr>');
});
if (msg.length >= detailLimit)
$('table#PortList > tbody:last').append('<tr class="load-more-tr-port"><td colspan="2"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalPort(\'' + ipaddress + '\',\'' + detailLimit + '\',' + (detailOffset + detailLimit) + ')">Load More</button></td></tr>');
}
});
$.ajax({
type: "GET",
url: "getMalwareAttack/" + ipaddress + "/" + detailLimit + "/" + detailOffset,
cache: false,
beforeSend: function() {
$("#MalwareList").css('display', 'none');
$("#malware-load-bar").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#malware-load-bar").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$("#MalwareList").removeAttr('style');
$('table#MalwareList > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#MalwareList > tbody:last').append('<tr><td style="cursor: pointer" onclick="getMalwareDetail(\'' + data.download_md5_hash + '\',\'' + data.virustotal_permalink + '\')"> <a href="#detail-modal" data-toggle="modal">' + data.download_md5_hash + '</td><td class="right-aligned">' + numberWithCommas(data.malCount) + '</td></tr>');
});
if (msg.length >= detailLimit)
$('table#MalwareList > tbody:last').append('<tr class="load-more-tr-malware"><td colspan="2"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalMalware(\'' + ipaddress + '\',\'' + detailLimit + '\', ' + (detailOffset + detailLimit) + ')">Load More</button></td></tr>');
}
});
}
function getMalwareDetail(md5, url) {
$.ajax({
type: "GET",
url: "getMalwareData/" + md5,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#vt-table").css('display', 'none');
$("#vt-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#result").html('');
},
complete: function() {
$("#vt-div").html('');
$("#result").html('<b>MD5 Hash: </b>' + md5);
}, //Hide spinner
success: function(msg) {
$("#vt-table").removeAttr('style');
$('table#vt-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#vt-table > tbody:last').append('<tr><td>' + data.virustotalscan_scanner + '</td><td>' + data.virustotalscan_result + '</td></tr>');
});
$('table#vt-table > tbody:last').append('<tr><td colspan=2><a href="' + url + '" target="_blank">Complete details on virustotal.com</a></td></tr>');
}
});
}<file_sep>var connection;
var username;
var markerIndex = 0;
var arrayMarkers = [];
function connect() {
connection = new WebSocket('wss://webservice-beta.honeynet.id/websocket/liveTicker');
connection.onopen = function () {
$('table#live > tbody:last').empty();
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (msg) {
var isi = JSON.parse(msg.data);
var sourceCountry = isi.sourceCountryCode;
var portDest = isi.destinationPort;
var myDate = new Date(isi.timestamp);
var hour;
var minute;
var second;
var mapWD = $('#world-map-container').vectorMap('get', 'mapObject');
if (myDate.getHours() < 10) {
hour = "0" + myDate.getHours();
}
else {
hour = myDate.getHours();
}
if (myDate.getMinutes() < 10) {
minute = "0" + myDate.getMinutes();
}
else {
minute = myDate.getMinutes();
}
if (myDate.getSeconds() < 10) {
second = "0" + myDate.getSeconds();
}
else {
second = myDate.getSeconds();
}
if(sourceCountry == "None"){
}
else {
$('table#live').prepend('<tr style="text-align: center"><td>' + hour + ":" + minute + ":" + second + '</td><td>' + sourceCountry + '</td><td>' + portDest + '</td></tr>')
var rowCount = $('table#live tr').length;
if (rowCount > 4) {
$('table#live tr:last').remove;
}
}
// if (sourceCountry != "NONE" || sourceCountry != "None") {
// console.log(sourceCountry);
// $('table#live').prepend('<tr style="text-align: center"><td>' + hour + ":" + minute + ":" + second + '</td><td>' + sourceCountry + '</td><td>' + portDest + '</td></tr>')
// var rowCount = $('table#live tr').length;
// if (rowCount > 4) {
// $('table#live tr:last').remove;
// }
// }
//document.getElementById('msgBox').innerHTML += myDate.getHours()+":"+ myDate.getMinutes()+ ":" + myDate.getSeconds() +" Attack to port "+ portDest + " from " + sourceCountry +'<br>';
};
}
function disconnect() {
connection.close()
}
connect();
<file_sep>$(document).ready(function() {
$('#categoryTable').on('click', '.category-table-td', function() {
var state = $(this).parent().hasClass('highlighted-tr');
$('.highlighted-tr').removeClass('highlighted-tr');
if (!state) {
$(this).parent().addClass('highlighted-tr');
}
});
$.ajax({
type: "GET",
url: "getCategory",
cache: false,
dataType: 'json',
beforeSend: function() {
$("#categoryTable").css('display', 'none');
$("#categoryList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#categoryList").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#categoryTable').removeAttr('style');
$('table#categoryTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#categoryTable > tbody:last').append('<tr><td class="category-table-td" style="cursor: pointer" onclick="getCategoryDetail(\'' + data.category_id + '\')">' + data.category_name + '</td><td>' + data.count + '</td><td><a class="btn btn-circle btn-inverse" href="editCategory/' + data.category_id + '"><i class="fa fa-pencil"></i></a></td></tr>');
//<td style="cursor: pointer" onclick="categoryDelete(\'' + data.category_id + '\')"><a href="#detail-modal" data-toggle="modal"><i class="fa fa-trash-o"></i></a></td>
});
}
});
});
function categoryDelete(id) {
document.getElementById("b").innerHTML = 'Are you sure?</br></br><table width="400" style="text-align: center;"><td><button type="button" onclick="del(\'' + id + '\')"><i class="fa fa-thumbs-o-up fa-3x"></i></button></td><td><button type="button" data-dismiss="modal"><i class="fa fa-thumbs-o-down fa-3x"></i></button></td></table>';
}
function del(id) {
$.ajax({
type: "GET",
url: "deleteCategory/" + id,
cache: false,
beforeSend: function() {
// $("#b").css('display', 'none');
$("#b").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#b").html('');
}, //Hide spinner
success: function() {
$("#b").append('Success!');
location.reload();
}
});
}
function getCategoryDetail(catId) {
$('#categoryDetailSpan').removeAttr('style');
$.ajax({
type: "GET",
url: "getCategoryInstitute/" + catId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#categoryInstituteTable").css('display', 'none');
$("#categoryInstituteDiv").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#categoryInstituteDiv").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#categoryInstituteTable').removeAttr('style');
$('table#categoryInstituteTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#categoryInstituteTable > tbody:last').append('<tr><td>' + data.institute_name + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getCategorySensor/" + catId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#category-sensor-table").css('display', 'none');
$("#category-sensor-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#category-sensor-div").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#category-sensor-table').removeAttr('style');
$('table#category-sensor-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#category-sensor-table > tbody:last').append('<tr><td>' + data.sensor_name + '</td><td>' + data.sensor_ip + '</td></tr>');
});
}
});
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SensorController extends Controller
{
function __construct()
{
$this->apiKey = config('app.api-key') ;
$this->host = config('app.api-url') ;
}
public function sensorList()
{
$sensor = $this->host . 'sensors/sensorCount/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$sensor);
$sensorlist = $res->getBody();
$sensorlist = json_decode($sensorlist);
return response()->json(['total' => $sensorlist] , 200);
}
public function sensorType()
{
$sensor = $this->host . 'sensors/sensorType/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$sensor);
$sensorlist = $res->getBody();
$sensorlist = json_decode($sensorlist);
return response()->json(['total' => $sensorlist] , 200);
}
public function ipAttackedList($sensorID)
{
$ipAttacked = $this->host . "sensors/attackerBySensor/" . $sensorID . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$ipAttacked);
$ipList = $res->getBody();
$ipList = json_decode($ipList);
return response()->json(['total' => $ipList] , 200);
}
public function PortAttackedList($sensorID)
{
$portAttacked = $this->host . "sensors/portBySensor/" . $sensorID . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$portAttacked);
$portList = $res->getBody();
$portList = json_decode($portList);
return response()->json(['total' => $portList] , 200);
}
public function malwareAttackedList($sensorID)
{
$malwareAttacked = $this->host . "sensors/malwareBySensor/" . $sensorID . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$malwareAttacked);
$malwareList = $res->getBody();
$malwareList = json_decode($malwareList);
return response()->json(['total' => $malwareList] , 200);
}
public function picSensorDetail($sensorID)
{
$picSensor = $this->host . "sensors/malwareBySensor/" . $sensorID . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$picSensor);
$picDetail = $res->getBody();
$picDetail = json_decode($picDetail);
return response()->json(['total' => $picDetail] , 200);
}
public function addSensorInstance($sensorName, $sensorIP, $user1Id, $user2Id, $sensorType){
$url = $this->host . "users/addSensor/" . Session::get('sessionKey') . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client;
$client->setDefaultOption('verify', false);
$req = $client->createRequest('POST', $url);
$req->setHeader('Content-Type', 'application/x-www-form-urlencoded');
$postBody = $req->getBody();
$postBody->setField('sensor_name', $sensorName);
$postBody->setField('sensor_ip', $sensorIP);
$postBody->setField('user_1_id', $user1Id);
$postBody->setField('user_2_id', $user2Id);
$postBody->setField('sensor_type', $sensorType);
try {
$resp = $client->send($req);
if ($resp) {
Session::flash('success', 'Successfully added new sensor!');
return Redirect::to('sensorList');
}
}
catch (\GuzzleHttp\Exception\ClientException $e){
// if($e->getResponse()->getStatusCode() == 400){
// Session::flash('failure', 'Wrong Username or Password');
// }
// return Redirect::to('login');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ApiController extends Controller
{
function __construct()
{
$this->apiKey = config('app.api-key') ;
$this->host = config('app.api-url') ;
}
// public function index(request $request){
// return view('pages.dashboard',compact('totalAttackResp'));
// }
public function getTotalAttack()
{
$totalAttack = $this->host . 'attackerList/totalAttack/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$totalAttack);
$totalAttackResp = $res->getBody();
$totalAttackResp = json_decode($totalAttackResp);
return response()->json(['total' => $totalAttackResp] , 200);
}
public function getTotalCountry()
{
$totalCountry = $this->host . 'attackerList/totalCountry/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$totalCountry);
$getTotal = $res->getBody();
$getTotal = json_decode($getTotal);
return response()->json(['total' => $getTotal] , 200);
}
public function getTotalMalware()
{
$totalMalware = $this->host . '/malwares/totalMalwareAttack/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$totalMalware);
$getTotal = $res->getBody();
$getTotal = json_decode($getTotal);
return response()->json(['total' => $getTotal] , 200);
}
public function getUniqueAttack()
{
$uniqueAttacker = $this->host . '/attackerList/uniqueAttacker/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$uniqueAttacker);
$uniqueattack = $res->getBody();
$uniqueattack = json_decode($uniqueattack);
return response()->json(['total' => $uniqueattack] , 200);
}
public function countryList()
{
$countryList = $this->host . '/attackerList/distinctCountry/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$countryList);
$listcountry = $res->getBody();
$listcountry = json_decode($listcountry);
return response()->json(['total' => $listcountry] , 200);
}
public function topCountry()
{
$topCountry = $this->host . 'connections/countryCounts/0/10/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$topCountry);
$topCountryResp = $res->getBody();
$topCountryResp = json_decode($topCountryResp);
return response()->json(['total' => $topCountryResp] , 200);
}
public function topFiveCountry()
{
$topfiveCountry = $this->host . 'connections/countryCounts/0/5/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$topfiveCountry);
$topCountryResp = $res->getBody();
$topCountryResp = json_decode($topCountryResp);
return response()->json(['total' => $topCountryResp] , 200);
}
public function topFivePort()
{
$fivePort = $this->host . 'connections/portCounts/0/5/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$fivePort);
$fivePortResp = $res->getBody();
$fivePortResp = json_decode($fivePortResp);
return response()->json(['total' => $fivePortResp] , 200);
}
public function topFiveMalware()
{
$topMalware = $this->host . 'malwares/malwareStats/AhnLab-V3/0/5/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$topMalware);
$malwareResp = $res->getBody();
$malwareResp = json_decode($malwareResp);
return response()->json(['total' => $malwareResp] , 200);
}
public function instituteCount()
{
$institute = $this->host . '/institutes/instituteCount/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$institute);
$instituteResp = $res->getBody();
$instituteResp = json_decode($instituteResp);
return response()->json(['total' => $instituteResp] , 200);
}
public function loadWorldMap()
{
$WorldStat = $this->host . "connections/countryCounts/" . 0 . "/" . 250 . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$WorldStat);
$WorldStatResp = $res->getBody();
$WorldStatResp = json_decode($WorldStatResp);
return response()->json(['total' => $WorldStatResp] , 200);
}
public function loadIndonesiaMap()
{
$provinceStat = $this->host . 'province/getProvinceAttackerStats/' . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$provinceStat);
$provinceStatResp = $res->getBody();
$provinceStatResp = json_decode($provinceStatResp);
return response()->json(['total' => $provinceStatResp] , 200);
}
public function attackerList()
{
$attacker = $this->host . "/attackerList/attackerIpCount/" . 0 . "/" . 300 . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client();
$res = $client->request('GET',$attacker);
$uniqueattack = $res->getBody();
$uniqueattack = json_decode($uniqueattack);
return response()->json(['total' => $uniqueattack] , 200);
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('pages.login');
});
Route::get('/welcome', function () {
return view('welcome');
});
Route::get('/dashboard',function(){
return view('pages.dashboard');
});
Route::resource('api','ApiController');
Route::get('getTotalAttack','ApiController@getTotalAttack');
Route::get('getTotalCountry','ApiController@getTotalCountry');
Route::get('getTotalMalwareAttack','ApiController@getTotalMalware');
Route::get('getUniqueAttack','ApiController@getUniqueAttack');
Route::get('countryList','ApiController@countryList');
Route::get('topCountry','ApiController@topCountry');
Route::get('topFiveCountry','ApiController@topFiveCountry');
Route::get('topFivePort','ApiController@topFivePort');
Route::get('topFiveMalware','ApiController@topFiveMalware');
Route::get('attackerList','ApiController@attackerList');
Route::get('instituteCount','InstitutionController@instituteCount');
Route::post('storeInstitute', 'InstitutionController@storeInstitute');
Route::get('sensorList','SensorController@sensorList');
Route::get('sensorType','SensorController@sensorType');
Route::get('userList','UserController@userList');
Route::get('getIPSensor/{sensorId}','SensorController@ipAttackedList');
Route::get('getPortSensor/{sensorId}','SensorController@PortAttackedList');
Route::get('getMalwareSensor/{sensorIP}', 'SensorController@malwareAttackedList');
Route::get('getPICSensor/{sensorID}', 'SensorController@picSensorDetail');
Route::get('loadWorldMap', 'ApiController@loadWorldMap');
Route::get('loadIndonesiaMap', 'ApiController@loadIndonesiaMap');
Route::post('storeUser', 'UserController@storeUser');<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ConnectionController extends Controller
{
public function addUserInstance($userName,$userTelp,$encodedEmail,$encodedPassword,$instituteId,$roleId){
$url = $this->host . "users/add/" . Session::get('sessionKey') . "/" . $this->apiKey;
$client = new \GuzzleHttp\Client;
$client->setDefaultOption('verify', false);
$req = $client->createRequest('POST', $url);
$req->setHeader('Content-Type', 'application/x-www-form-urlencoded');
$postBody = $req->getBody();
$postBody->setField('name', $userName);
$postBody->setField('telp', $userTelp);
$postBody->setField('encodedEmail', $encodedEmail);
$postBody->setField('encodedPassword', $<PASSWORD>);
$postBody->setField('instituteId', $instituteId);
$postBody->setField('roleId', $roleId);
try {
$resp = $client->send($req);
if($resp){
$user1Data = $this->host . 'users/byEmail/' . $encodedEmail . '/' . Session::get('sessionKey') . "/" . $this->apiKey;
$user1Resp = Httpful::get($user1Data)->send();
$user1 = $user1Resp->body;
return $user1;
}
}
catch (\GuzzleHttp\Exception\ClientException $e){
echo($e);
}
}
public function totalAttackTest($userId){
if(Session::get('role_level') == 4){
$baseurlTotalAttack = $this->host . '/attackerList/totalAttack/' . $userId . '/' . $this->apiKey;
$totalAttackResp = Httpful::get($baseurlTotalAttack)->send();
$totalAttack = $totalAttackResp->body;
}
else {
$baseurlTotalAttack = $this->host . '/attackerList/totalAttack/' . $this->apiKey;
$totalAttackResp = Httpful::get($baseurlTotalAttack)->send();
$totalAttack = $totalAttackResp->body;
}
foreach($totalAttack as $atk){
echo $atk->count;
}
}
}
<file_sep>$(document).ready(function() {
$('#instTable').on('click', '.inst-table-td', function() {
var state = $(this).parent().hasClass('highlighted-tr');
$('.highlighted-tr').removeClass('highlighted-tr');
if (!state) {
$(this).parent().addClass('highlighted-tr');
}
});
$.ajax({
type: "GET",
url: "getInstitutions",
cache: false,
dataType: 'json',
beforeSend: function() {
$("#instTable").css('display', 'none');
$("#instList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#sensorInstituteTable").css('display', 'none');
$("#sensorInstituteList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#instList").html('');
$("#sensorInstituteList").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#instTable').removeAttr('style');
$('table#instTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#instTable > tbody:last').append('<tr><td class="inst-table-td" style="cursor: pointer" onclick="getInstitutionDetail(\'' + data.instituteId + '\')">' + data.instituteName + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td><td><a class="btn btn-circle btn-inverse" href="editInstitute/' + data.instituteId + '"><i class="fa fa-pencil"></i></a></td></tr>');
//<td style="cursor: pointer" onclick="institutionDelete(\'' + data.institute_id + '\')"><a href="#detail-modal" data-toggle="modal"><i class="fa fa-trash-o"></i></a></td>
});
}
});
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function institutionDelete(id) {
document.getElementById("b").innerHTML = 'Are you sure?</br></br><table width="400" style="text-align: center;"><td><button type="button" onclick="del(\'' + id + '\')"><i class="fa fa-thumbs-o-up fa-3x"></i></button></td><td><button type="button" data-dismiss="modal"><i class="fa fa-thumbs-o-down fa-3x"></i></button></td></table>';
}
function del(id) {
$.ajax({
type: "GET",
url: "deleteInstitute/" + id,
cache: false,
beforeSend: function() {
// $("#b").css('display', 'none');
$("#b").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#b").html('');
}, //Hide spinner
success: function() {
$("#b").append('Success!');
location.reload();
}
});
}
function getInstitutionDetail(institutionId) {
$('#instituteDetailSpan').removeAttr('style');
$.ajax({
type: "GET",
url: "getInstitutionSensor/" + institutionId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#sensorInstituteTable").css('display', 'none');
$("#sensorInstituteList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#sensorInstituteList").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#sensorInstituteTable').removeAttr('style');
$('table#sensorInstituteTable > tbody:last').empty();
$.each(msg, function(i, data) {
if (data.hourdiff >= 2)
$('table#sensorInstituteTable > tbody:last').append('<tr><td>' + data.sensor_ip + '</td><td>' + data.sensor_name + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td><td><span class="btn btn-circle btn-danger btn-sm" data-toggle="tooltip" data-placement="top" title="Last Submit: ' + data.to_char + '" style="margin-left: 18px"></span></td></tr>');
else
$('table#sensorInstituteTable > tbody:last').append('<tr><td>' + data.sensor_ip + '</td><td>' + data.sensor_name + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td><td><span class="btn btn-circle btn-success btn-sm" data-toggle="tooltip" data-placement="top" title="Last Submit: ' + data.to_char + '" style="margin-left: 18px"></span></td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getInstitutionPort/" + institutionId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#port-institution-table").css('display', 'none');
$("#port-institution-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#port-institution-div").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#port-institution-table').removeAttr('style');
$('table#port-institution-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#port-institution-table > tbody:last').append('<tr><td>' + data.local_port + '</td><td class="right-aligned">' + numberWithCommas(data.total) + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getInstitutionMalware/" + institutionId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#mal-institution-table").css('display', 'none');
$("#mal-institution-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#mal-institution-div").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#mal-institution-table').removeAttr('style');
$('table#mal-institution-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#mal-institution-table > tbody:last').append('<tr><td style="cursor: pointer" onclick="getMalwareDetail(\'' + data.download_md5_hash + '\',\'' + data.virustotal_permalink + '\')"> <a href="#virus-detail-modal" data-toggle="modal">' + data.download_md5_hash + '</td><td class="right-aligned">' + numberWithCommas(data.total) + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getInstitutionPIC/" + institutionId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#pic-institution-table").css('display', 'none');
$("#pic-institution-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#pic-institution-div").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#pic-institution-table').removeAttr('style');
$('table#pic-institution-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#pic-institution-table > tbody:last').append('<tr><td>' + data.user_name + '</td><td>' + data.user_telp + '</td><td>' + data.user_email + '</td><td>' + data.to_char + '</td></tr>');
});
}
});
}
function getMalwareDetail(md5, url) {
$.ajax({
type: "GET",
url: "getMalwareData/" + md5,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#vt-table").css('display', 'none');
$("#vt-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#result").html('');
},
complete: function() {
$("#vt-div").html('');
$("#result").html('<b>MD5 Hash: </b>' + md5);
}, //Hide spinner
success: function(msg) {
$("#vt-table").removeAttr('style');
$('table#vt-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#vt-table > tbody:last').append('<tr><td>' + data.virustotalscan_scanner + '</td><td>' + data.virustotalscan_result + '</td></tr>');
});
$('table#vt-table > tbody:last').append('<tr><td colspan=2><a href="' + url + '" target="_blank">Complete details on virustotal.com</a></td></tr>');
}
});
// $.ajax({
// type: "GET",
// url: "getMalwareData/"+md5,
// cache: false,
// dataType: 'json',
// beforeSend: function() {
// $("#vt-table").css('display', 'none');
// $("#vt-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
// },
// complete: function() {
// $("#vt-div").html('');
// }, //Hide spinner
// dataType: 'json',
// success: function(msg) {
//// $('#mlDetailTable').removeAttr('style');
// $('table#vt-table > tbody:last').empty();
// $.each(msg, function(i, data) {
// $('table#vt-table > tbody:last').append('<tr ><td style="cursor: pointer">' + data.virustotalscan_scanner + '</td><td>' + data.virustotalscan_result + '</td></tr>');
// $('table#mlTable > tbody:last').append('<tr ><td style="cursor: pointer" onclick="getMalwareDetail('+url+')"> <a href="#detail-modal" data-toggle="modal">' + data.download_md5_hash + '</td><td>' + data.malware_count + '</a></td></tr>');
// });
// }
// });
// document.getElementById("virustotal").innerHTML = "<a href='"+url+"'>Complete URL</a>";
}
<file_sep>$(document).ready(function () {
$('#sensorTable').on('click', '.selected', function () {
var state = $(this).parent().hasClass('highlighted-tr');
$('.highlighted-tr').removeClass('highlighted-tr');
if (!state) {
$(this).parent().addClass('highlighted-tr');
}
});
$.ajax({
type: "GET",
url: "getSensors",
cache: false,
dataType: 'json',
beforeSend: function () {
$("#sensorTable").css('display', 'none');
$("#sensorList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function () {
$("#sensorList").html('');
}, //Hide spinner
dataType: 'json',
success: function (msg) {
$('#sensorTable').removeAttr('style');
$('table#sensorTable > tbody:last').empty();
var now = new Date();
$.each(msg, function (i, data) {
var lastSubmit = new Date(data.lastSubmited);
var lastSubmitDate = checkTime(lastSubmit.getDate()) + "-" + checkTime(lastSubmit.getMonth()+1) + "-" + lastSubmit.getFullYear() + " " + checkTime(lastSubmit.getHours()) + ":" + checkTime(lastSubmit.getMinutes()) + ":" + checkTime(lastSubmit.getSeconds());
if ((now - lastSubmit) >= 7200000)
$('table#sensorTable > tbody:last').append('<tr ><td class="selected sensor-table-td" style="cursor: pointer" onclick="getSensorDetail(\'' + data.sensorID + '\', \'' + data.sensorIP + '\')"> <a href=# data-toggle="modal" data-target="#sensor-detail-modal">' + data.sensorIP + '</a></td><td>' + data.sensorName + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td><td><span class="btn btn-circle btn-danger btn-sm" data-toggle="tooltip" data-placement="top" title="Last Submit: ' + lastSubmitDate + '" style="margin-left: 18px"></span></td><td><a class="btn btn-circle btn-inverse" href="editSensor/' + data.sensorID + '"><i class="fa fa-pencil"></i></a></td></tr>');
//<td style="cursor: pointer" onclick="sensorDelete(\'' + data.sensor_id + '\')"><a href="#detail-modal" data-toggle="modal"><i class="fa fa-trash-o"></i></a></td></tr>');
else
$('table#sensorTable > tbody:last').append('<tr ><td class="selected sensor-table-td" style="cursor: pointer" onclick="getSensorDetail(\'' + data.sensorID + '\', \'' + data.sensorIP + '\')"> <a href=# data-toggle="modal" data-target="#sensor-detail-modal">' + data.sensorIP + '</td><td>' + data.sensorName + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td><td><span class="btn btn-circle btn-success btn-sm" data-toggle="tooltip" data-placement="top" title="Last Submit: ' + lastSubmitDate + '" style="margin-left: 18px"></span></td><td><a class="btn btn-circle btn-inverse" href="editSensor/' + data.sensorID + '"><i class="fa fa-pencil"></i></a></td></tr>');
//<td style="cursor: pointer" onclick="sensorDelete(\'' + data.sensor_id + '\')"><a href="#detail-modal" data-toggle="modal"><i class="fa fa-trash-o"></i></a></td></tr>);
});
}
});
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}
; // add zero in front of numbers < 10
return i;
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function sensorDelete(id) {
document.getElementById("b").innerHTML = 'Are you sure?</br></br><table width="400" style="text-align: center;"><td><button type="button" onclick="del(\'' + id + '\')"><i class="fa fa-thumbs-o-up fa-3x"></i></button></td><td><button type="button" data-dismiss="modal"><i class="fa fa-thumbs-o-down fa-3x"></i></button></td></table>';
}
function del(id) {
$.ajax({
type: "GET",
url: "deleteSensor/" + id,
cache: false,
beforeSend: function () {
$("#b").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function () {
$("#b").html('');
}, //Hide spinner
success: function () {
$("#b").append('Success!');
location.reload();
}
});
}
function getSensorDetail(sensorID) {
$('#sensorDetailSpan').removeAttr('style');
$.ajax({
type: "GET",
url: "getIPSensor/" + sensorID,
cache: false,
dataType: 'json',
beforeSend: function () {
$("#ip-sensor-table").css('display', 'none');
$("#ip-sensor-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function () {
$("#ip-sensor-div").html('');
}, //Hide spinner
success: function (msg) {
$("#ip-sensor-table").removeAttr('style');
$('table#ip-sensor-table > tbody:last').empty();
$.each(msg, function (i, data) {
$('table#ip-sensor-table > tbody:last').append('<tr><td>' + data.countryIP + '</td><td><img src="public/assets/img/country/' + data.countryCode.toLowerCase() + '.png"> ' + data.countryName + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getPortSensor/" + sensorID,
cache: false,
dataType: 'json',
beforeSend: function () {
$("#port-sensor-table").css('display', 'none');
$("#port-sensor-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function () {
$("#port-sensor-div").html('');
}, //Hide spinner
success: function (msg) {
$("#port-sensor-table").removeAttr('style');
$('table#port-sensor-table > tbody:last').empty();
$.each(msg, function (i, data) {
$('table#port-sensor-table > tbody:last').append('<tr><td>' + data.portNumber + '</td><td>' + data.portName + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getMalwareSensor/" + sensorID,
cache: false,
dataType: 'json',
beforeSend: function () {
$("#mal-sensor-table").css('display', 'none');
$("#mal-sensor-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function () {
$("#mal-sensor-div").html('');
}, //Hide spinner
success: function (msg) {
$("#mal-sensor-table").removeAttr('style');
$('table#mal-sensor-table > tbody:last').empty();
$.each(msg, function (i, data) {
$('table#mal-sensor-table > tbody:last').append('<tr><td style="cursor: pointer" onclick="getMalwareDetail(\'' + data.malwareMd5 + '\',\'' + data.malwareUrl + '\')"> <a href="#virus-detail-modal" data-toggle="modal">' + data.malwareMd5 + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getPICSensor/" + sensorID,
cache: false,
dataType: 'json',
beforeSend: function () {
$("#pic-sensor-table").css('display', 'none');
$("#pic-sensor-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function () {
$("#pic-sensor-div").html('');
}, //Hide spinner
success: function (msg) {
$("#pic-sensor-table").removeAttr('style');
$('table#pic-sensor-table > tbody:last').empty();
$.each(msg, function (i, data) {
$('table#pic-sensor-table > tbody:last').append('<tr><td>' + data.userName + '</td><td>' + data.userEmail + '</td><td>' + data.instituteName + '</td></tr>');
});
}
});
}
function getMalwareDetail(md5, url) {
$.ajax({
type: "GET",
url: "getMalwareData/" + md5,
cache: false,
dataType: 'json',
beforeSend: function () {
$("#vt-table").css('display', 'none');
$("#vt-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#result").html('');
},
complete: function () {
$("#vt-div").html('');
$("#result").html('<b>MD5 Hash: </b>' + md5);
}, //Hide spinner
success: function (msg) {
$("#vt-table").removeAttr('style');
$('table#vt-table > tbody:last').empty();
$.each(msg, function (i, data) {
$('table#vt-table > tbody:last').append('<tr><td>' + data.virustotalscan_scanner + '</td><td>' + data.virustotalscan_result + '</td></tr>');
});
$('table#vt-table > tbody:last').append('<tr><td colspan=2><a href="' + url + '" target="_blank">Complete details on virustotal.com</a></td></tr>');
}
});
// $.ajax({
// type: "GET",
// url: "getMalwareData/"+md5,
// cache: false,
// dataType: 'json',
// beforeSend: function() {
// $("#vt-table").css('display', 'none');
// $("#vt-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
// },
// complete: function() {
// $("#vt-div").html('');
// }, //Hide spinner
// dataType: 'json',
// success: function(msg) {
//// $('#mlDetailTable').removeAttr('style');
// $('table#vt-table > tbody:last').empty();
// $.each(msg, function(i, data) {
// $('table#vt-table > tbody:last').append('<tr ><td style="cursor: pointer">' + data.virustotalscan_scanner + '</td><td>' + data.virustotalscan_result + '</td></tr>');
// $('table#mlTable > tbody:last').append('<tr ><td style="cursor: pointer" onclick="getMalwareDetail('+url+')"> <a href="#detail-modal" data-toggle="modal">' + data.download_md5_hash + '</td><td>' + data.malware_count + '</a></td></tr>');
// });
// }
// });
// document.getElementById("virustotal").innerHTML = "<a href='"+url+"'>Complete URL</a>";
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BaseController extends Controller
{
public function __construct() {
$this->apiKey = Config::get('app.apiKey');
$this->host = Config::get('app.webservice_host');
$client = new \GuzzleHttp\Client;
$client->setDefaultOption('verify', false);
}
}
<file_sep>$(document).ready(function() {
var d = new Date();
getLatestAttack(d.getMonth()+1, d.getFullYear());
$.ajax({
type: "GET",
url: "topCountry",
cache: false,
beforeSend: function() {
$("#topCountry").css('display', 'none');
$("#countryLoad").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#countryLoad").html('');
},
dataType: 'json',
success: function(msg) {
$('#topCountry').removeAttr('style');
$.each(msg, function(i, data) {
$('table#topCountry > tbody:last').append('<tr><td>' + data.totalCountry + '</td><td><img src="public/assets/img/country/' + data.countryid.toLowerCase() + '.png"> ' + data.country_name + '</td></tr>');
});
}
});
function getLatestAttack(month, year) {
$.ajax({
type: "GET",
dataType: 'json',
url: "getLatestAttack/"+month+"/"+year,
data: "",
error: function(e) {
},
cache: false,
success: function(msg) {
var options = {
lines: {show: true, fill: true},
points: {show: true},
xaxis: {mode: "time", timeformat: "%d/%m", tickSize: [1, "day"]}
};
var d1 = [];
$.each(msg, function(i, data) {
d1.push([new Date(year, month-1, data.timeUnit), data.value]);
});
$.plot($("#latest-attack"), [d1], options);
}});
}
});
<file_sep>$(document).ready(function() {
$('.filter-by-date').hide();
$('#filter').change(function() {
if ($(this).val() == 'filter-by-date') {
$('.filter-by-date').removeAttr('style');
}
else {
$('.filter-by-date').css('display', 'none');
getPort($("#country").val(), "Date", "Date");
}
});
$('#portTable').on('click', '.ports-table-td', function() {
var state = $(this).parent().hasClass('highlighted-tr');
$('.highlighted-tr').removeClass('highlighted-tr');
if (!state) {
$(this).parent().addClass('highlighted-tr');
}
});
$.ajax({
type: "GET",
url: "getCountry",
cache: false,
dataType: 'json',
success: function(msg) {
$("#country").append('<option value="all">All Countries</option>');
$.each(msg, function(i, data) {
if (data.countryCode == "ID") {
$('#country').append('<option value="' + data.countryCode + '" selected>' + data.countryName + '</option>');
} else {
$('#country').append('<option value="' + data.countryCode + '">' + data.countryName + '</option>');
}
});
}
});
getPort("ID", "Date", "Date");
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function getPort(country, from, to) {
$.ajax({
type: "GET",
url: "getPort/" + country + "/" + from + "/" + to,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#portTable").css('display', 'none');
$("#portList").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#portList").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#portTable').removeAttr('style');
$('table#portTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#portTable > tbody:last').append('<tr ><td class="ports-table-td" style="cursor: pointer" onclick="getPortDetail(\'' + data.portDestination + '\',0,20)"> <a href=# data-toggle="modal" data-target="#port-detail-modal">' + data.service + '</td><td class="right-aligned">' + numberWithCommas(data.countPort) + '</td></tr>');
});
}
});
}
function getPortDetail(portNumber, offset, limit) {
$('#portDetailSpan').removeAttr('style');
$.ajax({
type: "GET",
url: "getIPAttack/" + portNumber + "/" + offset + "/" + limit,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#AttackerList").css('display', 'none');
$("#attacker-table-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#attacker-table-div").html('');
}, //Hide spinner
success: function(msg) {
$("#AttackerList").removeAttr('style');
$('table#AttackerList > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#AttackerList > tbody:last').append('<tr><td>' + data.ipsource + '</td><td>' + data.countryName + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</tr>');
});
if (msg.length >= limit)
$('table#AttackerList > tbody:last').append('<tr class="load-more-tr"><td colspan="3"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalIP(\'' + portNumber + '\',\'' + (offset + limit) + '\',' + limit + ')">Load More</button></td></tr>');
}
});
}
function getAdditionalIP(portNumber, detailOffset, detailLimit) {
$.ajax({
type: "GET",
url: "getIPAttack/" + portNumber + "/" + detailOffset + "/" + detailLimit,
cache: false,
beforeSend: function () {
$('.load-more-tr').css('display', 'none');
$("table#AttackerList > tbody:last").append('<center class="load-other"><img style="margin-left: 90px;" src="public/assets/img/ajax-loader-1.gif" /></center>');
},
complete: function () {
$(".load-other").html('');
}, //Hide spinner
dataType: 'json',
success: function (msg) {
$.each(msg, function(i, data) {
$('table#AttackerList > tbody:last').append('<tr><td>' + data.ipsource + '</td><td>' + data.countryName + '</td><td class="right-aligned">' + numberWithCommas(data.count) + '</tr>');
});
if (msg.length >= detailLimit)
$('table#AttackerList > tbody:last').append('<tr class="load-more-tr"><td colspan="3"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalIP(\'' + portNumber + '\',\'' + (+detailOffset + +detailLimit) + '\',' + detailLimit + ')">Load More</button></td></tr>');
}
});
}
<file_sep>function getUser(username, limit, offset) {
//var country_new = country;
$.ajax({
type: "GET",
url: "searchUser/" + username + "/" + limit + "/" + offset,
cache: false,
beforeSend: function() {
$("#resultSearch").removeAttr('style');
$("#loading-search").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
$("#userFoundTable").css('display', 'none');
$("#not-found").css('display', 'none');
$("#user-searched").html(username)
},
complete: function() {
$("#loading-search").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
// $("#loading-search").html('');
if (msg.length != 0) {
$('#userFoundTable').removeAttr('style');
$('table#userFoundTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#userFoundTable > tbody:last').append('<tr ><td class="user-table-td" style="cursor: pointer" onclick="getUserDetail(\'' + data.id + '\',\''+data.name+'\', 20, 0)">' + data.name + '</td><td>' + data.institutionName + '</td><td>' + data.email + '</td><td>' + data.roleName + '</td></tr>');
});
if (msg.length >= limit)
$('table#userFoundTable > tbody:last').append('<tr class="load-more-tr"><td colspan="2"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalUser(\'' + username + '\', ' + limit + ', ' + (offset + limit) + ')">Load More</button></td></tr>');
}
else {
$("#not-found").removeAttr('style');
$("#not-found").html("<center><b><h3>No User found</h3></b><center>");
}
}
});
}
function getAdditionalUser(username, limit, offset) {
$.ajax({
type: "GET",
url: "searchUser/" + username + "/" + limit + "/" + offset,
cache: false,
beforeSend: function() {
$('.load-more-tr').css('display', 'none');
$("table#userFoundTable > tbody:last").append('<center class="load-other"><img style="margin-left: 90px;" src="public/assets/img/ajax-loader-1.gif" /></center>');
},
complete: function() {
$(".load-other").css('display', 'none');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$.each(msg, function(i, data) {
$('table#userFoundTable > tbody:last').append('<tr ><td class="user-table-td" style="cursor: pointer" onclick="getUserDetail(\'' + data.id + '\',\''+data.name+'\', 20, 0)">' + data.name + '</td><td>' + data.institutionName + '</td><td>' + data.email + '</td><td>' + data.roleName + '</td></tr>');
});
if(msg.length >= limit)
$('table#userFoundTable > tbody:last').append('<tr class="load-more-tr"><td colspan="2"><button style="width:200px;" class="btn btn-default load-more" onclick="getAdditionalUser(\'' + username + '\', ' + limit + ', ' + (offset + limit) + ')">Load More</button></td></tr>');
}
});
}
function getUserDetail(userId, name) {
$('#userDetailSpan').removeAttr('style');
$('#user_name').html('');
$('#user_name').append(name);
$.ajax({
type: "GET",
url: "getUserBio/" + userId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#userBiodataTable").css('display', 'none');
$("#userBiodataDiv").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#userBiodataDiv").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#userBiodataTable').removeAttr('style');
$('table#userBiodataTable > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#userBiodataTable > tbody:last').append('<tr><td>' + data.user_telp + '</td><td>' + data.user_last_activity + '</td></tr>');
});
}
});
$.ajax({
type: "GET",
url: "getUserSensor/" + userId,
cache: false,
dataType: 'json',
beforeSend: function() {
$("#user-sensor-table").css('display', 'none');
$("#user-sensor-div").html('<center><img src="public/assets/img/ajax-loader.gif" /><br/>Loading...</center>');
},
complete: function() {
$("#user-sensor-div").html('');
}, //Hide spinner
dataType: 'json',
success: function(msg) {
$('#user-sensor-table').removeAttr('style');
$('table#user-sensor-table > tbody:last').empty();
$.each(msg, function(i, data) {
$('table#user-sensor-table > tbody:last').append('<tr><td>' + data.sensor_name + '</td><td>' + data.sensor_ip + '</td></tr>');
});
}
});
}<file_sep>$(document).ready(function () {
$("input[name='categorySelect']").click(function () {
var value = $(this).val();
if (value == "existing") {
$("#category_selection").removeAttr("style");
$("#new-category").css('display', 'none');
$("input[name='instituteSelect'][value='existing']").prop("disabled", false);
$("input[name='userSelect'][value='existing']").prop("disabled", false);
$("#institution_category").show();
$("#categoryText").hide();
}
else if (value == "new") {
$("#new-category").removeAttr("style");
$("#category_selection").css('display', 'none');
$("input[name='instituteSelect'][value='existing']").prop("disabled", true);
$("input[name='userSelect'][value='existing']").prop("disabled", true);
$("#institution_category").hide();
$("#categoryText").show();
}
})
$("input[name='instituteSelect']").click(function () {
var value = $(this).val();
if (value == "existing") {
$("#institute_selection").removeAttr("style");
$("#new-institute").css('display', 'none');
$("input[name='userSelect'][value='existing']").prop("disabled", false);
$("#user_institute_1").show();
$("#user_institute_2").show();
$("#userInstituteText1").hide();
$("#userInstituteText2").hide();
}
else if (value == "new") {
$("#new-institute").removeAttr("style");
$("#institute_selection").css('display', 'none')
$("input[name='userSelect'][value='existing']").prop("disabled", true);
if($('#categoryText').length <= 0){
$("<span id='categoryText' style='display:block;'>"+$("#new_category_add").val()+"</span>").insertAfter("#institute_category_label")
}
$("#user_institute_1").hide();
$("#user_institute_2").hide();
$("#userInstituteText1").show();
$("#userInstituteText2").show();
}
})
$("input[name='userSelect']").click(function () {
var value = $(this).val();
if (value == "existing") {
$("#user_selection").removeAttr("style");
$("#new-user").css('display', 'none');
}
else if (value == "new") {
$("#new-user").removeAttr("style");
$("#user_selection").css('display', 'none')
if($('#userInstituteText1').length <= 0){
$("<span id='userInstituteText1' style='display:block;'>"+$("#new_institute_add").val()+"</span>").insertAfter("#institute_category_label_1")
}
if($('#userInstituteText2').length <= 0){
$("<span id='userInstituteText2' style='display:block;'>"+$("#new_institute_add").val()+"</span>").insertAfter("#institute_category_label_2")
}
}
})
$.validator.addMethod("userNotSame", function (value, element) {
return value != $("#user_1_id").val();
}, "User 1 and User 2 must not be the same")
//Validation of wizard form
if (jQuery().validate) {
var removeSuccessClass = function (e) {
$(e).closest('.form-group').removeClass('has-success');
}
var jq_validator = $('#wizard-validation').validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block', // default input error message class
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
focusInvalid: false, // do not focus the last invalid input
invalidHandler: function (event, validator) { //display error alert on form submit
},
highlight: function (element) { // hightlight error inputs
$(element).closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change dony by hightlight
$(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
setTimeout(function () {
removeSuccessClass(element);
}, 3000);
},
success: function (label) {
label.closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
}
});
}
//Look at onNext function to see how add validation to wizard
$('#form-wizard-add-sensor').bootstrapWizard({
'nextSelector': '.button-next',
'previousSelector': '.button-previous',
onTabClick: function (tab, navigation, index) {
alert('on tab click disabled');
return false;
},
onNext: function (tab, navigation, index) {
var valid = $("#wizard-validation").valid();
if (!valid) {
jq_validator.focusInvalid();
return false;
}
if (index == 1) {
var categorySelected = $("#category_id option:selected").val();
var url = "getInstituteByCategory/" + categorySelected;
$.getJSON(url, function (data) {
$("#institution_id").html("");
$.each(data, function (index, element) {
$("#institution_id").append("<option value='" + element.instituteId + "'>" + element.instituteName + "</option>")
})
})
$("#institution_category").val(categorySelected);
$("#institution_category").prop("disabled", true);
}
if (index == 2) {
var instituteSelected = $("#institution_id option:selected").val();
var url = "getUserByInstitute/" + instituteSelected;
$.getJSON(url, function (data) {
$("#user_1_id").html("");
$("#user_2_id").html("");
$.each(data, function (index, element) {
$("#user_1_id").append("<option value='" + element.id + "'>" + element.name + "</option>")
$("#user_2_id").append("<option value='" + element.id + "'>" + element.name + "</option>")
})
})
$("#user_institute_1").val(instituteSelected);
$("#user_institute_1").prop("disabled", true);
$("#user_institute_2").val(instituteSelected);
$("#user_institute_2").prop("disabled", true);
}
var total = navigation.find('li').length;
var current = index + 1;
var category, institute, user1, user2, sensorName, sensorIP;
if (current == total) {
if( $("#categorySelect1").is(":checked")){
category = ($("#category_id option:selected").text());
}
else {
category = ($("#categoryText").text());
}
if( $("#instituteSelect1").is(":checked")){
institute = ($("#institution_id option:selected").text());
}
else {
institute = ($("#new_institute_add").val());
}
if( $("#userSelectExisting").is(":checked")){
user1 = ($("#user_1_id option:selected").text());
user2 = ($("#user_2_id option:selected").text());
}
else {
user1 = ($("#user_name_1").val());
user2 = ($("#user_name_2").val());
}
sensorName = $("#sensor_name").val();
sensorIP = $("#sensor_ip").val();
$("#category-confirmation").html(category)
$("#institute-confirmation").html(institute)
$("#user1-confirmation").html(user1)
$("#user2-confirmation").html(user2)
$("#sensor-name-confirmation").html(sensorName);
$("#sensor-ip-confirmation").html(sensorIP);
}
// set wizard title
$('.step-title', $('#form-wizard-add-sensor')).text('Step ' + (index + 1) + ' of ' + total);
// set done steps
jQuery('li', $('#form-wizard-add-sensor')).removeClass("done");
var li_list = navigation.find('li');
for (var i = 0; i < index; i++) {
jQuery(li_list[i]).addClass("done");
}
if (current == 1) {
$('#form-wizard-add-sensor').find('.button-previous').hide();
} else {
$('#form-wizard-add-sensor').find('.button-previous').show();
}
if (current >= total) {
$('#form-wizard-add-sensor').find('.button-next').hide();
$('#form-wizard-add-sensor').find('.button-submit').show();
} else {
$('#form-wizard-add-sensor').find('.button-next').show();
$('#form-wizard-add-sensor').find('.button-submit').hide();
}
var $percent = (current / total) * 100;
$('#form-wizard-add-sensor').find('.progress-bar').css('width', $percent + '%');
$('html, body').animate({scrollTop: $("#form-wizard-add-sensor").offset().top}, 900);
},
onPrevious: function (tab, navigation, index) {
var total = navigation.find('li').length;
var current = index + 1;
$("input[name='instituteSelect']").prop('checked', false);
$("#institute_selection").css('display', 'none');
$("#new-institute").css('display', 'none');
// set wizard title
$('.step-title', $('#form-wizard-add-sensor')).text('Step ' + (index + 1) + ' of ' + total);
// set done steps
jQuery('li', $('#form-wizard-add-sensor')).removeClass("done");
var li_list = navigation.find('li');
for (var i = 0; i < index; i++) {
jQuery(li_list[i]).addClass("done");
}
if (current == 1) {
$('#form-wizard-add-sensor').find('.button-previous').hide();
} else {
$('#form-wizard-add-sensor').find('.button-previous').show();
}
if (current >= total) {
$('#form-wizard-add-sensor').find('.button-next').hide();
$('#form-wizard-add-sensor').find('.button-submit').show();
} else {
$('#form-wizard-add-sensor').find('.button-next').show();
$('#form-wizard-add-sensor').find('.button-submit').hide();
}
var $percent = (current / total) * 100;
$('#form-wizard-add-sensor').find('.progress-bar').css('width', $percent + '%');
$('html, body').animate({scrollTop: $("#form-wizard-add-sensor").offset().top}, 900);
},
onTabShow: function (tab, navigation, index) {
var total = navigation.find('li').length;
var current = index + 1;
var $percent = (current / total) * 100;
$('#form-wizard-add-sensor').find('.progress-bar').css({
width: $percent + '%'
});
}
});
$('#form-wizard-add-sensor').find('.button-previous').hide();
$('#form-wizard-add-sensor .button-submit').click(function () {
alert('Finished!');
}).hide();
}
)
| f58c5b406d3483b3f16ec92bf5ae5ed87eb0da6d | [
"JavaScript",
"PHP"
] | 19 | PHP | enriconathaniel/magang_kominfo | b66e013e744e67caf216a43e4af1adf44da75a1d | 99367445c004164c8e0effc7dd53c2fb1c7e3fb3 |
refs/heads/main | <file_sep>import React, { Component } from 'react'
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import AppBar from "material-ui/AppBar"
export class Success extends Component {
render() {
const {values} = this.props ;
return (
<MuiThemeProvider>
<React.Fragment>
<AppBar title="Congratulations !"/>
<h1>{values.firstName} your form is Submitted successfully</h1>
</React.Fragment>
</MuiThemeProvider>
)
}
}
export default Success
<file_sep>import React, { Component } from 'react'
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import AppBar from "material-ui/AppBar";
import List from "material-ui/List";
import ListItem from "material-ui/List/ListItem";
import { RaisedButton } from 'material-ui';
export class Confirm extends Component {
continue = e => {
e.preventDefault();
this.props.nextStep();
}
goback = e => {
e.preventDefault();
this.props.prevStep();
}
render() {
const {values: {firstName,lastName,email,city,contact,bio,branch}} = this.props;
return (
<MuiThemeProvider>
<React.Fragment>
<AppBar title="Check Your details"/>
<List>
<ListItem
primaryText="Fisrt Name"
secondaryText={firstName}
/>
<ListItem
primaryText="Last Name"
secondaryText={lastName}
/>
<ListItem
primaryText="Email"
secondaryText={email}
/>
<ListItem
primaryText="Branch"
secondaryText={branch}
/>
<ListItem
primaryText="Contact Number"
secondaryText={contact}
/>
<ListItem
primaryText="City"
secondaryText={city}
/>
<ListItem
primaryText="Bio"
secondaryText={bio}
/>
</List>
<RaisedButton
primary={false}
label="Go Back"
style={Styles.button}
onClick={this.goback}
/>
<RaisedButton
primary={true}
label ="Submit"
style={Styles.button}
onClick={this.continue}/>
</React.Fragment>
</MuiThemeProvider>
)
}
}
const Styles = {
button : {
margin: 15
}
}
export default Confirm
| dc1f83e96e248e38fd4c5339f8390793e668551f | [
"JavaScript"
] | 2 | JavaScript | sahukanishka/Multi-step-form-react | a9539ca1ec2c62cc2be087584b912ef27b52bed3 | e79008d25299d3285a69821ecc4cf1cb640a54b4 |
refs/heads/master | <file_sep>from pymongo import MongoClient
client = MongoClient()
from bson.objectid import ObjectId
if __name__ == '__main__':
db = client.csci2963
defs = db.definitions
for definition in defs.find():
print definition
print defs.find_one()
print defs.find({"word": "Word"})
print defs.find_one({"_id": ObjectId('56fe9e22bad6b23cde07b8b7')})
defs.insert_one({"word": "NotAWord", "definition": "NotADefinition"})
<file_sep>from pymongo import MongoClient
client = MongoClient()
import random
import time
def random_word_requester():
'''
This function should return a random word and its definition and also
log in the MongoDB database the timestamp that it was accessed.
'''
db = client.csci2963
defs = db.definitions
count = defs.count()
rand_word = defs.find().limit(-1).skip(random.randint(0, count-1))
for w in rand_word:
word = w
print
defs.update(word, {"$push": {"dates": time.strftime("%Y-%m-%d %H:%M:%S")}})
return defs.find_one(word)
if __name__ == '__main__':
print random_word_requester()
| 3d1ad854f1b1aff80ccb3f4ee2dfa6171b3bca65 | [
"Python"
] | 2 | Python | ToastyToes/csci2963_mongodb_lab | e67138bccb6de59125e3c2361a744021f854be9b | 92cc6d420152a7043845fd8ce13cfa2c4cfd54f0 |
refs/heads/master | <file_sep><?php
include "inc/dbconnection.php";
?>
<!DOCTYPE HTML>
<html>
<head lang="en">
<title>Contact page</title>
<!--Header information -->
<?php include "header.php" ?>
</head>
<body>
<div class="banner">
<!-- Navbar -->
<?php include "inc/navigation.php" ?>
</div>
<section>
<!-- Contact information form -->
<h1 class="contact-h1">I'm so excited to hear from you!</h1>
<div class="form-content">
<form id="form" name="form" action="thankyou.php" method="POST">
<div>
<label for="firstname">First Name<input type="text" id="firstname" name="firstname" placeholder="First Name" required/></label>
</div>
<div>
<label for="lastname">Last Name</label>
<input type="text" id="lastname" name="lastname" placeholder="Last Name" required />
</div>
<div>
<label for="company">Company</label>
<input type="text" id="company" name="company" placeholder="Company" required />
</div>
<div>
<label for="email">Email<input type="email" id="email" name="email" placeholder="Email" required /></label>
</div>
<div>
<p>Comments:</p>
<textarea placeholder="Please add comments here..." cols="80" rows="10" name="comment" id="comment" required></textarea>
</div>
<div id="submitbtn">
<input type="submit" name="submit" value="Submit"/>
</div>
</form>
</div>
<div>
<?php
// If there is something being sent to the database
if(!empty($_POST)){
try {
$db = new PDO('mysql:dbname=Portfolio; host=localhost', 'root', 'root');
// Make a new connection to the database
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Check to if there are errors
$info = 'INSERT INTO Contact(comment, firstname, lastname, email, company)
VALUES( :comment, :firstname, :lastname, :email, :company)';
// Insert the information into the table in the correct fields
$givenInfo = $db->prepare($info);
// prepare the database
$givenInfo->bindParam(':firstname',strip_tags($_POST['firstname']));
// Bind the firstname value from the form to the firstname value of the table
$givenInfo->bindParam(':lastname',strip_tags($_POST['lastname']));
// bind the last name value of the form with the lastname value of the table
$givenInfo->bindParam(':email',strip_tags($_POST['email']));
// bind the email value of the form with the email value of the table
$givenInfo->bindParam(':company',strip_tags($_POST['company']));
// bind the company value of the form witht the email value of the table
$givenInfo->bindParam(':comment',strip_tags($_POST['comment']));
// bind the comment value of the form with the comment value of the table
$givenInfo->execute();
// Run the query
} catch(Exception $e){
// check to see if there are errors
echo $e->getMessage();
exit;
}
}
?>
</div>
</section>
<?php
// footer
include "footer.php";
?>
<file_sep><!DOCTYPE HTML>
<html>
<head lang="en">
<?php include "header.php" ?>
<title>Thank You</title>
</head>
<body>
<div class="banner">
<?php include "inc/navigation.php" ?>
</div>
<section>
<h1>I have recieved your information and will be getting back to you within 2 - 3 business days.
<?php
include "footer.php";
?>
<file_sep><!-- Database connection -->
<?php
try {
// make a new connection to the database
$db = new PDO('mysql:dbname=tmcgee_ecommerce;host=localhost;', 'r2hstudent', 'SbFaGzNgGIE8kfP');
// check for errors
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e){
// if there is a error send the message
echo $e->getMessage();
exit;
}
?>
<file_sep><!DOCTYPE HTML>
<html>
<head lang="en">
<?php include "header.php" ?>
<!-- Heading information -->
<title>Codepen page</title>
</head>
<body>
<div class="banner">
<!--Navbar -->
<?php include "inc/navigation.php" ?>
</div>
<section>
<!-- Codepen challenges -->
<h1 class="codepen-h1">CodePen Challenges</h1>
<div class="codepen-container">
<div class="codepen-content">
<p data-height="265" data-theme-id="0" data-slug-hash="QMOKaw" data-default-tab="js,result" data-user="teiataylor" data-embed-version="2" data-pen-title="Fidget Registration" class="codepen">See the Pen <a href="https://codepen.io/teiataylor/pen/QMOKaw/">Fidget Registration</a> by Teia (<a href="https://codepen.io/teiataylor">@teiataylor</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
<p>Protect your fidget Investment | This challenge includes a jQuery validation plugin to validate the fidget protection form.</p>
</div>
<div class="codepen-content">
<p data-height="265" data-theme-id="0" data-slug-hash="wevyrp" data-default-tab="html,result" data-user="teiataylor" data-embed-version="2" data-pen-title=" En Heaven " class="codepen">See the Pen <a href="https://codepen.io/teiataylor/pen/wevyrp/"> En Heaven </a> by Teia (<a href="https://codepen.io/teiataylor">@teiataylor</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
<p>En heaven| This challenge include CSS, and HTML it was my very first assignment in the Road2hire program.</p>
</div>
<div class="codepen-content">
<p data-height="265" data-theme-id="0" data-slug-hash="YxerYR" data-default-tab="js,result" data-user="teiataylor" data-embed-version="2" data-pen-title="Go fidget " class="codepen">See the Pen <a href="https://codepen.io/teiataylor/pen/YxerYR/">Go fidget </a> by Teia (<a href="https://codepen.io/teiataylor">@teiataylor</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
<p>Go Fidget | This challenge includes a tabata timer using jQuery to set and count the workout time, rest, and cycles.</p>
</div>
</div>
</section>
<section>
<aside>
<!-- React challenges -->
<div class="cookiebook">
<a href="facebook"><h2>Discover and join in on the Cookie Book</h2></a>
</div>
<div class="guessinggame">
<a href="quiz"><h2>Try you luck at the Number Guessing game</h2></a>
</div>
</aside>
</section>
<?php
// footer
include "footer.php";
?>
<file_sep><!DOCTYPE HTML>
<html>
<head lang="en">
<?php include "header.php" ?>
<!-- Heading information -->
<title>Home page</title>
</head>
<body>
<div class="banner">
<!--Nav bar -->
<?php include "inc/navigation.php" ?>
</div>
<section>
<article>
<!--Home page information -->
<h1 class="home-h1"><NAME></h1>
<div class="homepage-container">
<div class="homepage-content1">
<h2>Welcome,</h2>
<p>My name is <NAME>, I am a aspiring Front-End Web developer and a Graduate of the Road2hire program.</p>
</div>
<div class="homepage-content2">
<h2>What is the Road2Hire program?</h2>
<p><a href="http://road2hire.org">Road2hire</a> is a tech academy, which speciailizes in educating motivated Charlotte area young adults in the field of Web development.</p>
<p>Including topics such as jQuery, Javascript, PHP, C#, CSS, HTML, and many more!</p>
</div>
</div>
</article>
</section>
<script src="lib/js/javascript.js"></script>
<?php
// footer
include "footer.php";
?>
<file_sep><!DOCTYPE HTML>
<html>
<head lang="en">
<?php include "header.php" ?>
<!-- Heading information -->
<title>Resume page</title>
</head>
<body>
<div class="banner">
<!-- Navbar -->
<?php include "inc/navigation.php" ?>
</div>
<section>
<article>
<div class="resume">
<!-- Resume information -->
<div class="resume-content">
<h1><NAME> | 4511 Rose vine place | Charlotte NC, 28217 | <EMAIL> | Cell: 919 - 454 -7716</h1>
<h2>Highly motivated and career-driven aspiring Front-End Web Developer, I have a diverse array of skills including
problem solving, time management, and a positive goal-driven attitude.</h2>
<div class="skillList">
<h3>Skills:</h3>
<ul class="skillList">
<li>Developed skills in JavaScript, CSS, and HTML.</li>
<li>Programming Languages: jQuery, React, and PHP.</li>
<li>Knowledgeable in GitHub, Git, Codepen, and Atom text editor.</li>
</ul>
</div>
<h3>Experience:</h3>
<h4>Road2Hire</h4>
<p>Aspiring Web Designer | Fort Mill, SC | Graduated</p>
<div class="resumelist">
<ul class="resumelist">
<li>Create webpages using HTML, CSS, Javascrpt, jQuery, and PHP</li>
<li>Advanced training in Professional Development.</li>
<li>Collabrate with team members to effectly complete projects.</li>
</ul>
</div>
<h4>McDonalds Corporation</h4>
<p>Customer Service Representative | Cary, NC | 08/15- 7/16</p>
<div class="resumelist">
<ul>
<li>Cross-trained and coordinated scheduling with team members to ensure excellent service.</li>
<li>Maintaining a sanitary work area.</li>
<li>Resolved complaints promptly and professionally.</li>
</ul>
</div>
<h4>Xerox Corporation</h4>
<p>Customer Service Representative | Cary, NC | 12/14-7/15 </p>
<div class="resumelist">
<ul>
<li>Resolve customer complaints via phone, email, mail, or social media.</li>
<li>Responsible for acting as a liaison between customers and companies.</li>
<li>Greet customers warmly and ascertain problem or reason for calling.</li>
</ul>
</div>
<h4><NAME></h4>
<p>Customer Service Representative | Raleigh, NC | 02/14-12/14</p>
<div class="resumelist">
<ul>
<li>Assist customers in making decisions by providing them with combination options.</li>
<li>Take orders and enter the information into the POS system.</li>
<li>Provide customers with information about new promotions.</li>
</ul>
</div>
<h4>Education:</h4>
<p><NAME> High school | Greensboro, NC | Graduated</p>
<p>Central Piedmont Community College | Charlotte, NC | 2016 </p>
</div>
</div>
</article>
</section>
<?php
// footer
include "footer.php";
?>
<file_sep><?php
try{
// makes a new connection to the database
$db = new PDO('mysql:dbname=tmcgee_ecommerce;host=localhost;', 'r2hstudent', 'SbFaGzNgGIE8kfP');
// check for errors
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e){
// Catches the error and sends the error message
echo $e->getMessage();
exit;
}
?>
<file_sep><!DOCTYPE HTML>
<html>
<head lang="en">
<title>Gallery page</title>
<?php include "header.php" ?>
<!-- Heading information -->
</head>
<body>
<div class="banner">
<!-- Navbar -->
<?php include "inc/navigation.php" ?>
</div>
<section>
<!--For the slick slideshow plugin chosen pictures -->
<h1 class="gallery-h1">The Adventure</h1>
<div class="gallery-pics">
<img src="lib/img/react.JPG" alt="React Problem">
<img src="lib/img/clothingdrive.JPG" alt="R2Hire clothing drive">
<img src="lib/img/ilios.JPG" alt="RV cafe">
<img src="lib/img/Inclass.JPG" alt="In class">
<img src="lib/img/rv.JPG" alt="RV building">
<img src="lib/img/fusionconf.JPG" alt="Fusion Conference">
</div>
<div>
<!--captions to the pictures placed around the page -->
<p class="Ilios">Ilios Cafe</p>
</div>
<div>
<p class="classroom">Working Hard In Class</p>
</div>
<div>
<p class="RV">RV Building</p>
</div>
<div>
<p class="React">React</p>
</div>
<div>
<p class="fusion">Fusion Conference</p>
</div>
<div>
<p class="clothing">Clothing Drive</p>
</div>
<script src="lib/js/javascript.js"></script>
</section>
<?php
// footer
include "footer.php";
?>
<file_sep><!DOCTYPE HTML>
<html>
<head lang="en">
<?php include "header.php" ?>
<title>Biography page</title>
</head>
<body>
<div class="banner">
<!-- Banner includes the navbar -->
<?php include "inc/navigation.php" ?>
</div>
<section>
<div class="bio-pics">
<div class="bio-pic1">
<!--Images of myself -->
<img src="lib/img/TEIA.JPG" alt="<NAME>" class="myimage">
</div>
<div class="bio-pic">
<img src="lib/img/TTRM.JPG" alt="<NAME>" class="myimage">
</div>
<div class="bio-pic1">
<img src="lib/img/TM.JPG" alt="<NAME>" class="myimage1">
</div>
</div>
</section>
<section>
<article>
<div class="bio-content">
<!-- Personal quotes -->
<h1 id="bio-header">" The sky is the limit is only for people that believe in limits. My dreams will change the world starting with html tag at a time."</h1>
</div>
<div class="bio-info">
<h2>Offical Information</h2>
<h3>Known Languages</h3>
<!-- Description of known languages -->
<ul class="bio-list">
<li>javascript</li>
<li>PHP</li>
<li>CSS</li>
<li>HTML</li>
<li>jQuery</li>
</ul>
<h3>Goals</h3>
<!-- List of Goals -->
<ol class="bio-list">
<li>Spread Peace, Love, and Happiness</li>
<li>Become a Master Front-End Developer</li>
<li>To spread 50 bad dad jokes per hour</li>
<li>Travel and explore different cultures</li>
</ol>
</div>
</article>
</section>
<?php
// footer
include "footer.php";
?>
| 57b1ea526877bfe7fa6feddaa4fb479caf4325ec | [
"PHP"
] | 9 | PHP | teiamcgee/biography | a152188e909ef5170bfad510b1db1714a586fbd9 | cdefb5fe7c9885b5a4ff5aa955d932b973c8ca08 |
refs/heads/master | <file_sep><?php
if ($_GET["a"] === "0" || $_POST["a"] === "0") {
$record = array();
$date = new \DateTime();
$record['id'] = getRealIpAddr();
$record['date'] = $date->format('Y-m-d');
$record['time'] = $date->format('H:i:s');
try {
$fp = fopen('data/pixel.csv', 'a+');
if ( !$fp ) {
throw new Exception('File open failed.');
}
if (flock($fp, LOCK_EX)){
fputcsv($fp, $record);
flock($fp, LOCK_UN);
fclose($fp);
}
} catch (Exception $e) {
exit;
}
} elseif ($_GET["a"] === "1" || $_POST["a"] === "1") {
try {
$fp = fopen('data/count.txt', 'c+');
if ( !$fp ) {
throw new Exception('File open failed.');
}
if (flock($fp, LOCK_EX)){
$count = (int)fread($fp, filesize('data/count.txt'));
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, ++$count);
flock($fp, LOCK_UN);
fclose($fp);
}
} catch (Exception $e) {
exit;
}
}
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
| abbe0b4b617b7052e19fc7c956d4c74b2e1dbc62 | [
"PHP"
] | 1 | PHP | aarocax/pixel | dbe83a9348ef95e079f2e2f6bde25993fb4a1b7b | 4ac84ced72f6757c6f8f4321ec7e5efd94feb2d6 |
refs/heads/master | <repo_name>AnnasSalman/Portfolio<file_sep>/src/App.js
import { ChakraProvider } from "@chakra-ui/react"
import "@fontsource/poppins/700.css";
import "@fontsource/montserrat/900.css";
import Home from "./containers/Home/Home";
import { extendTheme } from "@chakra-ui/react"
import defaultTheme from './styles/themes/default/index'
const theme = extendTheme(defaultTheme)
function App({ Component, pageProps }) {
return (
<ChakraProvider theme={theme}>
<Home {...pageProps}/>
</ChakraProvider>
);
}
export default App;
<file_sep>/src/styles/themes/default/index.js
import colors from "./colors";
export default {
colors: colors,
components: {
Text: {
baseStyle: {
color: 'black',
fontFamily: 'poppins',
}
}
}
}
<file_sep>/src/components/Header/Header.js
import React, {useRef, useState} from 'react'
import {Flex, Image, Text, Box, Button} from "@chakra-ui/react";
import logo from '../../assets/logos/mainLogo.png'
import menuButton from '../../assets/animations/lf30_editor_vrxkddkz.json'
import Lottie from "lottie-react";
const menuOptions = {
loop: true,
autoplay: true,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice'
}
};
const Header = props => {
const menu = useRef(null)
const [paused, setPaused] = useState(true)
const [menuSegments, setMenuSegments] = useState([0,13])
const onMenuClick = () => {
console.log('menu clicked')
props.menuOpened
? menu.current.playSegments([70, 140],true)
: menu.current.playSegments([0, 70],true)
props.onMenuClick()
// menu.current.playSegments([1, 70], false)
// setMenuSegments([0,30])
// menu.current.goToAndStop(menu.current.totalFrames, true);
}
return(
<Flex w={'100%'} h={['10vh', '15vh']} paddingX={'5%'} pos={'fixed'} top={0} alignItems={'center'} justifyContent={'space-between'} zIndex={'popover'}>
{/*<Image src={logo} h={'50%'} ml={'3%'}/>*/}
<Flex direction={'column'}>
<Text fontSize={'bold'} fontSize={'xl'} lineHeight={1} color={'gray.700'}>ANNAS</Text>
<Text textAlign={'center'}>SALMAN</Text>
<Box w={'100%'} h={1.5} bgColor={'brand.primary'}/>
</Flex>
<Flex
onClick={onMenuClick}
zIndex={10}
as={'button'}
borderRadius={20}
width={20}
bgColor={'brand.background'}
justifyContent={"center"}>
<Lottie
style={{width: '60%'}}
animationData={menuButton}
lottieRef={menu}
autoplay={false}
loop={false}
/>
</Flex>
</Flex>
);
};
export default Header;
<file_sep>/src/containers/Home/Intro/Intro.js
import React from 'react'
import {Flex, Box, Text, useMediaQuery} from "@chakra-ui/react";
import Lottie from 'react-lottie'
import workAnimation from '../../../assets/animations/lf30_editor_j4f9fcus.json'
import mobileAnimation from '../../../assets/animations/44644-mobile-unlock-code.json'
import reactLogoAnimation from '../../../assets/animations/lf30_editor_rkaf2znc.json'
import Slider from "react-slick";
import "slick-carousel/slick/slick-theme.css";
import "slick-carousel/slick/slick.css";
import TextLoop from "react-text-loop";
const sliderSettings = {
dots: false,
infinite: true,
autoplay: true,
arrows: false,
fade: true,
autoplaySpeed: 3500,
adaptiveHeight: true,
slidesToShow: 1,
slidesToScroll: 1,
draggable: false,
};
const Intro = props => {
const [isLargerThanTablet] = useMediaQuery("(min-width: 768px)")
const defaultOptions = {
loop: true,
autoplay: true,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice'
}
};
return(
<Flex h={'100vh'}>
<Box
w={['100%', '85%', '80%']}
h={'100%'} left={['0%', '0%', '-12%']}
bottom={0}
alignItems={'center'}
justifyContent={'center'}
position={'absolute'}
overflow={'hidden'}>
<Slider {...sliderSettings} style={{height: '100%'}}>
<Flex h={'100vh'}>
<Lottie options={{...defaultOptions, animationData: workAnimation}}
isClickToPauseDisabled={true}
isStopped={false}
isPaused={false}/>
</Flex>
<Flex h={'100vh'}>
<Lottie options={{...defaultOptions, animationData: mobileAnimation}}
width={isLargerThanTablet?'50%':'100%'}
isClickToPauseDisabled={true}
isStopped={false}
isPaused={false}/>
</Flex>
<Flex h={'100vh'}>
<Lottie options={{...defaultOptions, animationData: reactLogoAnimation}}
width={isLargerThanTablet?'60%':'100%'}
isClickToPauseDisabled={true}
isStopped={false}
isPaused={false}/>
</Flex>
</Slider>
</Box>
<Flex
ml={['5%','15%', '46%']}
direction={"column"}
justifyContent={"center"}
h={"100%"} zIndex={'docked'}
width={['90%','65%','45%']}
pb={'3%'}>
<Flex alignItems={'center'} mb={5}>
<Box w={7} h={7} bgColor={'brand.primary'} borderRadius={15} position={'absolute'}/>
<Text fontSize={["sm", "md"]} fontWeight={'bold'} zIndex={'docked'} ml={4}>Hello, I'm <NAME></Text>
</Flex>
<Text fontSize={["4xl", "4xl", "5xl"]}>I'm a</Text>
<Flex direction={["column", 'row', 'row']}>
<TextLoop>
{
['React', 'React Native', 'Full Stack', 'MERN Stack'].map((item)=>{
return(
<Text
fontSize={["4xl", "4xl", "5xl"]}
fontWeight={'black'}
textShadow={["1px 1px #0f0f0f", "1px 1px #0f0f0f", "0px 0px #0f0f0f"]}
color={'brand.primary'}>
{item}
</Text>
)
})
}
{/*<Text fontSize={["4xl", "4xl", "5xl"]} fontWeight={'black'} color={'brand.primary'}>React </Text>*/}
{/*<Text fontSize={["4xl", "4xl", "5xl"]} fontWeight={'black'} color={'brand.primary'}>React Native</Text>*/}
{/*<Text fontSize={["4xl", "4xl", "5xl"]} fontWeight={'black'} color={'brand.primary'}>Full Stack</Text>*/}
{/*<Text fontSize={["4xl", "4xl", "5xl"]} fontWeight={'black'} color={'brand.primary'}>MERN Stack</Text>*/}
</TextLoop>
<Text
fontSize={["4xl", "4xl", "5xl"]}
fontWeight={'black'}
color={'brand.primary'}
textShadow={["1px 1px #0f0f0f", "1px 1px #0f0f0f", "0px 0px #0f0f0f"]}
ml={[0, 0, 2]}>
{' '}Developer
</Text>
</Flex>
<Text fontSize={["4xl", "4xl", "5xl"]} fontWeight={'black'}>Based in Islamabad</Text>
</Flex>
</Flex>
)
}
export default Intro
<file_sep>/src/containers/Home/Home.js
import React, {useState, useRef} from 'react'
import {Box, Flex} from "@chakra-ui/react";
import Lottie from "lottie-react";
import menu from '../../assets/animations/lf30_editor_q4mkwhnu.json'
import Intro from "./Intro/Intro";
import Header from "../../components/Header/Header";
import Menu from "../../components/Menu/Menu";
const Home = props => {
const [menuOpened, setMenuOpened] = useState(false)
const onMenuClick = () => {
setMenuOpened(!menuOpened)
}
return(
<Box bg="brand.background">
<Intro/>
<Menu menuOpened={menuOpened}/>
<Header menuOpened={menuOpened} onMenuClick={onMenuClick}/>
<Flex h={'100vh'} w={'100%'} bgColor={'yellow.200'}/>
</Box>
);
};
export default Home;
<file_sep>/src/styles/themes/dark/index.js
const colors = {
brand: {
900: "#12463d",
800: "#451e76",
700: "#912773",
},
}
export default colors;
| 140ae9f808db3f5f0c3b946c8770cb9f685f2188 | [
"JavaScript"
] | 6 | JavaScript | AnnasSalman/Portfolio | 9d8334cd1585bea32a6d0f0e0ac6ab891bb079b1 | 751631ae071815a23d2781ace8bc91bcd4336d4a |
refs/heads/master | <repo_name>afzalmuhammadhassan/pythonDjangoProj<file_sep>/newyear/views.py
import datetime
from django.shortcuts import render
def index(request):
dt = datetime.datetime.now()
return render(request, 'newyear/index.html',{
'newyear': dt.day == 1 and dt.month == 1
})
<file_sep>/hello/views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render (request, 'hello/index.html')
def greeting(request, name):
return render (request,'hello/greeting.html',{
'name': name.capitalize(),
'var': 'Tested Text'
}) | 41c085045b62691bb0ba0a23138908e2f841ce57 | [
"Python"
] | 2 | Python | afzalmuhammadhassan/pythonDjangoProj | 7a1c01a6d96e8eb73ddf25c96aa46bafa55dd9ea | 92013ffd2c5f42c4a09a272ba70b84eaca0159af |
refs/heads/master | <repo_name>germanponce/addons_cb<file_sep>/argil_sale_order_invoice/__openerp__.py
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Cidog de <NAME> ( <EMAIL> )
# Skype: german_442
##############################################################################
{
"name": "Facturación Publico en General (Pedidos de Venta)",
"version": "1.1",
"author": "Argil Consulting",
"category": "Sale",
"description": """
Facturación Publico en General
==============================
Este modulo permite Generar la Facturación de Publico en General para todos los Pedidos de Venta.
""",
"website": "http://www.argil.mx",
"license": "AGPL-3",
"depends": ["base_setup",
"product",
"account",
"sale",
"argil_pos_invoice",
"sale_stock",
],
"data": [
"view/sale_invoice_view.xml",
# "view/account_view.xml"
],
"test": [],
"js": [],
"css": [],
"qweb": [],
"installable": True,
"auto_install": False,
"active": False
}<file_sep>/argil_stock_reports_cb/__openerp__.py
# -*- coding: utf-8 -*-
{
'name': 'Reportes de Inventario Casa Baltazar',
'version': '1.0',
'category': 'CasaBaltasar',
'description': """
Módulo para la Gestion de Reportes para Inventarios
""",
'author': '<NAME>',
'website': 'http://www.argil.mx',
'depends': ['jasper_reports','stock','sale_stock'],
'data': [
"report_cb.xml",
"stock.xml",
"security/ir.model.access.csv"
],
'installable': True,
'auto_install': False,
}
<file_sep>/argil_cb_pos_resumen/pos.py
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api, _
from openerp.tools import float_compare
import openerp.addons.decimal_precision as dp
from datetime import time, datetime
from openerp import SUPERUSER_ID
from openerp import tools
from openerp.osv import osv, fields, expression
from openerp.tools.translate import _
from openerp.exceptions import except_orm, Warning, RedirectWarning
import base64
import pytz
class pos_order_report_jasper(osv.osv):
_name = 'pos.order.report.jasper'
_description = 'Reporte Detallado de Ventas'
_columns = {
'sale_order_ids': fields.one2many('pos.order.report.jasper.line','report_id','Pedidos de Venta Relacionados'),
'sale_journal_ids': fields.one2many('pos.order.report.journal.line','report_id','Metodos de Pago'),
'sale_tax_ids': fields.one2many('pos.order.report.tax.line','report_id','Impuestos'),
'user_ids': fields.many2many('res.users', 'pos_details_report_user_rel2', 'user_id', 'report_id', 'Usuarios'),
'date_start': fields.date('Date Start', required=True),
'date_end': fields.date('Date End', required=True),
'company_id': fields.many2one('res.company', 'Compañia'),
'name': fields.char('Referencia', size=256),
'date': fields.datetime('Fecha Consulta'),
'total_invoiced': fields.float('Total Facturado', digits=(14,2)),
'total_discount': fields.float('Descuento Total', digits=(14,2)),
'total_of_the_day': fields.float('Total del dia', digits=(14,2)),
'total_paid': fields.float('Total Pagado', digits=(14,2)),
'total_qty': fields.float('Cantidad de Producto', digits=(14,2)),
'total_sale': fields.float('Total de Ventas', digits=(14,2)),
}
def _get_company(self, cr, uid, context=None):
user_br = self.pool.get('res.users').browse(cr, uid, uid, context)
company_id = user_br.company_id.id
return company_id
def _get_date(self, cr, uid, context=None):
date = datetime.now().strftime('%Y-%m-%d')
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return date_now
# start = datetime.strptime(date_now, "%Y-%m-%d %H:%M:%S")
# user = self.pool.get('res.users').browse(cr, uid, uid)
# tz = pytz.timezone(user.tz) if user.tz else pytz.utc
# start = pytz.utc.localize(start).astimezone(tz) # convert start in user's timezone
# tz_date = start.strftime("%Y-%m-%d %H:%M:%S")
# return tz_date
_defaults = {
'company_id': _get_company,
'date': _get_date,
}
_order = 'id desc'
class pos_order_report_jasper_line(osv.osv):
_name = 'pos.order.report.jasper.line'
_description = 'Pedidos de Venta Origen'
_rec_name = 'order_id'
_columns = {
'report_id': fields.many2one('pos.order.report.jasper', 'ID Ref'),
'order_id': fields.many2one('pos.order','Pedido de Venta (POS)'),
}
_defaults = {
}
class pos_order_report_journal_line(osv.osv):
_name = 'pos.order.report.journal.line'
_description = 'Pagos del Reporte'
_columns = {
'report_id': fields.many2one('pos.order.report.jasper', 'ID Ref'),
'name': fields.char('Descripcion', size=128),
'sum': fields.float('Total', digits=(14,2)),
}
_defaults = {
}
class pos_order_report_tax_line(osv.osv):
_name = 'pos.order.report.tax.line'
_description = 'Impuestos del Reporte'
_columns = {
'report_id': fields.many2one('pos.order.report.jasper', 'ID Ref'),
'name': fields.char('Descripcion', size=128),
'amount': fields.float('Total', digits=(14,2)),
}
_defaults = {
}
class pos_details(osv.osv_memory):
_name = 'pos.details'
_inherit ='pos.details'
_columns = {
}
_defaults = {
}
def print_report(self, cr, uid, ids, context=None):
pos_report_obj = self.pool.get('pos.order.report.jasper')
user_obj = self.pool.get('res.users')
for rec in self.browse(cr, uid, ids, context):
pos_order = self.pool.get('pos.order')
user_list_ids = [x.id for x in rec.user_ids]
company_id = user_obj.browse(cr, uid, uid).company_id.id
company_id_name = user_obj.browse(cr, uid, uid).company_id.name
if not user_list_ids:
pos_usr_ids = pos_order.search(cr, uid,
[('date_order','>=',rec.date_start + ' 00:00:00'),
('date_order','<=',rec.date_end + ' 23:59:59'),
('state','in',('done','paid','invoiced')),
('company_id','=',company_id),
])
if not pos_usr_ids:
raise except_orm(_('Error!'),
_("No existen Pedidos Relacionados con el Rango seleccionado."))
return True
cr.execute("""select user_id from pos_order
where id in %s group by user_id;
""",(tuple(pos_usr_ids),))
cr_res = cr.fetchall()
user_list_ids = [x[0] for x in cr_res if x]
pos_order_ids = pos_order.search(cr, uid,
[('date_order','>=',rec.date_start + ' 00:00:00'),
('date_order','<=',rec.date_end + ' 23:59:59'),
('user_id','in',tuple(user_list_ids)),
('state','in',('done','paid','invoiced')),
('company_id','=',company_id),
])
# pos_order_ids = pos_order.search(cr, uid,
# [('date_order','>=',rec.date_start),('date_order','<=',rec.date_end),
# ('user_id','in',tuple(user_list_ids))])
line_list = []
if pos_order_ids:
for pos in pos_order_ids:
xline = (0,0,{
'order_id': pos,
})
line_list.append(xline)
vals = {
'sale_order_ids': line_list ,
'user_ids': [(6,0,user_list_ids)],
'date_start': rec.date_start,
'date_end': rec.date_end,
'name': rec.date_start+"/"+rec.date_end+" "+company_id_name
}
#### TOTALES ###
total_invoiced = 0.0
total_discount = 0.0
pos_ids = pos_order_ids
total_lines = 0.0
total_of_the_day = 0.0
total_qty = 0.0
for pos in pos_order.browse(cr, uid, pos_ids):
for pol in pos.lines:
total_discount += ((pol.price_unit * pol.qty) * (pol.discount / 100))
total_lines += (pol.price_unit * pol.qty * (1 - (pol.discount) / 100.0))
total_qty += pol.qty
pos_inv_ids = pos_order.search(cr, uid,
[('date_order','>=',rec.date_start + ' 00:00:00'),
('date_order','<=',rec.date_end + ' 23:59:59'),
('user_id','in',tuple(user_list_ids)),
('state','in',('done','paid','invoiced')),
('company_id','=',company_id),
('invoice_id','<>',False)])
for pos in pos_order.browse(cr, uid, pos_inv_ids):
for pol in pos.lines:
total_invoiced += (pol.price_unit * pol.qty * (1 - (pol.discount) / 100.0))
if total_lines:
if total_lines == total_invoiced:
total_of_the_day = total_lines
else:
total_of_the_day = ((total_lines or 0.00) - (total_invoiced or 0.00))
else:
total_of_the_day = 0.0
vals.update({'total_invoiced': total_invoiced,
'total_discount': total_discount,
'total_of_the_day': total_of_the_day,
'total_paid': total_of_the_day,
'total_qty': total_qty,
'total_sale': total_lines,
})
report_id = pos_report_obj.create(cr, uid, vals, context)
######### RESUMEN DE LOS PAGOS ############
statement_line_obj = self.pool.get("account.bank.statement.line")
if pos_ids:
print "## SI POS IDS"
st_line_ids = statement_line_obj.search(cr, uid, [('pos_statement_id', 'in', pos_ids)])
print "########## ST LINE IDS >>>> ", st_line_ids
if st_line_ids:
st_id = statement_line_obj.browse(cr, uid, st_line_ids)
a_l=[]
for r in st_id:
a_l.append(r['id'])
cr.execute("select aj.name,sum(amount) from account_bank_statement_line as absl,account_bank_statement as abs,account_journal as aj " \
"where absl.statement_id = abs.id and abs.journal_id = aj.id and absl.id IN %s " \
"group by aj.name ",(tuple(a_l),))
data = cr.dictfetchall()
report_journal = self.pool.get('pos.order.report.journal.line')
for d in data:
d.update({'report_id': report_id})
journal_mov = report_journal.create(cr, uid, d, context)
#### IMPUESTOS ####
tax_report_obj = self.pool.get('pos.order.report.tax.line')
account_tax_obj = self.pool.get('account.tax')
taxes = {}
for order in pos_order.browse(cr, uid, pos_ids):
for line in order.lines:
line_taxes = account_tax_obj.compute_all(cr, uid, line.product_id.taxes_id, line.price_unit * (1-(line.discount or 0.0)/100.0), line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
for tax in line_taxes['taxes']:
taxes.setdefault(tax['id'], {'name': tax['name'], 'amount':0.0})
taxes[tax['id']]['amount'] += tax['amount']
taxes_vals = taxes.values()
if taxes_vals:
for tx in taxes_vals:
tx.update({'report_id': report_id})
tax_mov_r = tax_report_obj.create(cr, uid, tx, context)
report = {
'type': 'ir.actions.report.xml',
'report_name': 'Detalle-Ventas',
'datas': {
'model' : 'pos.order.report.jasper',
'ids' : [report_id],
}
}
return report
return True
<file_sep>/argil_reports_cb/__openerp__.py
# -*- coding: utf-8 -*-
{
'name': 'Reportes Casa Baltazar',
'version': '1.0',
'category': 'CasaBaltasar',
'description': """
Módulo para la Gestion de Reportes Casa Baltazar
* Cheques
* Etiquetas de producto
* Factura
""",
'author': '<NAME>',
'website': 'http://www.argil.mx',
'depends': ['jasper_reports','account_voucher','sale','sale_stock'],
'data': [
"report_cb.xml",
],
'installable': True,
'auto_install': False,
}
<file_sep>/argil_sale_order_invoice/model/__init__.py
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# <NAME> ( <EMAIL> )
# Skype: german_442
##############################################################################
import sale_invoice
# import account
<file_sep>/argil_stock_reports_cb/stock.py
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api, _
from openerp.tools import float_compare
import openerp.addons.decimal_precision as dp
from datetime import time, datetime
from openerp import SUPERUSER_ID
from openerp import tools
from openerp.osv import osv, fields, expression
from openerp.tools.translate import _
from openerp.exceptions import except_orm, Warning, RedirectWarning
import base64
import pytz
class pos_stock_inventory_categ(osv.osv):
_name = 'pos.stock.inventory.categ'
_description = 'Reporte Inventario por Categoria'
_columns = {
'report_lines': fields.one2many('pos.stock.inventory.categ.line','report_id','Lineas del Inventario'),
'company_id': fields.many2one('res.company', 'Compañia'),
'date': fields.datetime('Fecha Consulta'),
'name': fields.char('Descripcion del Inventario', size=128),
'location_id': fields.many2one('stock.location', 'Ubicacion Inventariada'),
'user_id': fields.many2one('res.users', 'Usuario Audito'),
}
def _get_company(self, cr, uid, context=None):
user_br = self.pool.get('res.users').browse(cr, uid, uid, context)
company_id = user_br.company_id.id
return company_id
def _get_date(self, cr, uid, context=None):
date = datetime.now().strftime('%Y-%m-%d')
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return date_now
# start = datetime.strptime(date_now, "%Y-%m-%d %H:%M:%S")
# user = self.pool.get('res.users').browse(cr, uid, uid)
# tz = pytz.timezone(user.tz) if user.tz else pytz.utc
# start = pytz.utc.localize(start).astimezone(tz) # convert start in user's timezone
# tz_date = start.strftime("%Y-%m-%d %H:%M:%S")
# return tz_date
def _get_uid(self, cr, uid, context=None):
return uid
_defaults = {
'company_id': _get_company,
'date': _get_date,
'user_id': _get_uid,
}
_order = 'id desc'
class pos_stock_inventory_categ_line(osv.osv):
_name = 'pos.stock.inventory.categ.line'
_description = ' Reporte Inventario Lineas de Categoria'
_rec_name = 'detail_id'
_columns = {
'report_id': fields.many2one('pos.stock.inventory.categ', 'ID Ref'),
'detail_id': fields.many2one('pos.stock.inventory.categ.detail','Inventario por Categoria'),
}
_defaults = {
}
class pos_stock_inventory_categ_detail(osv.osv):
_name = 'pos.stock.inventory.categ.detail'
_description = 'Inventario por Categoria'
_rec_name = 'product_category'
_columns = {
'ref_id': fields.many2one('pos.stock.inventory.categ.line', 'ID Ref'),
'product_category': fields.many2one('product.category', 'Categoria'),
'detail_line': fields.one2many('pos.stock.inventory.categ.detail.line', 'ref_id', 'Productos'),
}
_defaults = {
}
_order = 'id'
class pos_stock_inventory_categ_detail_line(osv.osv):
_name = 'pos.stock.inventory.categ.detail.line'
_description = 'Detalle del Inventario por Categoria'
_rec_name = 'product_id'
_columns = {
'ref_id': fields.many2one('pos.stock.inventory.categ.detail', 'ID Ref'),
'location_id': fields.many2one('stock.location', 'Ubicacion',),
'product_id': fields.many2one('product.product', 'Producto'),
'product_uom_id': fields.many2one('product.uom', 'Unidad Base',),
'product_qty': fields.float('Cantidad', digits=(14,2)),
'default_code': fields.related('product_id', 'default_code', type='char', string='Codigo Interno', readonly=True),
}
_defaults = {
}
_order = 'id'
class stock_inventory_line(osv.osv):
_name = 'stock.inventory.line'
_inherit ='stock.inventory.line'
_columns = {
'product_category': fields.related('product_id', 'categ_id',
type="many2one", relation="product.category", string='Categoria', store=True),
}
_defaults = {
}
class stock_inventory(osv.osv_memory):
_name = 'stock.inventory'
_inherit ='stock.inventory'
_columns = {
}
_defaults = {
}
def print_report(self, cr, uid, ids, context=None):
pos_report_obj = self.pool.get('pos.stock.inventory.categ')
inventory_line_obj = self.pool.get('stock.inventory.line')
user_obj = self.pool.get('res.users')
for rec in self.browse(cr, uid, ids, context):
cr.execute("""
delete from pos_stock_inventory_categ;
""")
cr.execute("""
delete from pos_stock_inventory_categ_line;
""")
cr.execute("""
delete from pos_stock_inventory_categ_detail;
""")
cr.execute("""
delete from pos_stock_inventory_categ_detail_line;
""")
####### PRIMERO A CONSTRUIR LAS CATEGORIAS Y SUS DETALLES ######
cr.execute("""
select product_category from stock_inventory_line
where inventory_id = %s group by product_category;
""" % rec.id)
cr_res = cr.fetchall()
category_ids = [x[0] for x in cr_res if x]
inventory_categ_detail = self.pool.get('pos.stock.inventory.categ.detail')
inventory_categ_detail_ids = []
for category in category_ids:
detail_lines = []
cr.execute("""
select id from stock_inventory_line where inventory_id = %s
and product_category = %s ;
""" % (rec.id, category, ))
cr_res = cr.fetchall()
inventory_line_ids = [x[0] for x in cr_res]
cr.execute("""
select location_id,
product_id,
product_uom_id,
product_qty
from stock_inventory_line where id in %s ;
""", (tuple(inventory_line_ids),))
detail_lines = cr.dictfetchall()
vals_d = {
'product_category': category,
'detail_line': [(0,0,x) for x in detail_lines],
}
inv_categ_detail_id = inventory_categ_detail.create(cr, uid, vals_d, context)
inventory_categ_detail_ids.append(inv_categ_detail_id)
categ_report_obj = self.pool.get('pos.stock.inventory.categ')
####### Al final el reporte #########
vals = {
'name': rec.name,
'location_id': rec.location_id.id,
'report_lines': [(0,0,{'detail_id':x}) for x in inventory_categ_detail_ids] ,
}
report_id = self.pool.get('pos.stock.inventory.categ').create(cr, uid, vals, context)
report = {
'type': 'ir.actions.report.xml',
'report_name': 'Detalle-Inventario',
'datas': {
'model' : 'pos.stock.inventory.categ',
'ids' : [report_id],
}
}
return report
return True
<file_sep>/argil_facturae_mx/__openerp__.py
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2015
# All Rights Reserved.
# info skype: german_442 email: (<EMAIL>)
############################################################################
{
'name': 'Modificacion y Extension del Reporte de Facturacion Electronica',
'version': '1',
"author" : "<NAME>",
"category" : "Facturae",
'description': """
Este modulo reemplaza el reporte de factura electronica del modulo l10n_mx_facturae_report.
""",
"website" : "http://www.argil.mx",
"license" : "AGPL-3",
"depends" : ["l10n_mx_facturae_report"],
"init_xml" : [],
"demo_xml" : [],
"update_xml" : [
"report.xml",
],
"installable" : True,
"active" : False,
}
<file_sep>/argil_sale_order_invoice/model/sale_invoice.py
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# <NAME> ( <EMAIL> )
# Skype: german_442
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
import time
from datetime import datetime, date
import pytz
from openerp.exceptions import except_orm, Warning, RedirectWarning
from openerp import netsvc, workflow
class account_invoice(osv.osv):
_name = 'account.invoice'
_inherit = 'account.invoice'
_columns = {
'invoiced_control': fields.boolean('Control de Facturacion'),
}
_defaults = {
}
def copy(self, cr, uid, id, default=None, context=None):
if not default:
default = {}
default.update({
'invoiced_control': False,
})
return super(account_invoice, self).copy(cr, uid, id, default, context=context)
class sale_order_line(osv.osv):
_name = 'sale.order.line'
_inherit = 'sale.order.line'
_columns = {
'send_ok': fields.boolean('Enviado'),
'invoiced_control': fields.boolean('Control de Facturacion'),
'invoiced_mark': fields.boolean('Facturado'),
}
_defaults = {
}
def copy_data(self, cr, uid, id, default=None, context=None):
if not default:
default = {}
default.update({
'send_ok': False,
'invoiced_control': False,
'invoiced_mark': False,
})
return super(sale_order_line, self).copy_data(cr, uid, id, default, context=context)
class sale_order(osv.osv):
_name = "sale.order"
_inherit = "sale.order"
_columns = {
'invoice_2_general_public': fields.boolean('Publico en General', help="Activa este campo para Facturar como Publico en General."),
}
def copy(self, cr, uid, id, default=None, context=None):
if not default:
default = {}
default.update({
'invoice_2_general_public': False,
})
return super(sale_order, self).copy(cr, uid, id, default, context=context)
def get_customer_id_for_general_public(self, cr, uid, ids, context=None):
partner_obj = self.pool.get('res.partner')
partner_id = partner_obj.search(cr, uid, [('use_as_general_public','=',1)], limit=1, context=context)
if not partner_id:
raise osv.except_osv(_('Error!'), _('Por favor Configura un Cliente para ser usado como Publico en General.'))
addr = partner_obj.address_get(cr, uid, partner_id, ['delivery', 'invoice', 'contact'])
partner_id = partner_obj.browse(cr, uid, addr['invoice'])[0].id
return partner_id
def get_customer_for_general_public(self, cr, uid, ids, context=None):
partner_obj = self.pool.get('res.partner')
partner_id = partner_obj.search(cr, uid, [('use_as_general_public','=',1)], limit=1, context=context)
if not partner_id:
raise osv.except_osv(_('Error!'), _('Por favor Configura un Cliente para ser usado como Publico en General.'))
addr = partner_obj.address_get(cr, uid, partner_id, ['delivery', 'invoice', 'contact'])
partner_id = partner_obj.browse(cr, uid, addr['invoice'])[0]
return partner_id
def action_invoice3(self, cr, uid, ids, date, journal_id=False, context=None):
print "###################### INVOICE 3 "
if context is None: context = {}
inv_ref = self.pool.get('account.invoice')
acc_tax_obj = self.pool.get('account.tax')
inv_line_ref = self.pool.get('account.invoice.line')
product_obj = self.pool.get('product.product')
sales_order_obj = self.pool.get('sale.order')
order_line_obj = self.pool.get('sale.order.line')
picking_obj = self.pool.get('stock.picking')
# bsl_obj = self.pool.get('account.bank.statement.line')
print "################# JOURNAL ID ", journal_id
partner = self.get_customer_for_general_public(cr, uid, ids, context)
inv_ids = []
po_ids = []
lines = {}
for order in self.pool.get('sale.order').browse(cr, uid, ids, context=context):
print "#################### ORDER NAME ", order.name
if order.invoiced:
for fac in order.invoice_ids:
inv_ids.append(fac.id)
continue
if not order.invoice_2_general_public:
res = self.manual_invoice(cr, uid, [order.id], context)
# res = self.action_invoice2(cr, uid, order, journal_id, context=context)
print "################### RES ", res
inv_ids.append(res['res_id'])
else:
# if order.state in ('progress','manual'):
# bsl_ids = [x.id for x in order.statement_ids]
# bsl_obj.write(cr, uid, bsl_ids, {'partner_id': partner.id}, context=context)
po_ids.append(order.id)
for line in order.order_line:
## Agrupamos las líneas según el impuesto
xval = 0.0
for tax in acc_tax_obj.browse(cr, uid, [x.id for x in line.product_id.taxes_id]):
xval += (tax.price_include and tax.amount or 0.0)
tax_names = ", ".join([x.name for x in line.product_id.taxes_id])
val={
'tax_names' : ", ".join([x.name for x in line.product_id.taxes_id]),
'taxes_id' : ",".join([str(x.id) for x in line.product_id.taxes_id]),
'price_subtotal' : line.price_subtotal * (1.0 + xval),
'price_subtotal_incl' : line.price_subtotal,
}
key = (val['tax_names'],val['taxes_id'])
if not key in lines:
lines[key] = val
lines[key]['price_subtotal'] = val['price_subtotal']
lines[key]['price_subtotal_incl'] = val['price_subtotal_incl']
else:
lines[key]['price_subtotal'] += val['price_subtotal']
lines[key]['price_subtotal_incl'] += val['price_subtotal_incl']
if po_ids:
uom_obj = self.pool.get('product.uom')
uom_id = uom_obj.search(cr, uid, [('use_4_invoice_general_public','=',1)], limit=1, context=context)
if not uom_id:
raise osv.except_osv(_('Error!'), _('Por favor configura una Unidad de Medida por defecto para la Facturacion de Publico en General.'))
acc = partner.property_account_receivable.id
print "########################### journal_id", journal_id
inv = {
'name' : _('Factura Cliente'),
'origin' : _('Pedidos de Venta %s' % (date[8:10]+'/'+date[5:7]+'/'+date[0:4])),
'account_id': acc,
'journal_id': journal_id or order.sale_journal.id,
'type' : 'out_invoice',
'reference' : order.name,
'partner_id': partner.id,
'comment' : _('Factura Creada desde Pedidos de Venta.'),
'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
}
inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', partner.id)['value'])
if not inv.get('account_id', None):
inv['account_id'] = acc
inv_id = inv_ref.create(cr, uid, inv, context=context)
# self.write(cr, uid, po_ids, {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
self.write(cr, uid, po_ids, { 'invoiced': True }, context=context)
### VALIDANDO LOS WORKFLOW ###
for so in po_ids:
cr.execute('INSERT INTO sale_order_invoice_rel \
(order_id,invoice_id) values (%s,%s)', (so, inv_id))
flag = True
data_sale = sales_order_obj.browse(cr, uid, so, context=context)
for line in data_sale.order_line:
if not line.invoiced:
flag = False
break
if flag:
wf_service.trg_validate(uid, 'sale.order', so, 'manual_invoice', cr)
# if data_sale.order_policy == 'picking':
print "########### si entra en esta parte ???? Validaciones finales"
picking_obj.write(cr, uid, map(lambda x: x.id, data_sale.picking_ids), {'invoice_state': 'invoiced'})
sales_order_obj.write(cr, uid, [so], {'state': 'progress'})
sales_order_obj.signal_workflow(cr, uid, [so], 'manual_invoice')
for delinv in data_sale.invoice_ids:
if delinv.id != inv_id:
self.pool.get('account.invoice').unlink(cr, uid, [delinv.id], context=None)
sales_order_obj.signal_workflow(cr, uid, [so], 'invoice_corrected')
# wf_service.trg_validate(uid, 'sale.order', so, 'manual_invoice', cr)
# wf_service.trg_validate(uid, 'sale.order', so, 'invoice_corrected', cr)
inv_ids.append(inv_id)
for key, line in lines.iteritems():
tax_name = ''
inv_line = {
'invoice_id': inv_id,
'product_id': False,
'name' : ('VENTA AL PUBLICO EN GENERAL DEL DIA %s DEL ALMACEN %s' % (date[8:10]+'/'+date[5:7]+'/'+date[0:4], order.warehouse_id.name)) +
(line['tax_names'] and (' CON %s' % line['tax_names']) or ''),
'quantity' : 1,
'account_id': order.order_line[0].product_id.property_account_income.id or order.order_line[0].product_id.categ_id.property_account_income_categ.id,
'uos_id' : uom_id[0],
'price_unit': line['price_subtotal'],
'discount' : 0,
'invoice_line_tax_id' : [(6, 0, line['taxes_id'].split(','))] if line['taxes_id'] else False,
}
inv_line_id = inv_line_ref.create(cr, uid, inv_line, context=context)
print "################# INV LINE ID ",inv_line_id
print "################# INV LINE ID ",inv_line_ref
order_line_obj.write(cr, uid, [x.id for x in order.order_line],
{'invoice_lines': [(4, inv_line_id)],'invoiced': True}, context=context)
inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
self.signal_workflow(cr, uid, po_ids, 'invoice')
inv_ref.signal_workflow(cr, uid, [inv_id], 'validate')
if not inv_ids: return {}
# ir_model_data = self.pool.get('ir.model.data')
# act_obj = self.pool.get('ir.actions.act_window')
# result = ir_model_data.get_object_reference(cr, uid, 'account', 'action_invoice_tree1')
# id = result and result[1] or False
# context.update({'type':'out_invoice'})
# result = act_obj.read(cr, uid, [id], context=context)[0]
# result['domain'] = "[('id','in', [" + ','.join(map(str, inv_ids)) + "])]"
# return result
ir_model_data = self.pool.get('ir.model.data')
form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
form_id = form_res and form_res[1] or False
tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree')
tree_id = tree_res and tree_res[1] or False
return {
'domain': "[('id','in', ["+','.join(map(str,inv_ids))+"])]",
'name': _('Facturas Publico en General / Clientes'),
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'account.invoice',
'view_id': False,
'views': [(tree_id, 'tree'),(form_id, 'form')],
'type': 'ir.actions.act_window',
'context': {'type': 'out_invoice'},
}
class sale_make_invoice(osv.osv_memory):
_name = "sale.make.invoice"
_inherit = "sale.make.invoice"
def default_get(self, cr, uid, fields, context=None):
#print "context: ", context
if context is None: context = {}
#print "context: ", context
res = super(sale_make_invoice, self).default_get(cr, uid, fields, context=context)
record_ids = context.get('active_ids', [])
sale_order_obj = self.pool.get('sale.order')
if not record_ids:
return {}
tickets = []
partner_id = sale_order_obj.get_customer_id_for_general_public(cr, uid, record_ids, context)
for ticket in sale_order_obj.browse(cr, uid, record_ids, context):
if ticket.state in ('invoiced','cancel') and bool(ticket.invoice_id):
continue
tickets.append({
'order_id' : ticket.id,
'date_order' : ticket.date_order,
'order_id': ticket.id,
'name' : ticket.client_order_ref,
'user_id' : ticket.user_id.id,
'partner_id' : ticket.partner_id and ticket.partner_id.id or False,
'amount_total' : ticket.amount_total,
#'invoice_2_general_public' : (ticket.partner_id.invoice_2_general_public or ticket.partner_id.id == partner_id) if ticket.partner_id else True,
'invoice_2_general_public' : True,
})
res.update(order_ids=tickets)
#print "res: ", res
return res
_columns = {
'invoice_2_general_public': fields.boolean('Facturar a Publico en General'),
'period_id' : fields.many2one('account.period', 'Force period', required=True),
'journal_id' : fields.many2one('account.journal', 'Invoice Journal', help='You can select here the journal to use for the Invoice that will be created.', required=True),
'order_ids' : fields.one2many('sale.order.invoice_wizard.line','wiz_id','Pedidos a Facturar', required=True),
}
def _get_date(self, cr, uid, context=None):
tz_date = False
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
start = datetime.strptime(date_now, "%Y-%m-%d %H:%M:%S")
user = self.pool.get('res.users').browse(cr, uid, uid, context=None)
tz = pytz.timezone(user.tz) if user.tz else pytz.utc
start = pytz.utc.localize(start).astimezone(tz)
tz_date = start.strftime("%Y-%m-%d %H:%M:%S")
return tz_date
def _get_journal(self, cr, uid, context=None):
obj_journal = self.pool.get('account.journal')
user_obj = self.pool.get('res.users')
if context is None:
context = {}
company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id
journal = obj_journal.search(cr, uid, [('type', '=', 'sale'), ('company_id','=',company_id)], limit=1, context=context)
return journal and journal[0] or False
def _get_period(self, cr, uid, context=None):
if context is None: context = {}
res = {}
cr.execute("""SELECT p.id
FROM account_period p
where p.date_start <= NOW()
and p.date_stop >= NOW()
AND p.special = false
AND p.company_id = %s
LIMIT 1
""" % (self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id))
data = cr.fetchall()
period = data and data[0] or False
return period
_defaults = {
'journal_id': _get_journal,
'period_id': _get_period,
'invoice_date': _get_date,
}
def make_invoices(self, cr, uid, ids, context=None):
self_br = self.browse(cr, uid, ids, context=None)[0]
sale_order_obj = self.pool.get('sale.order')
active_ids = context and context.get('active_ids', False)
cr.execute("""
select name from sale_order where id in %s and order_policy = 'picking';
""", (tuple(active_ids),))
cr_res = cr.fetchall()
order_name_rest = [str(x[0]) for x in cr_res]
order_name_rest = list(set(order_name_rest))
if order_name_rest:
raise except_orm(
_('Error !'),
_('No puedes Facturar pedidos a Facturar desde Albaran.\n %s' % str(order_name_rest)))
cr.execute("""select name from sale_order where state not in ('progress','manual')
and id in %s;""", (tuple(ids),))
cr_res = cr.fetchall()
validate_list = [str(x[0]) for x in cr_res if x[0]]
if validate_list:
raise except_orm(
_('Error !'),
_('Los siguientes pedidos no se pueden Facturar debido al Estado del registro.\n %s' % (str(validate_list),)))
invoice_2_general_public_list = [x.id for x in self_br.order_ids if x.invoice_2_general_public]
if not invoice_2_general_public_list and self_br.invoice_2_general_public:
if order_name_rest:
raise except_orm(
_('Error !'),
_('Tienes Activada la Opcion de Facturar a Publico en General, pero ningun registro esta Activado con la misma Opcion.\n %s' % str(order_name_rest)))
print "#################### INVOICE 2 GENERAL PUBLIC LIST ", invoice_2_general_public_list
if self_br.invoice_2_general_public:
cr.execute("""SELECT p.id
FROM account_period p
where p.date_start <= '%s'
and p.date_stop >= '%s'
AND p.special = false
AND p.company_id = %s
LIMIT 1
""" % (self_br.invoice_date, self_br.invoice_date, self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id))
data = cr.fetchall()
period = data[0][0] if data else False
if not period:
raise except_orm(
_('Error !'),
_('Crea un Periodo para la Fecha que intentas Facturar [ %s ]' % self_br.invoice_date))
ids_to_set_as_general_public, ids_to_invoice = [], []
res = {}
for rec in self.browse(cr, uid, ids, context):
for line in rec.order_ids:
ids_to_invoice.append(line.order_id.id)
if line.invoice_2_general_public:
ids_to_set_as_general_public.append(line.order_id.id)
if ids_to_set_as_general_public:
cr.execute("update sale_order set invoice_2_general_public=true where id IN %s",(tuple(ids_to_set_as_general_public),))
if ids_to_invoice:
# res = sale_order_obj.manual_invoice(cr, uid, ids_to_set_as_general_public, context=None )
res = self.pool.get('sale.order').action_invoice3(cr, uid, ids_to_invoice, rec.invoice_date, rec.journal_id.id)
return res
return result
res = super(sale_make_invoice, self).make_invoices(cr, uid, ids, context)
return res
def make_invoices_grouped(self, cr, uid, ids, active_ids, context=None):
invoice_create_ids = []
invoice_obj = self.pool.get('account.invoice')
sale_order_obj = self.pool.get('sale.order')
invoice_line_obj = self.pool.get('account.invoice.line')
sale_order_line = self.pool.get('sale.order.line')
active_ids = active_ids
wf_service = netsvc.LocalService("workflow")
################ INTERRUPCION DEL FLUJO PYTHON ############################
raise except_orm(_('Interrupcion del Flujo!'),
_('Debugeando el Codigo de Creacion de Factura desde lineas de Venta') )
ir_model_data = self.pool.get('ir.model.data')
form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
form_id = form_res and form_res[1] or False
tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree')
tree_id = tree_res and tree_res[1] or False
return {
'domain': "[('id','in', ["+','.join(map(str,invoice_create_ids))+"])]",
'name': _('Facturas'),
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'account.invoice',
'view_id': False,
'views': [(tree_id, 'tree'),(form_id, 'form')],
'type': 'ir.actions.act_window',
'context': {'type': 'out_invoice'},
}
class sale_order_invoice_wizard_line(osv.osv_memory):
_name = "sale.order.invoice_wizard.line"
_description = "Asistente para Crear Factura Publico en General"
"""
"""
_columns = {
'wiz_id' : fields.many2one('sale.make.invoice','Ref ID'),
'order_id' : fields.many2one('sale.order', 'Pedido de Venta'),
'date_order' : fields.related('order_id', 'date_order', type="datetime", string="Fecha", readonly=True),
'name' : fields.related('order_id', 'name', type="char", size=64, string="Referencia", readonly=True),
'user_id' : fields.related('order_id', 'user_id', type="many2one", relation="res.users", string="Vendedor", readonly=True),
'amount_total' : fields.related('order_id', 'amount_total', type="float", string="Total", readonly=True),
'partner_id' : fields.related('order_id', 'partner_id', type="many2one", relation="res.partner", string="Cliente", readonly=True),
'invoice_2_general_public': fields.boolean('Publico en General'),
}
<file_sep>/argil_sale_order_invoice/model/BackupSaleInvoice.py
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# <NAME> ( <EMAIL> )
# Skype: german_442
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
import time
class sale_order(osv.osv):
_name = "sale.order"
_inherit = "sale.order"
_columns = {
'invoice_2_general_public': fields.boolean('Publico en General', help="Activa este campo para Facturar como Publico en General."),
}
def get_customer_id_for_general_public(self, cr, uid, ids, context=None):
partner_obj = self.pool.get('res.partner')
partner_id = partner_obj.search(cr, uid, [('use_as_general_public','=',1)], limit=1, context=context)
if not partner_id:
raise osv.except_osv(_('Error!'), _('Por favor Configura un Cliente para ser usado como Publico en General.'))
addr = partner_obj.address_get(cr, uid, partner_id, ['delivery', 'invoice', 'contact'])
partner_id = partner_obj.browse(cr, uid, addr['invoice'])[0].id
return partner_id
def get_customer_for_general_public(self, cr, uid, ids, context=None):
partner_obj = self.pool.get('res.partner')
partner_id = partner_obj.search(cr, uid, [('use_as_general_public','=',1)], limit=1, context=context)
if not partner_id:
raise osv.except_osv(_('Error!'), _('Por favor Configura un Cliente para ser usado como Publico en General.'))
addr = partner_obj.address_get(cr, uid, partner_id, ['delivery', 'invoice', 'contact'])
partner_id = partner_obj.browse(cr, uid, addr['invoice'])[0]
return partner_id
def action_invoice2(self, cr, uid, order, journal_id, context=None):
print "############### ACA =====> "
inv_ref = self.pool.get('account.invoice')
acc_tax_obj = self.pool.get('account.tax')
inv_line_ref = self.pool.get('account.invoice.line')
product_obj = self.pool.get('product.product')
inv_ids = []
if order.invoice_id:
return False
if not order.partner_id:
raise osv.except_osv(_('Error!'), _('Selecciona un Cliente para la Factura.'))
partner_obj = self.pool.get('res.partner')
addr = partner_obj.address_get(cr, uid, order.partner_id.parent_id and order.partner_id.parent_id.id or order.partner_id.id, ['delivery', 'invoice', 'contact'])
partner = partner_obj.browse(cr, uid, addr['invoice'])[0]
acc = partner.property_account_receivable.id
inv = {
'name': order.name,
'origin': order.name,
'account_id': acc,
'journal_id': journal_id and journal_id or order.sale_journal.id,
'type': 'out_invoice',
'reference': order.name,
'partner_id': partner.id, #order.partner_id.id,
'fiscal_position': partner.property_account_position and partner.property_account_position.id or False,
'payment_term' : partner.property_payment_term and partner.property_payment_term.id or False,
'comment': order.note or '',
'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
}
inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', partner.id)['value'])
if not inv.get('account_id', None):
inv['account_id'] = acc
inv_id = inv_ref.create(cr, uid, inv, context=context)
self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
inv_ids.append(inv_id)
for line in order.lines:
inv_line = {
'invoice_id': inv_id,
'product_id': line.product_id.id,
'quantity': line.qty,
}
inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
line.product_id.id,
line.product_id.uom_id.id,
line.qty, partner_id = partner.id,
fposition_id=partner.property_account_position.id)['value'])
# if not inv_line.get('account_analytic_id', False):
# inv_line['account_analytic_id'] = \
# self._prepare_analytic_account(cr, uid, line,
# context=context)
xval = 0.0
for tax in acc_tax_obj.browse(cr, uid, inv_line['invoice_line_tax_id']):
xval += (tax.price_include and tax.amount or 0.0)
price_unit = line.price_unit * (1.0 + xval)
inv_line['price_unit'] = price_unit
inv_line['discount'] = line.discount
inv_line['name'] = inv_name
inv_line['invoice_line_tax_id'] = [(6, 0, inv_line['invoice_line_tax_id'])]
inv_line_id = inv_line_ref.create(cr, uid, inv_line, context=context)
inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
self.signal_workflow(cr, uid, [order.id], 'invoice')
inv_ref.signal_workflow(cr, uid, [inv_id], 'validate')
return inv_ids and inv_ids[0] or False
def action_invoice3(self, cr, uid, ids, date, journal_id=False, context=None):
if context is None: context = {}
inv_ref = self.pool.get('account.invoice')
acc_tax_obj = self.pool.get('account.tax')
inv_line_ref = self.pool.get('account.invoice.line')
product_obj = self.pool.get('product.product')
bsl_obj = self.pool.get('account.bank.statement.line')
partner = self.get_customer_for_general_public(cr, uid, ids, context)
inv_ids = []
po_ids = []
lines = {}
for order in self.pool.get('sale.order').browse(cr, uid, ids, context=context):
if order.invoice_id:
inv_ids.append(order.invoice_id.id)
continue
if not order.invoice_2_general_public:
res = self.action_invoice2(cr, uid, order, journal_id, context=context)
inv_ids.append(res)
else:
if order.session_id.state == 'opened':
bsl_ids = [x.id for x in order.statement_ids]
bsl_obj.write(cr, uid, bsl_ids, {'partner_id': partner.id}, context=context)
po_ids.append(order.id)
for line in order.lines:
## Agrupamos las líneas según el impuesto
xval = 0.0
for tax in acc_tax_obj.browse(cr, uid, [x.id for x in line.product_id.taxes_id]):
xval += (tax.price_include and tax.amount or 0.0)
tax_names = ", ".join([x.name for x in line.product_id.taxes_id])
val={
'tax_names' : ", ".join([x.name for x in line.product_id.taxes_id]),
'taxes_id' : ",".join([str(x.id) for x in line.product_id.taxes_id]),
'price_subtotal' : line.price_subtotal * (1.0 + xval),
'price_subtotal_incl' : line.price_subtotal_incl,
}
key = (val['tax_names'],val['taxes_id'])
if not key in lines:
lines[key] = val
lines[key]['price_subtotal'] = val['price_subtotal']
lines[key]['price_subtotal_incl'] = val['price_subtotal_incl']
else:
lines[key]['price_subtotal'] += val['price_subtotal']
lines[key]['price_subtotal_incl'] += val['price_subtotal_incl']
if po_ids:
uom_obj = self.pool.get('product.uom')
uom_id = uom_obj.search(cr, uid, [('use_4_invoice_general_public','=',1)], limit=1, context=context)
if not uom_id:
raise osv.except_osv(_('Error!'), _('Please configure an Unit of Measure as default for use as UoM in Invoice Lines.'))
acc = partner.property_account_receivable.id
inv = {
'name' : _('From POS Orders'),
'origin' : _('POS Orders from %s' % (date[8:10]+'/'+date[5:7]+'/'+date[0:4])),
'account_id': acc,
'journal_id': journal_id or order.sale_journal.id,
'type' : 'out_invoice',
'reference' : order.session_id.name,
'partner_id': partner.id,
'comment' : _('Invoice created from POS Orders'),
'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
}
inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', partner.id)['value'])
if not inv.get('account_id', None):
inv['account_id'] = acc
inv_id = inv_ref.create(cr, uid, inv, context=context)
self.write(cr, uid, po_ids, {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
inv_ids.append(inv_id)
for key, line in lines.iteritems():
tax_name = ''
inv_line = {
'invoice_id': inv_id,
'product_id': False,
'name' : ('VENTA AL PUBLICO EN GENERAL DEL DIA %s DEL ALMACEN %s' % (date[8:10]+'/'+date[5:7]+'/'+date[0:4], order.location_id.name)) +
(line['tax_names'] and (' CON %s' % line['tax_names']) or ''),
'quantity' : 1,
'account_id': order.lines[0].product_id.property_account_income.id or order.lines[0].product_id.categ_id.property_account_income_categ.id,
'uos_id' : uom_id[0],
'price_unit': line['price_subtotal'],
'discount' : 0,
'invoice_line_tax_id' : [(6, 0, line['taxes_id'].split(','))] if line['taxes_id'] else False,
}
inv_line_ref.create(cr, uid, inv_line, context=context)
inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
self.signal_workflow(cr, uid, po_ids, 'invoice')
inv_ref.signal_workflow(cr, uid, [inv_id], 'validate')
if not inv_ids: return {}
ir_model_data = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
result = ir_model_data.get_object_reference(cr, uid, 'account', 'action_invoice_tree1')
id = result and result[1] or False
context.update({'type':'out_invoice'})
result = act_obj.read(cr, uid, [id], context=context)[0]
result['domain'] = "[('id','in', [" + ','.join(map(str, inv_ids)) + "])]"
return result
class sale_order_invoice_wizard(osv.osv_memory):
_name = "sale.order.invoice_wizard"
_description = "Wizard to create Invoices from Sale Orders"
"""
"""
def _get_journal(self, cr, uid, context=None):
obj_journal = self.pool.get('account.journal')
user_obj = self.pool.get('res.users')
if context is None:
context = {}
company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id
journal = obj_journal.search(cr, uid, [('type', '=', 'sale'), ('company_id','=',company_id)], limit=1, context=context)
return journal and journal[0] or False
def default_get(self, cr, uid, fields, context=None):
#print "context: ", context
if context is None: context = {}
#print "context: ", context
res = super(pos_order_invoice_wizard, self).default_get(cr, uid, fields, context=context)
#print "context: ", context
record_ids = context.get('active_ids', [])
sale_order_obj = self.pool.get('sale.order')
if not record_ids:
return {}
tickets = []
partner_id = sale_order_obj.get_customer_id_for_general_public(cr, uid, record_ids, context)
# partner_obj = self.pool.get('res.partner')
# partner_id = partner_obj.search(cr, uid, [('use_as_general_public','=',1)], limit=1, context=context)
# if not partner_id:
# raise osv.except_osv(_('Error!'), _('Please configure a Partner as default for Use as General Public Partner.'))
# addr = partner_obj.address_get(cr, uid, partner_id, ['delivery', 'invoice', 'contact'])
# partner_id = partner_obj.browse(cr, uid, addr['invoice'])[0].id
for ticket in sale_order_obj.browse(cr, uid, record_ids, context):
#print "ticket.name: ", ticket.name
#print "ticket.state: ", ticket.state
#print "ticket.invoice_id: ", bool(ticket.invoice_id)
if ticket.state in ('invoiced','cancel') and bool(ticket.invoice_id):
continue
tickets.append({
'ticket_id' : ticket.id,
'date_order' : ticket.date_order,
'session_id' : ticket.session_id.id,
'pos_reference' : ticket.pos_reference,
'user_id' : ticket.user_id.id,
'partner_id' : ticket.partner_id and ticket.partner_id.id or False,
'amount_total' : ticket.amount_total,
'invoice_2_general_public' : (ticket.partner_id.invoice_2_general_public or ticket.partner_id.id == partner_id) if ticket.partner_id else True,
})
res.update(ticket_ids=tickets)
#print "res: ", res
return res
def _get_period(self, cr, uid, context=None):
if context is None: context = {}
res = {}
cr.execute("""SELECT p.id
FROM account_period p
where p.date_start <= NOW()
and p.date_stop >= NOW()
AND p.special = false
AND p.company_id = %s
LIMIT 1
""" % (self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id))
data = cr.fetchall()
period = data and data[0] or False
return period
_columns = {
'date' : fields.date('Date', help='This date will be used as the invoice date and period will be chosen accordingly!', required=True),
'period_id' : fields.many2one('account.period', 'Force period', required=True),
'journal_id' : fields.many2one('account.journal', 'Invoice Journal', help='You can select here the journal to use for the Invoice that will be created.', required=True),
'ticket_ids' : fields.one2many('sale.order.invoice_wizard.line','wiz_id','Tickets to Invoice', required=True),
}
_defaults = {
'date': lambda *a : time.strftime('%Y-%m-%d'),
'journal_id' : _get_journal,
'period_id' : _get_period,
}
def on_change_date(self, cr, uid, ids, date=False, context=None):
if context is None: context = {}
res = {}
if not date:
return res
cr.execute("""SELECT p.id
FROM account_period p
where p.date_start <= '%s'
and p.date_stop >= '%s'
AND p.special = false
AND p.company_id = %s
LIMIT 1
""" % (date, date, self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id))
data = cr.fetchall()
period = data and data[0] or False
return {'value': {'period_id': period}}
def create_invoice_from_pos(self, cr, uid, ids, context=None):
if context is None: context = {}
ids_to_set_as_general_public, ids_to_invoice = [], []
res = {}
for rec in self.browse(cr, uid, ids, context):
for line in rec.ticket_ids:
ids_to_invoice.append(line.ticket_id.id)
if line.invoice_2_general_public:
ids_to_set_as_general_public.append(line.ticket_id.id)
if ids_to_set_as_general_public:
cr.execute("update pos_order set invoice_2_general_public=true where id IN %s",(tuple(ids_to_set_as_general_public),))
if ids_to_invoice:
res = self.pool.get('sale.order').action_invoice3(cr, uid, ids_to_invoice, rec.date, rec.journal_id.id)
return res or {'type': 'ir.actions.act_window_close'}
class sale_order_invoice_wizard_line(osv.osv_memory):
_name = "sale.order.invoice_wizard.line"
_description = "Wizard to create Invoices from several POS Tickets2"
"""
"""
_columns = {
'wiz_id' : fields.many2one('sale.order.invoice_wizard','Wizard'),
'ticket_id' : fields.many2one('sale.order', 'POS Ticket'),
'date_order' : fields.related('ticket_id', 'date_order', type="datetime", string="Date", readonly=True),
'session_id' : fields.related('ticket_id', 'session_id', type="many2one", relation="pos.session", string="Session", readonly=True),
'pos_reference' : fields.related('ticket_id', 'pos_reference', type="char", size=64, string="Reference", readonly=True),
'user_id' : fields.related('ticket_id', 'user_id', type="many2one", relation="res.users", string="Salesman", readonly=True),
'amount_total' : fields.related('ticket_id', 'amount_total', type="float", string="Total", readonly=True),
'partner_id' : fields.related('ticket_id', 'session_id', type="many2one", relation="res.partner", string="Partner", readonly=True),
'invoice_2_general_public': fields.boolean('General Public'),
}
| 2a94e60460f91c4a4b919953ef1a15de4d89166a | [
"Python"
] | 9 | Python | germanponce/addons_cb | 858453d4f4c3e8b43d34a759b20306926f0bf63e | de8ddee13df36cf2278edbbc495564bbff8ea29e |
refs/heads/master | <file_sep>Flask==0.12.2
requests==2.18.4
sapcai ==4.0.0
psycopg2 ==2.8.3
textblob_de ==0.4.3
wikipedia ==1.4.0
strsim ==0.0.3
lxml ==4.4.1
spacy ==2.2.1
https://github.com/explosion/spacy-models/releases/download/de_core_news_sm-2.2.0/de_core_news_sm-2.2.0.tar.gz
# https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz
<file_sep>from datetime import datetime, date
import spacy
from io import StringIO
from dictionaries import dictionary,dict_list_bereinigt, list_pm, list_socialmedia, list_technologiemanagement, klausur_fragen
from xml.dom.minidom import parse as makeDomObjFromFile, parseString as makeDomObjFromString
import urllib
from textblob_de import TextBlobDE as TextBlob
from textblob_de import PatternParser
from textblob_de.packages import pattern_de as pd
import wikipedia
from similarity.jarowinkler import JaroWinkler
from wikipedia.exceptions import DisambiguationError
import requests
from bs4 import BeautifulSoup as soup
import lxml
import re
import os
import random
import json
from flask import Flask, jsonify, request, redirect, url_for
import nltk
nltk.download('punkt')
app = Flask(__name__)
port = int(os.environ["PORT"])
@app.route('/', methods=['POST'])
def index():
return 'Home Page'
@app.route('/wikipedia', methods=['GET','POST'])
def wikipedia_search():
if request.method == 'POST':
wikipedia.set_lang("de")
data = json.loads(request.get_data())
# print(data)
nlp = spacy.load('de_core_news_sm')
doc = nlp(data['nlp']['source'])
suchwort = []
for token in doc:
if token.tag_ in ['NE','NNE', 'NN']:
suchwort.append(token.text)
suchwort = ' '.join(suchwort)
print(suchwort)
try:
wikipediaseite = wikipedia.page(suchwort)
answer = 'Wikipedia sagt: '
answer += wikipedia.summary(suchwort, sentences=5) + " Weiterlesen? " + wikipediaseite.url
# replies=[{
# 'type': 'text',
# 'content': answer,
# }]
# return replies
return jsonify(
status=200,
replies=[{
'type': 'text',
'content': answer,
}],
conversation={
'memory': { 'key': 'value' }
}
)
except wikipedia.exceptions.DisambiguationError as e:
# replies=[{
# 'type': 'text',
# 'content': "Wikipedia sagt: Ich konnte leider keinen Eintrag zu dem Wort '"+suchwort+"' finden. Vielleicht meinst du eins der folgenden Worte "+ str(e.options)+"? Wenn ja, gib deine Frage nochmal mit dem richtigen Wort ein.",
# }]
# return replies
return e.options
return jsonify(
status=200,
replies=[{
'type': 'text',
'content': "Ich konnte leider keinen Eintrag zu dem Wort '"+suchwort+"' finden. Vielleicht meinst du eins der folgenden Worte "+ str(e.options)+"? Wenn ja, gib deine Frage nochmal mit dem richtigen Wort ein.",
}],
conversation={
'memory': { 'key': 'value' }
}
)
else:
return '<h1>Wrong Address, go back to home!</h1>'
@app.route('/wetter', methods=['POST'])
def wetter():
api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
data = json.loads(request.get_data())
# print(data)
city = data["nlp"]["entities"]["location"][0]['raw']
# city = input('City Name:')
# city = 'Berlin'
url = api_address + city
json_data = requests.get(url).json()
#print(json_data )
aktuelletemperatur = str(json_data["main"]["temp"]-273.15)
höchsttemperatur = str(json_data["main"]["temp_max"]-273.15)
windgeschwindigkeit= str(json_data["wind"]["speed"])
return jsonify(
status=200,
replies=[{
'type': 'text',
# 'content':city,
'content': "Die aktuelle Temperatur in "+ city+ " beträgt "+aktuelletemperatur [0:4] + " C°. Die Tageshöchstemperatur wird " + höchsttemperatur [0:4]+ " C° nicht übersteigen. Der Wind weht mit einer Geschwindigkeit von " + windgeschwindigkeit+" km/h.",
}],
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/news')
def news():
encoding=None
extracttags={"title":"no title","link":None,"description":"no description"}
dom_obj = makeDomObjFromFile(urllib.request.urlopen("http://www.tagesschau.de/newsticker.rdf"))
news = []
for item in dom_obj.getElementsByTagName("item"):
extracted_item={}
for tag in extracttags:
try:
text=""
for node in item.getElementsByTagName(tag)[0].childNodes:
if node.nodeType == node.TEXT_NODE:
text += node.data
assert text != ""
except (IndexError,AssertionError):
extracted_item[tag]=extracttags[tag]
else:
if encoding:
text=text.encode(encoding)
extracted_item[tag]=text
news.append(extracted_item)
sentences = ''
if len(news)>=5:
for i in range (0,3):
sentences += "Neues in der Welt:" + '\n' + news[i]['title'] + '\n' + news[i]['description'] + '\n' + news[i]['link'] + '\n'
else:
for i in range (0,len(news)):
sentences += "Neues in der Welt:" + '\n' + news[i]['title'] + '\n' + news[i]['description'] + '\n' + news[i]['link'] + '\n'
return jsonify(
status=200,
replies=[{
'type': 'text',
'content':sentences,
}],
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/mensa')
def mensa():
weekdays = {6:'Sonntag', 0:'Monntag', 1:'Dienstag', 2:'Mittwoch', 3:'Donnerstag', 4:'Freitag', 5:'Samstag'}
datetime.today().weekday()
heute_tag = weekdays[datetime.today().weekday()]
heute_zeit = date.today().strftime("%d.%m.%Y")
result = requests.get('https://www.werkswelt.de/index.php?id=isch')
text = soup(result.content, 'lxml')
final_text = text.findAll("div", {"style": 'background-color:#ecf0f1;border-radius: 4px 4px 0px 0px; padding: 8px;'})[0].get_text()
txt = re.sub('[\n\r\xa0]', '', final_text)
txt = re.sub(' +', ' ',txt)
txt = re.split('Essen [1-9]', txt)
del txt[0]
essen_list = [{"type": "list", "content": {"elements":[]}}]
intermediate_list = [{"title": "Speiseplan " + heute_tag + " " + heute_zeit ,"imageUrl": "","subtitle": "","buttons": []}]
for i in enumerate(txt,1):
myd = {
"title": "",
"imageUrl": "",
"subtitle": "",
"buttons": []
}
myd['title'] = 'Essen ' + str(i[0])
myd['subtitle'] = i[1]
intermediate_list.append(myd)
print(intermediate_list)
essen_list[0]['content']['elements'] = intermediate_list
# print(essen_list)
return jsonify(
status=200,
replies=essen_list,
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/search', methods=['POST'])
def search():
global result
result = []
data = json.loads(request.get_data())
jarowinkler = JaroWinkler()
page_list = []
suchwort = []
first_set = []
second_set = []
# nlp = spacy.load('de_core_news_sm')
nlp = spacy.load('de_core_news_sm')
# nlp = spacy.load('en_core_web_sm', disable=["parser",'ner'])
word = ' '.join([i.capitalize() for i in data['nlp']['source'].split(' ')])
doc = nlp(word)
for token in doc:
# if token.tag_ in ['NNP','NNPS', 'NN', 'NNS']:
if token.tag_ in ['NE','NNE', 'NN']:
suchwort.append(token.text)
print(word)
if suchwort:
if len(suchwort) >= 2:
for d in dict_list_bereinigt:
for key, value in d.items():
for i in value:
if jarowinkler.similarity(i.lower(), suchwort[-1].lower()) > 0.95:
first_set.append(key)
for d in dict_list_bereinigt:
for key, value in d.items():
for i in value:
if jarowinkler.similarity(i.lower(), suchwort[-2].lower()) > 0.95:
second_set.append(key)
found_pages = list(set(first_set).intersection(set(second_set)))
else:
for d in dict_list_bereinigt:
for key, value in d.items():
for i in value:
if jarowinkler.similarity(i.lower(), suchwort[-1].lower()) > 0.95:
first_set.append(key)
found_pages = first_set
searchlist = list(set(found_pages))
page_list = [int(i[0]) for i in [i.split('.') for i in searchlist]]
sentence = "Außerdem habe {} Seite(n) im Skript mit {} finden können".format(len(page_list),' '.join(suchwort))
pic_urls = [dictionary[sorted(searchlist)[i]] for i in range(0,len(searchlist),3)]
result.append({'type': 'text', 'content':sentence + ". Hier sind ein paar Beispiele " + " ".join(str(i) for i in sorted(page_list))})
for i in pic_urls:
myd = {'type': 'picture','content':''}
myd['content'] = i
result.append(myd)
if len(page_list) == 0:
result = [{'type': 'text','content': 'Ich konnte nichts im Skript zum Wort {} finden'.format(suchwort[0])}]
replies=result
# return replies
return jsonify(
status=200,
replies=result,
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/zeit')
def zeit():
now = str(datetime.now()).split(' ')[1].split('.')[0][:5]
time_str = 'Je noch dem wo du gerade bist... \n In Nürnberg ist es gerade {}'.format(now)
return jsonify(
status=200,
replies=[{
'type': 'text',
'content':time_str,
}],
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/abfrage_klausur', methods=['POST'])
def abfrage_klausur():
#data = json.loads(request.get_data())
#print(data['nlp'])
global result
result = []
index_frage=int(random.randint(0,38)*2)
index_antwort=int(index_frage+1)
myd_frage={"":""}
myd_antwort={"":""}
myd_frage = {'type': 'picture','content':'','delay': 5}
myd_frage['content'] = klausur_fragen[index_frage]
myd_antwort = {'type': 'picture','content':'','delay':1 }
myd_antwort['content'] = klausur_fragen[index_antwort]
result.append(myd_frage)
antwort={'content': 'Die richtige Antwortet lautet', 'type': 'text','delay':5}
result.append(antwort)
result.append(myd_antwort)
replies=result
# return replies
return jsonify(
status=200,
replies=result,
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/abfrage', methods=['GET','POST'])
def abfrage():
#data = json.loads(request.get_data())
#print(data['nlp'])
global result
result = []
data = json.loads(request.get_data())
print(data["nlp"])
print(data['conversation']['memory']['thema']['raw'])
thema=data['conversation']['memory']['thema']['raw'] # thema
anzahl_fragen=int(data['nlp']['source'])
for i in range(anzahl_fragen):
if thema in ['Projektmanagement','projektmanagement','projectmanagement']:
index_frage=int(random.randint(0,31)*2)
index_antwort=int(index_frage+1)
myd_frage={"":""}
myd_antwort={"":""}
myd_frage = {'type': 'picture','content':'','delay': 5}
myd_frage['content'] = list_pm[index_frage]
myd_antwort = {'type': 'picture','content':'','delay': 4}
myd_antwort['content'] = list_pm[index_antwort]
result.append(myd_frage)
antwort={'content': 'Die Antwortet lautet', 'type': 'text','delay':5}
result.append(antwort)
result.append(myd_antwort)
if thema in ['socialmedia','Socialmedia','SocialMedia','SocialMedia']:
index_frage=int(random.randint(0,38)*2)
index_antwort=int(index_frage+1)
myd_frage={"":""}
myd_antwort={"":""}
myd_frage = {'type': 'picture','content':'','delay': 5}
myd_frage['content'] = list_socialmedia[index_frage]
myd_antwort = {'type': 'picture','content':'','delay': 4}
myd_antwort['content'] = list_socialmedia[index_antwort]
result.append(myd_frage)
antwort={'content': 'Die Antwortet lautet', 'type': 'text','delay':5}
result.append(antwort)
result.append(myd_antwort)
if thema in ['Technologiemanagement','technologiemanagement','TechnologieManagement']:
index_frage=int(random.randint(0,29)*2)
index_antwort=int(index_frage+1)
myd_frage={"":""}
myd_antwort={"":""}
myd_frage = {'type': 'picture','content':'','delay': 5}
myd_frage['content'] = list_technologiemanagement[index_frage]
myd_antwort = {'type': 'picture','content':'','delay': 4}
myd_antwort['content'] = list_technologiemanagement[index_antwort]
result.append(myd_frage)
antwort={'content': 'Die Antwortet lautet', 'type': 'text','delay':5}
result.append(antwort)
result.append(myd_antwort)
replies=result
# return replies
return jsonify(
status=200,
replies=result,
conversation={
'memory': { 'key': 'value' }
}
)
@app.route('/abfrage_oleg')
def abfrage_oleg():
# return replies
return jsonify(
status=200,
replies= [{'content': {'elements': [{'buttons': [],
'imageUrl': '',
'subtitle': '',
'title': 'Welches Startup hat laut dem Wall Street Journal 2018 die höchste Bewertung ?'},
{'buttons': [], 'imageUrl': '', 'subtitle': 'Uber', 'title': ''},
{'buttons': [], 'imageUrl': '', 'subtitle': 'Airbnb', 'title': ''},
{'buttons': [], 'imageUrl': '', 'subtitle': 'SpaceX', 'title': ''},
{'buttons': [], 'imageUrl': '', 'subtitle': '<NAME>', 'title': ''}]},
'delay': 5,
'type': 'list'},
{'content': 'RWelches Startup hat laut dem Wall Street Journal 2018 die höchste Bewertung ?: a)Uber b)SpaceX c)Airbnb d) <NAME>', 'type': 'text'},
{'content': {'elements': [{'buttons': [],
'imageUrl': '',
'subtitle': '',
'title': 'Welche Merkmale unterscheiden ein Startup von einer gewöhnlichen Gründung?'},
{'buttons': [],
'imageUrl': '',
'subtitle': ' Innovationsgrad der Geschäftsidee und das Wachstumspotential ',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Größe des Gründerteams und die Finanzierungsart der Gründung',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'der Onlineauftritt und die Vertriebskanäle',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'es gibt keine wesentlichen Unterschiede',
'title': ''}]},
'delay': 0,
'type': 'list'},
{'content': 'Richtige Antwort: Uber', 'type': 'text'},
{'content': {'elements': [{'buttons': [],
'imageUrl': '',
'subtitle': '',
'title': 'Welche Merkmale unterscheiden ein Startup von einer gewöhnlichen Gründung?'},
{'buttons': [],
'imageUrl': '',
'subtitle': ' Innovationsgrad der Geschäftsidee und das Wachstumspotential ',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Größe des Gründerteams und die Finanzierungsart der Gründung',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'der Onlineauftritt und die Vertriebskanäle',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'es gibt keine wesentlichen Unterschiede',
'title': ''}]},
'delay': 0,
'type': 'list'},
{'content': 'Richtige Antwort: Uber', 'type': 'text'},
{'content': 'Richtige Antwort: Uber', 'type': 'text'},
{'content': {'elements': [{'buttons': [],
'imageUrl': '',
'subtitle': '',
'title': 'Welche Merkmale unterscheiden ein Startup von einer gewöhnlichen Gründung?'},
{'buttons': [],
'imageUrl': '',
'subtitle': ' Innovationsgrad der Geschäftsidee und das Wachstumspotential ',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Größe des Gründerteams und die Finanzierungsart der Gründung',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'der Onlineauftritt und die Vertriebskanäle',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'es gibt keine wesentlichen Unterschiede',
'title': ''}]},
'delay': 0,
'type': 'list'},
{'content': 'Richtige Antwort: Innovationsgrad der Geschäftsidee und das Wachstumspotential',
'type': 'text'},
{'content': {'elements': [{'buttons': [],
'imageUrl': '',
'subtitle': '',
'title': 'Was versteht man unter einem Unicorn Startup?'},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Ein privates Unternehmen, welches das Potential hat ein börsennotiertes Unternehmen zu werden.',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Ein privates Unternehmen mit einer Bewertung über 1 Mrd. USD.',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Ein börsennotiertes Unternehmen, das vor weniger als 5 Jahren gegründet worden ist.',
'title': ''},
{'buttons': [],
'imageUrl': '',
'subtitle': 'Ein junges börsennotiertes Unternehmen, das Umsätze über Mrd. USD erwirtschaftet.',
'title': ''}]},
'delay': 0,
'type': 'list'},
{'content': 'Richtige Antwort: Ein privates Unternehmen mit einer Bewertung über 1 Mrd. USD.',
'type': 'text'}],
conversation={
'memory': { 'key': 'value' }
}
)
# @app.route('/skript_and_wiki_search', methods=['POST'])
# def skript_and_wiki_search():
# data = json.loads(request.get_data())
# print(wikipedia_search())
# print(search())
# result = wikipedia_search() + search()
# return jsonify(
# status=200,
# replies=result,
# conversation={
# 'memory': { 'key': 'value' }
# })
# return 'Hello wordl'
# if search():
# return jsonify(
# status=200,
# replies=result,
# conversation={
# 'memory': { 'key': 'value' }
# })
# else:
# return redirect(url_for('wikipedia_search'), code=307)
@app.route('/errors',methods=['POST'])
def errors():
print(json.loads(request.get_data()))
return jsonify(status=200)
app.run(port=port,host="0.0.0.0")
@app.route('/lecture-search')
def lecture_search():
data = json.loads(request.get_data())
global result
result = []
site_result = ['https://filehorst.de/d/djCzzslt',
'https://filehorst.de/d/dqrouGAl',
'https://filehorst.de/d/dEtaCcxf',
'https://filehorst.de/d/dgFFbjHi',
'https://filehorst.de/d/dihAJgFo',
'https://filehorst.de/d/dcfhdnlh',
'https://filehorst.de/d/dujbxqiJ',
'https://filehorst.de/d/dyielhbu',
'https://filehorst.de/d/dozterIh',
'https://filehorst.de/d/dBJdDxjz',
'https://filehorst.de/d/drewBtzk',
'https://filehorst.de/d/drqGxlkn',
'https://filehorst.de/d/drspwjFG',
'https://filehorst.de/d/dqvrDGzG',
'https://filehorst.de/d/dbivbevB',
'https://filehorst.de/d/dIIepgdA',
'https://filehorst.de/d/dghCqCHJ',
'https://filehorst.de/d/dqnFhipz']
for i in site_result:
dict_result = {'type': 'text','content':''}
dict_result['content'] = i
result.append(dict_result)
result = [{'type': 'text','content':'it works'}]
# return replies
return jsonify(
status=200,
replies=result,
conversation={
'memory': { 'key': 'value' }
}
)
| 372913052eaec62d60d94ffa250d844026f80877 | [
"Python",
"Text"
] | 2 | Text | fauchatbot/chatbot | 5c586cc50f0b97589b5417e112ea93da8ac22c82 | 7a650cb36d1910e83ed0f5ccf42b69ceee0a0727 |
refs/heads/master | <file_sep>// The User model
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var userSchema = new Schema({
name: { type: String, default: '' },
email: { type: String, default: '' },
username: { type: String, default: '' },
provider: { type: String, default: '' },
hashed_password: { type: String, default: '' },
salt: { type: String, default: '' },
authToken: { type: String, default: '' },
google: {},
isAdmin: Boolean
})
userSchema.statics = {
/**
* Load
*
* @param {Object} options
* @param {Function} cb
* @api private
*/
load: function (options, cb) {
options.select = options.select || 'name username'
return this.findOne(options.criteria)
.select(options.select)
.exec(cb)
}
}
module.exports = mongoose.model('User', userSchema)
<file_sep>const nodemailer = require('nodemailer')
const Router = require('express')
const config = require('../config')
const logger = require('winston')
var rp = require('request-promise')
var ok = require('./utils').ok
var fail = require('./utils').fail
module.exports = class MessageController {
constructor () {
this.smtpConfig = {
host: config.mail.server,
port: config.mail.port,
secure: true, // use SSL
auth: {
user: config.mail.username,
pass: config.mail.password
}
}
}
sendSMS (sms) {
var data = {
'username': config.sms.username,
'password': <PASSWORD>.sms.<PASSWORD>,
'function': 'sendSms',
'number': sms.number,
'message': sms.message,
'senderid': 'GrogBurners'
}
return rp('https://www.my-cool-sms.com/api-socket.php', { json: true, body: data })
.then((resp) => {
if (resp.hasOwnProperty('errorcode')) {
logger.error('Send SMS failed: ' + resp.description)
throw new Error('SMS Send failed!')
} else {
logger.info('SMS Sent to: ' + JSON.Stringify(resp))
logger.debug('SMS Sent: ' + JSON.Stringify(resp))
return { message: 'Message sent' }
}
})
/* .catch((err) => {
return new Error('Error creating message: ' + err)
}); */
}
sendTestEmail (body) {
const mailOptions = {
from: '"' + config.mail.from.name + '" <' + config.mail.from.address + '>', // sender address
to: body.to, // list of receivers
subject: body.subject, // Subject line
text: body.text, // plaintext body
html: body.html // html body
}
return this.send(mailOptions)
}
sendEmail (email) {
const transporter = nodemailer.createTransport(this.smtpConfig)
return transporter.sendMail(email)
.then(() => {
return { message: 'Message sent' }
})
/* .catch((err) => {
return new Error('Error creating message: ' + err)
}); */
}
routeAPI () {
const router = new Router()
router.post('/email', (req, res) => {
this
.sendEmail(req.body)
.then(ok(res))
.then(null, fail(res))
})
router.post('/sms', (req, res) => {
this
.sendSMS(req.body)
.then(ok(res))
.then(null, fail(res))
})
return router
}
}
<file_sep>var mongoose = require('mongoose')
var Schema = mongoose.Schema
var addressSchema = require('./common/address')
var phoneSchema = require('./common/phone')
var customerSchema = new Schema({
name: { type: String, required: true },
address: [ addressSchema ],
phone: [ phoneSchema ],
createdOn: { type: Date, default: Date.now },
updatedOn: { type: Date, default: Date.now }
})
customerSchema.pre('save', function (next) {
// change the updatedOn field to current date
this.updatedOn = new Date()
next()
})
/**
* Statics
*/
customerSchema.statics = {
/**
* Find customer by id
*
* @param {ObjectId} id
* @api private
load: function (_id) {
return this.findOne({ _id })
.populate('name', 'address phone')
.populate('customer.name')
.exec();
},*/
/**
* List customers
*
* @param {Object} options
* @api private
*/
list: function (options) {
const criteria = options.criteria || {}
const page = options.page || 0
const limit = options.limit || 30
return this.find(criteria)
.populate('name', 'address phone')
.sort({ createdAt: -1 })
.limit(limit)
.skip(limit * page)
.exec()
}
}
module.exports = mongoose.model('Customer', customerSchema)
<file_sep>require('dotenv').config()
var env = process.env.NODE_ENV || 'development'
var config = require('./config')[env]
module.exports = config
module.exports.env = env
<file_sep>var chai = require('chai')
var server = require('../../app')
/* eslint-disable no-unused-vars */
var should = chai.should()
var nock = require('nock')
var nodemailer = require('nodemailer')
var sinon = require('sinon')
var expect = require('chai').expect
var prefix = '/api/messages'
describe('Test Email API', function () {
it('it should send an email', function (done) {
var transportStub = {
sendMail: function (options) {
return new Promise((resolve, reject) => { resolve(true, false) })
}
}
var sendMailSpy = sinon.spy(transportStub, 'sendMail')
var mailerStub = sinon.stub(nodemailer, 'createTransport').returns(transportStub)
var mail = {
to: '<EMAIL>',
subject: 'Hello ✔',
text: 'Hello world 🐴',
html: '<b>Hello world 🐴</b>'
}
chai.request(server)
.post(prefix + '/email')
.send(mail)
.end(function (err, res) {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.a('object')
res.body.should.have.property('message').eql('Message sent')
mailerStub.restore()
done()
})
})
it('it should send an email', function (done) {
var transportStub = {
sendMail: function (options) {
return new Promise((resolve, reject) => { reject(new Error('Something went wrong with mail service')) })
}
}
var sendMailSpy = sinon.spy(transportStub, 'sendMail')
var mailerStub = sinon.stub(nodemailer, 'createTransport').returns(transportStub)
var mail = {
to: '<EMAIL>',
subject: 'Hello ✔',
text: 'Hello world 🐴',
html: '<b>Hello world 🐴</b>'
}
chai.request(server)
.post(prefix + '/email')
.send(mail)
.end(function (err, res) {
//should.exist(err)
res.should.have.status(404)
res.body.should.be.a('object')
err.should.have.property('message').eql('Not Found')
mailerStub.restore()
done()
})
})
})
describe('Test SMS API', function () {
xit('it should send an sms', function (done) {
nock('https://www.my-cool-sms.com')
.get('/api-socket.php')
.reply(200, {
'success': true,
'smsid': 'ce184cc0a6d1714d1ac763f4fe89f521',
'body': 'Have a nice day!',
'bodyucs2': '0048006100760065002000610020006E00690063006500200064',
'bodygsm7': '486176652061206E6963652064617921',
'number': '+491234567890',
'senderid': '+449876543210',
'senderidenabled': true,
'unicode': false,
'numchars': 321,
'escapenumchars': 0,
'smscount': 3,
'charge': 0.112,
'balance': 752.121,
'countrycode': 'IE',
'prefix': '+353',
'timestamp': '2017-04-02T22:27:22-07:00',
'callbackurl': 'https://www.groganburners.ie/api/sms/callback'
})
var mail = {
number: '+353873791474',
message: 'Hello'
}
chai.request(server)
.post(prefix + '/sms')
.send(mail)
.end(function (err, res) {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.a('object')
res.body.should.have.property('message').eql('Message sent')
nock.cleanAll()
done()
})
})
it('it should fail to send an sms to invalid number', function (done) {
nock('https://www.my-cool-sms.com')
.get('/api-socket.php')
.reply(200, {
success: false,
errorcode: '210',
description: 'The number seems to be invalid'
})
var mail = {
number: '+35386',
message: 'Hello'
}
chai.request(server)
.post(prefix + '/sms')
.send(mail)
.end(function (err, res) {
should.exist(err)
res.should.have.status(404)
res.body.should.be.a('object')
err.should.have.property('message').eql('Not Found')
nock.cleanAll()
done()
})
})
})
<file_sep>var Router = require('express')
var passport = require('passport')
const passportConfig = require('../config/passport')
module.exports = class AuthController {
route () {
const router = new Router()
// GET /auth/google
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Google authentication will involve
// redirecting the user to google.com. After authorization, Google
// will redirect the user back to this application at /auth/google/callback
router.get('/google', passport.authenticate('google', {
scope: [
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.profile.emails.read']
}))
// GET /auth/google/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
router.get('/google/callback',
passport.authenticate('google', {
successRedirect: '/auth/account',
failureRedirect: '/auth/login'
}))
router.get('/account', passportConfig.ensureAuthenticated, function (req, res) {
res.render('account', { user: req.user })
})
router.get('/login', function (req, res) {
res.render('login', { user: req.user })
})
router.get('/logout', function (req, res) {
req.logout()
res.redirect('/')
})
return router
}
}
<file_sep>var mongoose = require('mongoose')
var addressSchema = require('./common/address')
var phoneSchema = require('./common/phone')
var companySchema = new mongoose.Schema({
name: { type: String, required: true, unique: true },
regNo: { type: String, required: false },
vatNo: { type: String, required: false },
addresses: [addressSchema],
phone: [phoneSchema],
createdOn: { type: Date, default: Date.now },
updatedOn: { type: Date, default: Date.now }
})
// on every save, add the date
companySchema.pre('save', function (next) {
// change the updated_at field to current date
this.updatedOn = new Date()
next()
})
module.exports = mongoose.model('Company', companySchema)
<file_sep>var chai = require('chai')
var chaiHttp = require('chai-http')
var logger = require('winston')
var expect = chai.expect
var server = server = require('../../app')
chai.use(chaiHttp)
describe('Testing Grogan Burners', function () {
it('fails, as expected', function (done) {
chai.request(server)
.get('/not-exist')
.end(function (res) {
expect(res).to.have.status(404)
done()
})
})
it('succeeds silently!', function (done) {
chai.request(server)
.get('/')
.end(function (err, res) {
if (err) logger.error(err.stack)
expect(res).to.have.status(200)
done()
})
})
})
<file_sep>'use strict'
var mongoose = require('mongoose')
var Company = mongoose.model('Company')
var chai = require('chai')
var expect = chai.expect
describe('Unit Test Company Model', function () {
it('should be invalid if name is empty', function (done) {
var company = new Company()
company.validate(function (err) {
expect(err.errors.name).to.exist
done()
})
})
it('should be valid with just a name', function (done) {
var company = new Company({name: 'ABC Boiler Parts Co.'})
company.validate(function (err) {
expect(err).to.not.exist
done()
})
})
})
<file_sep>'use strict'
var mongoose = require('mongoose')
var Company = mongoose.model('Company')
var Expense = mongoose.model('Expense')
var chai = require('chai')
var expect = chai.expect
describe('Unit Test Expense Model', function () {
it('should fail with invalid company', function (done) {
var expense = new Expense({
company: 'test',
items: [{ desc: 'Boiler Service and Repair', total: 80.00 }]
})
expense.validate(function (err) {
expect(err.errors.company).to.exist
done()
})
})
it('should fail with invalid line items', function (done) {
var expense = new Expense({
company: new Company({name: 'ABC Oil Gas Company'}),
items: [{test: 'test'}]
})
expense.validate(function (err) {
expect(err.errors).to.exist
done()
})
})
it('should be valid with minimal data', function (done) {
var expense = new Expense({
company: new Company({name: 'ABC Oil Gas Company'}),
items: [{ desc: 'Boiler Service and Repair', total: 80.00 }]
})
expense.validate(function (err) {
expect(err).to.not.exist
done()
})
})
})
<file_sep>const cont = require('../controllers')
const CustomerController = cont.Customer
const PriceController = cont.Price
const MessageController = cont.Message
const AuthController = cont.Auth
const passportConfig = require('./passport')
function cacheMiddleware(seconds){
return function (req, res, next) {
res.setHeader("Cache-Control", "public, max-age="+seconds)
next()
}
}
module.exports = function (app) {
// API
app.use('/api/customers', new CustomerController().routeAPI())
app.use('/customers', new CustomerController().route())
app.use('/api/prices', new PriceController().routeAPI())
app.use('/api/messages', new MessageController().routeAPI())
app.use('/auth', new AuthController().route())
// Ordinary web pages
app.get('/', cacheMiddleware(5 * 60), function (req, res, next) {
res.render('home/home', { title: 'Grogan Burner Services' })
})
// Testing Flash messages
app.get('/flash', function (req, res) {
req.flash('info', 'Hi there!')
res.redirect('/')
})
app.get('/no-flash', function (req, res) {
res.redirect('/')
})
app.get('/multiple-flash', function (req, res) {
req.flash('info', ['Welcome', 'Please Enjoy'])
res.redirect('/')
})
}
| 220834e5a64b462405650f68a99c4529178a4903 | [
"JavaScript"
] | 11 | JavaScript | GroganBurners/ferveo | 1f2501fb1150dbfb30a68dfb41b6a02a253e1064 | 8a503ff620b9a142f6d0b38f04b4e810a4060206 |
refs/heads/master | <file_sep>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import firebase from 'firebase/app'
import 'firebase/firestore'
import PulseLoader from 'vue-spinner/src/PulseLoader.vue'
import VueResource from 'vue-resource'
var config = {
apiKey: '<KEY>',
authDomain: 'pass-the-aux-cc6cd.firebaseapp.com',
databaseURL: 'https://pass-the-aux-cc6cd.firebaseio.com',
projectId: 'pass-the-aux-cc6cd',
storageBucket: 'pass-the-aux-cc6cd.appspot.com',
messagingSenderId: '678304408078'
}
firebase.initializeApp(config)
export const db = firebase.firestore()
db.settings({timestampsInSnapshots: true})
Vue.config.productionTip = false
Vue.use(VueResource)
// Vue.http.headers.common['Access-Control-Allow-Origin'] = 'http://xxx.xxx.xxx.xxx:94'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: {
App,
PulseLoader
},
http: {
root: '/root'
},
template: '<App/>'
})
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
import StartScreen from '../components/StartScreen'
import JoinParty from '../components/JoinParty'
import Playlist from '../components/Playlist'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
// { path: '*', component: StartScreen },
{ path: '/', component: StartScreen },
{ path: '/join', component: JoinParty },
{ path: '/party/:party', component: Playlist, name: 'party' }
]
})
<file_sep>const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
import {spotifyCredentials, clientID} from 'credentials'
// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions
exports.login = functions.https.onRequest((request, response) => {
cors(request, response, () => {
var SpotifyWebApi = require('spotify-web-api-node');
// credentials are optional
var spotifyApi = new SpotifyWebApi({
spotifyCredentials
});
var scopes = ['user-read-private', 'playlist-read-private', 'playlist-modify-public',
'playlist-modify-private', 'playlist-read-collaborative', 'user-read-currently-playing',
'user-read-playback-state'],
redirectUri = 'https://example.com/callback',
clientId = clientID,
state = 'some-state-of-my-choice';
var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
response.redirect(authorizeURL);
});
});
| d0fdd8d2185ba71d603904dfd0b9b7d10a43b5b3 | [
"JavaScript"
] | 3 | JavaScript | timtraversy/pass-the-aux | 3bab9dba99f9c181343c74aa7d9c8e67291ed4ce | 75ab9beac41be164e074c26a9c133e4420b0e1b6 |
refs/heads/master | <repo_name>10101010/phaser-game<file_sep>/game.js
window.onload = function() {
var game = new Game();
var socket = game.getSocket();
socket.emit('join', function(data) {
game.sync({
playersCount: parseInt(data.playersCount)
});
});
socket.on('joined', function(data) {
socket.id = data.socketId;
data.playersCount = parseInt(data.playersCount);
game.sync({
playersCount: parseInt(data.playersCount),
clientPlayers: data.clientPlayers
});
});
};
function Game() {
var socket = io();
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example');
var map;
var tileset;
var layer;
var player;
var facing = 'left';
var jumpTimer = 0;
var syncTimer = 0;
var cursors;
var jumpButton;
var bg;
var currentPlayer = 0;//game.rnd.integerInRange(100, 250);
var clientPlayers = {}
var master = false;
var moveFactor = 3;
var guys = {};
var totalPlayers;
var GameState = {
init: function(data) {
currentPlayer = data.player;
clientPlayers = data.clientPlayers;
var self = this;
console.log('totalPlayers ' + totalPlayers);
console.log('currentPlayer ' + currentPlayer);
},
preload: function() {
game.load.tilemap('level1', 'assets/games/starstruck/level1.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles-1', 'assets/games/starstruck/tiles-1.png');
game.load.spritesheet('dude', 'assets/games/starstruck/dude.png', 32, 48);
game.load.spritesheet('droid', 'assets/games/starstruck/droid.png', 32, 32);
game.load.spritesheet('mario', 'assets/games/starstruck/mario.png', 16, 21)
game.load.image('starSmall', 'assets/games/starstruck/star.png');
game.load.image('starBig', 'assets/games/starstruck/star2.png');
game.load.image('background', 'assets/games/starstruck/background2.png');
},
create: function(game) {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.stage.backgroundColor = '#000000';
bg = game.add.tileSprite(0, 0, 800, 600, 'background');
bg.fixedToCamera = true;
map = game.add.tilemap('level1');
map.addTilesetImage('tiles-1');
game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;
map.setCollisionByExclusion([13, 14, 15, 16, 46, 47, 48, 49, 50, 51]);
layer = map.createLayer('Tile Layer 1');
// Un-comment this on to see the collision tiles
// layer.debug = true;
layer.resizeWorld();
game.physics.arcade.gravity.y = 1000;
var guy = game.add.sprite(60, 60, 'mario');
game.physics.enable(guy, Phaser.Physics.ARCADE);
guy.body.bounce.y = 0.01;
guy.body.bounce.x = 0.01;
guy.body.collideWorldBounds = true;
guy.body.setSize(16, 21, 0, 0);
guy.animations.add('right', [0, 1, 2, 3], 30, true);
guy.animations.add('turn', [7], 30, true);
guy.animations.add('left', [7, 6, 4, 5], 30, true);
guy.body.checkCollision.left = true;
guy.body.checkCollision.right = true;
game.camera.follow(guy);
guys[socket.id] = guy;
jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
game.input.onDown.add(gofull, this);
function gofull() {
if (game.scale.isFullScreen) {
game.scale.stopFullScreen();
} else {
game.scale.startFullScreen(false);
}
}
},
update: function(data) {
socket.on('joined', function(data) {
clientPlayers = data.clientPlayers;
});
for (var player in clientPlayers) {
if (player != socket.id && !guys.hasOwnProperty(player)) {
var guy = game.add.sprite(60 + 30, 60 + 30, 'mario');
game.physics.enable(guy, Phaser.Physics.ARCADE);
guy.body.bounce.y = 0.01;
guy.body.bounce.x = 0.01;
// guy.body.collideWorldBounds = false;
guy.body.setSize(16, 21, 0, 0);
guy.body.checkCollision.left = true;
guy.body.checkCollision.right = true;
guy.animations.add('right', [0, 1, 2, 3], 30, true);
guy.animations.add('turn', [7], 30, true);
guy.animations.add('left', [7, 6, 4, 5], 30, true);
guys[player] = guy;
}
};
for (var guy in guys) {
for (var collideGuy in guys) {
game.physics.arcade.collide(guys[guy], guys[collideGuy]);
}
game.physics.arcade.collide(guys[guy], layer);
}
socket.on('disconnect', function(socketId) {
delete guys[socketId];
})
socket.on('clientUpdate', function(data) {
if (socket.id != data.socketId && guys.hasOwnProperty(data.socketId)) {
guys[data.socketId].body.velocity.x = data.velx;
guys[data.socketId].body.velocity.y = data.vely;
guys[data.socketId].animations.play(data.animation);
if (game.time.now > syncTimer) {
guys[data.socketId].x = data.posx;
guys[data.socketId].y = data.posy;
syncTimer = game.time.now + 1000;
}
if (data.facing == 'idle') {
guys[data.socketId].animations.stop();
}
}
});
if (cursors.left.isUp) {
guys[socket.id].body.velocity.x = -0;
} else if (cursors.right.isUp) {
guys[socket.id].body.velocity.x = 0;
} ;
if (cursors.left.isDown) {
guys[socket.id].body.velocity.x = -100;
if (facing != 'left') {
guys[socket.id].animations.play('left');
facing = 'left';
}
} else if (cursors.right.isDown) {
guys[socket.id].body.velocity.x = 100;
if (facing != 'right') {
guys[socket.id].animations.play('right');
facing = 'right';
}
} else {
if (facing != 'idle') {
guys[socket.id].animations.stop();
if (facing == 'left') {
guys[socket.id].frame = 0;
} else {
guys[socket.id].frame = 5;
}
facing = 'idle';
}
}
if (jumpButton.isDown && game.time.now > jumpTimer) {
guys[socket.id].body.velocity.y = -300;
jumpTimer = game.time.now + 600;
}
this.updateServer();
},
render: function() {
// game.debug.text(game.time.physicsElapsed, 32, 32);
game.debug.body(guys[socket.id]);
game.debug.bodyInfo(guys[socket.id], 16, 24);
},
updateServer: function() {
var data = {}
data['socketId'] = socket.id;
data['player'] = parseInt(socket.id);
data['velx'] = parseFloat(guys[socket.id].body.velocity.x);
data['vely'] = parseFloat(guys[socket.id].body.velocity.y);
data['posx'] = parseFloat(guys[socket.id].body.x);
data['posy'] = parseFloat(guys[socket.id].body.y);
data['animation'] = guys[socket.id].animations.currentAnim.name;
data['facing'] = facing
socket.emit('gameUpdate', data);
},
};
var SynchState = {
p: false,
players: 0,
countdown: false,
init: function(data) {
var self = this;
// totalPlayers = parseInt(data.playersCount);
// self.players = parseInt(data.playersCount);
self.p = data.playersCount - 1;
self.clientPlayers = data.clientPlayers;
// socket.on('joined', function(data) {
// currentPlayer = parseInt(data.playersCount);
// self.players = parseInt(data.playersCount);
// });
},
preload: function() {
cursors = game.input.keyboard.createCursorKeys();
},
create: function() {
},
update: function() {
this.initGame(2);
},
initGame: function(phase) {
switch (phase) {
case 1:
this.text.text = "GO!";
case 2:
game.state.start("game", false, false, {
player: this.p,
clientPlayers: this.clientPlayers
});
socket.removeAllListeners('joined');
socket.removeAllListeners('timeOut');
socket.removeAllListeners('playerLeft');
break;
}
}
};
game.state.add("sync", SynchState, false);
game.state.add("game", GameState, false);
this.switchToSync = function(data) {
game.stage.disableVisibilityChange = true;
game.state.start("sync", false, false, data);
};
this.getSocket = function() {
return socket;
};
return this;
}
Game.prototype.getSocket = function() {
return this.getSocket();
};
Game.prototype.sync = function(data) {
this.switchToSync(data);
};
<file_sep>/index.js
var express = require('express');
var path = require('path');
var compress = require('compression');
var _ = require('underscore');
var app = express();
app.use(compress());
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.use(express.static('.'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
var clients = {};
var clientPlayers = {};
server.lastPlayderID = 0; // Keep track of the last id assigned to a new player
io.on('connection', function(socket) {
clients[socket.id] = null;
socket.on('join', function(data) {
var playerNum = server.lastPlayderID++;
clientPlayers[socket.id] = playerNum;
console.log(clientPlayers);
console.log('client ' + socket.id + ' connected ' + ' (' + playerNum + ')');
io.emit('joined', {
playersCount: Object.keys(clientPlayers).length ,
clientPlayers: clientPlayers,
socketId: socket.id
});
});
socket.on("disconnect", (reason) => {
console.log(reason, socket.id);
delete clientPlayers[socket.id];
io.emit('disconnect', socket.id);
console.log('players', clientPlayers);
});
socket.on('gameUpdate', function(data) {
//delete data.socketId;
// console.log(data);
io.emit('clientUpdate', data);
});
});
server.listen(3000, function() {
console.log('listening on *:3000');
});
function getSocket(socketId) {
console.log(io.sockets.connected[socketId]);
return io.sockets.connected[socketId];
} | 7ebbd79bfa215d491aed3482cf7e7aaf7d38fa4c | [
"JavaScript"
] | 2 | JavaScript | 10101010/phaser-game | 4830b7f00645d5378e6b278dcd2b0d4e0ed92248 | 3ba43847bf47dba4a796f6095b5246d1494bee97 |
refs/heads/master | <file_sep>import entitites.User;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/login/*")
public class LoginServlet extends HttpServlet {
UserDAO userDao = new UserDAO();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try {
User user = new User();
user = userDao.authenticateUser(Integer.valueOf(request.getParameter("cpr")),
request.getParameter("password"));
if (user.isValid()) {
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser", user);
session.setAttribute("currentUserId", user.getCpr());
ServletContext servletContext = getServletContext();
RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/appointment");
requestDispatcher.forward(request, response);
// response.sendRedirect("appointment-page.jsp"); //logged-in page
} else{}
// response.sendRedirect("invalidLogin.jsp"); //error page
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
<file_sep>import entitites.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDAO {
private Connection conn;
public UserDAO() {
ConnectionProvider.connectToLocal("172.16.58.3");
}
public User authenticateUser(int cpr, String password) {
User user = new User();
try {
String sql = "SELECT * FROM users WHERE cpr=" + cpr + " and password='" + password + "';";
PreparedStatement ps = conn.
prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
user.setCpr(rs.getInt("cpr"));
user.setName(rs.getString("password"));
user.setName(rs.getString("name"));
user.setLastname(rs.getString("lastname"));
user.setDiverse(rs.getString("diverse"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
| f03fbf66f8d65bc14cbd798f9cac6364a3fb704a | [
"Java"
] | 2 | Java | s185160/IT3MedXML | f51cbdf0c6c09ebc7bdccfc22c4e533e562abcea | 6cfec5ce942c11e486b20c71250316b7100edaf7 |
refs/heads/master | <file_sep>//
// ViewController.swift
// case_Studies
//
// Created by <NAME> on 02/05/2017.
// Copyright © 2017 isabeljlee. All rights reserved.
//
import UIKit
import StarWars
class ViewController: UIViewController, UIViewControllerTransitioningDelegate {
var speed = 3.0
var size = 20.0
var wind = 0.0
var float = 0.25
@IBOutlet weak var sizeLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var windLabel: UILabel!
@IBOutlet weak var floatLabel: UILabel!
@IBOutlet weak var sizeStack: UIStackView!
@IBOutlet weak var speedStack: UIStackView!
@IBOutlet weak var windStack: UIStackView!
@IBOutlet weak var floatStack: UIStackView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var backgroundImageView: UIImageView!
let uiViewAnimator = StarWarsUIViewAnimator()
let uiDynamicAnimator = StarWarsUIDynamicAnimator()
let glaAnimator = StarWarsGLAnimator()
let windAnimator = StarWarsWindAnimator()
var currentAnimator: UIViewControllerAnimatedTransitioning!
@IBAction func sizeSliderMoved(_ sender: UISlider) {
let currentValue = Double(lroundf(sender.value))
print("Size: \(currentValue)")
sizeLabel.text = "\(currentValue)"
size = currentValue
uiViewAnimator.spriteWidth = CGFloat(size)
uiDynamicAnimator.spriteWidth = CGFloat(size)
windAnimator.spriteWidth = CGFloat(size)
}
@IBAction func speedSliderMoved(_ sender: UISlider) {
let currentValue = round(sender.value * 10)/10
print("Speed: \(currentValue)")
speedLabel.text = String(format: "%.1f", currentValue)
speed = Double(currentValue)
uiViewAnimator.duration = speed
}
@IBAction func windSliderMoved(_ sender: UISlider) {
let currentValue = sender.value
windLabel.text = String(format: "%.1f", currentValue)
wind = Double(currentValue)
windAnimator.wind = CGFloat(wind)
}
@IBAction func floatSliderMoved(_ sender: UISlider) {
let currentValue = sender.value
floatLabel.text = String(format: "%.1f", currentValue)
float = Double(currentValue)
windAnimator.float = CGFloat(float)
}
@IBAction func changeAnimationSegmentedControl(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
self.speedStack.isHidden = false
self.windStack.isHidden = true
self.floatStack.isHidden = true
currentAnimator = uiViewAnimator
return
case 1:
self.speedStack.isHidden = true
self.windStack.isHidden = true
self.floatStack.isHidden = true
currentAnimator = uiDynamicAnimator
return
case 2:
self.speedStack.isHidden = false
self.windStack.isHidden = true
self.floatStack.isHidden = true
return
case 3:
self.speedStack.isHidden = true
self.windStack.isHidden = false
self.floatStack.isHidden = false
currentAnimator = windAnimator
return
default:
return
}
}
override func viewDidLoad() {
super.viewDidLoad()
currentAnimator = uiViewAnimator
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func unwindToRoot(sender: UIStoryboardSegue) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewTransitionSegue" {
let destination = segue.destination
destination.transitioningDelegate = self
}
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch segmentedControl.selectedSegmentIndex {
case 0:
return uiViewAnimator
case 1:
return uiDynamicAnimator
case 2:
let animator = StarWarsGLAnimator()
animator.duration = speed
animator.spriteWidth = CGFloat(size)
return animator
case 3:
return windAnimator
default:
return uiViewAnimator
}
}
}
<file_sep>//
// TheEndViewController.swift
// case_Studies
//
// Created by <NAME> on 09/05/2017.
// Copyright © 2017 isabeljlee. All rights reserved.
//
import UIKit
import StarWars
class TheEndViewController: UIViewController {
@IBOutlet weak var blackView: UIView!
@IBOutlet weak var theEndButton: UIButton!
@IBOutlet weak var theEnd: UILabel!
@IBAction func theEndTapped(_ sender: UIButton) {
self.view.animateCircular(withDuration: 1, center: self.view.center, revert: true, animations: {
self.blackView.alpha = 1
self.theEnd.text = "Thanks"
})
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
<file_sep>//
// AnimationViewController.swift
// case_Studies
//
// Created by <NAME> on 02/05/2017.
// Copyright © 2017 isabeljlee. All rights reserved.
//
import UIKit
import StarWars
class AnimationViewController: UIViewController {
@IBOutlet weak var circularRevealButton: UIButton!
@IBOutlet weak var circularReverseButton: UIButton!
@IBOutlet weak var colorChangeButton: UIButton!
@IBOutlet weak var viewRevealButton: UIButton!
@IBOutlet weak var viewRevertButton: UIButton!
@IBOutlet weak var theEndButton: UIButton!
@IBAction func circularReveal(_ sender: UIButton) {
sender.layer.masksToBounds = true
let fillLayer = CALayer()
fillLayer.backgroundColor = UIColor.white.cgColor
fillLayer.frame = sender.layer.bounds
sender.layer.insertSublayer(fillLayer, at: 0)
let center = CGPoint(x: fillLayer.bounds.midX, y: fillLayer.bounds.midY)
let radius: CGFloat = max(sender.frame.width / 2 , sender.frame.height / 2)
let circularAnimation = CircularRevealAnimator(layer: fillLayer, center: center, startRadius: 0, endRadius: radius)
circularAnimation.duration = 0.2
circularAnimation.completion = {
fillLayer.opacity = 0
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0
opacityAnimation.duration = 0.2
opacityAnimation.delegate = AnimationDelegate {
fillLayer.removeFromSuperlayer()
}
fillLayer.add(opacityAnimation, forKey: "opacity")
}
circularAnimation.start()
}
@IBAction func CircularRevert(_ sender: UIButton) {
sender.layer.masksToBounds = true
let fillLayer = CALayer()
fillLayer.backgroundColor = UIColor.white.cgColor
fillLayer.frame = sender.layer.bounds
sender.layer.insertSublayer(fillLayer, at: 0)
let center = CGPoint(x: fillLayer.bounds.midX, y: fillLayer.bounds.midY)
let radius: CGFloat = max(sender.frame.width / 2 , sender.frame.height / 2)
let circularAnimation = CircularRevealAnimator(layer: fillLayer, center: center, startRadius: radius, endRadius: 0)
circularAnimation.duration = 0.2
circularAnimation.completion = {
fillLayer.opacity = 0
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0
opacityAnimation.duration = 0.2
opacityAnimation.delegate = AnimationDelegate {
fillLayer.removeFromSuperlayer()
}
fillLayer.add(opacityAnimation, forKey: "opacity")
}
circularAnimation.start()
}
@IBAction func colorChange(_ sender: UIButton) {
sender.layer.masksToBounds = true
let fillLayer = CALayer()
fillLayer.backgroundColor = UIColor.white.cgColor
fillLayer.frame = sender.layer.bounds
sender.layer.insertSublayer(fillLayer, at: 0)
let center = CGPoint(x: fillLayer.bounds.midX, y: fillLayer.bounds.midY)
let radius: CGFloat = max(sender.frame.width / 2 , sender.frame.height / 2)
let circularAnimation = CircularRevealAnimator(layer: fillLayer, center: center, startRadius: 0, endRadius: radius)
circularAnimation.duration = 0.2
circularAnimation.completion = {
fillLayer.removeFromSuperlayer()
sender.backgroundColor = UIColor.white
}
circularAnimation.start()
}
@IBAction func viewReveal(_ sender: UIButton) {
self.view.animateCircular(withDuration: 0.5, center: sender.center, revert: false, animations: {
self.backgroundImageView.image = UIImage(named: "background")
self.circularRevealButton.backgroundColor = UIColor.white
self.circularReverseButton.backgroundColor = UIColor.black
self.colorChangeButton.backgroundColor = UIColor.white
self.viewRevealButton.backgroundColor = UIColor.black
self.viewRevertButton.backgroundColor = UIColor.white
self.theEndButton.backgroundColor = UIColor.black
})
}
@IBAction func viewRevert(_ sender: UIButton) {
self.view.animateCircular(withDuration: 0.5, center: sender.center, revert: true, animations: {
self.backgroundImageView.image = UIImage(named: "background2")
self.circularRevealButton.backgroundColor = UIColor.black
self.circularReverseButton.backgroundColor = UIColor.white
self.colorChangeButton.backgroundColor = UIColor.black
self.viewRevealButton.backgroundColor = UIColor.white
self.viewRevertButton.backgroundColor = UIColor.black
self.theEndButton.backgroundColor = UIColor.white
})
}
@IBOutlet weak var backgroundImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 4d0e7d0e954fbc052453c2ed3ed4455a782c685a | [
"Swift"
] | 3 | Swift | uchicago-mobi/mpcs51032-2017-spring-case-study-ijl0322 | d01c8b6a75f1efad1a819fb5bc7407928d29f4fb | 5c41f803def42bef7363db76d59c7b488b68cadb |
refs/heads/master | <repo_name>pablosolarz/clienteEsteto2<file_sep>/app/src/main/java/com/example/pablo/clientteleestetoscopio2/MainActivity.java
package com.example.pablo.clientteleestetoscopio2;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
//Parámetros de audio
private static final String TAG = "VoiceRecord";
private static final int RECORDER_SAMPLERATE = 44100;
private static final int RECORDER_CHANNELS_IN = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_CHANNELS_OUT = AudioFormat.CHANNEL_OUT_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
// Initialize minimum buffer size in bytes.
private int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS_IN, RECORDER_AUDIO_ENCODING);
private ArrayAdapter<String> listAdapter ;
private AudioRecord recorder = null;
private Thread recordingThread = null;
private boolean isRecording = false;
int fileCount;
//Componentes de interfaz
TextView txNroTel, txNroReceptores;
Switch swConectar;
private String salida, retorno;
private Socket socketCliente = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txNroTel = (TextView) findViewById(R.id.txNroTel);
txNroReceptores = (TextView) findViewById(R.id.textNroReceptores);
swConectar = (Switch) findViewById(R.id.switchConectar);
final ConectaTCP conectaTCP = new ConectaTCP();
idTelefono();
iniNroReceptores();
iniEstadoConexion();
swConectar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.v("Switch State=", "" + isChecked);
conectaTCP.execute(txNroTel.getText().toString(), retorno,salida);
}
});
Socket copiaSocket = socketCliente;
//Activación audio rec
setButtonHandlers();
enableButtons(false);
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS_IN, RECORDER_AUDIO_ENCODING);
String pepe = "1";
}
private void setButtonHandlers() {
((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnPlay)).setOnClickListener(btnClick);
}
private View.OnClickListener btnClick = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart: {
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop: {
enableButtons(false);
try {
stopRecording();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
case R.id.btnPlay:{
//enableButtons(true);
try {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "Estetoscopio");
PlayShortAudioFileViaAudioTrack(folder + File.separator+"sndstet" + folder.listFiles().length + ".pcm");
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
};
int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format
private void startRecording() {
if( bufferSize == AudioRecord.ERROR_BAD_VALUE)
Log.e( TAG, "Bad Value for bufferSize recording parameters are not supported by the hardware");
if( bufferSize == AudioRecord.ERROR )
Log.e( TAG, "Bad Value for bufferSize implementation was unable to query the hardware for its output properties");
Log.e( TAG, "bufferSize = "+ bufferSize);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS_IN,
RECORDER_AUDIO_ENCODING,BufferElements2Rec);
//am.setSpeakerphoneOn(true);
//Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
recorder.startRecording();
//atrack.setPlaybackRate( RECORDER_SAMPLERATE);
isRecording = true;
Toast.makeText(MainActivity.this, "Inicio grabacion", Toast.LENGTH_LONG);
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
Toast.makeText(MainActivity.this, "Fin grabacion", Toast.LENGTH_LONG);
}
private void stopRecording() throws IOException {
// stops the recording activity
if (null != recorder) {
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}
private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException{
// We keep temporarily filePath globally as we have only two sample sounds now..
if (filePath==null)
return;
//Reading the file..
File file = new File(filePath);
byte[] byteData = new byte[(int) file.length()];
Log.d(TAG, (int) file.length()+"");
FileInputStream in = null;
try {
in = new FileInputStream( file );
in.read( byteData );
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Set and push to audio track..
int intSize = android.media.AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS_OUT, RECORDER_AUDIO_ENCODING);
Log.d(TAG, intSize+"");
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS_OUT, RECORDER_AUDIO_ENCODING, intSize, AudioTrack.MODE_STREAM);
if (at!=null) {
at.play();
// Write the byte array to the track
at.write(byteData, 0, byteData.length);
at.stop();
at.release();
}
else
Log.d(TAG, "audio track is not initialised ");
}
private void writeAudioDataToFile() {
boolean hecho;
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "Estetoscopio");
if (!folder.exists()) {
if(folder.mkdirs()){
Log.v(TAG,"Directorio creado");
}else{
Log.v(TAG,"Directorio NO creado");
}
}
/*
String pathEntero;
pathEntero = folder.getAbsolutePath();
// Write the output audio in byte
fileCount = folder.listFiles().length + 1;
//String filePath = "/sdcard/Sonidos Estetoscopio/ voice8K16bitmono"+fileCount+".pcm";
String filePath = folder.getAbsolutePath() + fileCount + ".pcm";
*/
int nroarchivo = folder.listFiles().length + 1;
File fsonido = new File(folder,"sndstet" + nroarchivo + ".pcm");
String spath = fsonido.getAbsolutePath();
try {
if(fsonido.createNewFile()){
Log.v(TAG, "File created");
}else {
Log.v(TAG, "File doesn't created");
}
} catch (IOException e) {
e.printStackTrace();
}
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
OutputStream os2 = null;
try {
os = new FileOutputStream(fsonido);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
os2 = socketCliente.getOutputStream();
PrintWriter ps2 = new PrintWriter(os2);
ps2.println("Record");
ps2.flush();
} catch (IOException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
//System.out.println("Short wirting to file" + sData.toString());
byte bData[];// = short2byte(sData);
try {
recorder.read(sData, 0, BufferElements2Rec);
bData = short2byte(sData);
// os.write(bData, 0, BufferElements2Rec * BytesPerElement);
os2.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
//listenAudioDataToFile();
//recorder.read((bData),0,BufferElements2Rec * BytesPerElement);
}
//Prueba al servidor
try {
os.close();
os2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnPlay, !isRecording);
enableButton(R.id.btnStop, isRecording);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
private void idTelefono() {
/* TelephonyManager tMgr;
tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String idDispositivo = tMgr.getDeviceId();
// if (idDispositivo != null) {
if (!idDispositivo.isEmpty())
txNroTel.setText(idDispositivo);
else
txNroTel.setText("ID Dispoitivo NO Encontrado");
*/
txNroTel.setText("#12345");
}
private void iniNroReceptores() {
txNroReceptores.setText("0");
}
private void iniEstadoConexion() {
if (swConectar.isChecked())
swConectar.toggle();
}
public class ConectaTCP extends AsyncTask<String, String, String> {
private StringReader strr;
private String frase, fraseModificada;
private static final int SERVERPORT = 6789;
private static final String SERVER_IP = "10.0.0.10";
// private String str;
public Socket conexion() {
//Socket socketCliente = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socketCliente = new Socket(SERVER_IP, SERVERPORT); //Aqui es detectada la conexión
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
} catch (Exception e) {
System.err.println("Error: " + e);
}
return socketCliente;
}
@Override
protected String doInBackground(String... str) {
strr = new StringReader(str[0]);
//String salida = new String();
StringBuilder builder = new StringBuilder();
//Socket socketCliente = null;
//DataOutputStream salidaAServidor;
PrintStream salidaAServidor;
String salida = "";
String inputLine, responseLine, respuestaServidor, ultimaRespuesta = "";
try {
BufferedReader entradaDesdeUsuario = new BufferedReader(strr);
//InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//socketCliente = new Socket(SERVER_IP,SERVERPORT); //Aqui es detectada la conexión
socketCliente = this.conexion();
//txtView.setText(entradaDesdeUsuario.readLine());
//salidaAServidor = new DataOutputStream(socketCliente.getOutputStream());
salidaAServidor = new PrintStream(socketCliente.getOutputStream());
BufferedReader entradaDesdeServidor = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
if (socketCliente != null && salidaAServidor != null && entradaDesdeServidor != null) {
try {
/*
* Keep on reading from/to the socket till we receive the "Ok" from the
* server, once we received that then we break.
*/
//System.out.println("The client started. Type any text. To quit it type 'Ok'.");
// String tmpDesdeServidor;
//tmpDesdeServidor=entradaDesdeServidor.readLine();
inputLine = entradaDesdeUsuario.readLine();
responseLine = inputLine;
salidaAServidor.println(responseLine); //Aqui envía el texto de entrada al servidor
//responseLine = entradaDesdeServidor.readLine();
///////stream audio + publishProgress(.....)
respuestaServidor = entradaDesdeServidor.readLine();
if (!respuestaServidor.isEmpty() && !respuestaServidor.equals(ultimaRespuesta)) //Verificar si es el id de otro telefono
publishProgress(respuestaServidor); //Incremento de usuarios activos (Aqui recibe la notificación de si mismo)
/*
* Close the output stream, close the input stream, close the socket.
*/
//salidaAServidor.close();
//entradaDesdeServidor.close();
//entradaDesdeUsuario.close();
//socketCliente.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
} catch (Exception e) {
System.err.println("Error: " + e);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("Unknown host...");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to connect...");
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
System.out.println("Error...");
}
salida = "Chau";
return salida;
}
@Override
protected void onProgressUpdate(String... s) {
// for (long i = 0; i < 1000000; i++) {
txNroReceptores.setText(String.valueOf(Integer.valueOf(txNroReceptores.getText().toString()) + 1));
}
protected void onPostExecute(String s) {
//Socket so = socketCliente;
Toast t = Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG);
t.show();
// iniEstadoConexion();
// iniNroReceptores();
}
}
private void conexionStramming(){}
}
| bc6ecf64229d00bb1b9a411e09c6984c7d06408f | [
"Java"
] | 1 | Java | pablosolarz/clienteEsteto2 | 28121314eb455bc1640510f5967dc4cdf77da8bc | 3ed2392e08e2d114431a739958e1a84b8bd53e43 |
refs/heads/master | <repo_name>jb-tester/SpringWebflow245_test2<file_sep>/src/main/java/com/mytests/spring/webflow244/javaConfig/test2/MyWebflowConfig.java
package com.mytests.spring.webflow244.javaConfig.test2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.webflow.config.AbstractFlowConfiguration;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.ViewFactoryCreator;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.executor.FlowExecutor;
import org.springframework.webflow.mvc.builder.MvcViewFactoryCreator;
import org.springframework.webflow.mvc.servlet.FlowHandlerAdapter;
import org.springframework.webflow.mvc.servlet.FlowHandlerMapping;
import java.util.Arrays;
/**
* *******************************
* Created by Irina.Petrovskaya on 10/21/2016.
* Project: test2
* *******************************
*/
@Configuration
public class MyWebflowConfig extends AbstractFlowConfiguration {
public static final String BASE_PATH = "/WEB-INF";
private final ExtraWebflowConfig extraWebflowConfig;
@Autowired
public MyWebflowConfig(@Qualifier("extraWebflowConfig") ExtraWebflowConfig extraWebflowConfig) {
this.extraWebflowConfig = extraWebflowConfig;
}
@Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder(this.extraWebflowConfig.flowBuilderServices())
.setParent(this.extraWebflowConfig.parentFlowRegistry())
// .addFlowLocation("/WEB-INF/myflows/flow1.xml")
// .addFlowLocation("/WEB-INF/myflows/flow2.xml")
// .addFlowLocation("/WEB-INF/myflows/flow1.xml")
//.addFlowLocation("/WEB-INF/myflows/flow2.xml","myflow2")
.setBasePath("/WEB-INF/webflows/")
.addFlowLocationPattern("flow?/flow?.xml")
// .setBasePath(BASE_PATH)
//.setBasePath("/WEB-INF/")
//.addFlowLocationPattern("webflows/flow?/flow?.xml")
.build();
}
@Bean
public FlowHandlerMapping flowHandlerMapping() {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
handlerMapping.setOrder(-1);
handlerMapping.setFlowRegistry(flowRegistry());
return handlerMapping;
}
@Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry()).build();
}
@Bean
public FlowHandlerAdapter flowHandlerAdapter() {
FlowHandlerAdapter handlerAdapter = new FlowHandlerAdapter();
handlerAdapter.setFlowExecutor(flowExecutor());
handlerAdapter.setSaveOutputToFlashScopeOnRedirect(true);
return handlerAdapter;
}
}
<file_sep>/src/main/java/com/mytests/spring/webflow244/javaConfig/test2/ExtraWebflowConfig.java
package com.mytests.spring.webflow244.javaConfig.test2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.webflow.config.AbstractFlowConfiguration;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.ViewFactoryCreator;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.mvc.builder.MvcViewFactoryCreator;
import java.util.Arrays;
/**
* *******************************
* Created by Irina.Petrovskaya on 6/5/2017.
* Project: test2
* *******************************
*/
@Configuration
public class ExtraWebflowConfig extends AbstractFlowConfiguration {
final
MyWebConfig myWebConfig;
@Autowired
public ExtraWebflowConfig(MyWebConfig myWebConfig) {
this.myWebConfig = myWebConfig;
}
@Bean
public FlowDefinitionRegistry parentFlowRegistry() {
return getFlowDefinitionRegistryBuilder(flowBuilderServices())
.addFlowLocation("/WEB-INF/extraflows/extra.xml", "extra")
.build();
}
@Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder().
setViewFactoryCreator(viewFactoryCreator())
.build();
}
@Bean
public ViewFactoryCreator viewFactoryCreator() {
MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator();
factoryCreator.setViewResolvers(Arrays.<ViewResolver>asList(this.myWebConfig.resolver()));
factoryCreator.setUseSpringBeanBinding(true);
return factoryCreator;
}
}
<file_sep>/src/main/java/com/mytests/spring/webflow244/javaConfig/test2/MyAppInitializer.java
package com.mytests.spring.webflow244.javaConfig.test2;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* *******************************
* Created by Irina.Petrovskaya on 10/21/2016.
* Project: test2
* *******************************
*/
public class MyAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{MyWebConfig.class, MyWebflowConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/views/*"};
}
}
| 8467fc0723820b034c596aa6da630caae3b6913f | [
"Java"
] | 3 | Java | jb-tester/SpringWebflow245_test2 | 434d5d7dd9d19c6051974097ddf8c924aae6cfe2 | a233b68eadc7a3e6677048d95b8551f8e7b5216c |
refs/heads/master | <repo_name>panda0107/ScriptKiddie<file_sep>/HackersAriseSSHBannerGrab.py
#! /usr/bin/python3
import socket
ip = input('Input IP: ')
Ports = [21,22,25,3306]
for i in range (0,4):
s = socket.socket()
Port = Ports[i]
print ('This Is the Banner for the Port')
print (Port)
try:
s.connect ((ip, Port))
answer = s.recv (1024)
print (answer)
s.close ()
except:
print ('no answer')
<file_sep>/tcp_server.py
#! /usr/bin/python3
import socket
TCP_IP = "192.168.1.122"
TCP_PORT = int(input('Input port: '))
BUFFER_SIZE = 100
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print('Connection address: ', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:
break
print("Received data: ", data)
conn.send(data) #echo
conn.close
<file_sep>/README.md
# ScriptKiddie
駭客腳本
HackersAriseSSHBannerGrab.py 掃描埠
WriteToDisk.java 浪費硬碟空間
ftpcracker.py 暴力破解 ftp 密碼
tcp_server.py tcp 伺服器監聽,取得客戶端資訊
參考
駭客的 Linux 基礎入門必修課
職業駭客的告白 秋聲 著
| 3a8880652d4dc2a6996045a85f524dd3de1201a0 | [
"Markdown",
"Python"
] | 3 | Python | panda0107/ScriptKiddie | 6306892678265d89d58d1f9b7b40cbf41167631b | 3b666cd6e4e07c06c9699801df003347ac7060e7 |
refs/heads/master | <repo_name>meriton42/kitten-accountant<file_sep>/src/app/cba-tooltip.directive.ts
import { Directive, ElementRef, HostListener, Injectable, Input } from "@angular/core";
import { CostBenefitAnalysis } from "./economy";
import { CbaTooltipService } from "./cba-tooltip.service";
@Directive({
selector: "[cba-tooltip]"
})
export class CbaTooltipDirective {
constructor(private anchor: ElementRef, private tooltipService: CbaTooltipService) { }
@Input("cba-tooltip")
cba: CostBenefitAnalysis;
@HostListener('mouseenter')
show(event: MouseEvent) {
this.tooltipService.show(this.cba, this.anchor);
}
@HostListener('mouseleave')
hide() {
this.tooltipService.hide();
}
}
<file_sep>/src/app/help.service.ts
import { Injectable, TemplateRef } from "@angular/core";
@Injectable()
export class HelpService {
topic: TemplateRef<void>;
}<file_sep>/README.md
# KittenAccountant
Kitten Accountant is an automatic advisor for playing [bloodrizer's kitten's game](http://bloodrizer.ru/games/kittens/). It runs alongside your game and gives you advice about how to most efficiently develop your colony.
## Running
1. Install node and yarn
2. check out this repository
3. open a shell to the directory you checked out, and do
```
yarn install
ng serve
```
4. point your browser to http://localhost:4200.
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { CostBenefitAnalysisComponent } from './cost-benefit-analysis.component';
import { PanelComponent } from './panel.component';
import { CbaTooltipDirective } from './cba-tooltip.directive';
import { HelpDirective } from './help.directive';
@NgModule({
declarations: [
AppComponent,
CbaTooltipDirective,
CostBenefitAnalysisComponent,
HelpDirective,
PanelComponent,
],
imports: [
BrowserModule,
FormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/cba-tooltip.service.ts
import { Injectable, ElementRef } from "@angular/core";
import { CostBenefitAnalysis } from "./economy";
@Injectable()
export class CbaTooltipService {
cba: CostBenefitAnalysis;
left: number;
top: number;
show(cba: CostBenefitAnalysis, anchor: ElementRef) {
const p = anchor.nativeElement.getBoundingClientRect();
this.cba = cba;
this.left = p.right;
this.top = p.top;
}
hide() {
this.cba = null;
}
}<file_sep>/src/app/economy.ts
import { state, Res, Building, Job, GameState, GameStateUpdate, resourceNames, Upgrade, ConvertedRes, BasicRes, Science, activatableBuildingNames, buildingNames, Metaphysic, replaceGameState } from "./game-state";
import { apply } from "./game-state-changer";
let currentBasicProduction: Cart;
let price: {[R in Res]: number};
let conversions: Conversion[];
let actions: Action[];
let sciences: ScienceInfo[];
let prerequisite: {[A in string]: ScienceInfo[]};
function updateEconomy() {
const {priceMarkup} = state;
const wage = 1;
const goldPrice = 10 * priceMarkup.gold;
const basicPrice : {[R in BasicRes]: number} = {
catnip: wage / workerProduction("farmer", "catnip"),
wood: wage / workerProduction("woodcutter", "wood"),
minerals: wage / workerProduction("miner", "minerals"),
iron: undefined, // assigned below
titanium: undefined, // assigned below
uranium: 100 * priceMarkup.uranium, // not derived from dragon trade, because uranium is usually obtained from them only very briefly
unobtainium: 1000 * priceMarkup.unobtainium,
coal: Math.max(0, wage - goldPrice * workerProduction("geologist", "gold")) / workerProduction("geologist", "coal") * priceMarkup.coal,
gold: goldPrice,
oil: 5 * priceMarkup.oil,
catpower: wage / workerProduction("hunter", "catpower"),
science: wage / workerProduction("scholar", "science"),
culture: priceMarkup.culture,
faith: wage / workerProduction("priest", "faith") * priceMarkup.faith,
unicorn: priceMarkup.unicorn,
alicorn: 20000 * priceMarkup.alicorn,
necrocorn: 20000 * priceMarkup.alicorn + 30000 * priceMarkup.necrocorn,
antimatter: 5000 * priceMarkup.antimatter,
};
price = <any>basicPrice;
price.iron = ironPrice(state, basicPrice),
price.starchart = 1000 * priceMarkup.starchart;
conversions = [
// in resource flow order, so conversion production can be calculated in a single pass
// (this is, for each resource, the conversion that uses is primarily should appear last
// among all conversions affecting that resource. This ensures that 100% conversionProportion
// consumes everything)
new CraftingConversion("slab", {minerals: 250}),
new LeviathanTrade(),
new DragonTrade(),
new ZebraTrade(),
new Hunt(),
new CraftingConversion("parchment", {fur: 175}),
new CraftingConversion("manuscript", {parchment: 25, culture: 400}),
new CraftingConversion("compendium", {manuscript: 50, science: 10000}),
new CraftingConversion("blueprint", {compendium: 25, science: 25000}),
new CraftingConversion("beam", {wood: 175}),
new CraftingConversion("steel", {coal: 100, iron: 100}),
new CraftingConversion("plate", {iron: 125}),
new CraftingConversion("megalith", {slab: 50, beam: 25, plate: 5}),
new CraftingConversion("scaffold", {beam: 50}),
new CraftingConversion("concrete", {slab: 2500, steel: 25}),
new CraftingConversion("alloy", {steel: 75, titanium: 10}),
new CraftingConversion("gear", {steel: 15}),
new CraftingConversion("eludium", {unobtainium: 1000, alloy: 2500}),
new KeroseneConversion(),
new UnicornSacrifice(),
new AlicornSacrifice(),
new RefineTears(),
new Smelting(), // only for display purposes (price is set previously)
];
const priceInitializer = {} as {[R in ConvertedRes]: Conversion};
for (const conv of conversions) {
priceInitializer[conv.product] = conv;
}
const priceProvider = (res: Res) => {
if (price[res] === undefined) {
priceInitializer[res].init(priceProvider);
}
return price[res];
}
for (const c of conversions) {
c.init(priceProvider);
}
}
function workerProduction(job: Job, res: Res) {
return delta(basicProduction, {
workers: {
[job]: state.workers[job] + 1,
},
extraKittens: 1,
})[res];
}
function ironPrice(state: GameState, price: {[R in BasicRes]: number}) {
/*
It is quite hard to find a way to price iron that appropriate for all stages of the game:
Early on, iron comes from smelters, so we should determine iron price based on that.
Later though, smelters also produce coal, gold, and titanium.
How do we deal with that?
We could simply ignore the value of the other outputs, but as they can be very valuable
at times (for instance: gold rally in early titanium age), iron price would be significantly
overestimated.
We could subtract the value of other outputs when setting the iron price, but their high
volatility would destabilize the iron price and require frequent player intervention.
Such hidden coupling among prices would also be hard to understand for players
(even I would be surprised that lowering blueprint prices massively reduces my iron price
due to increased titanium prices ...). Also, it would create a mutual dependency between
iron and titanium prices (smelters also produce titanium, trading for titanium also produces
iron), which the current pricing algorithm can not resolve.
Instead, we use a hybrid model, where large markup uses the full input costs, but small markup
also reduces input costs.
*/
const smelter = delta(basicProduction, {level: {Smelter: state.level.Smelter + 1}});
const inputCost = -smelter.wood * price.wood - smelter.minerals * price.minerals;
const m = state.priceMarkup.iron;
const c = 0.01;
const cost = m < c ? inputCost * m/c : inputCost + m;
return cost / smelter.iron;
}
type Cart = {[R in Res]?: number};
function delta(metric: (state: GameState) => Cart, change: GameStateUpdate): Cart {
const original = metric(state);
const undo = apply(state, change);
try {
const modified = metric(state);
const delta = {};
for (let r in original) {
delta[r] = modified[r] - original[r];
}
return delta;
} finally {
undo();
}
}
function hardLimit(min: number, x: number, max: number) {
return x < min ? min
: x > max ? max
: x;
}
function hyperbolicDecrease(x: number) {
return x < 0.75 ? (1 - x) : 0.25 / ((x - 0.5) / 0.25);
}
function hyperbolicLimit(x: number, limit: number) {
let a = x / limit;
if (a > 0.75) {
a = 1 - 0.25 / ((a - 0.5) / 0.25);
}
return a * limit;
}
/** called getTriValue in kittens game source code */
function triValue(value: number, stripe: number){
return (Math.sqrt(1 + 8 * value / stripe) - 1) / 2;
}
function invertTriValue(triValue: number, stripe: number) {
return ((triValue * 2 + 1) ** 2 - 1) / 8 * stripe;
}
/** multiplier to production caused by solar revolution */
export function solarRevolutionProductionBonus(state: GameState) {
return 1 + (state.upgrades.SolarRevolution && hyperbolicLimit(triValue(state.faith.stored, 1000), 1000) * 0.01);
}
// called GetTranscendenceRatio in kittens game source code
function transcendenceRatio(level: number) {
return (Math.pow(Math.exp(level)/5+1,2)-1)/80;
}
export function praiseBonus(state: GameState) {
const {faith} = state;
return triValue(faith.apocryphaPoints, 0.1) * 0.1;
}
export function setPraiseBonus(praiseBonus: number, state: GameState) {
state.faith.apocryphaPoints = invertTriValue(praiseBonus / 0.1, 0.1);
}
export function faithReset(state: GameState, undo?: boolean) {
const {faith} = state;
const newlyStored = undo ? faith.previouslyStored : 0;
faith.previouslyStored = faith.stored;
faith.stored = newlyStored;
const converted = faith.previouslyStored - faith.stored;
faith.apocryphaPoints += 1.01 * (1 + faith.transcendenceLevel)**2 * converted * 1E-6;
}
export function transcend(state: GameState, times: number) {
const {faith} = state;
const oldLevel = faith.transcendenceLevel;
const newLevel = oldLevel + times;
const cost = transcendenceRatio(newLevel) - transcendenceRatio(oldLevel);
faith.transcendenceLevel = newLevel;
faith.apocryphaPoints -= cost;
}
function countKittens(state: GameState) {
const {level} = state;
return level.Hut * 2 + level.LogHouse * 1 + level.Mansion * 1 + level.SpaceStation * 2 + level.TerraformingStation * 1;
}
export function reset(state: GameState) {
faithReset(state);
// TODO: update karma
state.paragon += Math.max(0, countKittens(state) - 70);
const {metaphysic, faith, karma, paragon} = state;
const {apocryphaPoints, transcendenceLevel} = faith;
replaceGameState({
metaphysic,
faith: {
apocryphaPoints,
transcendenceLevel,
},
karma,
paragon,
});
}
function activeLevel(state: GameState) {
const {level, active} = state;
const al = <{[B in Building]: number}> {};
for (const b of buildingNames) {
al[b] = active[b] === false ? 0 : level[b]; // active is undefined for buildings that are always active
}
return al;
}
function basicProduction(state: GameState): Cart {
// production is per second real time (neither per tick, nor per day)
const day = 2; // seconds
const year = 400 * day;
const {upgrades, metaphysic, workers, luxury} = state;
const level = activeLevel(state);
const kittens = countKittens(state);
const unhappiness = 0.02 * Math.max(kittens - 5, 0) * hyperbolicDecrease(level.Amphitheatre * 0.048 + level.BroadcastTower * 0.75);
const happiness = 1 + (luxury.fur && 0.1) + (luxury.ivory && 0.1) + (luxury.unicorn && 0.1) + (luxury.alicorn && 0.1) + (state.karma && 0.1 + state.karma * 0.01)
+ (level.SunAltar && level.Temple * (0.004 + level.SunAltar * 0.001)) - unhappiness;
const workerProficiency = 1 + 0.1875 * kittens / (kittens + 50) * (1 + (upgrades.Logistics && 0.15) + (upgrades.Augmentations && 1)); // approximation: the more kittens, the older the average kitten (assuming no deaths)
const workerEfficiency = happiness * workerProficiency;
let idle = kittens;
for (let j in workers) {
idle -= workers[j];
}
workers.farmer += idle + state.extraKittens; // so additional kittens are known to contribute production
const faithBonus = solarRevolutionProductionBonus(state);
const paragonBonus = 1 + 0.01 * hyperbolicLimit(state.paragon, 200);
const autoParagonBonus = 1 + 0.0005 * hyperbolicLimit(state.paragon, 200);
const scienceBonus = level.Library * 0.1
+ level.DataCenter * 0.1
+ level.Academy * 0.2
+ level.Observatory * 0.25 * (1 + level.Satellite * 0.05)
+ level.BioLab * (0.35 + (upgrades.BiofuelProcessing && 0.35))
+ level.SpaceStation * 0.5;
const astroChance = ((level.Library && 0.25) + level.Observatory * 0.2) * (1 + (metaphysic.Chronomancy && 0.1)) * (metaphysic.Astromancy ? 2 : 1) * 0.005 * Math.min(1, upgrades.SETI ? 1 : level.Observatory * 0.01 * (metaphysic.Astromancy ? 2 : 1));
const maxCatpower = (level.Hut * 75 + level.LogHouse * 50 + level.Mansion * 50 + level.Temple * (level.Templars && 50 + level.Templars * 25)) * (1 + state.paragon * 0.001);
const energyProduction = level.Steamworks * 1
+ level.Magneto * 5
+ level.HydroPlant * 5 * (1 + (upgrades.HydroPlantTurbines && 0.15))
+ level.Reactor * (10 + (upgrades.ColdFusion && 2.5))
+ level.SolarFarm * 2 * (1 + (upgrades.PhotovoltaicCells && 0.5)) * 0.75 /* assume worst season */ * (1 + (upgrades.ThinFilmCells && 0.15))
+ (upgrades.SolarSatellites && level.Satellite * 1)
+ level.Sunlifter * 30;
const energyConsumption = level.Calciner * 1
+ level.Factory * 2
+ (upgrades.Pumpjack && level.OilWell * 1)
+ (upgrades.BiofuelProcessing && level.BioLab * 1)
+ (level.DataCenter * (upgrades.Cryocomputing ? 1 : 2))
+ (!upgrades.SolarSatellites && level.Satellite * 1)
+ level.Accelerator * 2
+ level.SpaceStation * 10
+ level.LunarOutpost * 5
+ level.MoonBase * (upgrades.AntimatterBases ? 5 : 10)
+ level.OrbitalArray * 20
+ level.ContainmentChamber * 50 * (1 + level.HeatSink * 0.01);
const energyRatio = (energyProduction / energyConsumption) || 1;
const energyBonus = hardLimit(1, energyRatio, 1.75);
const energyDelta = hardLimit(0.25, energyRatio, 1); // TODO energy challenge reward
const magnetoBonus = 1 + level.Magneto * 0.02 * (1 + level.Steamworks * 0.15) * energyDelta;
const reactorBonus = 1 + level.Reactor * 0.05 * energyDelta;
const spaceRatioUranium = (1 + level.SpaceElevator * 0.01 + level.OrbitalArray * 0.02) // for some reason, space manuf. does not apply to uranium
const spaceRatio = spaceRatioUranium * (1 + (upgrades.SpaceManufacturing && level.Factory * (0.05 + (upgrades.FactoryLogistics && 0.01)) * 0.75)) * energyDelta;
const prodTransferBonus = level.SpaceElevator * 0.001;
const spaceParagonRatio = autoParagonBonus * magnetoBonus * reactorBonus * faithBonus;
const spaceAutoprodRatio = spaceRatio * (1 + (spaceParagonRatio - 1) * prodTransferBonus);
const unicornRatioReligion = level.UnicornTomb * 0.05 + level.IvoryTower * 0.1 + level.IvoryCitadel * 0.25 + level.SkyPalace * 0.5 + level.UnicornUtopia * 2.5 + level.SunSpire * 5;
return {
catnip: (level.CatnipField * 0.63 * (1.5 + 1 + 1 + 0.25) / 4
+ workers.farmer * workerEfficiency * 5 * (1 + (upgrades.MineralHoes && 0.5) + (upgrades.IronHoes && 0.3))
) * (1 + level.Aqueduct * 0.03 + level.Hydroponics * 0.025) * paragonBonus * faithBonus
- kittens * 4.25 * Math.max(1, happiness) * hyperbolicDecrease(level.Pasture * 0.005 + level.UnicornPasture * 0.0015) * (1 - (upgrades.RoboticAssistance && 0.25))
- (upgrades.BiofuelProcessing && level.BioLab * 5),
wood: workers.woodcutter * 0.09 * workerEfficiency
* (1 + (upgrades.MineralAxe && 0.7) + (upgrades.IronAxe && 0.5) + (upgrades.SteelAxe && 0.5) + (upgrades.TitaniumAxe && 0.5) + (upgrades.AlloyAxe && 0.5))
* (1 + level.LumberMill * 0.1 * (1 + (upgrades.ReinforcedSaw && 0.2) + (upgrades.SteelSaw && 0.2) + (upgrades.TitaniumSaw && 0.15) + (upgrades.AlloySaw && 0.15)))
* paragonBonus * magnetoBonus * reactorBonus * faithBonus
- level.Smelter * 0.25,
minerals: workers.miner * 0.25 * workerEfficiency * (1 + level.Mine * 0.2 + level.Quarry * 0.35) * paragonBonus * magnetoBonus * reactorBonus * faithBonus
- level.Smelter * 0.5 - level.Calciner * 7.5,
catpower: workers.hunter * 0.3 * workerEfficiency * (1 + (upgrades.CompositeBow && 0.5) + (upgrades.Crossbow && 0.25) + (upgrades.Railgun && 0.25)) * paragonBonus * faithBonus
- level.Mint * 3.75,
iron: (level.Smelter * 0.1 * (1 + (upgrades.ElectrolyticSmelting && 0.95)) + level.Calciner * 0.75 * (1 + (upgrades.Oxidation && 1) + (upgrades.RotaryKiln && 0.75) + (upgrades.FluidizedReactors && 1))) * autoParagonBonus * magnetoBonus * reactorBonus * faithBonus,
coal: 0 + ((upgrades.DeepMining && level.Mine * 0.015) + level.Quarry * 0.075 + workers.geologist * workerEfficiency * (0.075 + (upgrades.Geodesy && 0.0375) + (upgrades.MiningDrill && 0.05) + (upgrades.UnobtainiumDrill && 0.075)))
* (1 + (upgrades.Pyrolysis && 0.2))
* (1 + (level.Steamworks && (-0.8 + (upgrades.HighPressureEngine && 0.2) + (upgrades.FuelInjectors && 0.2))))
* paragonBonus * magnetoBonus * reactorBonus * faithBonus
+ (upgrades.CoalFurnace && level.Smelter * 0.025 * (1 + (upgrades.ElectrolyticSmelting && 0.95))) * autoParagonBonus,
gold: (level.Smelter * 0.005 * autoParagonBonus
+ (upgrades.Geodesy && workers.geologist * workerEfficiency * (0.004 + (upgrades.MiningDrill && 0.0025) + (upgrades.UnobtainiumDrill && 0.0025)) * paragonBonus)) * magnetoBonus * reactorBonus * faithBonus
- level.Mint * 0.025,
oil: level.OilWell * 0.1 * (1 + (upgrades.Pumpjack && 0.45) + (upgrades.OilRefinery && 0.35) + (upgrades.OilDistillation && 0.75)) * paragonBonus * reactorBonus * faithBonus
+ (upgrades.BiofuelProcessing && level.BioLab * 0.1 * (1 + (upgrades.GMCatnip && 0.6)))
+ level.HydraulicFracturer * 2.5 * spaceAutoprodRatio
- level.Calciner * 0.12 - level.Magneto * 0.25,
titanium: (level.Calciner * 0.0025 * (1 + (upgrades.Oxidation && 3) + (upgrades.RotaryKiln && 2.25) + (upgrades.FluidizedReactors && 3))
+ (upgrades.NuclearSmelters && level.Smelter * 0.0075))
* autoParagonBonus * magnetoBonus * reactorBonus * faithBonus
- level.Accelerator * 0.075,
science: workers.scholar * 0.18 * workerEfficiency * (1 + scienceBonus) * paragonBonus * faithBonus + astroChance * (30 * scienceBonus),
culture: (level.Amphitheatre * 0.025 + level.Temple * (0.5 + level.StainedGlass * 0.25 + (level.Basilica && 0.75 + level.Basilica * 0.25)) + level.Chapel * 0.25 + level.BroadcastTower * 5 * energyBonus) * paragonBonus * faithBonus,
faith: (level.Temple * 0.0075 + level.Chapel * 0.025 + workers.priest * workerEfficiency * 0.0075) * (1 + level.SolarChant * 0.1) * paragonBonus * faithBonus,
fur: level.Mint * 0.0004375 * maxCatpower - (luxury.fur && kittens * 0.05) * hyperbolicDecrease(level.TradePost * 0.04),
ivory: level.Mint * 0.000105 * maxCatpower - (luxury.ivory && kittens * 0.035) * hyperbolicDecrease(level.TradePost * 0.04),
unicorn: level.UnicornPasture * 0.005 * (1 + unicornRatioReligion + (upgrades.UnicornSelection && 0.25)) * paragonBonus * faithBonus
+ level.IvoryTower * 0.00025 * 500 * (1 + unicornRatioReligion * 0.1)
+ (luxury.unicorn && 1e-6), // add some unicorns so the building shows up
alicorn: (level.SkyPalace * 10 + level.UnicornUtopia * 15 + level.SunSpire * 30) / 100000 / day
+ (luxury.alicorn && level.SkyPalace * 0.0001 + level.UnicornUtopia * 0.000125 + level.SunSpire * 0.00025)
- level.Marker * 0.000005, // we assume no necrocorns yet - if you already have some the corruption will be slower
necrocorn: level.Marker * 0.000005, // likewise
manuscript: level.Steamworks * ((upgrades.PrintingPress && 0.0025) + (upgrades.OffsetPress && 0.0075) + (upgrades.Photolithography && 0.0225)),
starchart: astroChance * 1
+ ((level.Satellite * 0.005 + level.ResearchVessel * 0.05 + level.SpaceBeacon * 0.625) * spaceRatio + (upgrades.AstroPhysicists && workers.scholar * 0.0005 * workerEfficiency))
* (1 + (upgrades.HubbleSpaceTelescope && 0.3)) * paragonBonus * faithBonus,
uranium: (upgrades.OrbitalGeodesy && level.Quarry * 0.0025 * paragonBonus * magnetoBonus * faithBonus)
+ level.Accelerator * 0.0125 * autoParagonBonus * magnetoBonus * faithBonus
+ level.PlanetCracker * 1.5 * (1 + (upgrades.PlanetBuster && 1)) * spaceRatioUranium
- level.Reactor * 0.005 * (1 - (upgrades.EnrichedUranium && 0.25))
- level.LunarOutpost * 1.75,
unobtainium: level.LunarOutpost * 0.035 * (1 + (upgrades.MicroWarpReactors && 1)) * spaceRatio,
antimatter: energyRatio >= 1 && level.Sunlifter * 1 / year,
}
}
function production(state: GameState): {[R in Res]: number} {
const production: {[R in Res]: number} = <any>basicProduction(state);
for (const conversion of conversions) {
if (!conversion.instanteneous) {
continue; // the conversion is ongoing and included in basicProduction (like smelting iron)
}
let frequency = Infinity;
for (const res in conversion.resourceInvestment) {
if (production[res] === undefined) {
throw new Error(`invalid conversion order: ${conversion.product} requires ${res}, but ${res} is not yet initialized`);
}
let maxFrequency = production[res] / conversion.resourceInvestment[res];
if (res == conversion.primaryInput) {
maxFrequency *= state.conversionProportion[conversion.product];
}
if (frequency > maxFrequency) {
frequency = maxFrequency;
}
}
if (frequency < 0) { // this may happen due to rounding issues
frequency = 0; // don't consume resources. If we didn't do this, it might consume a little sorrow, which may have infinite price and wreck havoc with roi calcs
}
for (const xp of conversion.investment.expeditures) {
production[xp.res] -= xp.amount * frequency;
}
const produced = conversion.produced(state);
for (const product in produced) {
production[product] = (production[product] || 0) + produced[product] * frequency;
}
}
return production;
}
type Storage = {[R in BasicRes]: number};
function storage(state: GameState): Storage {
let {conversionProportion, level, upgrades, ships, compendia} = state;
const barnRatio = (upgrades.ExpandedBarns && 0.75) + (upgrades.ReinforcedBarns && 0.80) + (upgrades.TitaniumBarns && 1.00) + (upgrades.AlloyBarns && 1.00) + (upgrades.ConcreteBarns && 0.75) + (upgrades.ConcretePillars && 0.05);
const warehouseRatio = 1 + (upgrades.ReinforcedWarehouses && 0.25) + (upgrades.TitaniumWarehouses && 0.50) + (upgrades.AlloyWarehouses && 0.45) + (upgrades.ConcreteWarehouses && 0.35) + (upgrades.StorageBunkers && 0.20) + (upgrades.ConcretePillars && 0.05);
const harborRatio = 1 + (upgrades.ExpandedCargo && hyperbolicLimit(ships * 0.01, 2.25 + (upgrades.ReactorVessel && level.Reactor * 0.05)));
const acceleratorRatio = 0 + (upgrades.EnergyRifts && 1) + (upgrades.StasisChambers && 0.95) + (upgrades.VoidEnergy && 0.75) + (upgrades.DarkEnergy && 2.5) + (upgrades.TachyonAccelerators && 5);
const paragonBonus = 1 + state.paragon * 0.001;
const baseMetalRatio = 1 + level.Sunforge * 0.01;
const science = scienceLimits(state);
return {
catnip: ((5000 + level.Barn * 5000 + (upgrades.Silos && level.Warehouse * 750) + level.Harbor * harborRatio * 2500) * (1 + (upgrades.Silos && barnRatio * 0.25))
+ level.Accelerator * acceleratorRatio * 30000 + level.MoonBase * 45000) * paragonBonus * (1 + (upgrades.Refrigeration && 0.75) + level.Hydroponics * 0.1),
wood: ((200 + level.Barn * 200 + level.Warehouse * 150 + level.Harbor * harborRatio * 700) * (1 + barnRatio) * warehouseRatio + level.Accelerator * acceleratorRatio * 20000 + level.MoonBase * 25000 + level.Cryostation * 200000) * paragonBonus,
minerals: ((250 + level.Barn * 250 + level.Warehouse * 200 + level.Harbor * harborRatio * 950) * (1 + barnRatio) * warehouseRatio + level.Accelerator * acceleratorRatio * 25000 + level.MoonBase * 30000 + level.Cryostation * 200000) * paragonBonus,
iron: ((50 + level.Barn * 50 + level.Warehouse * 25 + level.Harbor * harborRatio * 150) * (1 + barnRatio) * warehouseRatio + level.Accelerator * acceleratorRatio * 7500 + level.MoonBase * 9000 + level.Cryostation * 50000) * baseMetalRatio * paragonBonus,
titanium: ((2 + level.Barn * 2 + level.Warehouse * 10 + level.Harbor * harborRatio * 50) * warehouseRatio + level.Accelerator * acceleratorRatio * 750 + level.MoonBase * 1250 + level.Cryostation * 7500) * baseMetalRatio * paragonBonus,
uranium: (250 + level.Reactor * 250 + level.MoonBase * 1750 + level.Cryostation * 5000) * baseMetalRatio * paragonBonus,
unobtainium: (150 + level.MoonBase * 150 + level.Cryostation * 750) * baseMetalRatio * paragonBonus,
coal: 0,
oil: (1500 + level.OilWell * 1500 + level.MoonBase * 3500 + level.Cryostation * 7500) * paragonBonus,
gold: ((10 + level.Barn * 10 + level.Warehouse * 5 + level.Harbor * harborRatio * 25 + level.Mint * 100) * warehouseRatio + level.Accelerator * acceleratorRatio * 250) * (1 + level.SkyPalace * 0.01) * baseMetalRatio * paragonBonus,
catpower: 1e9, // I never hit the limit, so this should be ok
science: science.byBuildings + Math.min(science.byCompendia, compendia * science.perCompendium),
culture: 1e9, // I never hit the limit, so this should be ok (Ziggurats would boost this)
faith: (100 + level.Temple * (100 + level.SunAltar * 50)) * (1 + (level.GoldenSpire && 0.4 + level.GoldenSpire * 0.1)) * paragonBonus,
unicorn: 1e9, // there is no limit
alicorn: 1e9, // there is no limit
necrocorn: 1e9, // there is no limit
antimatter: (100 + level.ContainmentChamber * 50 * (1 + level.HeatSink * 0.02)) * paragonBonus, // TODO barnRatio? warehouseRatio? harborRatio?
}
}
function scienceLimits(state: GameState) {
const {level, upgrades, paragon} = state;
const paragonBonus = 1 + paragon * 0.001;
const libraryRatio = (upgrades.TitaniumReflectors && 0.02) + (upgrades.UnobtainiumReflectors && 0.02) + (upgrades.EludiumReflectors && 0.02);
const datacenterBoosts = (1 + (upgrades.Uplink && level.BioLab * 0.01))// * (1 + (upgrades.MachineLearning && level.AiCore * dataCenterAiRatio));
const spaceScienceRatio = (1 + (upgrades.AntimatterReactors && 0.95))
const scienceMax = (level.Library * 250 + level.DataCenter * 750 * datacenterBoosts) * (1 + level.Observatory * libraryRatio)
+ level.Academy * 500
+ level.Observatory * (upgrades.Astrolabe ? 1500 : 1000) * (1 + level.Satellite * 0.05)
+ level.BioLab * 1500 * (1 + level.DataCenter * ((upgrades.Uplink && 0.01) + (upgrades.Starlink && 0.01)))
+ level.Temple * (level.Scholasticism && 400 + level.Scholasticism * 100)
+ level.Accelerator * (upgrades.LHC && 2500)
+ level.ResearchVessel * 10000 * spaceScienceRatio
+ level.SpaceBeacon * 25000 * spaceScienceRatio
const scienceMaxCompendia = level.DataCenter * 1000 * datacenterBoosts;
return {
byBuildings: scienceMax * paragonBonus,
byCompendia: (scienceMax + scienceMaxCompendia) * paragonBonus,
perCompendium: 10 * paragonBonus,
}
}
interface Expense {
name: string;
cost: number;
}
class Expediture implements Expediture {
price: number;
cost: number;
constructor(public amount: number, public res: Res) {
if (isNaN(amount)) {
debugger;
throw new Error("amount is NaN");
}
this.price = price[res];
this.cost = amount * this.price;
}
}
export class Investment {
cost = 0;
expeditures: Expediture[] = [];
expenses: Expense[] = [];
alsoRequired: Expense[] = [];
alsoRequiredCost = 0;
add(xp: Expediture) {
if (Math.abs(xp.cost) > 1e-6 || Math.abs(xp.amount) > 1e-6) {
this.expeditures.push(xp);
this.cost += xp.cost;
}
}
addExpense(expense: Expense) {
this.expenses.push(expense);
this.cost += expense.cost;
}
addAdditionalRequirement(expense: Expense) {
this.alsoRequired.push(expense);
this.alsoRequiredCost += expense.cost;
}
}
export class CostBenefitAnalysis {
investment = new Investment();
return = new Investment();
instanteneous = false;
}
export abstract class Conversion extends CostBenefitAnalysis {
instanteneous = true;
private currentlyProduced = this.produced(state);
private initialized = false;
constructor(public product: ConvertedRes, public resourceInvestment: Cart) {
super();
}
/** also sets the price of the product! */
init(priceFor: (res: Res) => number) {
if (this.initialized) return;
let cost = 0;
let benefit = 0;
for (const res in this.resourceInvestment) {
const number = this.resourceInvestment[res]
cost += number * priceFor(<Res>res);
this.investment.add(new Expediture(number, <Res>res));
}
for (const res in this.currentlyProduced) {
const p = this.currentlyProduced[res];
if (p) {
if (res != this.product) {
if (p < 0) {
cost -= p * priceFor(<Res>res);
} else {
benefit += p * priceFor(<Res>res);
}
this.return.add(new Expediture(p, <Res>res));
}
}
}
price[this.product] = price[this.product] || Math.max(0, (cost * (state.priceMarkup[this.product] || 1) - benefit) / this.currentlyProduced[this.product]);
this.return.add(new Expediture(this.currentlyProduced[this.product], this.product)); // can't do this earlier, because it needs the price ...
this.initialized = true;
}
get primaryInput(): Res {
for (const r in this.resourceInvestment) {
return <Res>r; // the first
}
}
abstract produced(state: GameState): Cart;
}
class Smelting extends Conversion {
constructor() {
super("iron", {});
this.instanteneous = false;
}
produced(state: GameState) {
return delta(basicProduction, {
level: {
Smelter: state.level.Smelter + 1
}
});
}
}
class Hunt extends Conversion {
constructor() {
price.ivory = 0;
super("fur", {catpower: 100});
}
produced(state: GameState){
const {upgrades} = state;
const huntingBonus = 0 + (upgrades.Bolas && 1) + (upgrades.HuntingArmor && 2) + (upgrades.SteelArmor && 0.5) + (upgrades.AlloyArmor && 0.5) + (upgrades.Nanosuits && 0.5);
return {
fur: 40 + huntingBonus * 32,
ivory: (0.44 + huntingBonus * 0.02) * (25 + huntingBonus * 20),
unicorn: 0.05,
}
}
}
abstract class Trade extends Conversion {
constructor(product: ConvertedRes, input: Cart) {
super(product, {gold: 15, catpower: 50, ...input});
}
get friendly() {
return 0;
}
get hostile() {
return 0;
}
produced(state: GameState) {
const {level, metaphysic} = state;
let output = this.output(state, 1 + level.TradePost * 0.015);
const standingRatio = level.TradePost * 0.0035 + (metaphysic.Diplomacy && 0.1);
const friendlyChance = this.friendly && Math.max(1, this.friendly + standingRatio / 2);
const hostileChance = this.hostile && Math.max(0, this.hostile - standingRatio);
const expectedSuccess = 1 - hostileChance + friendlyChance * 0.25;
for (const k in output) {
output[k] *= expectedSuccess;
}
output["blueprint"] = expectedSuccess * 0.1 * 1;
return output;
}
abstract output(state: GameState, tradeRatio: number): {[R in Res]?: number};
}
class ZebraTrade extends Trade {
constructor() {
super("titanium", {slab: 50});
}
// must be a getter to be available to the super constructor
get hostile() {
return 0.3;
}
output(state: GameState, tradeRatio: number) {
const {ships} = state;
const titaniumChance = Math.min(1, 0.15 + ships * 0.0035);
const titaniumAmount = 1.5 + ships * 0.03;
return {
titanium: titaniumChance * titaniumAmount,
plate: 0.65 * 2 * 1.05 * tradeRatio,
iron: 1 * 300 * 1.00 * tradeRatio,
}
}
}
class DragonTrade extends Trade {
constructor() {
super("uranium", {titanium: 250});
}
output(state: GameState, tradeRatio: number) {
return {
uranium: 0.95 * 1 * tradeRatio,
}
}
}
class LeviathanTrade extends Trade {
constructor() {
super("relic", {unobtainium: 5000});
}
get primaryInput(): Res {
return "unobtainium";
}
output(state: GameState, tradeRatio: number): Cart {
const raceRatio = 1 + state.leviathanEnergy * 0.02;
const ratio = tradeRatio * raceRatio;
return {
timecrystal: 0.98 * 0.25 * ratio,
sorrow: 0.15 * 1 * ratio,
starchart: 0.5 * 250 * ratio,
relic: 0.05 * 1 * ratio
}
}
}
class CraftingConversion extends Conversion {
constructor(product: ConvertedRes, resourceInvestment: Cart) {
super(product, resourceInvestment);
}
produced(state: GameState) {
const {level, upgrades} = state;
const produced: Cart = {};
produced[this.product] = craftRatio(state, this.product);
return produced;
}
}
class KeroseneConversion extends CraftingConversion {
constructor() {
super("kerosene", {oil: 7500});
}
produced(state: GameState) {
const {level, upgrades} = state;
const p = super.produced(state);
p[this.product] *= 1 + level.Factory * (upgrades.FactoryProcessing && 0.05) * 0.75;
return p;
}
}
class UnicornSacrifice extends Conversion {
constructor() {
super("tear", {unicorn: 2500});
}
produced(state: GameState): Cart {
return {
tear: state.level.Ziggurat
}
}
}
class RefineTears extends Conversion {
constructor() {
super("sorrow", {tear: 10000});
}
produced(state: GameState): Cart {
return {
sorrow: 1
}
}
}
class AlicornSacrifice extends Conversion {
constructor() {
super("timecrystal", {alicorn: 25})
}
produced(state: GameState): Cart {
const {level} = state;
const tcRefineRatio = 1 + level.UnicornUtopia * 0.05 + level.SunSpire * 0.10;
return {
timecrystal: 1 * tcRefineRatio
}
}
}
function craftRatio(state: GameState, res?: ConvertedRes) {
const {level, upgrades, metaphysic} = state;
const ratio = 1 + level.Workshop * 0.06 + level.Factory * (0.05 + (upgrades.FactoryLogistics && 0.01))
let resCraftRatio = 0;
let globalResCraftRatio = 0;
if (res == "blueprint") {
resCraftRatio = upgrades.CADsystem && 0.01 * (level.Library + level.Academy + level.Observatory + level.BioLab);
} else if (res == "manuscript") {
resCraftRatio = metaphysic.CodexVox && 0.25;
globalResCraftRatio = metaphysic.CodexVox && 0.05;
}
return (ratio + resCraftRatio) * (1 + globalResCraftRatio);
}
export class ScienceInfo extends CostBenefitAnalysis {
constructor(public name: Science, public resourceInvestment: Cart, unlocks: Array<Science | Upgrade | Building | Job>) {
super();
for (const res in resourceInvestment) {
this.investment.add(new Expediture(resourceInvestment[res], <Res>res));
}
for (const unlock of unlocks) {
prerequisite[unlock] = prerequisite[unlock] || [];
prerequisite[unlock].push(this);
}
}
get visible() {
return state.researched[this.name] ? state.showResearchedUpgrades : collectMissingPrerequisites(this.name).length <= 3;
}
get stateInfo() {
return state.researched[this.name] ? 'R' : '';
}
effect(times: number) {
return {
researched: {
[this.name]: times > 0
}
}
}
}
function collectMissingPrerequisites(thing: string, results: ScienceInfo[] = []) {
for (const p of prerequisite[thing] || []) {
if (!state.researched[p.name]) {
collectMissingPrerequisites(p.name, results);
results.push(p);
}
}
return results;
}
export abstract class Action extends CostBenefitAnalysis {
roi: number;
constructor(s: GameState, public name: string, resourceInvestment: Cart, resourceMultiplier = 1) {
super();
for (const res in resourceInvestment) {
const number = resourceInvestment[res];
this.investment.add(new Expediture(number * resourceMultiplier, <Res>res));
}
this.procurePrerequisite();
this.procureStorage(this.investment.expeditures, s);
}
assess() {
const deltaProduction = delta(production, this.effect(1));
for (const r of resourceNames) {
if (deltaProduction[r] !== undefined) {
this.return.add(new Expediture(deltaProduction[r], r));
}
}
this.roi = this.investment.cost / this.return.cost;
if (this.return.cost <= 0 || this.roi > 1e6) {
this.roi = Infinity;
}
return this; // for chaining
}
private static procuringStorage = false;
procureStorage(xps: Expediture[], state: GameState) {
const undoers: Array<() => void> = [];
try {
let currentStorage = storage(state);
for (const xp of this.investment.expeditures) {
while (xp.amount > currentStorage[xp.res]) {
if (Action.procuringStorage) {
// don't recurse (for performance, and to avoid endless recursion if a building needs storage, and considers building itself to fix that :-)
this.investment.cost = Infinity;
return;
}
Action.procuringStorage = true;
try {
// what's the best way to expand our storage?
let bestRoI = 0;
let bestAction: Action = null;
let bestStorage: Storage;
if (this.investment.expenses.length < 9) { // limit depth to save CPU time
for (const sa of storageActions(state, xp.res == "science" && xp.amount)) {
const undo = apply(state, sa.effect(1));
let newStorage = storage(state);
undo();
const gain = newStorage[xp.res] - currentStorage[xp.res];
const cost = sa.investment.cost;
const roi = gain / cost;
if (roi > bestRoI) {
bestRoI = roi;
bestAction = sa;
bestStorage = newStorage;
}
}
}
if (bestAction) {
this.investment.addExpense({
name: bestAction.name,
cost: bestAction.investment.cost
});
const undo = apply(state, bestAction.effect(1));
undoers.push(undo);
currentStorage = bestStorage;
} else {
this.investment.addExpense({
name: "<more storage needed>",
cost: Infinity,
});
return;
}
} finally {
Action.procuringStorage = false;
}
}
}
} finally {
while (undoers.length) {
undoers.pop()();
}
}
}
procurePrerequisite() {
for (const p of collectMissingPrerequisites(this.name)) {
const expense = {name: p.name, cost: p.investment.cost};
if (this.repeatable) {
this.investment.addAdditionalRequirement(expense); // it would be misleading to have the first action pay the entire cost
} else {
this.investment.addExpense(expense); // but here it makes sense
}
}
}
available(state: GameState) {
return true;
}
abstract effect(times: number): GameStateUpdate;
abstract readonly stateInfo: string | number;
abstract readonly repeatable: boolean;
}
const obsoletes: {[B in Building]?: Building} = {
BroadcastTower: "Amphitheatre",
DataCenter: "Library",
HydroPlant: "Aqueduct",
SolarFarm: "Pasture",
}
const obsoletedBy: {[B in Building]?: Building} = {
Amphitheatre: "BroadcastTower",
Aqueduct: "HydroPlant",
Library: "DataCenter",
Pasture: "SolarFarm",
}
class BuildingAction extends Action {
constructor(name: Building, private initialConstructionResources: Cart, priceRatio: number, s = state, priceReduction: number | null = 0) {
super(s, name, initialConstructionResources, Math.pow(BuildingAction.priceRatio(s, priceRatio, priceReduction), s.level[name]));
}
static priceRatio(s: GameState, ratio: number, reduction: number | null) {
if (reduction !== null) {
const {metaphysic} = s;
// cf. getPriceRatioWithAccessor in buildings.js
const ratioBase = ratio - 1;
const ratioDiff = reduction
+ (metaphysic.Engineering && 0.01)
+ (metaphysic.GoldenRatio && (1+Math.sqrt(5))/2 * 0.01)
+ (metaphysic.DivineProportion && 0.16 / 9)
+ (metaphysic.VitruvianFeline && 0.02)
+ (metaphysic.Renaissance && 0.0225);
ratio = ratio - hyperbolicLimit(ratioDiff, ratioBase);
}
return ratio;
}
available(state: GameState) {
return super.available(state) && !this.obsolete(state);
}
obsolete(state: GameState) {
const ob = obsoletedBy[this.name];
return ob && state.level[ob];
}
private levelUpdateEffect(newLevel: number) {
const update: GameStateUpdate = {
level: {
[this.name]: newLevel,
}
};
if (newLevel) {
const o = obsoletes[this.name];
if (o) {
update.level[o] = 0;
}
}
return update;
}
get stateInfo(): number {
return state.level[this.name];
}
set stateInfo(newValue: number) {
apply(state, this.levelUpdateEffect(newValue));
}
effect(times: number) {
return this.levelUpdateEffect(state.level[this.name] + times);
}
get repeatable() {
return true;
}
}
class SpaceAction extends BuildingAction {
constructor(name: Building, initialConstructionResources: Cart, priceRatio: number, s = state) {
if (initialConstructionResources.oil) {
initialConstructionResources.oil *= 1 - hyperbolicLimit(s.level.SpaceElevator * 0.05, 0.75);
initialConstructionResources.oil *= Math.pow(1.05, s.level[name]) / Math.pow(priceRatio, s.level[name]); // price ratio for oil is always 1.05
}
super(name, initialConstructionResources, priceRatio, s, null);
}
}
class ReligiousAction extends BuildingAction {
constructor(name: Building, initialConstructionResources: Cart, s = state) {
super(name, initialConstructionResources, 2.5, s, null);
}
available(state: GameState) {
const {level, upgrades} = state;
return super.available(state) && (level[this.name] == 0 || upgrades.Transcendence || state.showResearchedUpgrades);
}
}
class ZigguratBuilding extends BuildingAction {
constructor(name: Building, initialConstructionResources: Cart, priceRatio: number, s = state) {
super(name, initialConstructionResources, priceRatio, s, null);
}
available(state: GameState) {
return super.available(state) && state.level.Ziggurat > 0;
}
}
class UpgradeAction extends Action {
constructor(name: Upgrade, resourceCost: Cart, s = state) {
super(s, name, resourceCost);
}
get stateInfo() {
return state.upgrades[this.name] ? "R" : " ";
}
available(state: GameState) {
return super.available(state) && state.level.Workshop && (state.showResearchedUpgrades || !state.upgrades[this.name]);
}
effect(times: number): GameStateUpdate {
return {
upgrades: {
[this.name]: times > 0,
}
}
}
get repeatable() {
return false;
}
}
class MetaphysicAction extends Action {
constructor(name: Metaphysic, private paragonCost: number, s = state) {
super(s, name, {});
}
get stateInfo() {
return state.metaphysic[this.name] ? "R" : " ";
}
available(state: GameState) {
return true;
}
effect(times: number): GameStateUpdate {
return {
metaphysic: {
[this.name]: times > 0,
},
paragon: state.paragon - times * this.paragonCost,
}
}
get repeatable() {
return false;
}
}
class TradeshipAction extends Action {
constructor(s = state) {
super(s, "TradeShip", {scaffold: 100, plate: 150, starchart: 25});
}
effect(times: number) {
return {ships: state.ships + times * craftRatio(state)}
}
get stateInfo() {
return "";
}
get repeatable() {
return true;
}
}
class PraiseAction extends Action {
constructor() {
super(state, "PraiseTheSun", {faith: 1000});
}
effect(times: number) {
return {
faith: {
stored: state.faith.stored + times * 1000 * (1 + praiseBonus(state))
}
}
}
get stateInfo() {
return "";
}
get repeatable() {
return true;
}
}
function compendiaAction(state: GameState, desiredScienceLimit: number) {
const scienceLimit = scienceLimits(state);
const desiredScienceByCompendia = desiredScienceLimit - scienceLimit.byBuildings;
const available = 0 < desiredScienceByCompendia && desiredScienceByCompendia < scienceLimit.byCompendia;
const desiredCompendia = desiredScienceByCompendia / scienceLimit.perCompendium + 1e-6; // guard against floating point rounding errors
const neededCompendia = desiredCompendia - state.compendia;
return new class A extends Action {
constructor() {
super(state, `${Math.round(neededCompendia)} compendia`, {compendium: neededCompendia}, 1);
}
available() {
return available;
}
effect(times: number) {
return {
compendia: desiredCompendia,
}
}
stateInfo = "";
repeatable = false;
}
}
class FeedEldersAction extends Action {
constructor() {
super(state, "FeedElders", {necrocorn: 1})
}
effect(times: number) {
return {
leviathanEnergy: state.leviathanEnergy + times
}
}
get stateInfo() {
return "";
}
get repeatable() {
return true;
}
}
function updateSciences() {
prerequisite = {};
const infos = [
new ScienceInfo("Calendar", {science: 30}, ["Agriculture"]),
new ScienceInfo("Agriculture", {science: 100}, ["Mining", "Archery", "Barn", "farmer"]),
new ScienceInfo("Archery", {science: 300}, ["AnimalHusbandry", "hunter"]),
new ScienceInfo("AnimalHusbandry", {science: 500}, ["CivilService", "Mathematics", "Construction", "Pasture", "UnicornPasture"]),
new ScienceInfo("Mining", {science: 500}, ["MetalWorking", "Mine", "Workshop", "Bolas"]), // also enables meteors
new ScienceInfo("MetalWorking", {science: 900}, ["Smelter", "HuntingArmor"]),
new ScienceInfo("Mathematics", {science: 1000}, ["Academy"]), // celestial mechanics
new ScienceInfo("Construction", {science: 1300}, ["Engineering", "LogHouse", "Warehouse", "LumberMill", "Ziggurat", "CompositeBow", "ReinforcedSaw"]), // catnip enrichment
new ScienceInfo("CivilService", {science: 1500}, ["Currency"]),
new ScienceInfo("Engineering", {science: 1500}, ["Writing", "Aqueduct"]),
new ScienceInfo("Currency", {science: 2200}, ["TradePost"]),
new ScienceInfo("Writing", {science: 3600}, ["Philosophy", "Machinery", "Steel", "Amphitheatre"]), // register
new ScienceInfo("Philosophy", {science: 9500}, ["Theology", "Temple"]),
new ScienceInfo("Steel", {science: 12000}, ["SteelAxe", "ReinforcedWarehouses", "CoalFurnace", "DeepMining", "HighPressureEngine", "SteelArmor"]),
new ScienceInfo("Machinery", {science: 15000}, ["Steamworks", "PrintingPress", "Crossbow"]), // workshop automation
new ScienceInfo("Theology", {science: 20000, manuscript: 35}, ["Astronomy", "Cryptotheology", "priest"]),
new ScienceInfo("Astronomy", {science: 28000, manuscript: 65}, ["Navigation", "Observatory"]),
new ScienceInfo("Navigation", {science: 35000, manuscript: 100}, ["Architecture", "Physics", "Geology", "Harbor", "TitaniumAxe", "ExpandedCargo", "Astrolabe", "TitaniumReflectors"]), // Caravanserai
new ScienceInfo("Architecture", {science: 42000, compendium: 10}, ["Acoustics", "Mansion", "Mint"]),
new ScienceInfo("Physics", {science: 50000, compendium: 35}, ["Chemistry", "Electricity", "Metaphysics", "SteelSaw", "Pyrolysis"]), //pneumatic press
new ScienceInfo("Metaphysics", {science: 55000, unobtainium: 5}, []),
new ScienceInfo("Chemistry", {science: 60000, compendium: 50}, ["OilWell", "Calciner", "AlloyAxe", "AlloyBarns", "AlloyWarehouses", "AlloyArmor"]),
new ScienceInfo("Acoustics", {science: 60000, compendium: 60}, ["DramaAndPoetry", "Chapel"]),
new ScienceInfo("Geology", {science: 65000, compendium: 65}, ["Biology", "Quarry", "Geodesy", "geologist"]),
new ScienceInfo("DramaAndPoetry", {science: 90000, parchment: 5000}, []), // enables festivals
new ScienceInfo("Electricity", {science: 75000, compendium: 85}, ["Industrialization", "Magneto"]),
new ScienceInfo("Biology", {science: 85000, compendium: 100}, ["Biochemistry", "BioLab"]),
new ScienceInfo("Biochemistry", {science: 145000, compendium: 500}, ["Genetics", "BiofuelProcessing"]),
new ScienceInfo("Genetics", {science: 190000, compendium: 1500}, ["UnicornSelection", "GMCatnip"]),
new ScienceInfo("Industrialization", {science: 100000, blueprint: 25}, ["Mechanization", "Metallurgy", "Combustion", "Logistics"]), // Barges, AdvancedAutomation
new ScienceInfo("Mechanization", {science: 115000, blueprint: 45}, ["Electronics", "Factory", "ConcretePillars", "Pumpjack"]),
new ScienceInfo("Combustion", {science: 115000, blueprint: 45}, ["Ecology", "OffsetPress", "FuelInjectors", "OilRefinery"]),
new ScienceInfo("Metallurgy", {science: 125000, blueprint: 60}, ["ElectrolyticSmelting", "Oxidation", "MiningDrill"]),
new ScienceInfo("Ecology", {science: 125000, blueprint: 55}, ["SolarFarm"]),
new ScienceInfo("Electronics", {science: 135000, blueprint: 70}, ["Robotics", "NuclearFission", "Rocketry", "Refrigeration", "CADsystem", "SETI", "FactoryLogistics", "Telecommunication", "BroadcastTower", "DataCenter"]), // FactoryOptimization
new ScienceInfo("Robotics", {science: 140000, blueprint: 80}, ["ArtificialIntelligence", "HydroPlant", "RotaryKiln", "RoboticAssistance"]), // SteelPlants, FactoryRobotics, Tanker
new ScienceInfo("ArtificialIntelligence", {science: 250000, blueprint: 150}, ["QuantumCryptography"]), // AICore, NeuralNetworks, AIEngineers
//new ScienceInfo("QuantumCryptography", {science: 1250000, relic: })
// new ScienceInfo("Blackchain"),
new ScienceInfo("NuclearFission", {science: 150000, blueprint: 100}, ["Nanotechnology", "ParticlePhysics", "Reactor", "ReactorVessel", "NuclearSmelters"]),
new ScienceInfo("Rocketry", {science: 175000, blueprint: 125}, ["Satellites", "OilProcessing", "OilDistillation", "OrbitalLaunch"]),
new ScienceInfo("OilProcessing", {science: 215000, blueprint: 150}, ["FactoryProcessing"]), // kerosene
new ScienceInfo("Satellites", {science: 190000, blueprint: 125}, ["OrbitalEngineering", "Satellite", "Photolithography", "OrbitalGeodesy", "Uplink", "ThinFilmCells"]),
new ScienceInfo("OrbitalEngineering", {science: 250000, blueprint: 250}, ["Exogeology", "Thorium", "HubbleSpaceTelescope", "AstroPhysicists", "SpaceStation", "SpaceElevator", "SolarSatellites", "Starlink"]), // SpaceEngineers
new ScienceInfo("Thorium", {science: 375000, blueprint: 375}, []), // ThoriumReactors, ThoriumDrive
new ScienceInfo("Exogeology", {science: 275000, blueprint: 250}, ["AdvancedExogeology", "UnobtainiumReflectors", "UnobtainiumHuts", "UnobtainiumDrill", "HydroPlantTurbines", "StorageBunkers"]),
new ScienceInfo("AdvancedExogeology", {science: 325000, blueprint: 350}, ["PlanetBuster", "EludiumHuts", "MicroWarpReactors", "EludiumReflectors"]),
new ScienceInfo("Nanotechnology", {science: 200000, blueprint: 150}, ["Superconductors", "PhotovoltaicCells", "Nanosuits", "Augmentations", "FluidizedReactors", "SpaceElevator"]),
new ScienceInfo("Superconductors", {science: 225000, blueprint: 175}, ["Antimatter", "ColdFusion", "SpaceManufacturing", "Cryocomputing"]),
new ScienceInfo("Antimatter", {science: 500000, relic: 1}, ["Terraformation", "AntimatterBases", "AntimatterReactors", "AntimatterFission", "AntimatterDrive"]),
new ScienceInfo("Terraformation", {science: 750000, relic: 5}, ["HydroPonics", "TerraformingStation"]),
new ScienceInfo("HydroPonics", {science: 1000000, relic: 25}, ["Exophysics", "Hydroponics"]), // Tectonic
// new ScienceInfo("Exophysics", )
new ScienceInfo("ParticlePhysics", {science: 185000, blueprint: 135}, [/*"Chronophysics"*/, "DimensionalPhysics", "Accelerator", "EnrichedUranium", "Railgun"]),
new ScienceInfo("DimensionalPhysics", {science: 235000}, ["EnergyRifts", "LHC"]),
new ScienceInfo("Chronophysics", {science: 250000, timecrystal: 5}, ["TachyonTheory", "StasisChambers", "VoidEnergy", "DarkEnergy"]),
new ScienceInfo("TachyonTheory", {science: 750000, timecrystal: 25, relic: 1}, ["VoidSpace", "TachyonAccelerators", /*"Chronoforge"*/]),
// ...
new ScienceInfo("OrbitalLaunch", {starchart: 250, catpower: 5000, science: 100000, oil: 15000}, ["Satellite", "SpaceElevator", "MoonMission", "SpaceStation"]),
new ScienceInfo("MoonMission", {starchart: 500, titanium: 5000, science: 125000, oil: 45000}, ["LunarOutpost", "MoonBase", "DuneMission", "PiscineMission"]),
new ScienceInfo("DuneMission", {starchart: 1000, titanium: 7000, science: 175000, kerosene: 75}, ["HeliosMission", "PlanetCracker", "HydraulicFracturer", "SpiceRefinery"]),
new ScienceInfo("PiscineMission", {starchart: 1500, titanium: 9000, science: 200000, kerosene: 250}, ["TMinusMission", "ResearchVessel", "OrbitalArray"]),
new ScienceInfo("HeliosMission", {starchart: 3000, titanium: 15000, science: 250000, kerosene: 1250}, ["YarnMission", "Sunlifter", "ContainmentChamber", "HeatSink", "Sunforge"]),
new ScienceInfo("TMinusMission", {starchart: 2500, titanium: 12000, science: 225000, kerosene: 750}, ["HeliosMission", "KairoMission", "Cryostation"]),
new ScienceInfo("KairoMission", {starchart: 5000, titanium: 20000, science: 300000, kerosene: 7500}, ["RorschachMission", "SpaceBeacon"]),
new ScienceInfo("YarnMission", {starchart: 7500, titanium: 35000, science: 350000, kerosene: 12000}, ["UmbraMission", "TerraformingStation", "Hydroponics"]),
// ...
];
sciences = infos.filter(info => info.visible);
}
function scienceBuildings(state: GameState) {
return [
new BuildingAction("Accelerator", {titanium: 7500, concrete: 125, uranium: 25}, 1.15, state),
new BuildingAction("Library", {wood: 25}, 1.15, state),
new BuildingAction("DataCenter", {concrete: 10, steel: 100}, 1.15, state),
new BuildingAction("Academy", {wood: 50, minerals: 70, science: 100}, 1.15, state),
new BuildingAction("Observatory", {scaffold: 50, slab: 35, iron: 750, science: 1000}, 1.10, state),
new BuildingAction("BioLab", {slab: 100, alloy: 25, science: 1500}, 1.10, state),
new SpaceAction("ResearchVessel", {starchart: 100, alloy: 2500, titanium: 12500, kerosene: 250}, 1.15, state),
new SpaceAction("SpaceBeacon", {starchart: 25000, antimatter: 50, alloy: 25000, kerosene: 7500}, 1.15),
];
}
function activationActions() {
return activatableBuildingNames.map(building => {
const active = state.active[building];
return new class A extends Action {
constructor() {
super(state, building, {});
}
effect(times: number) {
return {
active: {
[building]: !active
}
}
}
stateInfo = active ? "on" : "off";
repeatable = false;
};
});
}
function updateActions() {
const {upgrades} = state;
actions = [
new BuildingAction("CatnipField", {catnip: 10}, 1.12),
new BuildingAction("Pasture", {catnip: 100, wood: 10}, 1.15),
new BuildingAction("SolarFarm", {titanium: 250}, 1.15),
new BuildingAction("Aqueduct", {minerals: 75}, 1.12),
new BuildingAction("HydroPlant", {concrete: 100, titanium: 2500}, 1.15),
new BuildingAction("Hut", {wood: 5}, 2.5, state, (upgrades.IronWoodHuts && 0.5) + (upgrades.ConcreteHuts && 0.3) + (upgrades.UnobtainiumHuts && 0.25) + (upgrades.EludiumHuts && 0.1)),
new BuildingAction("LogHouse", {wood: 200, minerals: 250}, 1.15),
new BuildingAction("Mansion", {slab: 185, steel: 75, titanium: 25}, 1.15),
...scienceBuildings(state),
new BuildingAction("Mine", {wood: 100}, 1.15),
new BuildingAction("Quarry", {scaffold: 50, steel: 125, slab:1000}, 1.15),
new BuildingAction("LumberMill", {wood: 100, iron: 50, minerals: 250}, 1.15),
new BuildingAction("OilWell", {steel: 50, gear: 25, scaffold: 25}, 1.15),
new BuildingAction("Steamworks", {steel: 65, gear: 20, blueprint: 1}, 1.25),
new BuildingAction("Magneto", {alloy: 10, gear: 5, blueprint: 1}, 1.25),
new BuildingAction("Smelter", {minerals: 200}, 1.15),
new BuildingAction("Calciner", {steel: 100, titanium: 15, blueprint: 1, oil: 500}, 1.15),
new BuildingAction("Factory", {titanium: 2000, plate: 2500, concrete: 15}, 1.15),
new BuildingAction("Reactor", {titanium: 3500, plate: 5000, concrete: 50, blueprint: 25}, 1.15),
new BuildingAction("Amphitheatre", {wood: 200, minerals: 1200, parchment: 3}, 1.15),
new BuildingAction("BroadcastTower", {iron: 1250, titanium: 75}, 1.18),
new BuildingAction("Chapel", {minerals: 2000, culture: 250, parchment: 250}, 1.15),
new BuildingAction("Temple", {slab: 25, plate: 15, manuscript: 10, gold: 50}, 1.15),
new BuildingAction("Workshop", {wood: 100, minerals: 400}, 1.15),
new BuildingAction("TradePost", {wood: 500, minerals: 200, gold: 10}, 1.15),
new BuildingAction("Mint", {minerals: 5000, plate: 200, gold: 500}, 1.15),
new BuildingAction("UnicornPasture", {unicorn: 2}, 1.75),
new BuildingAction("Ziggurat", {megalith: 50, scaffold: 50, blueprint: 1}, 1.25),
new SpaceAction("SpaceElevator", {titanium: 6000, science: 100000, unobtainium: 50}, 1.15),
new SpaceAction("Satellite", {starchart: 325, titanium: 2500, science: 100000, oil: 15000}, 1.08),
new SpaceAction("SpaceStation", {starchart: 425, alloy: 750, science: 150000, oil: 35000}, 1.12),
new SpaceAction("LunarOutpost", {starchart: 650, uranium: 500, alloy: 750, concrete: 150, science: 100000, oil: 55000}, 1.12),
new SpaceAction("PlanetCracker", {starchart: 2500, alloy: 1750, science: 125000, kerosene: 50}, 1.18),
new SpaceAction("HydraulicFracturer", {starchart: 750, alloy: 1025, science: 150000, kerosene: 100}, 1.18),
new SpaceAction("OrbitalArray", {starchart: 2000, eludium: 100, science: 250000, kerosene: 500}, 1.15),
new SpaceAction("Sunlifter", {science: 500000, eludium: 225, kerosene: 2500}, 1.15),
new SpaceAction("TerraformingStation", {antimatter: 25, uranium: 5000, kerosene: 5000}, 1.25),
new SpaceAction("Hydroponics", {kerosene: 500}, 1.15),
new UpgradeAction("MineralHoes", {science: 100, minerals: 275}),
new UpgradeAction("IronHoes", {science: 200, iron: 25}),
new UpgradeAction("MineralAxe", {science: 100, minerals: 500}),
new UpgradeAction("IronAxe", {science: 200, iron: 50}),
new UpgradeAction("SteelAxe", {science: 20000, steel: 75}),
new UpgradeAction("ReinforcedSaw", {science: 2500, iron: 1000}),
new UpgradeAction("SteelSaw", {science: 52000, steel: 750}),
new UpgradeAction("AlloySaw", {science: 85000, alloy: 75}),
new UpgradeAction("TitaniumSaw", {science: 75000, titanium: 500}),
new UpgradeAction("TitaniumAxe", {science: 38000, titanium: 10}),
new UpgradeAction("AlloyAxe", {science: 70000, alloy: 25}),
new UpgradeAction("PhotovoltaicCells", {titanium: 5000, science: 75000}),
new UpgradeAction("ThinFilmCells", {unobtainium: 200, uranium: 1000, science: 125000}),
new UpgradeAction("SolarSatellites", {alloy: 750, science: 225000}),
new UpgradeAction("IronWoodHuts", {science: 30000, wood: 15000, iron: 3000}),
new UpgradeAction("ConcreteHuts", {science: 125000, concrete: 45, titanium: 3000}),
new UpgradeAction("UnobtainiumHuts", {science: 200000, unobtainium: 350, titanium: 15000}),
new UpgradeAction("EludiumHuts", {eludium: 125, science: 275000}),
new UpgradeAction("CompositeBow", {science: 500, iron: 100, wood: 200}),
new UpgradeAction("Crossbow", {science: 12000, iron: 1500}),
new UpgradeAction("Railgun", {science: 150000, titanium: 5000, blueprint: 25}),
new UpgradeAction("Bolas", {science: 1000, minerals: 250, wood: 50}),
new UpgradeAction("HuntingArmor", {science: 2000, iron: 750}),
new UpgradeAction("SteelArmor", {science: 10000, steel: 50}),
new UpgradeAction("AlloyArmor", {science: 50000, alloy: 25}),
new UpgradeAction("Nanosuits", {science: 185000, alloy: 250}),
new UpgradeAction("Geodesy", {titanium: 250, starchart: 500, science: 90000}),
new UpgradeAction("MiningDrill", {titanium: 1750, steel: 750, science: 100000}),
new UpgradeAction("UnobtainiumDrill", {unobtainium: 250, alloy: 1250, science: 250000}),
new UpgradeAction("CoalFurnace", {minerals: 5000, iron: 2000, beam: 35, science: 5000}),
new UpgradeAction("DeepMining", {iron: 1200, beam: 50, science: 5000}),
new UpgradeAction("Pyrolysis", {compendium: 5, science: 35000}),
new UpgradeAction("ElectrolyticSmelting", {titanium: 2000, science: 100000}),
new UpgradeAction("Oxidation", {steel: 5000, science: 100000}),
new UpgradeAction("RotaryKiln", {titanium: 5000, gear: 500, science: 145000}),
new UpgradeAction("FluidizedReactors", {alloy: 200, science: 175000}),
new UpgradeAction("NuclearSmelters", {uranium: 250, science: 165000}),
new UpgradeAction("OrbitalGeodesy", {alloy: 1000, oil: 35000, science: 150000}),
new UpgradeAction("PrintingPress", {gear: 45, science: 7500}),
new UpgradeAction("OffsetPress", {gear: 250, oil: 15000, science: 100000}),
new UpgradeAction("Photolithography", {alloy: 1250, oil: 50000, uranium: 250, science: 250000}),
new UpgradeAction("Cryocomputing", {eludium: 15, science: 125000}),
new UpgradeAction("HighPressureEngine", {gear: 25, science: 20000, blueprint: 5}),
new UpgradeAction("FuelInjectors", {gear: 250, oil: 20000, science: 100000}),
new UpgradeAction("FactoryLogistics", {gear: 250, titanium: 2000, science: 100000}),
new UpgradeAction("SpaceManufacturing", {titanium: 125000, science: 250000}),
new UpgradeAction("HydroPlantTurbines", {unobtainium: 125, science: 250000}),
new UpgradeAction("AntimatterBases", {eludium: 15, antimatter: 250}),
//new UpgradeAction("AntimatterFission", {antimatter: 175, thorium: 7500, science: 525000}), // effect not calculated (speed up eludium crafting by 25%)
new UpgradeAction("AntimatterDrive", {antimatter: 125, science: 450000}), // effect not calculated (routeSpeed 25)
new UpgradeAction("Pumpjack", {titanium: 250, gear: 125, science: 100000}),
new UpgradeAction("BiofuelProcessing", {titanium: 1250, science: 150000}),
new UpgradeAction("UnicornSelection", {titanium: 1500, science: 175000}),
new UpgradeAction("GMCatnip", {titanium: 1500, catnip: 1000000, science: 175000}),
new UpgradeAction("CADsystem", {titanium: 750, science: 125000}),
new UpgradeAction("SETI", {titanium: 250, science: 125000}),
new UpgradeAction("Logistics", {gear: 100, scaffold: 1000, science: 100000}),
new UpgradeAction("Augmentations", {titanium: 5000, uranium: 50, science: 150000}),
new UpgradeAction("EnrichedUranium", {titanium: 7500, uranium: 150, science: 175000}),
new UpgradeAction("ColdFusion", {eludium: 25, science: 200000}),
new UpgradeAction("OilRefinery", {titanium: 1250, gear: 500, science: 125000}),
new UpgradeAction("HubbleSpaceTelescope", {alloy: 1250, oil: 50000, science: 250000}),
new UpgradeAction("AstroPhysicists", {unobtainium: 350, science: 250000}),
new UpgradeAction("MicroWarpReactors", {eludium: 50, science: 150000}),
new UpgradeAction("PlanetBuster", {eludium: 250, science: 275000}),
new UpgradeAction("OilDistillation", {titanium: 5000, science: 175000}),
new UpgradeAction("FactoryProcessing", {titanium: 7500, concrete: 125, science: 195000}),
// new UpgradeAction("Telecommunication", {titanium: 5000, uranium: 50, science: 150000}), // effect not calculated (increases learn ratio)
new UpgradeAction("RoboticAssistance", {steel: 10000, gear: 250, science: 100000}),
new ReligiousAction("SolarChant", {faith: 100}),
new ReligiousAction("SunAltar", {faith: 500, gold: 250}),
new ReligiousAction("StainedGlass", {faith: 500, gold: 250}),
new ReligiousAction("Basilica", {faith: 1250, gold: 750}), // effect on culture storage not calculated
new ReligiousAction("Templars", {faith: 3500, gold: 3000}),
new UpgradeAction("SolarRevolution", {faith: 750, gold: 500}),
new UpgradeAction("Transcendence", {faith: 7500, gold: 7500}),
new ZigguratBuilding("UnicornTomb", {ivory: 500, tear: 5}, 1.15),
new ZigguratBuilding("IvoryTower", {ivory: 25000, tear: 25}, 1.15),
new ZigguratBuilding("IvoryCitadel", {ivory: 50000, tear: 50}, 1.15), // effect on ivory meteors not calculated
new ZigguratBuilding("SkyPalace", {ivory: 125000, megalith: 5, tear: 500}, 1.15), // effect on ivory meteors not calculated
new ZigguratBuilding("UnicornUtopia", {ivory: 1000000, gold: 500, tear: 5000}, 1.15), // effect on ivory meteors not calculated
new ZigguratBuilding("SunSpire", {ivory: 750000, gold: 1250, tear: 25000}, 1.15), // effect on ivory meteors not calculated
new ZigguratBuilding("Marker", {/*spice: 50000,*/ tear: 5000, unobtainium: 2500, megalith: 750 }, 1.15),
// Markers, etc.
new ZigguratBuilding("BlackPyramid", {/*spice: 150000,*/ sorrow: 5, unobtainium: 5000, megalith: 2500}, 1.15),
...activationActions(),
new TradeshipAction(),
new PraiseAction(),
new FeedEldersAction(),
];
actions = actions.filter(a => a.available(state)).map(a => a.assess());
actions.sort((a,b) => a.roi - b.roi);
}
function storageActions(state: GameState, desiredScienceLimit?: number) {
return [
new BuildingAction("Barn", {wood: 50}, 1.75, state),
new BuildingAction("Warehouse", {beam: 1.5, slab: 2}, 1.15, state),
new BuildingAction("Harbor", {scaffold: 5, slab: 50, plate: 75}, 1.15, state),
new BuildingAction("OilWell", {steel: 50, gear: 25, scaffold: 25}, 1.15, state),
...scienceBuildings(state),
...(desiredScienceLimit ? [compendiaAction(state, desiredScienceLimit)] : []),
new SpaceAction("MoonBase", {starchart: 700, titanium: 9500, concrete: 250, science: 100000, unobtainium: 50, oil: 70000}, 1.12, state),
new SpaceAction("Cryostation", {eludium: 25, concrete: 1500, science: 200000, kerosene: 500}, 1.12, state),
new SpaceAction("ContainmentChamber", {science: 500000, kerosene: 2500}, 1.125, state),
// new SpaceAction("HeatSink", {science: 125000, thorium: 12500, relic: 1, kerosene: 5000}, 1.12, state), // needs thorium
new SpaceAction("Sunforge", {science: 100000, relic: 1, kerosene: 1250, antimatter: 250}, 1.12),
new UpgradeAction("ExpandedBarns", {science: 500, wood: 1000, minerals: 750, iron: 50}, state),
new UpgradeAction("ReinforcedBarns", {science: 800, beam: 25, slab: 10, iron: 100}, state),
new UpgradeAction("ReinforcedWarehouses", {science: 15000, plate: 50, steel: 50, scaffold: 25}, state),
new UpgradeAction("Silos", {science: 50000, steel: 125, blueprint: 5}, state),
new UpgradeAction("ExpandedCargo", {science: 55000, blueprint: 15}, state),
new UpgradeAction("ReactorVessel", {science: 135000, titanium: 5000, uranium: 125}, state),
new UpgradeAction("TitaniumBarns", {science: 60000, titanium: 25, steel: 200, scaffold: 250}, state),
new UpgradeAction("AlloyBarns", {science: 75000, alloy: 20, plate: 750}, state),
new UpgradeAction("ConcreteBarns", {science: 100000, concrete: 45, titanium: 2000}, state),
new UpgradeAction("TitaniumWarehouses", {science: 70000, titanium: 50, steel: 500, scaffold: 500}, state),
new UpgradeAction("AlloyWarehouses", {science: 90000, titanium: 750, alloy: 50}, state),
new UpgradeAction("ConcreteWarehouses", {science: 100000, titanium: 1250, concrete: 35}, state),
new UpgradeAction("StorageBunkers", {science: 25000, unobtainium: 500, concrete: 1250}, state),
new UpgradeAction("EnergyRifts", {science: 200000, titanium: 7500, uranium: 250}),
new UpgradeAction("StasisChambers", {alloy: 200, uranium: 2000, timecrystal: 1, science: 235000}),
new UpgradeAction("VoidEnergy", {alloy: 250, uranium: 2500, timecrystal: 2, science: 275000}),
new UpgradeAction("DarkEnergy", {eludium: 75, timecrystal: 3, science: 350000}),
new UpgradeAction("TachyonAccelerators", {eludium: 125, timecrystal: 10, science: 500000}),
new UpgradeAction("LHC", {science: 250000, unobtainium: 100, alloy: 150}, state),
new UpgradeAction("Refrigeration", {science: 125000, titanium: 2500, blueprint: 15}, state),
new UpgradeAction("ConcretePillars", {science: 100000, concrete: 50}, state),
new UpgradeAction("Uplink", {alloy: 1750, science: 75000}, state),
new UpgradeAction("Starlink", {alloy: 5000, oil: 25000, science: 175000}, state),
new UpgradeAction("Astrolabe", {titanium: 5, starchart: 75, science: 25000}, state),
new UpgradeAction("TitaniumReflectors", {titanium: 15, starchart: 20, science: 20000}, state),
new UpgradeAction("UnobtainiumReflectors", {unobtainium: 75, starchart: 750, science: 250000}, state),
new UpgradeAction("EludiumReflectors", {eludium: 15, science: 250000}, state),
new UpgradeAction("AntimatterReactors", {eludium: 35, antimatter: 750}, state),
new ReligiousAction("Scholasticism", {faith: 250}, state),
new ReligiousAction("GoldenSpire", {faith: 350, gold: 150}, state),
].filter(a => a.available(state));
}
function metaphysicActions() {
return [
new MetaphysicAction("Engineering", 5),
new MetaphysicAction("Diplomacy", 5),
new MetaphysicAction("GoldenRatio", 50),
new MetaphysicAction("DivineProportion", 100),
new MetaphysicAction("VitruvianFeline", 250),
new MetaphysicAction("Renaissance", 750),
new MetaphysicAction("CodexVox", 25),
new MetaphysicAction("Chronomancy", 25),
new MetaphysicAction("Astromancy", 50),
].filter(a => a.available(state)).map(a => a.assess());
}
class FurConsumptionReport extends CostBenefitAnalysis {
constructor(state: GameState) {
super();
const productionDelta = delta(production, {luxury: {fur: !state.luxury.fur}});
for (const r of resourceNames) {
if (productionDelta[r]) {
this.return.add(new Expediture(productionDelta[r] * (state.luxury.fur ? -1 : 1), r));
}
}
}
}
export function economyReport() {
updateEconomy();
updateSciences();
currentBasicProduction = basicProduction(state);
updateActions();
return {
production: production(state),
price,
conversions,
actions,
storageActions: storageActions(state).map(a => a.assess()),
sciences,
metaphysicActions: metaphysicActions(),
furReport: new FurConsumptionReport(state),
};
}<file_sep>/src/app/help.directive.ts
import { Directive, TemplateRef, Input, HostListener } from "@angular/core";
import { HelpService } from "./help.service";
@Directive({
selector: '[help]',
})
export class HelpDirective {
@Input()
help: TemplateRef<void>;
prevTopic: TemplateRef<void>;
constructor(private helpService: HelpService) {}
@HostListener("mouseenter")
enter() {
this.prevTopic = this.helpService.topic;
this.helpService.topic = this.help;
}
@HostListener("mouseleave")
leave() {
this.helpService.topic = this.prevTopic;
}
}<file_sep>/src/app/cost-benefit-analysis.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { CostBenefitAnalysis } from "./economy";
@Component({
selector: 'cost-benefit-analysis',
templateUrl: './cost-benefit-analysis.component.html',
})
export class CostBenefitAnalysisComponent implements OnInit {
@Input()
cba: CostBenefitAnalysis;
ngOnInit() {
}
}
<file_sep>/src/app/game-state-changer.ts
export type Update<T> = {[K in keyof T]?: Update<T[K]>}
/**
* Modifies state by patching in the new property values
* @returns a function to undo the change
*/
export function apply<S>(state: S, update: Update<S>) {
// while cloning would be safer than modifying the object in place,
// it turned out to be too slow (the state object is huge, and modified states are needed very often)
const memento = _apply(state, update);
return () => {
_apply(state, memento);
}
}
function _apply(s: Object, update: Object) {
const memento = {};
for (const k in update) {
if (update[k] instanceof Object) {
memento[k] = _apply(s[k], update[k]);
} else {
memento[k] = s[k];
s[k] = update[k];
}
}
return memento;
}<file_sep>/src/app/game-state.ts
import { apply, Update } from './game-state-changer';
// created on an ongoing basis
const basicResources = {
catnip: 0,
wood: 0,
minerals: 0,
coal: 0,
iron: 0,
titanium: 0,
uranium: 0,
unobtainium: 0,
gold: 0,
oil: 0,
catpower: 0,
science: 0,
culture: 0,
faith: 0,
unicorn: 0,
alicorn: 0,
necrocorn: 0,
antimatter: 0,
};
/* these resources are created on command and have unlimited storage */
const convertedResources = {
iron: 0,
titanium: 0,
starchart: 0,
uranium: 0,
unobtainium: 0,
eludium: 0,
fur: 0,
ivory: 0,
beam: 0,
slab: 0,
concrete: 0,
plate: 0,
steel: 0,
gear: 0,
alloy: 0,
scaffold: 0,
kerosene: 0,
parchment: 0,
manuscript: 0,
compendium: 0,
blueprint: 0,
megalith: 0,
tear: 0,
sorrow: 0,
timecrystal: 0,
relic: 0,
};
const initialGameState = {
workers: {
farmer: 0,
woodcutter: 0,
miner: 0,
hunter: 0,
scholar: 0,
priest: 0,
geologist: 0,
},
conversionProportion: {
...convertedResources
},
luxury: {
fur: false,
ivory: false,
unicorn: false,
alicorn: false,
},
faith: {
stored: 0,
previouslyStored: 0,
apocryphaPoints: 0,
transcendenceLevel: 0,
},
level: {
// normal buildings
CatnipField: 0,
Pasture: 0,
SolarFarm: 0,
Aqueduct: 0,
HydroPlant: 0,
Hut: 0,
LogHouse: 0,
Mansion: 0,
Library: 0,
DataCenter: 0,
Academy: 0,
Observatory: 0,
BioLab: 0,
Barn: 0,
Warehouse: 0,
Harbor: 0,
Mine: 0,
Quarry: 0,
LumberMill: 0,
OilWell: 0,
Accelerator: 0,
Steamworks: 0,
Magneto: 0,
Smelter: 0,
Calciner: 0,
Factory: 0,
Reactor: 0,
Amphitheatre: 0,
BroadcastTower: 0,
Chapel: 0,
Temple: 0,
Workshop: 0,
TradePost: 0,
Mint: 0,
UnicornPasture: 0,
Ziggurat: 0,
// unicorn buildings
UnicornTomb: 0,
IvoryTower: 0,
IvoryCitadel: 0,
SkyPalace: 0,
UnicornUtopia: 0,
SunSpire: 0,
Marker: 0,
BlackPyramid: 0,
// order of the sun
SolarChant: 0,
Scholasticism: 0,
GoldenSpire: 0,
SunAltar: 0,
StainedGlass: 0,
Basilica: 0,
Templars: 0,
// space buildings
SpaceElevator: 0,
Satellite: 0,
SpaceStation: 0,
LunarOutpost: 0,
MoonBase: 0,
PlanetCracker: 0,
HydraulicFracturer: 0,
SpiceRefinery: 0,
ResearchVessel: 0,
OrbitalArray: 0,
Sunlifter: 0,
ContainmentChamber: 0,
HeatSink: 0,
Sunforge: 0,
Cryostation: 0,
SpaceBeacon: 0,
TerraformingStation: 0,
Hydroponics: 0,
},
active: {
Calciner: true,
Steamworks: true,
},
upgrades: {
// same order as http://bloodrizer.ru/games/kittens/wiki/index.php?page=workshop
MineralHoes: false,
IronHoes: false,
MineralAxe: false,
IronAxe: false,
SteelAxe: false,
ReinforcedSaw: false,
SteelSaw: false,
TitaniumSaw: false,
AlloySaw: false,
TitaniumAxe: false,
AlloyAxe: false,
ExpandedBarns: false,
ReinforcedBarns: false,
ReinforcedWarehouses: false,
TitaniumBarns: false,
AlloyBarns: false,
ConcreteBarns: false,
TitaniumWarehouses: false,
AlloyWarehouses: false,
ConcreteWarehouses: false,
StorageBunkers: false,
EnergyRifts: false,
StasisChambers: false,
VoidEnergy: false,
DarkEnergy: false,
TachyonAccelerators: false,
LHC: false,
PhotovoltaicCells: false,
ThinFilmCells: false,
SolarSatellites: false,
ExpandedCargo: false,
ReactorVessel: false,
IronWoodHuts: false,
ConcreteHuts: false,
UnobtainiumHuts: false,
EludiumHuts: false,
Silos: false,
Refrigeration: false,
CompositeBow: false,
Crossbow: false,
Railgun: false,
Bolas: false,
HuntingArmor: false,
SteelArmor: false,
AlloyArmor: false,
Nanosuits: false,
Geodesy: false,
ConcretePillars: false,
MiningDrill: false,
UnobtainiumDrill: false,
CoalFurnace: false,
DeepMining: false,
Pyrolysis: false,
ElectrolyticSmelting: false,
Oxidation: false,
RotaryKiln: false,
FluidizedReactors: false,
NuclearSmelters: false,
OrbitalGeodesy: false,
PrintingPress: false,
OffsetPress: false,
Photolithography: false,
Uplink: false,
Starlink: false,
Cryocomputing: false,
HighPressureEngine: false,
FuelInjectors: false,
FactoryLogistics: false,
SpaceManufacturing: false,
Astrolabe: false,
TitaniumReflectors: false,
UnobtainiumReflectors: false,
EludiumReflectors: false,
HydroPlantTurbines: false,
AntimatterBases: false,
AntimatterFission: false,
AntimatterDrive: false,
AntimatterReactors: false,
Pumpjack: false,
BiofuelProcessing: false,
UnicornSelection: false,
GMCatnip: false,
CADsystem: false,
SETI: false,
Logistics: false,
Augmentations: false,
EnrichedUranium: false,
ColdFusion: false,
OilRefinery: false,
HubbleSpaceTelescope: false,
AstroPhysicists: false,
MicroWarpReactors: false,
PlanetBuster: false,
OilDistillation: false,
FactoryProcessing: false,
Telecommunication: false,
RoboticAssistance: false,
SolarRevolution: false,
Transcendence: false,
},
metaphysic: {
Engineering: false,
Diplomacy: false,
GoldenRatio: false,
DivineProportion: false,
VitruvianFeline: false,
Renaissance: false,
CodexVox: false,
Chronomancy: false,
Astromancy: false,
},
researched: {
Calendar: false,
Agriculture: false,
Archery: false,
AnimalHusbandry: false,
Mining: false,
MetalWorking: false,
Mathematics: false,
Construction: false,
CivilService: false,
Engineering: false,
Currency: false,
Writing: false,
Philosophy: false,
Steel: false,
Machinery: false,
Theology: false,
Astronomy: false,
Navigation: false,
Architecture: false,
Physics: false,
Metaphysics: false,
Chemistry: false,
Acoustics: false,
Geology: false,
DramaAndPoetry: false,
Electricity: false,
Biology: false,
Biochemistry: false,
Genetics: false,
Industrialization: false,
Mechanization: false,
Combustion: false,
Metallurgy: false,
Ecology: false,
Electronics: false,
Robotics: false,
ArtificialIntelligence: false,
QuantumCryptography: false,
Blackchain: false,
NuclearFission: false,
Rocketry: false,
OilProcessing: false,
Satellites: false,
OrbitalEngineering: false,
Thorium: false,
Exogeology: false,
AdvancedExogeology: false,
Nanotechnology: false,
Superconductors: false,
Antimatter: false,
Terraformation: false,
HydroPonics: false, // weird spelling to avoid name clash with building
Exophysics: false,
ParticlePhysics: false,
DimensionalPhysics: false,
Chronophysics: false,
TachyonTheory: false,
Cryptotheology: false,
VoidSpace: false,
ParadoxTheory: false,
// space missions
OrbitalLaunch: false,
MoonMission: false,
DuneMission: false,
PiscineMission: false,
HeliosMission: false,
TMinusMission: false,
KairoMission: false,
RorschachMission: false,
YarnMission: false,
UmbraMission: false,
CharonMission: false,
CentaurusMission: false,
FurthestRingMission: false,
},
priceMarkup: {
iron: 1,
coal: 1,
gold: 1,
oil: 1,
culture: 1,
faith: 1,
starchart: 1,
blueprint: 1,
uranium: 1,
unobtainium: 1,
unicorn: 1,
alicorn: 1,
necrocorn: 1,
antimatter: 1,
sorrow: 1,
timecrystal: 1,
},
showResearchedUpgrades: true,
compendia: 0,
ships: 0,
karma: 0,
paragon: 0,
leviathanEnergy: 0,
extraKittens: 0,
notes: "",
}
export type GameState = typeof initialGameState;
export type GameStateUpdate = Update<GameState>;
export const state = initialGameState;
const savedState: GameStateUpdate = localStorage.kittensGameState ? JSON.parse(localStorage.kittensGameState) : {};
apply(state, savedState);
window["state"] = state; // helpful for debugging
export function saveGameState() {
localStorage.kittensGameState = JSON.stringify(state);
}
export function replaceGameState(newState: GameStateUpdate) {
localStorage.kittensGameState = JSON.stringify(newState);
window.location.reload();
}
function keyNames<T>(o: T): Array<keyof T> {
const keys : Array<keyof T> = <any>[];
for (let k in o) {
keys.push(k);
}
return keys;
}
export type BasicRes = keyof typeof basicResources;
export const basicResourceNames = keyNames(basicResources);
export type ConvertedRes = keyof typeof convertedResources;
export const convertedResourceNames = keyNames(convertedResources);
export type UserPricedRes = keyof typeof state.priceMarkup;
export const userPricedResourceNames = keyNames(state.priceMarkup);
export type Res = BasicRes | ConvertedRes;
export const resourceNames = keyNames({...basicResources, ...convertedResources}); // duplicates are removed by the object spread operator
export type Job = keyof typeof state.workers;
export const jobNames = keyNames(state.workers);
export type Building = keyof typeof state.level;
export const buildingNames = keyNames(state.level);
export type ActivatableBuilding = keyof typeof state.active;
export const activatableBuildingNames = keyNames(state.active);
export type Upgrade = keyof typeof state.upgrades;
export type Metaphysic = keyof typeof state.metaphysic;
export type Science = keyof typeof state.researched;<file_sep>/src/app/panel.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'panel',
template: `
<h2 style="text-align: center">{{heading}}</h2>
<ng-content></ng-content>
`
})
export class PanelComponent {
@Input() heading: string;
}<file_sep>/src/app/app.component.ts
import { Component, OnInit, EventEmitter } from '@angular/core';
import { resourceNames, Res, state, saveGameState, jobNames, Job, ConvertedRes, userPricedResourceNames } from "./game-state";
import { economyReport, Action, CostBenefitAnalysis, Conversion, solarRevolutionProductionBonus, ScienceInfo, praiseBonus, setPraiseBonus, faithReset, transcend, reset } from "./economy";
import { CbaTooltipService } from './cba-tooltip.service';
import { HelpService } from './help.service';
import { debounceTime } from 'rxjs/operators';
import { apply } from './game-state-changer';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [
CbaTooltipService,
HelpService,
]
})
export class AppComponent implements OnInit {
showGame = false;
showHelp = false;
state = state;
resourceNames = resourceNames;
jobNames = jobNames;
workers = state.workers;
luxury = state.luxury;
level = state.level;
upgrades = state.upgrades;
price: {[R in Res]: number};
production: {[R in Res]: number};
actions: Action[];
storageActions: Action[];
sciences: ScienceInfo[];
metaphysicActions: Action[];
furReport: CostBenefitAnalysis;
conversions: {[R in ConvertedRes]?: Conversion};
updateRequest = new EventEmitter();
constructor(public cbaTooltip: CbaTooltipService, public helpService: HelpService) {
this.updateRequest.pipe(debounceTime(200)).subscribe(() => {
// since the Viewcontainer moves subviews by temporarily removing them, moved elements may lose keyboard focus
// we therefore delay the update until the user has (hopefullly) finished typing, and restore the focus manually afterwards
// (we realize this is hacky, but short of patching angular itself we didn't find a better solution)
const previouslyFocused = document.activeElement as HTMLElement;
this.update();
setTimeout(() => { // after the DOM update
previouslyFocused.focus();
})
})
}
ngOnInit() {
this.update();
}
saveGameState() {
saveGameState();
}
update() {
saveGameState();
const eco = economyReport();
this.price = eco.price;
this.production = eco.production;
this.actions = eco.actions;
this.storageActions = eco.storageActions;
this.sciences = eco.sciences;
this.metaphysicActions = eco.metaphysicActions;
this.furReport = eco.furReport;
this.conversions = {};
for (const conv of eco.conversions) {
this.conversions[conv.product] = conv;
}
}
reset() {
reset(state);
}
addWorker(job: Job, count: number) {
state.workers[job] += count;
state.workers.farmer -= count;
this.update();
return false; // suppress context menu
}
apply(action: Action | ScienceInfo, click: MouseEvent) {
let times = click.button == 0 ? 1 : -1;
if (click.ctrlKey) {
times *= 10;
}
apply(state, action.effect(times));
this.update();
return false; // suppress context menu
}
increasePrice(res: Res, count: number) {
if (userPricedResourceNames.includes(<any>res)) {
state.priceMarkup[res] *= Math.pow(1.15, count);
if (state.priceMarkup.faith > 1) {
alert("Using priests would be more efficient");
state.priceMarkup.faith = 1;
}
if (state.priceMarkup.coal > 1) {
alert("using geologists would be more efficient");
state.priceMarkup.coal = 1;
}
this.update();
return false;
}
}
toggleLuxury(res: "fur", event) {
state.luxury[res] = !state.luxury[res];
this.update();
event.stopPropagation();
return false;
}
get faithBonus() {
return solarRevolutionProductionBonus(state);
}
get praiseBonus() {
return Math.round(100 * praiseBonus(state));
}
set praiseBonus(praiseBonus: number) {
setPraiseBonus(praiseBonus / 100, state);
this.update(); // recalculate PraiseTheSun
}
faithReset(times: number) {
faithReset(state, times < 0);
this.update();
return false;
}
transcend(times: number) {
transcend(state, times);
this.update();
return false;
}
numeric(x: any) {
return typeof x === 'number';
}
sameName(index: number, action: Action) {
return action.name;
}
}
| bab5654adcb9662367048d3a505d08e8feb1011b | [
"Markdown",
"TypeScript"
] | 12 | TypeScript | meriton42/kitten-accountant | 49a0ef18f9e08a3fb5f70e0a403634d5afde82bf | 797f3803cac413af295aa59ab044cf8fed89d188 |
refs/heads/master | <file_sep>package fibonacci;
import javax.swing.*;
/**
* @title Fibonacci
* @author <NAME>
* @teacher <NAME>
* @date 23-Mar-2015 12:16:17 PM
* @purpose The purpose of this program is to calculate terms of the Fibonacci sequence
*/
public class Fibonacci {
public static void main(String[] args) {
int num;//get user input for the term that is wanted
num = Integer.parseInt(JOptionPane.showInputDialog("Which fibonacci term would you like to see"));
num = F(num);
System.out.println(num);
}
private static int F(int num) {
if ((num == 1) || (num == 2)) {//if it is the first 2 terms return 1
return 1;
} else {
return F(num - 1) + F(num - 2);//add the terms together until all terms are added
}
}
}
| f5bd798bfae69f5b52b2f1cc5a8cf64bf63f4dc8 | [
"Java"
] | 1 | Java | PoisonedMinds/Fibonacci | 21d3e93516114728eda3e5de008809825c107551 | 55eca02fe1e3fa5dc0aa42eafdf0cc550e22a898 |
refs/heads/master | <file_sep>import play.mvc.EssentialFilter;
import play.http.DefaultHttpFilters;
import play.filters.gzip.GzipFilter;
import javax.inject.Inject;
import javax.inject.Singleton;
import naranjalab.filters.*;
/**
* This class configures filters that run on every request. This
* class is queried by Play to get a list of filters.
*
* https://www.playframework.com/documentation/latest/ScalaCsrf
* https://www.playframework.com/documentation/latest/AllowedHostsFilter
* https://www.playframework.com/documentation/latest/SecurityHeaders
*/
@Singleton
public class Filters extends DefaultHttpFilters {
// @Inject
// public Filters(CSRFFilter csrfFilter,
// AllowedHostsFilter allowedHostsFilter,
// SecurityHeadersFilter securityHeadersFilter) {
// super(csrfFilter, allowedHostsFilter, securityHeadersFilter);
// }
@Inject
public Filters(GzipFilter gzip, LoggingFilter logging) {
super(gzip, logging);
}
}
<file_sep>package naranjalab.dao;
import java.util.List;
import naranjalab.evaluaciones.descriptors.UserDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author salcaino
*/
public class UsuariosDAO {
private static final Logger logger = LoggerFactory.getLogger(UsuariosDAO.class);
public static boolean usuarioDisponible(String username){
if(username == null || username.isEmpty()) return false;
String sql = "SELECT * FROM users WHERE username = '" + username + "' ";
DBQueryExecutor exec = DBAccessFactory.getExecutor();
return exec.hayResultados(sql);
}
public static String guardarUsuario(UserDescriptor user) {
if(user == null) return "Usuario invalido";
String sql = "INSERT INTO users(username, password, valid, associatedUser, nombre, apellidoPat, apellidoMat) VALUES (?, ?, ?, ?, ?, ?, ?)";
String valores[] = new String[7];
valores[0] = user.getUsername();
valores[1] = user.getPwd();
valores[2] = user.getValid();
valores[3] = user.getAssociatedUser();
valores[4] = user.getNombre();
valores[5] = user.getPaterno();
valores[6] = user.getMaterno();
DBQueryExecutor exec = DBAccessFactory.getExecutor();
return exec.ejecutarDBUpdate(sql, valores);
}
public static String cambiarPwd(String user, String pwd) {
if(usuarioDisponible(user)){
return "Usuario no existe";
}
String sql = "UPDATE users SET password = ? WHERE username=?";
String valores[] = new String[]{user, pwd};
DBQueryExecutor exec = DBAccessFactory.getExecutor();
return exec.ejecutarDBUpdate(sql, valores);
}
public static UserDescriptor getUserDescriptor(String username) {
String sql = "SELECT * FROM users WHERE username = '" + username + "'";
DBQueryExecutor exec = DBAccessFactory.getExecutor();
DBResultDescriptor queryresult = exec.ejecutarDBQuery(sql, "username", "password", "role", "associatedUser", "valid", "id");
if(queryresult.getError() != null){
logger.warn("Error al ejecutar query: {}", queryresult.getError());
return null;
}
List<Object[]> resultados = queryresult.getResultados();
if(resultados.isEmpty()){
logger.info("No se encontraron usuarios buscando por: {}", username);
}
Object[] registro = resultados.get(0);
UserDescriptor ret = new UserDescriptor();
ret.setUsername(registro[0].toString());
ret.setPwd(registro[1].toString());
ret.setRole(registro[2].toString());
ret.setAssociatedUser(registro[3].toString());
ret.setValid(registro[4].toString());
ret.setId(Integer.parseInt(registro[5].toString()));
return ret;
}
}
<file_sep>login.title=Ingreso Usuarios Evaluadores
main.title=Evaluaciones
login.remember=Recordarme
login.user.placeholder=Usuario o Email
login.pwd.placeholder=<PASSWORD>
login.pwd.forgot=<PASSWORD>?
login.pwd.reset=Click aqui para recuperarla
login.pwd.new.placeholder=<PASSWORD>
login.pwd.confirm.placeholder=<PASSWORD>
login.btn.login=Ingresar
login.btn.reset=Resetear<file_sep>package naranjalab.evaluaciones.tests;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestDescriptor {
protected Logger logger = LoggerFactory.getLogger("ProcesoTest");
protected String nombreTest;
protected String descripcionTest;
protected String errorMsg;
protected TestDescriptor(String nombre, String descripcion) {
this.nombreTest = nombre;
this.descripcionTest = descripcion;
}
public String getNombreTest() {
return nombreTest;
}
public void setNombreTest(String nombreTest) {
this.nombreTest = nombreTest;
}
public String getDescripcionTest() {
return descripcionTest;
}
public void setDescripcionTest(String descripcionTest) {
this.descripcionTest = descripcionTest;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
<file_sep>package naranjalab.dao;
public class DBAccessFactory {
private static DBQueryExecutor executor = new DBQueryExecutor();
public static DBQueryExecutor getExecutor(){
return executor;
}
}
<file_sep>package naranjalab.form;
import java.util.Arrays;
public class IngresoForm {
private String inputrut;
private String nombreinput;
private String paternoinput;
private String maternoinput;
private String nacimiento;
private String profesion;
private String inputemail;
private String inputtelefono;
private String inputdireccion;
private String inputcomuna;
private String checktest1;
private String ICRespuestas[];
public IngresoForm() {
ICRespuestas = new String[25];
}
public String getInputrut() {
return inputrut;
}
public void setInputrut(String inputrut) {
this.inputrut = inputrut;
}
public String getNombreinput() {
return nombreinput;
}
public void setNombreinput(String nombreinput) {
this.nombreinput = nombreinput;
}
public String getPaternoinput() {
return paternoinput;
}
public void setPaternoinput(String paternoinput) {
this.paternoinput = paternoinput;
}
public String getMaternoinput() {
return maternoinput;
}
public void setMaternoinput(String maternoinput) {
this.maternoinput = maternoinput;
}
public String getNacimiento() {
return nacimiento;
}
public void setNacimiento(String nacimiento) {
this.nacimiento = nacimiento;
}
public String getProfesion() {
return profesion;
}
public void setProfesion(String profesion) {
this.profesion = profesion;
}
public String getInputemail() {
return inputemail;
}
public void setInputemail(String inputemail) {
this.inputemail = inputemail;
}
public String getInputtelefono() {
return inputtelefono;
}
public void setInputtelefono(String inputtelefono) {
this.inputtelefono = inputtelefono;
}
public String getInputdireccion() {
return inputdireccion;
}
public void setInputdireccion(String inputdireccion) {
this.inputdireccion = inputdireccion;
}
public String getInputcomuna() {
return inputcomuna;
}
public void setInputcomuna(String inputcomuna) {
this.inputcomuna = inputcomuna;
}
public String getChecktest1() {
return checktest1;
}
public void setChecktest1(String checktest1) {
this.checktest1 = checktest1;
}
public String[] getICRespuestas() {
return ICRespuestas;
}
public void setICRespuestas(String[] iCRespuestas) {
ICRespuestas = iCRespuestas;
}
@Override
public String toString() {
return "IngresoForm [inputrut=" + inputrut + ", nombreinput=" + nombreinput + ", paternoinput=" + paternoinput
+ ", maternoinput=" + maternoinput + ", nacimiento=" + nacimiento + ", profesion=" + profesion
+ ", inputemail=" + inputemail + ", inputtelefono=" + inputtelefono + ", inputdireccion="
+ inputdireccion + ", inputcomuna=" + inputcomuna + ", checktest1=" + checktest1 + ", ICRespuestas="
+ (ICRespuestas == null ? "null" : getRespuestas());
}
private String getRespuestas() {
if(ICRespuestas == null || ICRespuestas.length == 0) return null;
String ret = "{";
for (int i = 0; i < ICRespuestas.length; i++) {
ret += i + "[" + ICRespuestas[i] + "]";
}
ret += "}";
return ret;
}
}
<file_sep>package controllers;
import play.mvc.*;
import views.html.*;
/**
* This controller contains an action to handle HTTP requests
* to the application's home page.
*/
public class BlankController extends Controller {
public Result mainContainer() {
return ok(blank.render());
}
}
<file_sep>package naranjalab.dao;
import naranjalab.evaluaciones.descriptors.SujetoDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author salcaino
*/
public class EvaluacionesDAO {
private static final Logger logger = LoggerFactory.getLogger(EvaluacionesDAO.class);
public String guardarSujetoEvaluacion(SujetoDescriptor sujeto){
if(sujeto == null) return "Sujeto invalido";
logger.info("Se va a guardar sujeto nombre {}", sujeto.getNombre());
String sql = "INSERT INTO users(username, password, valid, associatedUser, nombre, apellidoPat, apellidoMat) VALUES (?, ?, ?, ?, ?, ?, ?)";
String valores[] = new String[7];
valores[0] = sujeto.getRut();
valores[1] = sujeto.getNombre();
valores[2] = sujeto.getApellidoPaterno();
valores[3] = sujeto.getApellidoMaterno();
valores[4] = sujeto.getEmail();
valores[5] = sujeto.getDireccion();
valores[6] = sujeto.getFechaNcto();
valores[7] = sujeto.getProfesion();
valores[8] = sujeto.getTelefono();
// DBQueryExecutor exec = DBAccessFactory.getExecutor();
return null;
}
}
<file_sep>package naranjalab.common.util;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
public final class Utility {
private Utility() {
}
public static final String dateFormatString = "dd/MM/YYYY";
public static final Path currentLocation = Paths.get(System.getProperty("user.dir"));
public static final Path libLocation = currentLocation.resolve("lib");
public static final String fileSeparator = System.getProperty("file.separator");
public static final Path pathRespuestasIC = libLocation.resolve("respuestasic.txt");
public static final String sdfFormatMiliseconds = "yyyymmddssSSSS";
public static String generarId(){
SimpleDateFormat sdf = new SimpleDateFormat(sdfFormatMiliseconds);
return sdf.format(new Date());
}
public static Integer getHashCode(String... target){
if(target == null || target.length == 0) return null;
int finalhash = 0;
for (String string : target) {
int hash = 5;
hash = 83 * hash + Objects.hashCode(string);
finalhash += hash;
}
return finalhash;
}
}
<file_sep>@import naranjalab.form.IngresoForm
@import views.html.helper._
@(userform: Form[IngresoForm])
<div style="width:100%;border-style:solid;border-width:1px;border-color:blue;text-align:center;">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">1. Test de Instrucciones Complejas</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
@ic(userform)
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">2. Test de nose cuanto</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
<p>Bootstrap is a powerful front-end framework for faster and easier web development. It is a collection of CSS and HTML conventions. <a href="https://www.tutorialrepublic.com/twitter-bootstrap-tutorial/" target="_blank">Learn more.</a></p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">3. Otro test</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse">
<div class="panel-body">
<p>CSS stands for Cascading Style Sheet. CSS allows you to specify various style properties for a given HTML element such as colors, backgrounds, fonts etc. <a href="https://www.tutorialrepublic.com/css-tutorial/" target="_blank">Learn more.</a></p>
</div>
</div>
</div>
</div>
</div>
<file_sep>package naranjalab.evaluaciones;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import naranjalab.evaluaciones.tests.ICTest;
import naranjalab.evaluaciones.tests.TestDescriptor;
import naranjalab.common.util.Utility;
import naranjalab.evaluaciones.descriptors.ICTestResultDescriptor;
import naranjalab.evaluaciones.descriptors.ResultadoEvalDescriptor;
import naranjalab.evaluaciones.descriptors.SujetoDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author salcaino
*/
public class Evaluacion {
private static final Logger logger = LoggerFactory.getLogger(Evaluacion.class.getName());
private static final Map<String, Evaluacion> evaluacionesActuales = Collections.synchronizedMap(new HashMap<String, Evaluacion>());
private final String evaluacionId;
private SujetoDescriptor sujeto;
private List<TestDescriptor> evaluaciones;
private Date fechaTest;
private String error;
private String userCreador;
private ICTest icTest;
private Evaluacion(String user){
evaluacionId = Utility.generarId();
this.userCreador = user;
}
public String agregarICTest(String[] icRespuestas){
if(icRespuestas != null && icRespuestas.length > 0){
logger.info("Agregando ICTest a la evaluacion con {} respuestas", icRespuestas.length);
icTest = new ICTest();
icTest.setIcRespuestas(icRespuestas);
} else
return "Parametros invalidos para iniciar un IC test";
return null;
}
public static Evaluacion creaEvaluacion(String username){
Evaluacion ret = new Evaluacion(username);
String key = String.valueOf(Utility.getHashCode(username, ret.getEvaluacionId()));
logger.info("Agregando evaluacion para usuario {}, id {}, hash {}", username, ret.getEvaluacionId(), key);
evaluacionesActuales.put(key, ret);
return ret;
}
public static Evaluacion buscarEvaluacion(String username, String evId){
if(username == null || evId == null) return null;
Integer hashCode = Utility.getHashCode(username, evId);
logger.info("Buscando evaluacion id {} para usuario {} hash value {}", evId, username, hashCode);
Evaluacion got = evaluacionesActuales.get(hashCode.toString());
if(got == null){
logger.debug("No se encontro evaluacion de usuario {} con id {}", username, evId);
}
return got;
}
public ResultadoEvalDescriptor procesarEvaluacion(){
logger.info("Iniciando evaluacion");
if(sujeto == null){
return new ResultadoEvalDescriptor("Falta informacion del sujeto");
// logger.info("Se va a guardar la informacion del sujeto a evaluar");
// if(sujeto.getRut() == null || sujeto.getRut().isEmpty()){
//
// }
}
ResultadoEvalDescriptor ret = new ResultadoEvalDescriptor();
if(icTest != null){
logger.info("Se va a iniciar test IC");
icTest.runTest();
logger.debug("Se termino de procesar test IC, buenas {}, malas {}", icTest.getBuenas(), icTest.getMalas());
ICTestResultDescriptor icTestResult;
if(icTest.getErrorMsg() != null && !icTest.getErrorMsg().isEmpty()){
logger.warn("Test IC termino con errores, {}", icTest.getErrorMsg());
icTestResult = new ICTestResultDescriptor("Error al procesar IC test. " + icTest.getErrorMsg());
} else {
icTestResult = new ICTestResultDescriptor();
icTestResult.setBuenas(icTest.getBuenas());
icTestResult.setMalas(icTest.getMalas());
icTestResult.setRespuestas(icTest.getListaRespuestas());
}
ret.setIcTestResult(icTestResult);
}
return ret;
}
public SujetoDescriptor getSujeto() {
return sujeto;
}
public void setSujeto(SujetoDescriptor sujeto) {
this.sujeto = sujeto;
}
public List<TestDescriptor> getEvaluaciones() {
return evaluaciones;
}
public void setEvaluaciones(List<TestDescriptor> evaluaciones) {
this.evaluaciones = evaluaciones;
}
public Date getFechaTest() {
return fechaTest;
}
public void setFechaTest(Date fechaTest) {
this.fechaTest = fechaTest;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getEvaluacionId() {
return evaluacionId;
}
public String getUserCreador() {
return userCreador;
}
public void setUserCreador(String userCreador) {
this.userCreador = userCreador;
}
}
<file_sep>package naranjalab.common.util;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.apache.commons.validator.routines.EmailValidator;
import naranjalab.dao.DBAccessFactory;
import naranjalab.dao.DBQueryExecutor;
import naranjalab.dao.UsuariosDAO;
import naranjalab.evaluaciones.descriptors.UserDescriptor;
import naranjalab.evaluaciones.descriptors.UserDescriptorStatus;
import naranjalab.form.NewUserDescriptor;
public class UserUtilities {
private static final Integer periodoDias = Integer.parseInt(System.getProperty("valido.dias", "30"));
private static final Map<String, UserDescriptor> users = new HashMap<>();
public static String updateUser(String user, String pwd) {
if (user == null || user.isEmpty()) {
return "Usuario Invalido";
}
if (pwd == null || pwd.isEmpty()) {
return "Contraseña invalida";
}
DBQueryExecutor dbexecutor = DBAccessFactory.getExecutor();
if (dbexecutor == null) {
return "Invalid db executor";
}
EncryptionHelper helper = new EncryptionHelper();
try {
String encrypted = helper.encrypt(pwd);
pwd = encrypted;
} catch (GeneralSecurityException e) {
play.Logger.warn("Cant encrypt pwd", e);
}
return UsuariosDAO.cambiarPwd(user, pwd);
}
public static UserDescriptor userLogin(String username, String pwd, Logger logger) {
if (username == null || username.isEmpty()) {
return new UserDescriptor("Usuario Invalido");
}
if (pwd == null || pwd.isEmpty()) {
return new UserDescriptor("Clave invalida");
}
UserDescriptor user = UsuariosDAO.getUserDescriptor(username);
logger.info("Got result: {}", new Object[]{user});
if (user == null) {
return new UserDescriptor("Usuario Invalido");
}
EncryptionHelper helper = new EncryptionHelper();
String old = pwd;
try {
pwd = helper.encrypt(pwd);
} catch (GeneralSecurityException e) {
logger.info("Cant encrypt", e);
}
if ((user.getStatus() == UserDescriptorStatus.GOOD || user.getStatus() == UserDescriptorStatus.RESET_PASSWORD)
&& (user.getPwd().equals(pwd) || user.getPwd().equals(old))) {
return user;
} else {
return new UserDescriptor("Usuario Invalido");
}
}
public static String getUserRole(String username) {
if (username == null || username.isEmpty()) {
return null;
}
UserDescriptor userDescriptor = UsuariosDAO.getUserDescriptor(username);
if (userDescriptor != null) {
return userDescriptor.getRole();
}
return null;
}
public static String creaUser(NewUserDescriptor newuser, Logger logger) {
String email = newuser.getEmailinput();
EmailValidator validator = EmailValidator.getInstance();
if (email == null || email.isEmpty() || !validator.isValid(email)) {
return "Direccion de email invalida";
}
String nombre = newuser.getNombreinput();
if (nombre == null || nombre.isEmpty()) {
return "Nombre invalido";
}
String apellido = newuser.getPaternoinput();
if (apellido == null || apellido.isEmpty()) {
return "Apellido Paterno invalido";
}
String materno = newuser.getPaternoinput();
if (materno == null || materno.isEmpty()) {
return "Apellido Materno invalido";
}
String valido = newuser.getValidinput();
Date hasta = null;
SimpleDateFormat sdf = new SimpleDateFormat(Utility.dateFormatString);
if (valido != null && !valido.isEmpty()) {
try {
hasta = sdf.parse(valido);
} catch (ParseException e) {
}
}
if (hasta == null) {
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DAY_OF_YEAR, periodoDias);
hasta = instance.getTime();
}
if (!UsuariosDAO.usuarioDisponible(email)) {
return "Usuario ya existe";
}
UserDescriptor user = new UserDescriptor();
user.setUsername(email);
EncryptionHelper helper = new EncryptionHelper();
String pwd = null;
try {
pwd = helper.encrypt(pwd);
} catch (GeneralSecurityException e) {
logger.info("Cant encrypt", e);
pwd = "<PASSWORD>";
}
user.setPwd(pwd);
user.setNombre(nombre);
user.setPaterno(apellido);
user.setMaterno(materno);
user.setValid(sdf.format(hasta));
user.setAssociatedUser(newuser.getAssociatedUser());
return UsuariosDAO.guardarUsuario(user);
}
public static NewUserDescriptor getUser(Map<String, String> data) {
if (data == null || data.isEmpty()) {
return null;
}
NewUserDescriptor ret = new NewUserDescriptor();
for (Map.Entry<String, String> tmp : data.entrySet()) {
switch (tmp.getKey()) {
case "nombreinput":
ret.setNombreinput(tmp.getValue() != null && !tmp.getValue().isEmpty() ? tmp.getValue() : "");
break;
case "paternoinput":
ret.setPaternoinput(tmp.getValue() != null && !tmp.getValue().isEmpty() ? tmp.getValue() : "");
break;
case "maternoinput":
ret.setMaternoinput(tmp.getValue() != null && !tmp.getValue().isEmpty() ? tmp.getValue() : "");
break;
case "validinput":
ret.setValidinput(tmp.getValue() != null && !tmp.getValue().isEmpty() ? tmp.getValue() : "");
break;
case "emailinput":
ret.setEmailinput(tmp.getValue() != null && !tmp.getValue().isEmpty() ? tmp.getValue() : "");
break;
}
}
return ret;
}
}
<file_sep>package naranjalab.evaluaciones.descriptors;
/**
* @author salcaino
*/
public class ResultadoEvalDescriptor {
private String errorMsg;
private EvalStatus status = EvalStatus.NEW;
private ICTestResultDescriptor icTestResult;
public ResultadoEvalDescriptor(String errorMsg) {
this.errorMsg = errorMsg;
}
public ResultadoEvalDescriptor() {
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public EvalStatus getStatus() {
return status;
}
public void setStatus(EvalStatus status) {
this.status = status;
}
public ICTestResultDescriptor getIcTestResult() {
return icTestResult;
}
public void setIcTestResult(ICTestResultDescriptor icTestResult) {
this.icTestResult = icTestResult;
}
}
<file_sep>package naranjalab.evaluaciones.descriptors;
import java.util.List;
/**
* @author salcaino
*/
public class ICTestResultDescriptor {
private String error;
private int buenas, malas;
private List<RespuestaIC> respuestas;
private EvalStatus status;
public ICTestResultDescriptor() {
status = EvalStatus.NEW;
}
public ICTestResultDescriptor(String error) {
this.error = error;
status = EvalStatus.ERROR;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public int getBuenas() {
return buenas;
}
public void setBuenas(int buenas) {
this.buenas = buenas;
}
public int getMalas() {
return malas;
}
public void setMalas(int malas) {
this.malas = malas;
}
public List<RespuestaIC> getRespuestas() {
return respuestas;
}
public void setRespuestas(List<RespuestaIC> respuestas) {
this.respuestas = respuestas;
}
public EvalStatus getStatus() {
return status;
}
public void setStatus(EvalStatus status) {
this.status = status;
}
}
<file_sep>package naranjalab.evaluaciones.descriptors;
public enum OpcionRespuesta {
A,
B,
C,
D,
SIN_CONTESTAR;
}
<file_sep>package naranjalab.evaluaciones.tests;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import naranjalab.common.util.Utility;
import naranjalab.evaluaciones.descriptors.OpcionRespuesta;
import naranjalab.evaluaciones.descriptors.RespuestaIC;
public class ICTest extends TestDescriptor {
private List<RespuestaIC> listaRespuestas;
private static List<RespuestaIC> respuestasCorrectas;
private int buenas, malas;
private String[] icRespuestas;
public ICTest() {
super("IC Test", "Instrucciones Complejas");
loadRespuestasCorrectas();
}
private void loadRespuestasCorrectas() {
if (respuestasCorrectas != null) {
return;
}
respuestasCorrectas = new ArrayList<>(25);
try {
List<String> respuestas = FileUtils.readLines(Utility.pathRespuestasIC.toFile());
if (respuestas == null || respuestas.isEmpty()) {
logger.warn("No se pudo leer el archivo de respuestas correctas");
respuestasCorrectas = null;
return;
}
int i = 0;
for (String leido : respuestas) {
if (leido == null || leido.isEmpty()) {
logger.warn("No se puede reconocer esta linea, {}", leido);
} else {
leido = leido.substring(1, leido.length() - 1);
String[] partes = leido.split(",");
OpcionRespuesta[] respuesta = new OpcionRespuesta[3];
respuesta[0] = partes.length > 0 && partes[0].equals("x") ? OpcionRespuesta.A : OpcionRespuesta.SIN_CONTESTAR;
respuesta[1] = partes.length > 1 && partes[1].equals("x") ? OpcionRespuesta.A : OpcionRespuesta.SIN_CONTESTAR;
respuesta[2] = partes.length > 2 && partes[2].equals("x") ? OpcionRespuesta.A : OpcionRespuesta.SIN_CONTESTAR;
respuestasCorrectas.add(i, new RespuestaIC(i, respuesta));
}
i++;
}
logger.info("Termino de cargar respuestas correctas. Se cargaron {} respuestas", respuestasCorrectas.size());
logger.debug("Respuestas cargadas:{}", respuestasCorrectas);
} catch (IOException e) {
logger.warn("No se puede leer archivo en {}", Utility.pathRespuestasIC, e);
}
}
public String[] getIcRespuestas() {
return icRespuestas;
}
public void setIcRespuestas(String[] icRespuestas) {
this.icRespuestas = icRespuestas;
}
public void runTest() {
logger.info("Inicio test IC");
if (icRespuestas == null || icRespuestas.length == 0) {
errorMsg = "Respuestas invalidas";
return;
}
if (respuestasCorrectas == null || respuestasCorrectas.isEmpty()) {
errorMsg = "Respuestas Correctas no se pudieron cargar";
return;
}
RespuestaIC respuestaIC, correcta;
listaRespuestas = new ArrayList<>(icRespuestas.length);
for (int i = 0; i < icRespuestas.length; i++) {
respuestaIC = new RespuestaIC(i, icRespuestas[i], logger);
listaRespuestas.add(respuestaIC);
logger.debug(respuestaIC.toString());
correcta = respuestasCorrectas.get(i);
if (correcta.equals(respuestaIC)) {
logger.info("Respuesta correcta");
buenas++;
} else {
logger.warn("Respuesta equivocada, deberia ser {}", correcta);
malas++;
}
}
logger.info("Resultado es: {} correctas y {} malas", buenas, malas);
}
public List<RespuestaIC> getListaRespuestas() {
return listaRespuestas;
}
public void setListaRespuestas(List<RespuestaIC> listaRespuestas) {
this.listaRespuestas = listaRespuestas;
}
public static List<RespuestaIC> getRespuestasCorrectas() {
return respuestasCorrectas;
}
public static void setRespuestasCorrectas(List<RespuestaIC> respuestasCorrectas) {
ICTest.respuestasCorrectas = respuestasCorrectas;
}
public int getBuenas() {
return buenas;
}
public void setBuenas(int buenas) {
this.buenas = buenas;
}
public int getMalas() {
return malas;
}
public void setMalas(int malas) {
this.malas = malas;
}
}
<file_sep>package controllers;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import naranjalab.common.util.UserUtilities;
import naranjalab.common.util.HasherUtility;
import naranjalab.evaluaciones.descriptors.UserDescriptor;
import naranjalab.evaluaciones.descriptors.UserDescriptorStatus;
import naranjalab.form.UserForm;
import play.Configuration;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;
public class LoginController extends Controller {
private final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Inject
private FormFactory ff;
@Inject
private Configuration config;
public Result showLogin() {
Form<UserForm> form = ff.form(UserForm.class);
return ok(views.html.login.render("Ingreso", form, flash()));
}
private void resetSession() {
session().clear();
session("attempts", "1");
session("creation", Long.toString(new Date().getTime()));
}
public Result logout() {
resetSession();
Form<UserForm> form = ff.form(UserForm.class);
return ok(views.html.login.render("Ingreso", form, flash()));
}
public Result doPost() {
Form<UserForm> userForm = ff.form(UserForm.class).bindFromRequest();
if (userForm.hasErrors())
return loginError("Datos Incompletos");
UserForm userform = userForm.get();
String user = userform.getLogin();
String pwd = userform.getPassword();
logger.info("Username is: " + user);
logger.info("Password is: " + pwd);
logger.info("Remember me is: " + userform.getRememberMe());
if (user == null || user.isEmpty())
return loginError("Datos invalidos");
if (pwd == null || pwd.isEmpty())
return loginError("Datos invalidos");
String attempts = session("attempts");
int tries = -1;
if (attempts != null && !attempts.isEmpty()) {
try {
tries = Integer.parseInt(attempts);
if (tries >= 5) {
String creation = session("creation");
if (creation != null) {
long time = Long.parseLong(creation);
long timeNow = new Date().getTime();
long diff = timeNow - time;
long secs = diff / 1000l;
int minSeconds = 30;
if (config != null) {
String timedelay = config.getString("retry.delay", "30");
try {
minSeconds = Integer.parseInt(timedelay);
} catch (Exception e) {
minSeconds = 30;
}
} else {
logger.info("config is null");
}
if (minSeconds >= secs)
return loginError("Se ha superado la cantidad de intentos");
else {
logger.info("Se esperaron {} segundos. clearing cookie", secs);
resetSession();
}
} else
resetSession();
} else
logger.info("Attempts is {}", tries);
} catch (Exception e) {
logger.warn("got invalid attempt", e);
resetSession();
}
} else {
logger.info("Session attempts is null");
resetSession();
}
UserDescriptor result = UserUtilities.userLogin(user, pwd, logger);
if (result == null || (result.getStatus() != UserDescriptorStatus.GOOD && result.getStatus() != UserDescriptorStatus.RESET_PASSWORD)) {
tries++;
session("attempts", String.valueOf(tries));
session("creation", Long.toString(new Date().getTime()));
return loginError(result.getErrMsg());
}
if(result.getStatus() == UserDescriptorStatus.RESET_PASSWORD) {
if(willReset(userform)) {
return resetUser(userform);
}
flash("resetit", "true");
Form<UserForm> form = ff.form(UserForm.class);
UserForm newform = new UserForm();
newform.setLogin(result.getUsername());
Form<UserForm> filled = ff.form(UserForm.class).fill(newform);
return ok(views.html.login.render("Resetear contraseña", filled, flash()));
}
String id = Long.toString(System.currentTimeMillis());
id = HasherUtility.getHashedRandomVersion(id);
logger.info("id is: {}", id);
session("id", id);
String userRole = UserUtilities.getUserRole(user);
logger.info("User role is {}", userRole);
session("role", userRole);
session("auxIndx", String.valueOf(result.getId()));
session("user", user);
return redirect(controllers.routes.MainContainerController.mainContainer());
}
private boolean willReset(UserForm form) {
return form.getLogin() != null && !form.getLogin().isEmpty() &&
form.getNewpassword() != null && !form.getNewpassword().isEmpty() &&
form.getNewpasswordconfirmation() != null && !form.getNewpasswordconfirmation().isEmpty() &&
form.getNewpassword().equals(form.getNewpasswordconfirmation());
}
private Result resetUser(UserForm userform) {
return redirect(controllers.routes.MainContainerController.mainContainer());
}
private Result loginError(String msg) {
logger.info("Returning error msg: {}", msg);
flash("err", msg);
return ok(views.html.login.render("Ingreso", ff.form(UserForm.class), flash()));
}
}
| 5a4355191f8763356e237c1b977071eb752ccd8e | [
"JavaScript",
"Java",
"HTML"
] | 17 | Java | salcaino/evaluadores | bf2884861c908215560accd8bcda015b57150ab7 | cbf479027ba11d1de435d5ce2f9fa0f9d74cb757 |
refs/heads/master | <repo_name>rtsaunders19/Austin_Recycles<file_sep>/src/components/MainPage.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image
} from 'react-native';
class MainPage extends Component {
render() {
return (
<View>
<View style={styles.mainSection}>
<Text style={styles.mainHeader}>Recycleable?</Text>
<View style={styles.box} >
<Text style={styles[this.props.recycleable.toLowerCase()]}>{this.props.recycleable}</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 30, height: 40 }}>
<Text style={styles.description}>{this.props.description}</Text>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
mainSection: {
justifyContent: 'center',
alignItems: 'center',
height: 200
},
mainHeader: {
color: 'white',
fontSize: 16
},
box: {
flex: 1
},
description: {
color: 'white',
fontSize: 15,
width: 290,
height: 200
},
yes: {
color: '#8BC34A',
fontSize: 20
},
no: {
color: 'red',
fontSize: 20
}
});
export default MainPage;
<file_sep>/src/Recycle.js
import React, { Component } from 'react';
import { Actions } from 'react-native-router-flux';
import Button from 'react-native-button';
import {
StyleSheet,
Text,
View,
Slider,
Image,
Animated,
Easing
} from 'react-native';
import MainPage from './components/MainPage';
class Recycle extends Component {
constructor(props) {
super(props);
this.state = {
num: 1,
chemical: 'PET (Polyethylene Terephthalate)',
recycleable: 'YES',
description: 'PET is one of the most commonly used plastics in consumer products, and is found in most water and pop bottles, and some packaging. It is intended for single use applications; repeated use increases the risk of leaching and bacterial growth.',
color: 'green',
spinValue: new Animated.Value(0)
};
}
onSlide(value) {
switch (value) {
case 1:
this.setState({
num: 1,
chemical: 'PET (Polyethylene Terephthalate)',
recycleable: 'YES',
description: 'PET is one of the most commonly used plastics in consumer products, and is found in most water and pop bottles, and some packaging. It is intended for single use applications; repeated use increases the risk of leaching and bacterial growth.'
});
break;
case 2:
this.setState({
num: 2,
chemical: 'HDPE (High-Density Polyethylene)',
recycleable: 'YES',
description: 'HDPE is a stiff plastic used to make picnic tables, plastic lumber, waste bins, park benches, bed liners for trucks and other products which require durability and weather-resistance. Products made of HDPE are reusable and recyclable.'
});
break;
case 3:
this.setState({
num: 3,
chemical: 'PVC (Polyvinyl Chloride)',
recycleable: 'NO',
description: 'PVC is dubbed the “poison plastic” because it contains numerous toxins which it can leach throughout its entire life cycle. Because PVC is relatively impervious to sunlight and weather, it is used to make window frames, and garden hoses.',
});
break;
case 4:
this.setState({
num: 4,
chemical: 'LDPE (Low-Density Polyethylene)',
recycleable: 'YES',
description: 'It is not commonly recycled, however, this is changing in many communities today as more recycling programs gear up to handle this material like the city of Austin. When recycled, LDPE plastic is used for plastic lumber, garbage can liners and floor tiles.'
});
break;
case 5:
this.setState({
num: 5,
chemical: 'PP (Polypropylene)',
recycleable: 'YES',
description: 'Polypropylene is recyclable through some curbside recycling programs, but only about 3% of PP products are currently being recycled in the US. Recycled PP is used to make landscaping border stripping, battery cases, brooms, bins and trays. However, #5 plastic is today becoming more accepted by recyclers.'
});
break;
case 6:
this.setState({
num: 6,
chemical: 'PS (Polystyrene)',
recycleable: 'NO',
description: 'Polystyrene is an inexpensive, lightweight and easily-formed plastic with a wide variety of uses. It is most often used to make disposable styrofoam drinking cups, take-out “clamshell” food containers, egg cartons, plastic picnic cutlery, foam packaging and those ubiquitous “peanut” foam chips in packages.'
});
break;
case 7:
this.setState({
num: 7,
chemical: 'Other (BPA, Polycarbonate and LEXAN)',
recycleable: 'NO',
description: '#7 plastics are not for reuse, unless they have the PLA compostable coding. When possible it is best to avoid #7 plastics, especially for children’s food. Plastics with the recycling labels #1, #2 and #4 on the bottom are safer choices and do not contain BPA.'
});
}
}
handlePress() {
if (this.state.num === 1 || this.state.num === 2 || this.state.num === 4 || this.state.num === 5) {
Animated.timing(
this.state.spinValue, {
toValue: 1,
duration: 500,
easing: Easing.linear
}).start();
}
}
render() {
const spin = this.state.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
});
return (
<View style={{ flex: 1, backgroundColor: '#00A5CF' }}>
<View style={[styles.headerStyle, styles[this.state.num]]}>
<Text style={styles.headerText}>Can I Recycle This?</Text>
</View>
<View style={styles.logoArea}>
<Text style={styles.name}>{this.state.chemical}</Text>
<Animated.Image
style={{ height: 100,
width: 100,
justifyContent: 'center',
alignItems: 'center',
marginTop: 20,
transform: [{ rotate: spin }] }} source={{ uri: 'https://openclipart.org/image/2400px/svg_to_png/196353/recycle-plastic.png' }}
>
<Text style={styles.number}>{this.state.num}</Text>
</Animated.Image>
</View>
<MainPage
recycleable={this.state.recycleable}
description={this.state.description}
/>
<View style={styles.slider}>
<Slider
minimumTrackTintColor={'white'}
style={styles.slider}
value={this.props.num}
minimumValue={1}
maximumValue={7}
step={1}
onValueChange={newValue => this.onSlide(newValue)}
/>
</View>
<View style={styles.buttonArea}>
<Button
style={{ }}
styleDisabled={{ color: 'red' }}
onPress={this.handlePress.bind(this)}
>
<Image style={styles.buttonImage} source={{ uri: 'https://www.shareicon.net/download/2016/07/12/794699_recycle-bin_512x512.png' }} />
</Button>
</View>
<View style={styles.nextPage}>
<Text style={styles.achievements} onPress={() => Actions.achievements()}>ACHIEVEMENTS</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
headerStyle: {
alignItems: 'center',
justifyContent: 'center',
height: 60,
paddingTop: 25,
backgroundColor: '#8BC34A',
color: 'white'
},
headerText: {
fontSize: 20,
color: 'white'
},
logoArea: {
justifyContent: 'center',
alignItems: 'center',
paddingTop: 35
},
name: {
fontSize: 18,
color: 'white'
},
number: {
fontSize: 20,
color: 'black',
},
image: {
height: 100,
width: 100,
justifyContent: 'center',
alignItems: 'center',
marginTop: 20
},
slider: {
justifyContent: 'center',
marginTop: 18
},
button: {
height: 30
},
nextPage: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
buttonArea: {
justifyContent: 'center',
alignItems: 'center',
flex: 1
},
buttonImage: {
height: 50,
width: 50,
justifyContent: 'center',
alignItems: 'center'
},
achievements: {
fontSize: 20,
color: 'gold'
},
3: {
backgroundColor: 'red'
},
6: {
backgroundColor: 'red'
},
7: {
backgroundColor: 'red'
}
});
export default Recycle;
<file_sep>/src/components/Achievements.js
import React, { Component } from 'react';
import { Actions } from 'react-native-router-flux';
import { View, Text, StyleSheet, Image } from 'react-native';
class Achievements extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<View style={styles.headerStyle}>
<Text style={styles.headerText}>Achievements</Text>
</View>
<View style={{ marginTop: 35, flex: 1 }}>
<View style={styles.unlock}>
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
</View>
<View style={styles.unlock}>
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
</View>
<View style={styles.unlock}>
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
<Image style={styles.image} source={{ uri: 'https://www.iconexperience.com/_img/g_collection_png/standard/256x256/lock.png' }} />
</View>
</View>
<View style={styles.textStyle}>
<Text onPress={() => Actions.recycle()}>Back</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
textStyle: {
alignItems: 'center'
},
headerStyle: {
alignItems: 'center',
justifyContent: 'center',
height: 60,
paddingTop: 25,
backgroundColor: '#8BC34A',
color: 'white'
},
headerText: {
fontSize: 20,
color: 'white'
},
unlock: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
marginTop: 7
},
image: {
height: 100,
width: 100,
}
});
export default Achievements;
<file_sep>/README.md
#Description
React Native app that helps you know what the recycling resin numbers mean and whether or not you can recycle them. For certain numbers it depends on the city you live in, so for this app the numbers are relevant to Austin. It also keeps track of what you've recycled, unlocking items that your recycled items will be used to make
#Challenges
- UX (thank you Ronak)
- Learning React Native again
- Communicating data between two different scenes
- Passing data up through props (able to do it in ReactJS but not React Native)
#Tech used
- React Native
- Flex Box
- React-Native-router-flux
#Tech I want to used
- firebase
- Redux
#Interesting Facts
Nineteen PET bottles produce enough fiber for one XL T-shirt.
Twenty five PET bottles produce enough for one sweater.
1050 milk jugs can produce enough fiberfill for a sleeping bag.
Nineteen bottles make enough fiber to make one square foot of carpet.
Fourteen bottles yield enough fiberfill for a ski jacket.
| 733533c8d0b57b40e0b19edae03cf2769fcebe5c | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | rtsaunders19/Austin_Recycles | ec0e334cec9afc91451d75d457dc3c01ed341b48 | 75870fe43d8c4dc92ee934c112fa5cf428d721ca |
refs/heads/master | <repo_name>vgorin/hello_cgo<file_sep>/hello/hello.go
package hello
// #include "hello.h"
import "C"
func Random() int {
return int(C.rnd())
}
<file_sep>/README.md
hello_cgo
=========
The simplest cgo demo, describes and hopefully solves my old problem "Weird things happening while compiling a Go program with C code (go build, Eclipse, Mac OS X)"
-------------------------
https://groups.google.com/forum/#!searchin/Golang-Nuts/vgorin/golang-nuts/IxPSrh1X7QE/JnWfb8vMX5MJ
Original problem post(s):
=========================
Hello, guys,
I'm compiling a simple Go program which just executes some C code from the *.c files.
All program files are located in the same directory, these are five *.c files, five *.h files (headers are used in *.c files) and one *.go file with package main and function main declared in it.
I'm compiling the app on OS X 10.8.4.
When I compile with Eclipse I do not have any problems - the program builds and runs perfectly.
Now I'm trying to build with "go build" and receive a weird error. The error says that there are "69 duplicate symbols for architecture x86_64". The files which have errors are _obj/*.cgo2.o and _obj/*.o - I think it means that this is a linker error.
The thing I do not understand is how then Eclipse compiles the code with no errors? Does it use mechanism other then go build? It definitely uses the same gcc, as there is no gcc path specified in Eclipse itself so it can use just the one which in the $PATH.
Please post your ideas why such a thing can happen.
Thank you
-------------------------
To simplify everything I've created a more simple app with only two files: hello.go and hello.c:
hello.c:
--------
<pre>
#include <stdlib.h>
int rnd() {
return random();
}
</pre>
hello.go:
---------
<pre>
package main
// #include "hello.c"
import "C"
import "fmt"
func Random() int {
return int(C.rnd())
}
func main() {
fmt.Println(Random());
}
</pre>
The symptoms of compiling these are exactly the same. It compiles in eclipse, but not with go build:
<pre>
KIEV-AIR:src vgorin$ go build
# _/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src
duplicate symbol _rnd in:
$WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.cgo2.o
$WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.o
ld: 1 duplicate symbol for architecture x86_64
collect2: ld returned 1 exit status
</pre>
Output of go build -x:
<pre>
KIEV-AIR:src vgorin$ go build -x
WORK=/<KEY>go-build388081714
mkdir -p $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/
cd /Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src
/usr/local/go/pkg/tool/darwin_amd64/cgo -objdir $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ -- -I $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ hello.go
/usr/local/go/pkg/tool/darwin_amd64/6c -F -V -w -I $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ -I /usr/local/go/pkg/darwin_amd64 -o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_defun.6 -D GOOS_darwin -D GOARCH_amd64 $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_defun.c
gcc -I . -g -O2 -fPIC -m64 -pthread -fno-common -print-libgcc-file-name
gcc -I . -g -O2 -fPIC -m64 -pthread -fno-common -I $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ -o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_main.o -c $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_main.c
gcc -I . -g -O2 -fPIC -m64 -pthread -fno-common -I $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ -o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_export.o -c $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_export.c
gcc -I . -g -O2 -fPIC -m64 -pthread -fno-common -I $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ -o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.cgo2.o -c $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.cgo2.c
gcc -I . -g -O2 -fPIC -m64 -pthread -fno-common -I $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/ -o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.o -c ./hello.c
gcc -I . -g -O2 -fPIC -m64 -pthread -fno-common -o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_.o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_main.o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/_cgo_export.o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.cgo2.o $WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.o
# _/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src
duplicate symbol _rnd in:
$WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.cgo2.o
$WORK/_/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src/_obj/hello.o
ld: 1 duplicate symbol for architecture x86_64
collect2: ld returned 1 exit status
</pre>
Environment variables are set:
<pre>
KIEV-AIR:src vgorin$ echo $GOROOT
/usr/local/go
KIEV-AIR:src vgorin$ echo $GOPATH
/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/
KIEV-AIR:src vgorin$ echo $GOBIN
/usr/local/go/bin
KIEV-AIR:src vgorin$ echo $GOOS
darwin
KIEV-AIR:src vgorin$ echo $GOARCH
amd64
KIEV-AIR:src vgorin$ pwd
/Users/vgorin/DEVELOP/eclipse_workspace/hello_world_c/src
</pre>
My considerations as for 23/10/2013
===================================
'go build' tries to compile every file it finds (both *.go and *.c types) and then it links everything together.
'go build gofile.go' tries to compile only gofile.go and its dependencies.
Thus, for the first command to work including *.c files into go code with // #include won't work, need to include header files *.h only, corresponding *.c files will be compiled separetelly and then linked;
including *.c files will cause an error because these files will be compiled twice and there will be a conflict during linking;
for the second command to work we need to include *.c files or provide already compiled libraries if we want to include header files *.h
This project shows the approach which works, but perhaps its not ideal – probably there is a better solution with ompiler and linker flags – this should be investigated.
<file_sep>/hello/hello.c
#include <stdlib.h>
int rnd() {
return random();
}
<file_sep>/main.go
package main
import "fmt"
import "hello"
func main() {
fmt.Println(hello.Random());
}
<file_sep>/hello/hello.h
int rnd(); | bb82cf286d936bc4bfe3327e2f62b0f709194cdd | [
"Markdown",
"C",
"Go"
] | 5 | Go | vgorin/hello_cgo | ab4889297a79b2c6334c79021e4ebaa7f9156a3e | 3f4cdda72a4998977175f3332d535a2f84405ea9 |
refs/heads/master | <file_sep># Journal-Doc-Trigger
Google Doc App Script to create a daily diary.
<file_sep>
function scheduleTrigger() {
var builder = ScriptApp.newTrigger("createAndSendDocument").forDocument('1DIa59PP8e6yG-0MWJLTmVv1KjEc2rlvUk_AYJZP-Ba8').onOpen();
builder.create();
}
/*function BuildUI() {
//create the application itself
var app = UiApp.createApplication();
app.setTitle("Journal Trigger");
//create panels and add them to the UI
var panel = app.createVerticalPanel();
//create a submit button
var button = app.createButton('Click');
//add the button to the panel
panel.add(button);
var handler = app.createServerHandler("createAndSendDocument");
button.addClickHandler(handler);
handler.addCallbackElement(panel);
//add the panel to the application
app.add(panel);
var doc = DocumentApp.getActive();
doc.show(app);
}
*/
function createAndSendDocument() {
// Create a new Google Doc with the name structured based upon date.
var date = Utilities.formatDate(new Date(), "GMT-5", "yyyyMMdd");
var doc = DocumentApp.create(date + " Personal Log");
// Access the body of the document, then add paragraphs.
doc.getBody().appendParagraph(date + " Personal Log");
doc.getBody().appendParagraph('This is the journal of <NAME> Jr.');
doc.getBody().appendParagraph('');
// Get Weather and Parse it.
var url = 'http://api.wunderground.com/api/58b235c28b602b1e/conditions/q/pws:KMENOBLE2.json';
var response = UrlFetchApp.fetch(url);
var contentText = response.getContentText();
var conditions = JSON.parse(contentText);
var temp_f = conditions.current_observation.temp_f;
var wind_string = conditions.current_observation.wind_string;
var weather = conditions.current_observation.weather;
var observation_time = conditions.current_observation.observation_time;
var station_id = conditions.current_observation.station_id;
var history_url = conditions.current_observation.history_url;
var url = 'http://api.wunderground.com/api/58b235c28b602b1e/forecast/q/pws:KMENOBLE2.json';
//Inserting the Weather into the document.
doc.getBody().appendParagraph('Current Weather: ');
doc.getBody().appendParagraph(weather + ', ' + temp_f + 'ºF, ' + 'Wind: ' + wind_string);
doc.getBody().appendParagraph(observation_time);
doc.getBody().appendParagraph('Station ID: ' + station_id);
doc.getBody().appendParagraph(history_url);
// Some formating in the document.
doc.getBody().appendParagraph('');
doc.getBody().appendHorizontalRule();
doc.getBody().appendParagraph('');
// Inserting ISO time into the document.
var time = Utilities.formatDate(new Date(), 'GMT-5', 'yyyy-MM-dd\'T\'HH:mm:ss\'-5\'');
doc.getBody().appendParagraph('Time: ' + time);
doc.getBody().appendParagraph('');
// Some formating in the document.
doc.getBody().appendHorizontalRule();
doc.getBody().appendParagraph('');
// Get the URL of the document.
var url = doc.getUrl();
// Get the email address of the active user - that's you.
var email = Session.getActiveUser().getEmail();
// Get the name of the document to use as an email subject line.
var subject = doc.getName();
// Append a new string to the "url" variable to use as an email body.
var body = 'Link to your doc: ' + url;
// Send yourself an email with a link to the document.
GmailApp.sendEmail(email, subject, body);
}
| de3f68b4187d388a1585362e009ee7756f936f90 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mjohnson16/Journal-Doc-Trigger | 9518fef9027718341385ed3771cc86f543ffcd3d | c4b0a3f12ad683e20a86149b305012b9fbc080b8 |
refs/heads/master | <file_sep>import { Injectable } from '@nestjs/common';
import { ConcertRepository } from './concerts.repository';
import { GetConcertDto } from './dto/get-concert.dto';
import {
GetConcertsQueryParamsByBandIds,
GetConcertsQueryParamsByBandIdsAndLocation,
GetConcertsQueryParamsByLocation,
} from './dto/get-concerts-query-params.dto';
@Injectable()
export class ConcertsService {
constructor(private readonly concertsRepository: ConcertRepository) {}
getConcertsByBandIds(
concertsQueryByBandIds: GetConcertsQueryParamsByBandIds,
) {
return this.concertsRepository.getConcertsByBandIds(concertsQueryByBandIds);
}
getConcertsByLocationAndByRadius(
concertsQueryByLocation: GetConcertsQueryParamsByLocation,
): Promise<GetConcertDto[]> {
return this.concertsRepository.getConcertsByLocationAndByRadius(
concertsQueryByLocation,
);
}
getConcertsByBandIdsAndByLocationAndByRadius(
concertsQueryByBandIdsAndLocation: GetConcertsQueryParamsByBandIdsAndLocation,
): Promise<GetConcertDto[]> {
return this.concertsRepository.getConcertsByBandIdsAndByLocationAndByRadius(
concertsQueryByBandIdsAndLocation,
);
}
}
<file_sep>import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { Band } from './Band';
import { Venue } from './Venue';
@Index('concert_pkey', ['bandId', 'venueId', 'date'], { unique: true })
@Entity('concert', { schema: 'public' })
export class Concert {
@Column('integer', { primary: true, name: 'band_id' })
bandId: number;
@Column('integer', { primary: true, name: 'venue_id' })
venueId: number;
@Column('bigint', { primary: true, name: 'date' })
date: string;
@ManyToOne(() => Band, band => band.concerts)
@JoinColumn([{ name: 'band_id', referencedColumnName: 'id' }])
band!: Band;
@ManyToOne(() => Venue, venue => venue.concerts)
@JoinColumn([{ name: 'venue_id', referencedColumnName: 'id' }])
venue!: Venue;
}
<file_sep>import {
Column,
Entity,
Index,
OneToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { Concert } from "./Concert";
@Index("venue_pkey", ["id"], { unique: true })
@Entity("venue", { schema: "public" })
export class Venue {
@PrimaryGeneratedColumn({ type: "integer", name: "id" })
id: number;
@Column("text", { name: "name" })
name: string;
@Column("float", { name: "latitude" })
latitude: number;
@Column("float", { name: "longitude" })
longitude: number;
@OneToMany(() => Concert, concert => concert.venue)
concerts: Concert[];
}
<file_sep>// Add global setup here<file_sep>import {
Controller,
Get,
Injectable,
InternalServerErrorException,
Query,
} from '@nestjs/common';
import { PinoLogger } from 'nestjs-pino';
import { ParseConcertsQueryParamsPipe } from '../utils/parse-concerts-query-params.pipe';
import { ConcertsService } from './concerts.service';
import { GetConcertDto } from './dto/get-concert.dto';
import { GetConcertsQueryParamsDto } from './dto/get-concerts-query-params.dto';
@Injectable()
@Controller('/api/concerts')
export class ConcertsController {
constructor(
private readonly logger: PinoLogger,
private readonly concertsService: ConcertsService,
) {
this.logger.setContext('ConcertsController');
}
/**
*
* @param params - Query params used to query concerts, containing at leat location info or list of band ids
* @throws BadRequestException|InternalServerErrorException
*/
@Get()
async getConcertsAroundLocation(
@Query(new ParseConcertsQueryParamsPipe())
params: GetConcertsQueryParamsDto,
): Promise<GetConcertDto[]> {
let result;
try {
switch (params.type) {
case 'by_bands':
result = await this.concertsService.getConcertsByBandIds(params);
break;
case 'by_location':
result = await this.concertsService.getConcertsByLocationAndByRadius(
params,
);
break;
case 'by_bands_and_location':
result = await this.concertsService.getConcertsByBandIdsAndByLocationAndByRadius(
params,
);
break;
}
} catch (error) {
this.logger.error('getConcertsAroundLocation() %o', error);
throw new InternalServerErrorException();
}
return result;
}
}
<file_sep>import { getRepository, MigrationInterface } from 'typeorm';
import * as bands from '../data/bands.json';
import * as concerts from '../data/concerts.json';
import * as venues from '../data/venues.json';
export class BandInit1589223049595 implements MigrationInterface {
public async up(): Promise<void> {
// importing data to band table
await getRepository('band').save(bands);
// importing data to venue table
await getRepository('venue').save(venues);
// importing data to concert table
for (let i = 1; i <= 20; i++) {
const concertsToBeSaved = concerts
.slice((i - 1) * 1000, i * 1000)
.map((c) => ({
bandId: c.bandId,
venueId: c.venueId,
date: c.date,
}));
await getRepository('concert').save(concertsToBeSaved);
}
const remainingConcertsToBeSaved = concerts
.slice(20000, 20627)
.map((c) => ({
bandId: c.bandId,
venueId: c.venueId,
date: c.date,
}));
await getRepository('concert').save(remainingConcertsToBeSaved);
}
public async down(): Promise<void> {
// Truncate all tables
await getRepository('concert').delete({});
await getRepository('band').delete({});
await getRepository('venue').delete({});
// Reset sequences
await getRepository('band').query("SELECT setval('band_id_seq', 1, false);");
await getRepository('band').query("SELECT setval('venue_id_seq', 1, false);");
}
}
<file_sep>import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ConcertsService } from '../../src/concerts/concerts.service';
import { Concert } from '../../src/entities/Concert';
describe('ConcertsService', () => {
let concertsService: ConcertsService;
const concertsRepository = {
getConcertsByBandIds: jest.fn(),
getConcertsByLocationAndByRadius: jest.fn(),
getConcertsByBandIdsAndByLocationAndByRadius: jest.fn(),
};
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
ConcertsService,
{
provide: getRepositoryToken(Concert),
useValue: concertsRepository,
},
],
}).compile();
concertsService = moduleRef.get<ConcertsService>(ConcertsService);
});
it('[getConcertsByBandIds] should return concerts filtered by band ids from db ordered by up coming concerts first', async () => {
const filteredConcerts = [
{
date: 1571808436512,
band: '3OH!3',
location: 'Rivoli, Toronto, ON, Canada',
latitude: 43.64944970000001,
longitude: -79.3949696,
},
{
date: 1559108692447,
band: 'Arkells',
location: 'The Garrison, Toronto, ON, Canada',
latitude: 43.6492659,
longitude: -79.42233209999999,
},
{
date: 1550266041260,
band: '4 Non Blondes',
location: 'Sony Centre for the Performing Arts, Toronto, ON, Canada',
latitude: 43.6466723,
longitude: -79.3760205,
},
{
date: 1424652665767,
band: '3OH!3',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
{
date: 1359976491899,
band: '4 Non Blondes',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
];
concertsRepository.getConcertsByBandIds.mockResolvedValue(filteredConcerts);
expect(
await concertsService.getConcertsByBandIds({ bandIds: [1, 2, 3] }),
).toEqual(filteredConcerts);
});
it('[getConcertsByBandIds] should throw an error when query operation fails', async () => {
concertsRepository.getConcertsByBandIds.mockRejectedValue(
new Error('test db operation error'),
);
await expect(
concertsService.getConcertsByBandIds({ bandIds: [1, 2, 3] }),
).rejects.toEqual(new Error('test db operation error'));
});
it('[getConcertsByLocationAndByRadius] should return concerts filtered by location and radius from db ordered by up coming concerts first', async () => {
const filteredConcerts = [
{
date: 1577765869761,
band: 'Oingo Boingo',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
{
date: 1577355392972,
band: 'Dave Grohl',
location: 'The Rockpile West, Toronto, ON, Canada',
latitude: 43.6294203,
longitude: -79.5489308,
},
{
date: 1569271217188,
band: 'Snowcake',
location: 'Warehouse, Toronto, ON, Canada',
latitude: 43.6501841,
longitude: -79.3900334,
},
{
date: 1569126340647,
band: 'Del Amitri',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
];
concertsRepository.getConcertsByLocationAndByRadius.mockResolvedValue(
filteredConcerts,
);
expect(
await concertsService.getConcertsByLocationAndByRadius({
latitude: 43.6818538,
longitude: -79.5121349,
radius: 100,
}),
).toEqual(filteredConcerts);
});
it('[getConcertsByLocationAndByRadius] should throw an error when query operation fails', async () => {
concertsRepository.getConcertsByLocationAndByRadius.mockRejectedValue(
new Error('test db operation error'),
);
await expect(
concertsService.getConcertsByLocationAndByRadius({
latitude: 43.6818538,
longitude: -79.5121349,
radius: 100,
}),
).rejects.toEqual(new Error('test db operation error'));
});
it('[getConcertsByBandIdsAndByLocationAndByRadius] should return concerts filtered both by location, radius and band ids from db ordered by up coming concerts first', async () => {
const filteredConcerts = [
{
date: 1571808436512,
band: '3OH!3',
location: 'Rivoli, Toronto, ON, Canada',
latitude: 43.64944970000001,
longitude: -79.3949696,
},
{
date: 1559108692447,
band: 'Arkells',
location: 'The Garrison, Toronto, ON, Canada',
latitude: 43.6492659,
longitude: -79.42233209999999,
},
{
date: 1550266041260,
band: '4 Non Blondes',
location: 'Sony Centre for the Performing Arts, Toronto, ON, Canada',
latitude: 43.6466723,
longitude: -79.3760205,
},
{
date: 1424652665767,
band: '3OH!3',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
{
date: 1359976491899,
band: '4 Non Blondes',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
];
concertsRepository.getConcertsByBandIdsAndByLocationAndByRadius.mockResolvedValue(
filteredConcerts,
);
expect(
await concertsService.getConcertsByBandIdsAndByLocationAndByRadius({
latitude: 43.6818538,
longitude: -79.5121349,
radius: 100,
bandIds: [42, 6, 9],
}),
).toEqual(filteredConcerts);
});
it('[getConcertsByBandIdsAndByLocationAndByRadius] should throw an error when query operation fails', async () => {
concertsRepository.getConcertsByBandIdsAndByLocationAndByRadius.mockRejectedValue(
new Error('test db operation error'),
);
await expect(
concertsService.getConcertsByBandIdsAndByLocationAndByRadius({
latitude: 43.6818538,
longitude: -79.5121349,
radius: 100,
bandIds: [42, 6, 9],
}),
).rejects.toEqual(new Error('test db operation error'));
});
});
<file_sep>import { EntityRepository, Repository, SelectQueryBuilder } from 'typeorm';
import { Concert } from '../entities/Concert';
import { GetConcertDto } from './dto/get-concert.dto';
import {
GetConcertsQueryParamsByBandIds,
GetConcertsQueryParamsByBandIdsAndLocation,
GetConcertsQueryParamsByLocation,
} from './dto/get-concerts-query-params.dto';
/**
* Using postgis functions, we compute the distance between 2 points
* (projected from the lat long 4326 to the meters 3857 spatial reference system)
*
* Then the distance is converted to km to be compared to the input
*
* References:
* https://postgis.net/docs/ST_Distance.html
* https://postgis.net/docs/ST_Transform.html
* https://postgis.net/docs/ST_SetSRID.html
* https://postgis.net/docs/ST_MakePoint.html
*/
const distanceBetweenTwoPointsCondition = `
(ST_Distance(
ST_Transform(ST_SetSRID(ST_MakePoint(venue.longitude, venue.latitude), 4326), 3857),
ST_Transform(ST_SetSRID(ST_MakePoint(:longitude, :latitude), 4326), 3857)
) / 1000 < :radiusInKm)
`;
@EntityRepository(Concert)
export class ConcertRepository extends Repository<Concert> {
private buildBaseQueryBuilder(): SelectQueryBuilder<Concert> {
return this.createQueryBuilder('concert')
.select('band.name', 'band')
.addSelect('venue.name', 'location')
.addSelect('concert.date', 'date')
.addSelect('venue.latitude', 'latitude')
.addSelect('venue.longitude', 'longitude')
.innerJoin('concert.band', 'band')
.innerJoin('concert.venue', 'venue');
}
getConcertsByBandIds({
bandIds,
}: GetConcertsQueryParamsByBandIds): Promise<GetConcertDto[]> {
return this.buildBaseQueryBuilder()
.where('band.id IN (:...bandIds)', { bandIds })
.orderBy('concert.date', 'DESC')
.getRawMany();
}
getConcertsByLocationAndByRadius({
longitude,
latitude,
radius: radiusInKm,
}: GetConcertsQueryParamsByLocation): Promise<GetConcertDto[]> {
return this.buildBaseQueryBuilder()
.where(distanceBetweenTwoPointsCondition, {
longitude,
latitude,
radiusInKm,
})
.orderBy('concert.date', 'DESC')
.getRawMany();
}
getConcertsByBandIdsAndByLocationAndByRadius({
bandIds,
longitude,
latitude,
radius: radiusInKm,
}: GetConcertsQueryParamsByBandIdsAndLocation): Promise<GetConcertDto[]> {
return this.buildBaseQueryBuilder()
.where('band.id IN (:...bandIds)', { bandIds })
.andWhere(distanceBetweenTwoPointsCondition, {
longitude,
latitude,
radiusInKm,
})
.orderBy('concert.date', 'DESC')
.getRawMany();
}
}
<file_sep>export interface GetConcertDto {
band: string;
location: string;
date: number;
latitude: number;
longitude: number;
}
<file_sep>import {
Column,
Entity,
Index,
OneToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { Concert } from "./Concert";
@Index("band_pkey", ["id"], { unique: true })
@Entity("band", { schema: "public" })
export class Band {
@PrimaryGeneratedColumn({ type: "integer", name: "id" })
id: number;
@Column("text", { name: "name" })
name: string;
@OneToMany(() => Concert, concert => concert.band)
concerts: Concert[];
}
<file_sep>import * as Joi from 'joi';
export type GetConcertsQueryParamsByBandIdsDto = GetConcertsQueryParamsByBandIds & {
type: 'by_bands';
};
export interface GetConcertsQueryParamsByBandIds {
bandIds: number[];
}
export type GetConcertsQueryParamsByLocationDto = GetConcertsQueryParamsByLocation & {
type: 'by_location';
};
export interface GetConcertsQueryParamsByLocation {
longitude: number;
latitude: number;
radius: number;
}
export type GetConcertsQueryParamsByBandIdsAndLocationDto = GetConcertsQueryParamsByBandIdsAndLocation & {
type: 'by_bands_and_location';
};
export interface GetConcertsQueryParamsByBandIdsAndLocation {
bandIds: number[];
longitude: number;
latitude: number;
radius: number;
}
export type GetConcertsQueryParamsDto =
| GetConcertsQueryParamsByBandIdsDto
| GetConcertsQueryParamsByLocationDto
| GetConcertsQueryParamsByBandIdsAndLocationDto;
const customJoi = Joi.extend((joi) => ({
base: joi.array(),
name: 'integerArray',
coerce: (value, state, options) =>
value && value.split ? value.split(',') : value,
}));
export const getConcertsQueryParamsByBandIdsSchema = {
type: Joi.string().default('by_bands'),
bandIds: customJoi
.integerArray()
.items(Joi.number().integer().positive())
.required(),
};
export const getConcertsQueryParamsByLocationSchema = {
type: Joi.string().default('by_location'),
longitude: Joi.number().required(),
latitude: Joi.number().required(),
radius: Joi.number().integer().positive().required(),
};
/**
* Schema matching all possible valid data alternatives
*/
export const getConcertsQueryParamsSchema = Joi.alternatives().try(
Joi.object(getConcertsQueryParamsByBandIdsSchema),
Joi.object(getConcertsQueryParamsByLocationSchema),
Joi.object({
...getConcertsQueryParamsByBandIdsSchema,
...getConcertsQueryParamsByLocationSchema,
type: Joi.string().default('by_bands_and_location'),
}),
);
<file_sep>### Introduction
Here we discuss possible changes if we wanted to handel 2 million bands, 10,000 venues, and 200 million events, while delivering low latency & high uptime.
### 1) Database
* We already using postgresql + postgis for the spatial part of the query, but as seen in the query plan (online: http://tatiyants.com/pev/#/plans/plan_1589232747242), the part of the query costing the most is the condition for the distance calculation.
* One way to try to improve the situation would be to create new columns in the venue table to store the longitute & latitude as geometric point type, then create an index on them.
* Another aspect would be inspecting the use of the columns in the select, join & their order in the query in terms of impact for the planning.
* Also, not sure, but creating a descending index on the `concert.date` could help, as we order by it in the query.
* On the infrastructure side of things: configuring things such as enough ram to optimize for query data being in ram, so we do less I/O operations on disk. (this can get expensive though)
* A last ditch would be denormalizing the data to fit everything into one table, but changes in the data would incur eventual consistency through synchonization processes. (note: a promising tool for this kind of work is debezium : https://debezium.io/)
* In any case, as usual, these "optimizations" need to be guided by looking the query plan and understanding where we are spending most of the time. Also the generated plan can change also depending on the size of the data.
### 2) Application
There are a few ways we can make sure to not overload the database, by changing our requirements:
* Paging, limiting the number of results: most people won't go through 1000+ events.
* Loading only up comming concerts, we may not need to display those past a certain date in the past?
* Instead of using precise latitude/longitude/radius: defining radius groups (ex: 10<30<50+ km), but more importantly defining a geographic grid so people in a specific zone would have way more chance of making the same query, which means caching the results becomes a viable option.
(either through some additional store such as redis or studying the use of materialized views)
### 3) Monitoring
* Using a tool such as the mongodb Ops manager, which enable monitoring of query metrics/stats, but also alterting. Offers query plans based on usage + recommendations.
* Ingesting the database operation logs into our log stack, so we can run our own searches/graphs/alerts on them.<file_sep>import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { PinoLogger } from 'nestjs-pino';
import * as request from 'supertest';
import { ConcertsController } from '../../src/concerts/concerts.controller';
import { ConcertsService } from '../../src/concerts/concerts.service';
describe('GET /api/concerts', () => {
let app: INestApplication;
const concertsService: jest.Mocked<Partial<ConcertsService>> = {
getConcertsByBandIds: jest.fn(),
getConcertsByLocationAndByRadius: jest.fn(),
getConcertsByBandIdsAndByLocationAndByRadius: jest.fn(),
};
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [ConcertsController],
providers: [
{
provide: PinoLogger,
useValue: { setContext: () => {}, error: () => {} },
},
{
provide: ConcertsService,
useValue: concertsService,
},
],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it('should return concerts matched by band ids ordered by up coming concerts first', async () => {
const filteredConcerts = [
{
date: 1571808436512,
band: '3OH!3',
location: 'Rivoli, Toronto, ON, Canada',
latitude: 43.64944970000001,
longitude: -79.3949696,
},
{
date: 1559108692447,
band: 'Arkells',
location: 'The Garrison, Toronto, ON, Canada',
latitude: 43.6492659,
longitude: -79.42233209999999,
},
{
date: 1550266041260,
band: '4 Non Blondes',
location: 'Sony Centre for the Performing Arts, Toronto, ON, Canada',
latitude: 43.6466723,
longitude: -79.3760205,
},
{
date: 1424652665767,
band: '3OH!3',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
{
date: 1359976491899,
band: '4 Non Blondes',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
];
concertsService.getConcertsByBandIds.mockResolvedValue(filteredConcerts);
const { status, body } = await request(app.getHttpServer())
.get('/api/concerts?bandIds=64,3,2')
.send();
expect({ status, body }).toEqual({
status: 200,
body: filteredConcerts,
});
});
it('should return concerts matched by location & radius around Toronto ordered by up coming concerts first', async () => {
const filteredConcerts = [
{
date: 1577765869761,
band: 'Oingo Boingo',
location: 'Sound Academy, Toronto, ON, Canada',
latitude: 43.63967479999999,
longitude: -79.3535794,
},
{
date: 1577355392972,
band: 'Dave Grohl',
location: 'The Rockpile West, Toronto, ON, Canada',
latitude: 43.6294203,
longitude: -79.5489308,
},
{
date: 1577044931451,
band: 'VHS or Beta',
location: 'Air Canada Centre, Toronto, ON, Canada',
latitude: 43.6434661,
longitude: -79.3790989,
},
{
date: 1576741788468,
band: 'Pierce the Veil',
location: 'Warehouse, Toronto, ON, Canada',
latitude: 43.6501841,
longitude: -79.3900334,
},
];
concertsService.getConcertsByLocationAndByRadius.mockResolvedValue(
filteredConcerts,
);
const { status, body } = await request(app.getHttpServer())
.get('/api/concerts?longitude=-79.5121349&latitude=43.6818538&radius=100')
.send();
expect({ status, body }).toEqual({
status: 200,
body: filteredConcerts,
});
});
it('should return concerts matched both location & radius and band ids ordered by up coming concerts first', async () => {
const filteredConcerts = [
{
date: 1571808436512,
band: '3OH!3',
location: 'Rivoli, Toronto, ON, Canada',
latitude: 43.64944970000001,
longitude: -79.3949696,
},
{
date: 1559108692447,
band: 'Arkells',
location: 'The Garrison, Toronto, ON, Canada',
latitude: 43.6492659,
longitude: -79.42233209999999,
},
{
date: 1550266041260,
band: '4 Non Blondes',
location: 'Sony Centre for the Performing Arts, Toronto, ON, Canada',
latitude: 43.6466723,
longitude: -79.3760205,
},
];
concertsService.getConcertsByBandIdsAndByLocationAndByRadius.mockResolvedValue(
filteredConcerts,
);
const { status, body } = await request(app.getHttpServer())
.get(
'/api/concerts?longitude=-79.5121349&latitude=43.6818538&radius=100&bandIds=64,3,2',
)
.send();
expect({ status, body }).toEqual({
status: 200,
body: filteredConcerts,
});
});
it('should return 400 error for missing radius query param when filtering by location', async () => {
const { status, body } = await request(app.getHttpServer())
.get('/api/concerts?longitude=-79.5121349&latitude=43.6818538')
.send();
expect({ status, body }).toEqual({
status: 400,
body: {
statusCode: 400,
error: 'Bad Request',
message: 'Validation failed',
},
});
});
it('should return 400 error for query param with unexpected type', async () => {
const { status, body } = await request(app.getHttpServer())
.get('/api/concerts?longitude=true&latitude=43.6818538&radius=5')
.send();
expect({ status, body }).toEqual({
status: 400,
body: {
statusCode: 400,
error: 'Bad Request',
message: 'Validation failed',
},
});
});
it('should return 500 error when the db query has failed', async () => {
concertsService.getConcertsByLocationAndByRadius.mockRejectedValue(
new Error('db test error'),
);
const { status, body } = await request(app.getHttpServer())
.get('/api/concerts?longitude=-79.5121349&latitude=43.6818538&radius=5')
.send();
expect({ status, body }).toEqual({
status: 500,
body: {
statusCode: 500,
message: 'Internal Server Error',
},
});
});
});
<file_sep>### Concerts finder
If you are looking for the answers regarding scalability, please take a look at `scalability.md`
### Installation
Recommended Node.js version: `12.16+` (install it using `nvm` if needed)
The application uses Typescript + NestJs.
`npm install`
### Api
```
GET /api/concerts?bandIds=..&latitude=..&longitude=..&radius=..
bandIds: String - Comma separated list of bandIds
latitude: float
longitude: float
radius: Int - In kilometers
Validation: bandIds AND/OR latitude/longitude/radius
Returns a list of concerts ordered by descending date:
[
{
"band": string,
"location": string,
"date": bigint,
"latitude": float,
"longitude": float
}
...
]
```
Example:
```
GET /api/concerts?bandIds=64,3,2&longitude=-79.5121349&latitude=43.6818538&radius=100
Response:
status: 200
body: [
{
"date": "1571808436512",
"band": "3OH!3",
"location": "Rivoli, Toronto, ON, Canada",
"latitude": 43.64944970000001,
"longitude": -79.3949696
},
{
"date": "1559108692447",
"band": "Arkells",
"location": "The Garrison, Toronto, ON, Canada",
"latitude": 43.6492659,
"longitude": -79.42233209999999
},
{
"date": "1550266041260",
"band": "4 Non Blondes",
"location": "Sony Centre for the Performing Arts, Toronto, ON, Canada",
"latitude": 43.6466723,
"longitude": -79.3760205
},
...
]
```
In case of invalid query params (missing or unexpected type), a 400 error is returned:
```
GET /api/concerts?bandIds=64,3,2&longitude=-79.5121349&latitude=true8&radius=100
Response:
status: 400
body: {
statusCode: 400,
error: 'Bad Request',
message: 'Validation failed',
}
```
In case of a failure while querying the database, a 500 error is returned:
```
GET /api/concerts?bandIds=64,3,2
Response:
status: 500
body: {
statusCode: 500,
message: 'Internal Server Error',
}
```
### Running
1) This application depends on a postgresql database with postgis extensions installed, so you can start a local docker container with:
`docker run --name some-postgis -e POSTGRES_PASSWORD=<PASSWORD> -p 5432:5432 -d postgis/postgis`
2) We need to create db schemas, tables, etc...
Do so with `npm run typeorm schema:sync`
3) Let's import the provided data into the created tables! (might take a while :) )
`npm run typeorm migration:run`
4) At last, you should be able to start the application itself with: `npm run start`
### Testing
`npm test` to run the test suite.
`npm run test:cov` to also generate code coverage.
### Things missing
* End to end testing with a database
* Writting tests for the migration script
* Swagger integration
* Dabase schema is missing some constrains (not null, handling cascade changes)<file_sep>import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LoggerModule } from 'nestjs-pino';
import { Band } from '../entities/Band';
import { Concert } from '../entities/Concert';
import { Venue } from '../entities/Venue';
import { ConcertsController } from './concerts.controller';
import { ConcertRepository } from './concerts.repository';
import { ConcertsService } from './concerts.service';
@Module({
imports: [
LoggerModule.forRoot(),
TypeOrmModule.forFeature([Concert, Band, Venue, ConcertRepository]),
],
providers: [ConcertsService],
controllers: [ConcertsController],
})
export class ConcertsModule {}
<file_sep>import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';
import * as Joi from 'joi';
import {
GetConcertsQueryParamsDto,
getConcertsQueryParamsSchema,
} from '../concerts/dto/get-concerts-query-params.dto';
@Injectable()
export class ParseConcertsQueryParamsPipe
implements PipeTransform<any, GetConcertsQueryParamsDto> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
transform(value: any, metadata: ArgumentMetadata): GetConcertsQueryParamsDto {
const {
value: validatedValue,
error,
}: {
value: any;
error?: Joi.ValidationError;
} = getConcertsQueryParamsSchema.validate(value);
if (error) {
throw new BadRequestException('Validation failed');
}
return validatedValue;
}
}
| 3c25b5a04c3b9d3c522d730c7097c4c6c94e48cf | [
"Markdown",
"TypeScript"
] | 16 | TypeScript | MohamedJeffal/concerts-finder | 3aeed4bbae494fdf8f8c7fc2a676a6c44edee588 | 0cd5f53e9eaf9b992d06c770c6247985687ca07f |
refs/heads/main | <repo_name>Vie-Etudiante-UL/Somewhere-in-the-Dark<file_sep>/Assets/Script/SoundGen.cs
using System;
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
using Random = UnityEngine.Random;
public class SoundGen : MonoBehaviour
{
[Header("Visual")]
[SerializeField] private SoundCirlce soundCircleBase;
[SerializeField] private Gradient feedBackColors;
[SerializeField] private float maxColorThreshold;
[Header("Audio")]
[SerializeField] private AudioSource audio;
[SerializeField] private List<AudioClip> walkingDefaultSounds = new List<AudioClip>();
[SerializeField] private List<AudioClip> runnningDefaultSounds = new List<AudioClip>();
[SerializeField] private List<AudioClip> doorOpeningSounds = new List<AudioClip>();
[SerializeField] private float maxSoundMultThreshold;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void GenSound(float soundMult)
{
if (!soundCircleBase)
throw new NullReferenceException(
"Fo rajouter une référence au prefab CercleSon dans le champ de référence \"Sound Circle Base\"");
if (Instantiate(soundCircleBase.gameObject, transform.position, new Quaternion())
.TryGetComponent(out SoundCirlce newSC))
{
float time = soundMult / maxColorThreshold ;
Color sCColor = feedBackColors.Evaluate(time);
newSC.InitCircle(soundMult,sCColor);
}
}
public void GenWalkingSound(float soundMult)
{
List<AudioClip> clips = walkingDefaultSounds;
if (IsNoiseZone(out NoisyZone noisyZone))
{
soundMult += noisyZone.soundMult;
clips = noisyZone.WalkSounds;
}
GenSound(soundMult);
PlayAudio(clips, soundMult);
}
public void GenRunningSound(float soundMult)
{
List<AudioClip> clips = runnningDefaultSounds;
if (IsNoiseZone(out NoisyZone noisyZone))
{
soundMult += noisyZone.soundMult;
clips = noisyZone.RunSounds;
}
GenSound(soundMult);
PlayAudio(clips, soundMult);
}
public void GenDoorOpeningSound(float soundMult)
{
List<AudioClip> clips = doorOpeningSounds;
GenSound(soundMult);
if(!audio.isPlaying)PlayAudio(clips, soundMult);
}
private bool IsNoiseZone(out NoisyZone noisyZone)
{
LayerMask noisyMask = LayerMask.GetMask("Noisy");
Collider2D other = Physics2D.OverlapCircle(transform.position, 0.1f, noisyMask);
if (other && other.TryGetComponent(out noisyZone)) {/*oups le if moyen util*/}
else noisyZone = null;
return other;
}
private void PlayAudio(AudioClip audioClip, float soundMult)
{
audio.volume = soundMult / maxSoundMultThreshold;
audio.clip = audioClip;
audio.Play();
}
private void PlayAudio([NotNull] List<AudioClip> clips, float soundMult)
{
if (clips == null) throw new ArgumentNullException(nameof(clips));
PlayAudio(clips[Random.Range(0,clips.Count)], soundMult);
}
/*
private IEnumerator TestGenSound()
{
while (true)
{
yield return new WaitForSeconds(1);
float alea = Random.Range(0.1f, 5);
GenSound(alea);
}
}
*/
}
<file_sep>/Assets/Script/Inventaire/Inventory.cs
using UnityEngine;
using System.Collections.Generic;
using System.Data;
using UnityEngine.UI;
public class Inventory : MonoBehaviour
{
[SerializeField] private KeyUnitUI keyUnitUIBase;
private List<KeyUnitUI> content = new List<KeyUnitUI>();
[SerializeField] private Transform listItems;
private static Inventory cela;
public static Inventory instance
{
get
{
if (!cela) cela = FindObjectOfType<Inventory>();
return cela;
}
}
private void Awake()
{
}
private void Start()
{
}
public void AddItem(Item item)
{
if (Instantiate(keyUnitUIBase.gameObject, listItems.transform).TryGetComponent(out KeyUnitUI unit))
{
unit.Init(item);
content.Add(unit);
}
}
public bool Contain(int idItem, out Item item)
{
foreach (KeyUnitUI unit in content)
{
if (unit.Item.id == idItem)
{
item = unit.Item;
return true;
}
}
item = null;
return false;
}
public bool Contain(int idItem)
{
foreach (KeyUnitUI unit in content)
{
if (unit.Item.id == idItem) return true;
}
return false;
}
public void RemoveItem(Item item)
{
List<KeyUnitUI> newContent = new List<KeyUnitUI>(content);
foreach (KeyUnitUI unit in content)
{
if (unit.Item == item)
{
newContent.Remove(unit);
Destroy(unit.gameObject);
}
}
content = newContent;
}
}
<file_sep>/Assets/Script/PlayerController/PlayerController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
[RequireComponent(typeof(SoundGen))]
public class PlayerController : MonoBehaviour
{
[Header("movements")]
[SerializeField] private float speed = 1.0f;
[SerializeField] private float multRun;
private bool isHiding;
public bool IsHiding => isHiding;
[SerializeField] private Rigidbody2D body;
[Header("Visual")]
[SerializeField] private Animator animator;
[SerializeField] private SpriteRenderer sprRend;
[Header("Sound")]
[SerializeField] public AudioSource source;
[SerializeField] public AudioClip Soundclip;
[HideInInspector] public HideOut currentHideout;
[HideInInspector] public Door currentDoor;
[HideInInspector] public PickUpItem currentItem;
private Vector3 bufferPosition;
private static readonly int IsMoving = Animator.StringToHash("isMoving");
private static readonly int IsRunning = Animator.StringToHash("isRunning");
// Start is called before the first frame update
private void Start()
{
}
private void Update()
{
ControleHiding();
LookForward();
}
// Update is called once per frame
private void FixedUpdate()
{
if(!isHiding) ControleMoving();
}
private void ControleHiding()
{
if (Input.GetButtonDown("Fire1") )
{
if(currentHideout) GetHidden();
if(currentItem) PickUp();
if(currentDoor) OpenDoor();
}
}
private void ControleMoving()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
float _multRun = Input.GetButton("Fire2") ? multRun : 1;
Vector2 newVelocity = new Vector2(horizontal * speed * _multRun, vertical * speed * _multRun);
animator.SetBool(IsMoving, newVelocity.magnitude > 0);
animator.SetBool(IsRunning, _multRun > 1);
body.velocity = newVelocity;
}
private void OpenDoor()
{
currentDoor.Open();
}
private void PickUp()
{
currentItem.Pick();
}
private void GetHidden()
{
animator.SetBool(IsMoving, false);
animator.SetBool(IsRunning, false);
if(!isHiding)
{
currentHideout.Use(true);
body.velocity = Vector2.zero;
bufferPosition = transform.position;
transform.position = currentHideout.transform.position;
source.PlayOneShot(Soundclip);
isHiding = true;
}
else
{
currentHideout.Use(false);
Vector3 exitPoint = new Vector3();
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if (Mathf.Abs(horizontal) > Mathf.Abs(vertical))
{
if (horizontal > 0 && currentHideout.ExitPointRight)
{
exitPoint = currentHideout.ExitPointRight.position;
}
else if(currentHideout.ExitPointLeft)
{
exitPoint = currentHideout.ExitPointLeft.position;
}
}
else
{
if (vertical > 0 && currentHideout.ExitPointUp)
{
exitPoint = currentHideout.ExitPointUp.position;
}
else if (currentHideout.ExitPointDown)
{
exitPoint = currentHideout.ExitPointDown.position;
}
}
if (exitPoint.magnitude == 0) exitPoint = bufferPosition;
exitPoint.z = transform.position.z;
transform.position = exitPoint;
isHiding = false;
}
}
private void LookForward()
{
Vector3 direction = body.velocity.normalized;
float angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, -Vector3.forward);
}
}
<file_sep>/Assets/Script/Key_Door/Key.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Key : PickUpItem
{
[Header("Visual")]
[SerializeField] private SpriteRenderer stone;
[SerializeField] private Color stoneColor;
private void OnValidate()
{
if (stone && item)
{
item.color = stoneColor;
stone.color = item.color;
}
}
protected override void Awake()
{
base.Awake();
stone.color = item.color;
}
}
<file_sep>/Assets/Script/Key_Door/PickUpItem.cs
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class PickUpItem : MonoBehaviour
{
// normalement ca doit pouvoir ramasser d'autres objets que les cles
//private Text interactUI;
public Item item;
private AudioSource audio;
public AudioClip clip;
[Header("Interface")]
[SerializeField] private Canvas interactUI;
[SerializeField] private TextMeshProUGUI textInfo;
protected virtual void Awake()
{
interactUI.gameObject.SetActive(false);
interactUI.worldCamera = Camera.main;
}
void Update()
{
}
public void Pick()
{
if (!Inventory.instance) throw new NullReferenceException("Y manque un Inventaire dans cette scene");
Inventory.instance.AddItem(item);
audio = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<AudioSource>();
audio.PlayOneShot(clip);
Destroy(gameObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.TryGetComponent(out PlayerController player))
{
interactUI.gameObject.SetActive(true);
player.currentItem = this;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.TryGetComponent(out PlayerController player))
{
interactUI.gameObject.SetActive(false);
player.currentItem = null;
}
}
}
<file_sep>/Assets/Script/HideOut.cs
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
[RequireComponent(typeof(CircleCollider2D))]
public class HideOut : MonoBehaviour
{
[Header("Trigger")]
[SerializeField] private CircleCollider2D trigger;
[SerializeField] private Collider2D collider;
[Header("UI")]
[SerializeField] private Canvas signInput;
[SerializeField] private TextMeshProUGUI messageInput;
private bool isUsed;
[Header("ExitPoints")]
[SerializeField] private Transform exitPointUp;
[SerializeField] private Transform exitPointDown;
[SerializeField] private Transform exitPointRight;
[SerializeField] private Transform exitPointLeft;
public Transform ExitPointUp
{
get
{
LayerMask obstacleMask = LayerMask.GetMask("Obstacle");
return Physics2D.OverlapCircle(exitPointUp.position, 0.1f, obstacleMask) ? null : exitPointUp;
}
}
public Transform ExitPointDown
{
get
{
LayerMask obstacleMask = LayerMask.GetMask("Obstacle");
return Physics2D.OverlapCircle(exitPointDown.position, 0.1f, obstacleMask) ? null : exitPointDown;
}
}
public Transform ExitPointRight
{
get
{
LayerMask obstacleMask = LayerMask.GetMask("Obstacle");
return Physics2D.OverlapCircle(exitPointRight.position, 0.1f, obstacleMask) ? null : exitPointRight;
}
}
public Transform ExitPointLeft
{
get
{
LayerMask obstacleMask = LayerMask.GetMask("Obstacle");
return Physics2D.OverlapCircle(exitPointLeft.position, 0.1f, obstacleMask) ? null : exitPointLeft;
}
}
private void OnDrawGizmos()
{
if(exitPointDown && exitPointUp && exitPointLeft && exitPointRight)
{
Gizmos.color = ExitPointUp ? Color.green : Color.red;
Gizmos.DrawSphere(exitPointUp.position, 0.2f);
Gizmos.color = ExitPointDown ? Color.green : Color.red;
Gizmos.DrawSphere(exitPointDown.position, 0.2f);
Gizmos.color = ExitPointRight ? Color.green : Color.red;
Gizmos.DrawSphere(exitPointRight.position, 0.2f);
Gizmos.color = ExitPointLeft ? Color.green : Color.red;
Gizmos.DrawSphere(exitPointLeft.position, 0.2f);
}
}
private void OnValidate()
{
if (!trigger) TryGetComponent(out trigger);
if(signInput) signInput.worldCamera = Camera.main;
}
// Start is called before the first frame update
private void Start()
{
if (!signInput) throw new NullReferenceException("Y manque une ref à Sign Input ! C pas bien !");
if (!exitPointDown || !exitPointUp || !exitPointLeft || !exitPointRight)
throw new NullReferenceException("Y manque les Exit Points !");
signInput.gameObject.SetActive(false);
}
// Update is called once per frame
private void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent(out PlayerController player))
{
player.currentHideout = this;
messageInput.text = "Press (Space) to hide";
SetSignVisible(true);
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.TryGetComponent(out PlayerController player))
{
player.currentHideout = null;
SetSignVisible(false);
}
}
private void SetSignVisible(bool visible)
{
signInput.gameObject.SetActive(visible);
}
public void Use(bool use)
{
collider.enabled = !use;
isUsed = use;
messageInput.text = use ? "Press (Space) to exit" : "Press (Space) to hide";
}
}
<file_sep>/Assets/Script/Key_Door/Item.cs
using UnityEngine;
[CreateAssetMenu(fileName = "Item", menuName = "Inventory/Item")]
public class Item : ScriptableObject
{
public int id;
// correspondance entre cl� et porte
public string name;
public string description;
public Sprite image;
public Color color;
}
<file_sep>/Assets/Script/Key_Door/Door.cs
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using System.Data;
using System.Collections.Generic;
public class Door : MonoBehaviour
{
public int doorId;
//public GameObject collision;
// un gameObject enfant de Door qui contient un box collider (isTrigger=false) pour bloquer le personnage, celui de Door est déjà utilisé pour détecter le joueur
[Header("Cette valeur override l'axe z de la rotation dans l'éditeur")]
[SerializeField] private float rotationDoor;
[SerializeField] private Transform rotationRoot;
private List<GameObject> content = new List<GameObject>();
[Header("Interface")]
[SerializeField] private Canvas interactUI;
[SerializeField] private TextMeshProUGUI textInfo;
[Header("Visual")]
[SerializeField] private Animator animator;
private bool isOpen;
private static readonly int OpenDoor = Animator.StringToHash("OpenDoor");
private void OnValidate()
{
if(rotationRoot)rotationRoot.rotation = Quaternion.Euler(0, 0, rotationDoor);
CounterRotationForUI();
}
void Awake()
{
interactUI.gameObject.SetActive(false);
interactUI.worldCamera = Camera.main;
}
void Update()
{
CounterRotationForUI();
}
public void Open()
{
if (!Inventory.instance) throw new NullReferenceException("Y a pas d'inventaire dans cette scene");
if(!isOpen)
{
if (Inventory.instance.Contain(doorId, out Item key))
{
animator.SetTrigger(OpenDoor);
interactUI.gameObject.SetActive(false);
Inventory.instance.RemoveItem(key);
isOpen = true;
}
else
{
textInfo.text = "Don't have right key";
}
}
}
private void CounterRotationForUI()
{
if(interactUI && rotationRoot) interactUI.transform.localRotation = Quaternion.Euler(0,0,-rotationRoot.eulerAngles.z);
}
// Entree dans le collider de la porte
private void OnTriggerEnter2D(Collider2D collision)
{
if(!isOpen && collision.TryGetComponent(out PlayerController player))
{
interactUI.gameObject.SetActive(true);
textInfo.text = "Press (Space) to open";
player.currentDoor = this;
}
}
// Sortie du collider de la porte
private void OnTriggerExit2D(Collider2D collision)
{
if (!isOpen && collision.TryGetComponent(out PlayerController player))
{
interactUI.gameObject.SetActive(false);
player.currentDoor = null;
}
}
public void speedMonster(float speed)
{
Array table = GameObject.FindGameObjectsWithTag("Monster");
foreach (GameObject item in table)
{
item.GetComponent<MonsterBehaviour>().changeSpeed(speed);
}
}
public void backtonormal(float speed)
{
Array table = GameObject.FindGameObjectsWithTag("Monster");
foreach (GameObject item in table)
{
item.GetComponent<MonsterBehaviour>().backToNormalSpeed(speed);
}
}
}
<file_sep>/Assets/Script/MonsterBehaviour.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class MonsterBehaviour : MonoBehaviour
{
[SerializeField] private Vector3 target;
[SerializeField] private Animator animator;
PlayerController player;
private NavMeshAgent agent;
private bool continueCoroutine = true;
private static readonly int IsMoving = Animator.StringToHash("isMoving");
// Start is called before the first frame update
void Start()
{
StartCoroutine(getPlayerPosition());
//target = GameObject.FindGameObjectWithTag("Player").transform.position;
player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
}
// Update is called once per frame
void Update()
{
agent.SetDestination(target);
LookForward();
if(agent.velocity.magnitude > 0) animator.SetBool(IsMoving, true);
else animator.SetBool(IsMoving, false);
//Debug.Log("is hiding" + player.IsHiding);
}
public void GetPlayerPosition()
{
target = GameObject.FindGameObjectWithTag("Player").transform.position;
}
public Vector3 RandomNavmeshLocation(float radius)
{
Vector3 randomDirection = Random.insideUnitSphere * radius;
randomDirection += transform.position;
NavMeshHit hit;
Vector3 finalPosition = Vector3.zero;
if (NavMesh.SamplePosition(randomDirection, out hit, radius, 1))
{
finalPosition = hit.position;
}
return finalPosition;
}
IEnumerator getPlayerPosition()
{
while (continueCoroutine)
{ //variable that enables you to kill routine
//Debug.Log("OnCoroutine: " + Time.time + target);
if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>().IsHiding)
{
target = RandomNavmeshLocation(Random.Range(8.0f, 20.0f));
}
else
{
target = RandomNavmeshLocation(Random.Range(8.0f, 20f));
}
yield return new WaitForSeconds(Random.Range(2.0f, 7.0f));
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Player"))
{
GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>().GameOver(true);
}
}
public void changeSpeed(float speed)
{
agent.speed = agent.speed + speed;
}
public void backToNormalSpeed(float speed)
{
agent.speed = agent.speed - speed;
}
private void LookForward()
{
Vector2 direction = agent.velocity.normalized;
float angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, -Vector3.forward);
}
}
<file_sep>/Assets/Script/NoisyZone.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class NoisyZone : MonoBehaviour
{
public float soundMult;
[SerializeField] private BoxCollider2D zone;
[SerializeField] private List<AudioClip> walkSounds;
[SerializeField] private List<AudioClip> runSounds;
public List<AudioClip> WalkSounds => walkSounds;
public List<AudioClip> RunSounds => runSounds;
private void OnValidate()
{
if (!zone) TryGetComponent(out zone);
}
private void OnDrawGizmos()
{
if(!zone) return;
Color newCol = Color.blue;
newCol.a = 0.1f;
Gizmos.color = newCol;
Vector3 position = transform.position;
Gizmos.DrawCube(position + (Vector3)zone.offset, zone.size);
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(position + (Vector3)zone.offset,zone.size);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/Script/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
private static GameManager cela;
public static GameManager instance
{
get
{
if (!cela) cela = FindObjectOfType<GameManager>();
return cela;
}
}
// Start is called before the first frame update
[SerializeField] private GameObject gameOverUI;
[SerializeField] private GameObject pauseUI;
[SerializeField] private GameObject winUI;
private bool isWin;
private bool gameOver;
void Start()
{
if(gameOverUI) gameOverUI.SetActive(false);
if(pauseUI) pauseUI.SetActive(false);
if (winUI) winUI.SetActive(false);
DoPause(false);
}
public void GameOver(bool isGameOver)
{
gameOver = isGameOver;
gameOverUI.SetActive(true);
DoPause(isGameOver);
}
public void Win()
{
isWin = true;
winUI.SetActive(true);
DoPause(true);
}
private void DoPause(bool pause)
{
Time.timeScale = pause ? 0 : 1;
}
public void pauseMenu()
{
if (pauseUI.activeSelf)
{
pauseUI.SetActive(false);
Time.timeScale = 1.0f;
}
else
{
pauseUI.SetActive(true);
Time.timeScale = 0.0f;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Submit") && (gameOver || isWin))
{
SceneManager.LoadScene("Level1");
}
if (Input.GetButtonDown("Start"))
{
pauseMenu();
}
}
public void LoadMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void LoadLevel()
{
SceneManager.LoadScene("Level1");
}
public void ExitGame()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#elif UNITY_WEBGL
Application.OpenURL("about:blank");
#endif
Application.Quit();
}
}
<file_sep>/README.md
<h1>Somewhere in the Dark</h1>
Jeu réalisé dans le cadre de la Spooky2DJam à laquelle les étudiants ont participés pour une animation de la e.MDE de l'Université de Lorraine.
Vous devez fuir un manoir habité par des monstres aveugles mais entendants. Retrouvez les clés qui ouvrent les nombreuses portes verrouillées, et se cachez-vous dans les placards et sous les tables lorsque les monstres tentent de vous attraper !
<h2>Equipe :</h2>
- Gestion de projet : Camélia « Camliax13 » Abdou
- Producteur sonore : Félicien "Spitch" Cuny
- Artiste numérique : Marion « Philadelfiad » Nussbaum
- Artiste numérique : Margot « bizarreorange »
- Programmeurs Gameplay / Game Design : Sylve « Oxy »
- Programmeurs Gameplay / Game Design : Leodar
- Programmeurs Gameplay : Simon
Les Quiches de Lorraine
Page itch.io : https://leodar.itch.io/somewhere-in-the-dark
<file_sep>/Assets/MonsterSoundGen.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterSoundGen : MonoBehaviour
{
[Header("Audio")]
[SerializeField] private AudioSource audio;
[SerializeField] private List<AudioClip> walkingDefaultSounds = new List<AudioClip>();
[SerializeField] public AudioClip roarSound;
[SerializeField] public AudioSource roarSource;
// Start is called before the first frame update
public void GenWalkingSound(float soundMult)
{
List<AudioClip> clips = walkingDefaultSounds;
PlayAudio(clips[0], soundMult);
}
public void GenRoarSound(float soundMult)
{
if (!roarSource.isPlaying) roarSource.PlayOneShot(roarSound);
}
private void PlayAudio(AudioClip audioClip, float soundMult)
{
audio.volume = soundMult;
audio.clip = audioClip;
audio.pitch = Random.Range(-3.0f, 1.0f);
audio.Play();
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/Script/SoundCirlce.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundCirlce : MonoBehaviour
{
[SerializeField] private LineRenderer line;
[SerializeField] private float radius;
[SerializeField] private float maxRadius;
[SerializeField] private float depth;
[SerializeField] private int segments;
[SerializeField] private float thickness;
[Tooltip("Temps que met le cercle à atteindre sa taille maximum")]
[SerializeField] private float maxGrowTime;
private float growTime;
private bool canBeDrawn;
private void OnValidate()
{
if(line && segments > 0) DrawCircle();
}
// Start is called before the first frame update
private void Start()
{
radius = 0;
}
// Update is called once per frame
private void Update()
{
if (canBeDrawn) GrowCicle();
}
private void GrowCicle()
{
if (radius >= maxRadius) Destroy(gameObject);
radius = Mathf.Lerp(0, maxRadius, growTime / maxGrowTime);
growTime += Time.deltaTime;
DrawCircle();
}
public void InitCircle(float maxSize, Color colorCircle)
{
Gradient newGradient = new Gradient();
newGradient.SetKeys(
new [] { new GradientColorKey(colorCircle, 0.0f), new GradientColorKey(colorCircle,1.0f) },
new [] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(1.0f, 1.0f) }
);
line.colorGradient = newGradient;
maxRadius = maxSize;
canBeDrawn = true;
radius = 0;
growTime = 0;
FireSoundDetection(maxSize);
}
private void DrawCircle()
{
line.positionCount = segments + 2;
line.widthMultiplier = thickness;
for (int i = 0; i < line.positionCount; i++)
{
float angle = 2 * Mathf.PI / segments * i;
Vector3 newPos = new Vector3
{
x = Mathf.Cos(angle) * radius,
y = Mathf.Sin(angle) * radius,
z = depth
};
line.SetPosition(i,newPos);
}
}
private void FireSoundDetection(float size)
{
LayerMask monsterMask = LayerMask.GetMask("Monster");
size *= 5;
Collider2D other = Physics2D.OverlapCircle(transform.position, size, monsterMask);
if (other && other.TryGetComponent(out MonsterBehaviour monster))
{
monster.GetPlayerPosition();
}
}
}
| c4da1ad2f507e02cc56f555c984da9355a5ca1e5 | [
"Markdown",
"C#"
] | 14 | C# | Vie-Etudiante-UL/Somewhere-in-the-Dark | 05b52d09e1f3d3664c25dc6bd06f7acbf2a91a64 | 45aed55f275e654a733fe361501d800d9d9e1ffc |
refs/heads/master | <repo_name>annikamonari/ICMSciThesisHiggsInv-2<file_sep>/src/histo_plot.cpp
#include "../include/histo_plot.h"
#include <algorithm>
void HistoPlot::draw_plot(Variable* var, std::vector<DataChain*> bg_chains,
DataChain* signal_chain, DataChain* data, bool with_cut,
std::vector<Variable*>* variables, bool plot_data, std::string file_name,
std::string mva_cut)
{
TCanvas* c1 = new TCanvas("c1", var->name_styled, 800, 800);
TPad* p1 = new TPad("p1", "p1", 0.0, 0.95, 1.0, 1.0);
TPad* p2 = new TPad("p2", "p2", 0.0, 0.2, 1.0, 0.95);
TPad* p3 = new TPad("p3", "p3", 0.0, 0.0, 1.0, 0.2);
TLegend* legend = new TLegend(0.0, 0.5, 0.0, 0.88);
p1->SetLeftMargin(0.102);
p2->SetBottomMargin(0.012);
p2->SetLeftMargin(0.105);
p3->SetBottomMargin(0.3);
p3->SetLeftMargin(0.102);
p1->Draw();
p2->Draw();
p3->Draw();
p2->cd();
std::cout << "mva cut: " << mva_cut << std::endl;
THStack stack = draw_stacked_histo(legend, var, bg_chains, with_cut, variables, data, mva_cut);
std::cout << "drew stack" << std::endl;
TH1F* signal_histo = draw_signal(signal_chain, var, with_cut, legend, variables, mva_cut);
std::cout << "drew signal" << std::endl;
std::cout << signal_histo << std::endl;
TH1F* data_histo;
if (plot_data) {data_histo = draw_data(data, var, with_cut, legend, variables, mva_cut);}
stack.Draw();
signal_histo->Draw("SAME");
if (plot_data) {data_histo->Draw("SAME");}
std::cout << "drew all" << std::endl;
style_stacked_histo(&stack, var->name_styled);
/*TH1F* plot_histos[3] = {(TH1F*)(stack.GetStack()->Last()), data_histo, signal_histo};
if (!plot_data) {plot_histos[1] = NULL;}
std::vector<TH1F*> plot_histos_vector (plot_histos, plot_histos + sizeof(plot_histos) / sizeof(plot_histos[0]));
TH1F* max_histo = get_max_histo(plot_histos_vector);
std::cout << "got max" << max_histo << std::endl;
stack.SetMaximum(get_histo_y_max(max_histo)*1.15);*/
build_legend(legend, signal_histo, var, with_cut);
draw_subtitle(var, variables, with_cut, data, "", mva_cut);
std::cout << "drew subtitle" << std::endl;
p3->cd();
TH1F* data_bg_ratio_histo;
if (plot_data)
{
std::cout << "data histo isnt null" << std::endl;
data_bg_ratio_histo = data_to_bg_ratio_histo(data_histo, (TH1F*)(stack.GetStack()->Last()));
}
else
{
std::cout << "data_histo appaz is null" << std::endl;
data_bg_ratio_histo = data_to_bg_ratio_histo(signal_histo, (TH1F*)(stack.GetStack()->Last()));
}
data_bg_ratio_histo->Draw("e1");
style_ratio_histo(data_bg_ratio_histo, var->name_styled);
draw_yline_on_plot(var, with_cut, 1.0);
std::cout << "ratio histo done" << std::endl;
std::string img_name;
if (file_name == "")
{
img_name = build_file_name(var, with_cut);
}
else
{
img_name = file_name;
}
std::cout << "file name" << std::endl;
p1->cd();
draw_title(var->name_styled);
c1->SaveAs(img_name.c_str());
c1->Close();
}
void HistoPlot::draw_yline_on_plot(Variable* var, bool with_cut, double y)
{
double x_min = 0.0;
double x_max = 1.0;
if (with_cut)
{
x_min = atof(var->x_min_cut);
x_max = atof(var->x_max_cut);
}
else
{
x_min = atof(var->x_min_nocut);
x_max = atof(var->x_max_nocut);
}
TLine *line = new TLine(x_min, y, x_max, y);
line->SetLineColor(13);
line->SetLineStyle(2);
line->Draw("SAME");
}
void HistoPlot::draw_title(const char* title)
{
TPaveText* pt = new TPaveText(0.1, 0.1, 0.9, 1.0, "blNDC");
pt->SetBorderSize(0);
pt->SetFillColor(0);
pt->AddText(title);
pt->SetAllWith(title, "size", 0.8);
pt->Draw();
}
std::string HistoPlot::get_selection(Variable* variable, std::vector<Variable*>* variables,
bool with_cut, bool is_signal, DataChain* bg_chain, double mc_weight,
std::string mva_cut)
{
std::string selection;
if ((variables != NULL) && (with_cut))
{
selection = variable->build_multicut_selection(is_signal, variables);
}
else
{
selection = variable->build_selection_string(with_cut, is_signal);
}
selection.insert(selection.find("(") + 1, lep_sel_default());
selection = HistoPlot::add_mva_cut_to_selection(selection, mva_cut);
std::cout << selection << std::endl;
return add_mc_to_selection(bg_chain, variable, selection, mc_weight);
}
std::string HistoPlot::add_mc_to_selection(DataChain* bg_chain, Variable* variable, std::string selection, double mc_weight)
{
std::string mc_weight_str = get_string_from_double(mc_weight);
std::string sel_new = selection += "*" + mc_weight_str; //selection.insert(selection.find("*") + 1, mc_weight_str + "*");
return sel_new;
}
std::string HistoPlot::add_mva_cut_to_selection(std::string selection, std::string mva_cut_str)
{
if (mva_cut_str != "")
{
std::string mva_cut = "(";
mva_cut.append(mva_cut_str);
mva_cut.append(")&&");
selection.insert(selection.find("(") + 1, mva_cut);
}
return selection;
}
std::vector<double> HistoPlot::mc_weights(DataChain* data, std::vector<DataChain*> bg_chains,
Variable* var, bool with_cut, std::vector<Variable*>* variables,
std::string mva_cut)
{
double mc_weight[bg_chains.size()];
double zll_weight;
for(int i=0; i<bg_chains.size();i++)
{
mc_weight[i] = 1;
if (bg_chains[i]->lep_sel != "")
{
double mc_weight_val = MCWeights::calc_mc_weight(data, bg_chains, bg_chains[i], (*variables)[0], with_cut,
variables, mva_cut);
if (mc_weight_val > 0)
{
mc_weight[i] = mc_weight_val;
}
if(!strcmp(bg_chains[i]->label, "bg_zll"))
{
zll_weight = mc_weight[i];
}
}
if (!strcmp(bg_chains[i]->label, "bg_zjets_vv"))
{
if (zll_weight != 1)
{
mc_weight[i] = zll_weight*5.651*1.513;
}
}
//std::cout<<i<<": "<<mc_weight[i]<<"\n";
}
std::vector<double> mc_weights_vector (mc_weight, mc_weight + sizeof(mc_weight) / sizeof(mc_weight[0]));
return mc_weights_vector;
}
// new function written just like the one above: HistoPlot::mc_weights, which calculates the right error for the bgs without a control
// region (its just sqrt(unweighted mc events in signal) / unweighted mc events in signal)
// note:: changed so that if mc weight is 1 then dont calculate the mc weight error
// TODO make error use sumw2 and integralanderror
std::vector<double> HistoPlot::get_mc_weight_errors(DataChain* data, std::vector<DataChain*> bg_chains, Variable* var, bool with_cut,
std::vector<Variable*>* variables, std::vector<double> bg_mc_weights,
std::string mva_cut)
{
double mc_weight_errors[bg_chains.size()];
double zll_weight_error;
for(int i = 0; i < bg_chains.size();i++)
{
TH1F* histo = build_1d_histo(bg_chains[i], var,with_cut, false, "goff", variables, "", 1, mva_cut);
double integral = get_histo_integral(histo, with_cut, var);
mc_weight_errors[i] = std::pow(integral, 0.5);
if (bg_mc_weights[i] != 1)
{
mc_weight_errors[i] = single_bg_error(data, bg_chains, bg_chains[i], var, with_cut, variables, bg_mc_weights[i], mva_cut);
if(!strcmp(bg_chains[i]->label, "bg_zll"))
{
zll_weight_error = mc_weight_errors[i];
}
}
if (!strcmp(bg_chains[i]->label, "bg_zjets_vv"))
{
mc_weight_errors[i] = zll_weight_error * 5.651 * 1.513;
}
}
std::vector<double> mc_weights_vector (mc_weight_errors, mc_weight_errors + sizeof(mc_weight_errors) / sizeof(mc_weight_errors[0]));
return mc_weights_vector;
}
// problem: TH1F* bg doesn't plot with the mc weight? in the function above this, whenever we call this we pass through
// the mc weight (see last arg: double weight), so if you realise we need it then just put it onto the end of the build_1d_histo call
double HistoPlot::single_bg_error(DataChain* data, std::vector<DataChain*> bg_chains, DataChain* bg_chain,
Variable* var, bool with_cut, std::vector<Variable*>* variables, double weight,
std::string mva_cut)
{
TH1F* bg = build_1d_histo(bg_chain, var, with_cut, false, "goff", variables, "", 1, mva_cut);
double MC_N_S = get_histo_integral(bg, with_cut, var);
double sigma_N = std::pow(MC_N_S, 0.5);
double sigma_w = MCWeights::calc_weight_error(data, bg_chains, bg_chain, var, with_cut, variables, mva_cut);
double sigma_total_sq = std::pow(sigma_w*MC_N_S,2)+std::pow(sigma_N*weight,2);
double sigma_total = std::pow(sigma_total_sq,0.5);
std::cout << bg_chain->label << " - single bg error: " << sigma_total << std::endl;
return sigma_total;
}
std::string HistoPlot::get_string_from_double(double num)
{
std::ostringstream num_ss;
num_ss << num;
std::string num_str(num_ss.str());
return num_str;
}
double HistoPlot::sig_to_bg_ratio(Variable* var, TH1F* bg,
TH1F* signal_histo, bool with_cut)
{
double bg_integral = get_histo_integral(bg, with_cut, var);
double sig_integral = get_histo_integral(signal_histo, with_cut, var);
float signal_mult = atof(var->signal_multiplier);
float sig_to_bg = sig_integral / bg_integral / signal_mult;
return sig_to_bg;
}
double HistoPlot::get_histo_integral(TH1F* histo, bool with_cut, Variable* var)
{
int nbins;
if (with_cut)
{
nbins = (int) (atof(var->bins_cut.c_str()) + 0.5);
}
else
{
nbins = (int) (atof(var->bins_nocut) + 0.5);
}
double integral = histo->Integral(0, nbins + 1);
return integral;
}
std::string HistoPlot::replace_all(std::string str, const std::string& from, const std::string& to)
{
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
}
std::string HistoPlot::style_selection(std::string selection)
{
std::string sele = replace_all(replace_all(replace_all(replace_all(selection, ")", ""), ">", " > "), "==", " = "), "&&", ", ");
return replace_all(replace_all(replace_all(replace_all(replace_all(sele, "_", " "), "))", ""), "(", ""), "((", ""), "<", " < ");
}
void HistoPlot::draw_subtitle(Variable* variable, std::vector<Variable*>* variables,
bool with_cut, DataChain* data, std::string supervar_selection,
std::string mva_cut)
{
std::string sel;
if (variables == NULL)
{
sel = supervar_selection;
}
else
{
sel = style_selection(get_selection(variable, variables, with_cut, false, data, 1.0, mva_cut));
}
std::cout << sel << std::endl;
std::string selection = "Selection: " + sel;
std::string l1 = "#font[12]{" + selection.substr(0, 90) + "-}";
std::string l2 = "#font[12]{" + selection.substr(88, 90) + "-}";
std::string l3 = "#font[12]{" + selection.substr(178, 88) + "}";
TPaveText* pts = new TPaveText(0.1, 1.0, 0.9, 0.9, "blNDC");
pts->SetBorderSize(0);
pts->SetFillColor(0);
pts->AddText(l1.c_str());
pts->AddText(l2.c_str());
pts->AddText(l3.c_str());
pts->SetAllWith(l1.c_str(), "size", 0.03);
pts->SetAllWith(l2.c_str(), "size", 0.03);
pts->SetAllWith(l3.c_str(), "size", 0.03);
pts->Draw();
}
THStack HistoPlot::draw_stacked_histo(TLegend* legend, Variable* var, std::vector<DataChain*> bg_chains,
bool with_cut, std::vector<Variable*>* variables, DataChain* data, std::string mva_cut)
{
THStack stack(var->name_styled, "");
std::vector<double> mc_weights_vector = mc_weights(data, bg_chains, var, with_cut, variables, mva_cut);
for(int i = 0; i < bg_chains.size(); i++) {
TH1F* single_bg_histo = draw_background(bg_chains[i], var, colours()[i], with_cut, variables, mc_weights_vector[i],
mva_cut);
stack.Add(single_bg_histo);
std::string legend_str(bg_chains[i]->legend);
legend_str += (" #font[12]{(MC weight: " + get_string_from_double(mc_weights_vector[i]) + ")}");
legend->AddEntry(single_bg_histo, legend_str.c_str(), "f");
}
return stack;
}
TH1F* HistoPlot::get_max_histo(std::vector<TH1F*> plot_histos)
{
double plot_max = 0.0;
TH1F* histo_max = NULL;
for (int i = 0; i < plot_histos.size(); i++)
{
if (plot_histos[i] != NULL)
{
double y_max = get_histo_y_max(plot_histos[i]);
if (y_max > plot_max)
{
plot_max = y_max;
histo_max = plot_histos[i];
}
}
}
return histo_max;
}
double HistoPlot::get_histo_y_max(TH1F* histo)
{
return histo->GetBinContent(histo->GetMaximumBin());
}
void HistoPlot::build_legend(TLegend* legend, TH1F* max_histo, Variable* var, bool with_cut)
{
double x1 = position_legend_x1(max_histo, var, with_cut);
double x2 = x1 + 0.26;
style_legend(legend);
legend->SetX1(x1);
legend->SetX2(x2);
legend->Draw();
}
double HistoPlot::position_legend_x1(TH1F* max_histo, Variable* var, bool with_cut)
{
int max_bin = max_histo->GetMaximumBin();
double nbins = var->get_bins(with_cut);
double max_bin_x1 = get_x1_from_bin(max_bin, nbins);
if (max_bin_x1 > 0.5)
{
return 0.12;
}
else
{
return 0.56;
}
}
double HistoPlot::get_x1_from_bin(double max_bin, double nbins)
{
return max_bin * 0.8 / nbins + 0.1;
}
void HistoPlot::style_stacked_histo(THStack* hs, const char* x_label)
{
hs->GetYaxis()->SetTitle("Events");
hs->GetYaxis()->SetLabelSize(0.035);
hs->GetYaxis()->SetTitleOffset(1.55);
hs->GetXaxis()->SetLabelSize(0);
}
void HistoPlot::style_ratio_histo(TH1F* single_histo, const char* x_label)
{
single_histo->GetYaxis()->SetTitle("Signal/Background"); //when not tmva was data/MC
single_histo->GetYaxis()->SetLabelSize(0.12);
single_histo->GetYaxis()->SetTitleOffset(0.45);
single_histo->GetYaxis()->SetTitleSize(0.12);
single_histo->GetXaxis()->SetLabelSize(0.12);
single_histo->GetXaxis()->SetTitle(x_label);
single_histo->GetXaxis()->SetTitleSize(0.12);
single_histo->GetXaxis()->SetTitleOffset(1.1);
single_histo->SetTitle("");
single_histo->SetStats(false);
single_histo->GetYaxis()->SetNdivisions(5, 5, 0);
}
void HistoPlot::style_legend(TLegend* legend)
{
legend->SetTextSize(0.025);
legend->SetBorderSize(0);
legend->SetFillStyle(0);
}
TH1F* HistoPlot::build_1d_histo(DataChain* data_chain, Variable* variable, bool with_cut, bool is_signal,
const char* option, std::vector<Variable*>* variables, std::string selection,
double mc_weight, std::string mva_cut)
{
std::string var_arg = variable->build_var_string(data_chain->label, with_cut);
std::string selection_str;
if (selection == "")
{
selection_str = get_selection(variable, variables, with_cut, is_signal, data_chain, mc_weight, mva_cut);
}
else
{
selection_str = selection;
}
data_chain->chain->Draw(var_arg.c_str(), selection_str.c_str(), option);
TH1F* histo = (TH1F*)gDirectory->Get(data_chain->label);
return histo;
}
TH1F* HistoPlot::draw_data(DataChain* data_chain, Variable* variable, bool with_cut, TLegend* legend,
std::vector<Variable*>* variables, std::string mva_cut)
{
data_chain->chain->SetMarkerStyle(7);
data_chain->chain->SetMarkerColor(1);
data_chain->chain->SetLineColor(1);
TH1F* data_histo = set_error_bars(build_1d_histo(data_chain, variable, with_cut, false, "E1", variables, "", 1,
mva_cut));
legend->AddEntry(data_histo, data_chain->legend, "lep");
return data_histo;
}
TH1F* HistoPlot::draw_signal(DataChain* data_chain, Variable* variable, bool with_cut, TLegend* legend,
std::vector<Variable*>* variables, std::string mva_cut)
{
data_chain->chain->SetLineColor(2);
data_chain->chain->SetLineWidth(3);
data_chain->chain->SetFillColor(0);
TH1F* signal_histo = build_1d_histo(data_chain, variable, with_cut, true, "goff", variables, "", 1, mva_cut);
legend->AddEntry(signal_histo, (build_signal_leg_entry(variable, data_chain)).c_str(), "l");
return signal_histo;
}
TH1F* HistoPlot::draw_background(DataChain* data_chain, Variable* variable, int fill_colour, bool with_cut,
std::vector<Variable*>* variables, double mc_weight, std::string mva_cut)
{
data_chain->chain->SetLineColor(1);
data_chain->chain->SetFillColor(fill_colour);
std::cout << "in draw background: " << mva_cut << std::endl;
return build_1d_histo(data_chain, variable, with_cut, false, "goff", variables, "", mc_weight, mva_cut);
}
TH1F* HistoPlot::data_to_bg_ratio_histo(TH1F* data_histo, TH1F* bg_histo)
{
TH1F* ratio_histo = (TH1F*) data_histo->Clone();
ratio_histo->Divide(bg_histo);
ratio_histo->SetMarkerColor(1);
return set_ratio_error_bars(ratio_histo, data_histo, bg_histo);
}
TH1F* HistoPlot::set_ratio_error_bars(TH1F* ratio_histo, TH1F* data_histo, TH1F* bg_histo)
{
int nbins = ratio_histo->GetNbinsX();
for(int i = 0; i < nbins; i++)
{
double error_val = std::pow(get_data_error(data_histo, i), 0.5) / get_data_error(bg_histo, i);
ratio_histo->SetBinError(i, error_val);
}
return ratio_histo;
}
TH1F* HistoPlot::set_error_bars(TH1F* histo)
{
int nbins = histo->GetNbinsX();
for(int i = 0; i < nbins; i++) {
double error_val = std::pow(get_data_error(histo, i), 0.5);
histo->SetBinError(i, error_val);
}
return histo;
}
void HistoPlot::set_th1d_error_bars(TH1D* histo)
{
int nbins = histo->GetNbinsX();
for(int i = 0; i < nbins; i++) {
double error_val = std::pow(get_th1d_data_error(histo, i), 0.5);
histo->SetBinError(i, error_val);
}
}
float HistoPlot::get_data_error(TH1F* histo, int bin)
{
return histo->Integral(bin, bin + 1);
}
double HistoPlot::get_th1d_data_error(TH1D* histo, int bin)
{
return histo->Integral(bin, bin + 1);
}
std::string HistoPlot::build_file_name(Variable* variable, bool with_cut)
{
std::string file_name(variable->name);
if (with_cut)
{
file_name += "_cut_";
file_name.append((variable->bins_cut).c_str());
file_name += "_";
file_name.append(variable->x_min_cut);
file_name += "_";
file_name.append(variable->x_max_cut);
}
else
{
file_name += "_nocut_";
file_name.append(variable->bins_nocut);
file_name += "_";
file_name.append(variable->x_min_nocut);
file_name += "_";
file_name.append(variable->x_max_nocut);
}
file_name += ".png";
return file_name;
}
std::string HistoPlot::build_signal_leg_entry(Variable* var, DataChain* signal_chain)
{
std::string signal_leg_str(signal_chain->legend);
signal_leg_str += " (x";
signal_leg_str.append(var->signal_multiplier);
signal_leg_str += ")";
return signal_leg_str;
}
<file_sep>/include/mlp_analysis.h
#ifndef Mlp_Analysis_h
#define Mlp_Analysis_h
#include "../include/histo_plot.h"
#include "../include/mc_weights.h"
#include <cstdlib>
#include "TObjString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TStopwatch.h"
#include "TMVA/Factory.h"
#include "TMVA/Tools.h"
#include "TMVA/Reader.h"
#include "TMVA/MethodCuts.h"
class MLPAnalysis
{
public:
static TFile* create_MLP(DataChain* bg_chain, DataChain* signal_chain, std::vector<Variable*>* variables,
std::string folder_name, const char* NeuronType, const char* NCycles, const char* HiddenLayers,
const char* LearningRate, std::string job_name);
static TTree* evaluate_MLP(DataChain* bg_chain, std::vector<Variable*>* variables, std::string output_name,
std::string job_name, bool unique_output_files);
static DataChain* get_MLP_results(DataChain* bg_chain, std::vector<Variable*>* variables, std::string output_name,
std::string job_name, bool unique_output_files);
static std::string MLP_options_str(const char* NeuronType, const char* NCycles, const char* HiddenLayers, const char* LearningRate);
static std::string MLP_output_name_str(const char* NeuronType, const char* NCycles,
const char* HiddenLayers, const char* LearningRate,
const char* bg_chain_label, std::string job_name);
static std::string MLP_output_file_path(std::string folder_name, std::string job_name, bool is_train_file,
const char* NeuronType, const char* NCycles, const char* HiddenLayers,
const char* LearningRate, const char* bg_chain_label);
};
#endif
<file_sep>/src/mva_analysis.cpp
#include "../include/mva_analysis.h"
#include "../include/bdt_analysis.h"
#include "../include/mlp_analysis.h"
void MVAAnalysis::get_plots_varying_params(std::vector<DataChain*> bg_chains, int bg_to_train, DataChain* signal_chain, DataChain* data_chain,
SuperVars* super_vars, std::string method_name, std::string dir_name,
std::vector<const char*> NTrees, std::vector<const char*> BoostType,
std::vector<const char*> AdaBoostBeta, std::vector<const char*> SeparationType,
std::vector<const char*> nCuts, std::vector<const char*> NeuronType, std::vector<const char*> NCycles,
std::vector<const char*> HiddenLayers, std::vector<const char*> LearningRate,
bool unique_output_files, bool create_cards, std::string job_name)
{
std::vector<const char*> file_paths = vary_parameters(bg_chains, bg_to_train, signal_chain, data_chain, super_vars, method_name, dir_name,
NTrees, BoostType, AdaBoostBeta, SeparationType, nCuts, NeuronType, NCycles, HiddenLayers,
LearningRate, unique_output_files, create_cards, job_name);
std::vector<TFile*> files = get_files_from_paths(file_paths);
std::string bg_label = bg_chains[bg_to_train]->label;
std::string folder_name = "analysis/" + method_name + "_varying_" + dir_name + "/" + bg_label + "/";
std::cout << "=> Set Folder Name: " << folder_name << std::endl;
std::vector<Variable*> variables = super_vars->get_signal_cut_vars();
//ClassifierOutputs::plot_classifiers_for_all_files(files, method_name, folder_name, bg_chains[bg_to_train]->label);
RocCurves::get_rocs(files, signal_chain, bg_chains[bg_to_train], super_vars, method_name, folder_name);
}
std::vector<TFile*> MVAAnalysis::get_files_from_paths(std::vector<const char*> file_paths)
{
TFile* files_arr[file_paths.size()];
for (int i = 0; i < file_paths.size(); i++)
{
files_arr[i] = TFile::Open(file_paths[i]);
}
std::vector<TFile*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
std::cout << "File paths size: " << file_paths.size() << std::endl;
std::cout << "files size: " << files.size() << std::endl;
return files;
}
TFile* MVAAnalysis::get_mva_results(std::vector<DataChain*> bg_chains, int bg_to_train, DataChain* signal_chain, DataChain* data_chain,
SuperVars* super_vars, std::string folder_name, std::string method_name, const char* NTrees,
const char* BoostType, const char* AdaBoostBeta,const char* SeparationType,const char* nCuts,
const char* NeuronType, const char* NCycles, const char* HiddenLayers, const char* LearningRate,
bool unique_output_files,
bool create_cards, std::string job_name, std::string mva_cut)
{
std::vector<Variable*> vars = super_vars->get_signal_cut_vars();
std::vector<Variable*> vars2 = super_vars->get_discriminating_vars();
std::string selection_str = super_vars->get_final_cuts_str();
TFile* trained_output;
const char* trained_bg_label = bg_chains[bg_to_train]->label;
std::string app_output_name = BDTAnalysis::BDT_output_file_path(folder_name, job_name, false,
NTrees, BoostType, AdaBoostBeta, SeparationType, nCuts,
trained_bg_label);
if (method_name == "BDT")
{
trained_output = BDTAnalysis::create_BDT(bg_chains[bg_to_train], signal_chain, &vars2, folder_name,
NTrees,BoostType,AdaBoostBeta, SeparationType, nCuts, job_name);
}
else if (method_name == "MLP")
{
trained_output = MLPAnalysis::create_MLP(bg_chains[bg_to_train], signal_chain, &vars2, folder_name,
NeuronType, NCycles, HiddenLayers, LearningRate, job_name);
}
std::cout << "=> Trained method " << method_name << ", output file: " << trained_output->GetName() << std::endl;
/*
std::vector<DataChain*> output_bg_chains = get_output_bg_chains(bg_chains, vars, method_name, app_output_name, job_name,
trained_bg_label, unique_output_files);
std::cout << "=> All background put through BDT" << std::endl;
DataChain* output_signal_chain = get_output_signal_chain(signal_chain, vars, method_name, app_output_name, job_name,
trained_bg_label, unique_output_files);
std::cout << "=> Signal put through BDT" << std::endl;
DataChain* output_data_chain = get_output_signal_chain(data_chain, vars, method_name, app_output_name, job_name,
trained_bg_label, unique_output_files);
std::cout << "=> Data put through BDT" << std::endl;
Variable* mva_output;
if (method_name == "BDT")
{
mva_output = new Variable("output","MVA Output","-1.0","1.0","-0.8","0.8","125","1", "", false);
}
else if (method_name == "MLP")
{
mva_output = new Variable("output","MVA Output","-1.25","1.5","-1.25","","100","1", "", false);
}
std::cout << "=> Declared MVA_Output Variable" << std::endl;
std::string output_graph_name = build_output_graph_name(trained_output, mva_cut);
std::cout << "mva output graph name: " << output_graph_name << std::endl;
HistoPlot::draw_plot(mva_output, output_bg_chains, output_signal_chain, output_data_chain, true, &vars, false,
output_graph_name, mva_cut);
if (create_cards) {create_datacards(output_data_chain, output_signal_chain, output_bg_chains,
mva_output, true, &vars, trained_output, method_name);}
std::cout << "=> Drew MVA Output plot for all backgrounds and signal" << std::endl;
std::cout << "Trained output name: "<< trained_output->GetName() << " " << trained_output << std::endl;
*/
return trained_output;
}
// creates datacards for a variety of output values
void MVAAnalysis::create_datacards(DataChain* output_data_chain, DataChain* output_signal_chain, std::vector<DataChain*> output_bg_chains,
Variable* mva_output, bool with_cut, std::vector<Variable*>* variables, TFile* trained_output,
std::string method_name)
{
if (method_name == "BDT")
{
std::string cut_arr[] = {"output>-0.8", "output>-0.7", "output>-0.6", "output>-0.5", "output>-0.4", "output>-0.3", "output>-0.2",
"output>-0.1", "output>0.0", "output>0.1", "output>0.2", "output>0.3", "output>0.4", "output>0.5",
"output>0.6","output>0.7", "output>0.8", "output>0.9"};
for (int i = 0; i < sizeof(cut_arr)/sizeof(cut_arr[0]); i++)
{
std::string output_graph_name = build_output_graph_name(trained_output, cut_arr[i]);
DataCard::create_datacard(output_data_chain, output_signal_chain, output_bg_chains,
mva_output, true, variables, output_graph_name, cut_arr[i]);
}
}
else
{
std::string cut_arr[] = {"output>-1.5", "output>-1.4", "output>-1.3", "output>-1.2", "output>-1.1", "output>-1.0", "output>-0.8",
"output>-0.7", "output>-0.6", "output>-0.5", "output>-0.4", "output>-0.3", "output>-0.2",
"output>-0.1", "output>0.0", "output>0.1", "output>0.2", "output>0.3", "output>0.4", "output>0.5",
"output>0.6","output>0.7", "output>0.8", "output>0.9", "output>1.0", "output>1.1"};
for (int i = 0; i < sizeof(cut_arr)/sizeof(cut_arr[0]); i++)
{
std::string output_graph_name = build_output_graph_name(trained_output, cut_arr[i]);
DataCard::create_datacard(output_data_chain, output_signal_chain, output_bg_chains,
mva_output, true, variables, output_graph_name, cut_arr[i]);
}
}
}
// gets the name for the reader output Tfile
std::string MVAAnalysis::get_app_filename_for_chain(std::string app_output_name, const char* trained_bg_label, const char* app_label)
{
std::string app_label_str = app_label;
std::string trained_bg_label_str = trained_bg_label;
int last_trained_idx = app_output_name.rfind(trained_bg_label_str);
return app_output_name.replace(last_trained_idx, trained_bg_label_str.length(), app_label_str);
}
std::vector<DataChain*> MVAAnalysis::get_output_bg_chains(std::vector<DataChain*> bg_chains, std::vector<Variable*> vars,
std::string method_name, std::string app_output_name, std::string job_name,
const char* trained_bg_label, bool unique_output_files)
{
std::vector<DataChain*> output_bg_chains;
for (int i = 0; i < bg_chains.size(); i++)
{
DataChain* combined_output;
std::string real_app_output_name = get_app_filename_for_chain(app_output_name, trained_bg_label, bg_chains[i]->label);
if (method_name == "BDT")
{
combined_output = BDTAnalysis::get_BDT_results(bg_chains[i], &vars, real_app_output_name, job_name,
unique_output_files);
}
else if (method_name == "MLP")
{
combined_output = MLPAnalysis::get_MLP_results(bg_chains[i], &vars, real_app_output_name, job_name,
unique_output_files);
}
output_bg_chains.push_back(combined_output);
}
return output_bg_chains;
}
DataChain* MVAAnalysis::get_output_signal_chain(DataChain* signal_chain, std::vector<Variable*> vars, std::string method_name,
std::string app_output_name, std::string job_name, const char* trained_bg_label,
bool unique_output_files)
{
std::string real_app_output_name = get_app_filename_for_chain(app_output_name, trained_bg_label, signal_chain->label);
if (method_name == "BDT")
{
return BDTAnalysis::get_BDT_results(signal_chain, &vars, real_app_output_name, job_name, unique_output_files);
}
else
{
return MLPAnalysis::get_MLP_results(signal_chain, &vars, real_app_output_name, job_name, unique_output_files);
}
}
std::string MVAAnalysis::build_output_graph_name(TFile* trained_output, std::string mva_cut)
{
std::string file_name = trained_output->GetName();
if (mva_cut != "")
{
return HistoPlot::replace_all(file_name, ".root", mva_cut + ".png");
}
else
{
return HistoPlot::replace_all(file_name, ".root", "output_nocuts.png");
}
}
std::vector<const char*> MVAAnalysis::vary_parameters(std::vector<DataChain*> bg_chains, int bg_to_train, DataChain* signal_chain,
DataChain* data_chain, SuperVars* super_vars, std::string method_name,
std::string dir_name, std::vector<const char*> NTrees, std::vector<const char*> BoostType,
std::vector<const char*> AdaBoostBeta, std::vector<const char*> SeparationType,
std::vector<const char*> nCuts, std::vector<const char*> NeuronType,
std::vector<const char*> NCycles, std::vector<const char*> HiddenLayers,
std::vector<const char*> LearningRate,
bool unique_output_files, bool create_cards, std::string job_name)
{
std::string bg_label = bg_chains[bg_to_train]->label;
std::string folder_name = "analysis/" + method_name + "_varying_" + dir_name + "/" + bg_label;
if (method_name == "BDT")
{
if (dir_name == "NTrees")
{
const char* files_arr[NTrees.size()];
for (int i = 0; i < NTrees.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars, folder_name,
method_name, NTrees[i], BoostType[0], AdaBoostBeta[0], SeparationType[0], nCuts[0], NeuronType[0],
NCycles[0], HiddenLayers[0], LearningRate[0],
unique_output_files, create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "BoostType")
{
const char* files_arr[BoostType.size()];
for (int i = 0; i < BoostType.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0],
BoostType[i], AdaBoostBeta[0], SeparationType[0], nCuts[0], NeuronType[0],
NCycles[0], HiddenLayers[0], LearningRate[0],
unique_output_files, create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "AdaBoostBeta")
{
const char* files_arr[AdaBoostBeta.size()];
for (int i = 0; i < AdaBoostBeta.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0],
BoostType[0], AdaBoostBeta[i], SeparationType[0], nCuts[0], NeuronType[0],
NCycles[0], HiddenLayers[0], LearningRate[0],
unique_output_files, create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "SeparationType")
{
const char* files_arr[SeparationType.size()];
for (int i = 0; i < SeparationType.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0],
BoostType[0], AdaBoostBeta[0], SeparationType[i], nCuts[0], NeuronType[0],
NCycles[0], HiddenLayers[0], LearningRate[0], unique_output_files,
create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "nCuts")
{
const char* files_arr[nCuts.size()];
for (int i = 0; i < nCuts.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0],
BoostType[0], AdaBoostBeta[0], SeparationType[0], nCuts[i],
NeuronType[0], NCycles[0], HiddenLayers[0], LearningRate[0], unique_output_files,
create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
}
else if (method_name == "MLP")
{
if (dir_name == "NeuronType")
{
const char* files_arr[NeuronType.size()];
for (int i = 0; i < NeuronType.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0], BoostType[0],
AdaBoostBeta[0], SeparationType[0], nCuts[0], NeuronType[i], NCycles[0],
HiddenLayers[0], LearningRate[0], unique_output_files, create_cards, job_name, "");
const char* file_path = file->GetName();
std::cout << file_path << std::endl;
files_arr[i] = file_path;
std::cout << files_arr[i] << std::endl;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "NCycles")
{
const char* files_arr[NCycles.size()];
for (int i = 0; i < NCycles.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0], BoostType[0],
AdaBoostBeta[0], SeparationType[0], nCuts[0], NeuronType[0],
NCycles[i], HiddenLayers[0],LearningRate[0], unique_output_files, create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "HiddenLayers")
{
const char* files_arr[HiddenLayers.size()];
for (int i = 0; i < HiddenLayers.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0],
BoostType[0], AdaBoostBeta[0], SeparationType[0], nCuts[0],
NeuronType[0], NCycles[0], HiddenLayers[i], LearningRate[0], unique_output_files,
create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
else if (dir_name == "LearningRate")
{
const char* files_arr[LearningRate.size()];
for (int i = 0; i < LearningRate.size(); i++)
{
TFile* file = get_mva_results(bg_chains, bg_to_train, signal_chain, data_chain, super_vars,
folder_name, method_name, NTrees[0],
BoostType[0], AdaBoostBeta[0], SeparationType[0], nCuts[0],
NeuronType[0], NCycles[0], HiddenLayers[0], LearningRate[i], unique_output_files,
create_cards, job_name, "");
const char* file_path = file->GetName();
files_arr[i] = file_path;
}
std::vector<const char*> files (files_arr, files_arr + sizeof(files_arr) / sizeof(files_arr[0]));
return files;
}
}
}
//_________________________________________________________________________________________________________
//__________________ Unused methods from old TMVA classification attempt with categories __________________
TH1F* MVAAnalysis::plot_output(DataChain* combined_data)
{
combined_data->chain->Draw("output>>output_hist(100, -0.8, 0.8)");
TH1F* histo = (TH1F*)gDirectory->Get("output_hist");
return histo;
}
std::vector<double> MVAAnalysis::get_categories(TH1F* output_histo)
{
int first_bin = output_histo->FindFirstBinAbove(0.0, 1);
int zero_bin = output_histo->FindBin(0.0);
int last_bin = output_histo->FindLastBinAbove(0.0, 1);
double total_integral = output_histo->Integral(0, output_histo->GetNbinsX() + 1);
double tmp_integral_bg;
double tmp_integral_sig;
int bg_bin;
int sig_bin;
//bg
for (int i = zero_bin; i > first_bin; i--)
{
tmp_integral_bg = output_histo->Integral(first_bin, i);
bg_bin = i;
if ((tmp_integral_bg / total_integral) < 0.1)
{
break;
}
}
std::cout << "bg" << bg_bin << std::endl;
//sig
for (int i = zero_bin; i < last_bin; i++)
{
tmp_integral_sig = output_histo->Integral(i, last_bin);
sig_bin = i;
if ((tmp_integral_bg / total_integral) < 0.1)
{
break;
}
}
std::cout << "sig" << sig_bin << std::endl;
double bg_up_lim = output_histo->GetBinCenter(bg_bin);
double sig_low_lim = output_histo->GetBinCenter(sig_bin);
double x_arr[] = {-0.8, bg_up_lim, 0, sig_low_lim, 0.8};
std::cout << "bg_xmax" << bg_up_lim << std::endl;
std::cout << "sig_xmin" << sig_low_lim << std::endl;
std::vector<double> categories (x_arr, x_arr + sizeof(x_arr) / sizeof(x_arr[0]));
return categories;
}
std::vector<std::string> MVAAnalysis::get_category_strs(std::vector<double> categories)
{
std::string cat_strs[4];
for (int i = 0; i < 4; i++)
{
cat_strs[i] = "(output > " + HistoPlot::get_string_from_double(categories[i]) + ")&&(output <= " + HistoPlot::get_string_from_double(categories[i+1]) + ")";
}
std::vector<std::string> cat_strs_vector (cat_strs, cat_strs + sizeof(cat_strs) / sizeof(cat_strs[0]));
std::cout << "cat_strs_vector done" << cat_strs_vector[0] << std::endl;
return cat_strs_vector;
}
TH1F* MVAAnalysis::build_histo(DataChain* combined_output, std::string selection_str, Variable* variable, std::string histo_label)
{
std::string hist_label = combined_output->extra_label + histo_label;
std::string var_arg = variable->build_var_string(hist_label.c_str(), true);
combined_output->chain->Draw(var_arg.c_str(), selection_str.c_str(), "goff");
TH1F* histo = (TH1F*)gDirectory->Get(hist_label.c_str());
return histo;
}
std::string MVAAnalysis::build_output_sel_str(std::string category, std::string final_cuts)
{
std::string selection_str = final_cuts;
selection_str.insert(selection_str.find("(") + 1, category + "&&");
return selection_str;
}
TH1F* MVAAnalysis::draw_signal(DataChain* combined_output, std::string category, std::string final_cuts, Variable* variable)
{
combined_output->chain->SetLineColor(2);
combined_output->chain->SetLineWidth(3);
combined_output->chain->SetFillColor(0);
TH1F* histo = build_histo(combined_output, build_output_sel_str(category, final_cuts), variable, "signal");
return histo;
}
TH1F* MVAAnalysis::draw_background(DataChain* combined_output, std::string category, std::string final_cuts, Variable* variable)
{
combined_output->chain->SetLineColor(1);
combined_output->chain->SetFillColor(40);
TH1F* hist = build_histo(combined_output, build_output_sel_str(category, final_cuts), variable, "bg");
return hist;
}
void MVAAnalysis::style_histo(TH1F* histo)
{
histo->GetYaxis()->SetTitle("Events");
histo->GetYaxis()->SetLabelSize(0.035);
histo->GetYaxis()->SetTitleOffset(1.55);
histo->GetXaxis()->SetLabelSize(0);
histo->SetStats(kFALSE);
histo->SetTitle("");
}
void MVAAnalysis::draw_histo(DataChain* combined_output, std::string final_cuts, Variable* variable)
{
std::vector<std::string> category_strs = get_category_strs(get_categories(plot_output(combined_output)));
TLegend* legend = new TLegend(0.0, 0.5, 0.0, 0.88);
TCanvas* c1 = new TCanvas("c1", variable->name_styled, 800, 800);
TPad* p1 = new TPad("p1", "p1", 0.0, 0.95, 1.0, 1.0);
TPad* p2 = new TPad("p2", "p2", 0.0, 0.2, 1.0, 0.95);
TPad* p3 = new TPad("p3", "p3", 0.0, 0.0, 1.0, 0.2);
p1->SetLeftMargin(0.102);
p2->SetBottomMargin(0.012);
p2->SetLeftMargin(0.105);
p3->SetBottomMargin(0.3);
p3->SetLeftMargin(0.102);
p1->Draw();
p2->Draw();
p3->Draw();
p2->cd();
TH1F* very_sig = draw_signal(combined_output, category_strs[3], final_cuts, variable);
TH1F* very_bg = draw_background(combined_output, category_strs[0], final_cuts, variable);
legend->AddEntry(very_sig, "Signal (Top 10% of output)", "f");
legend->AddEntry(very_bg, "Background (Bottom 10% of output)", "f");
HistoPlot::style_legend(legend);
very_bg->Draw();
very_sig->Draw("SAME");
legend->Draw("SAME");
style_histo(very_bg);
style_histo(very_sig);
TH1F* plot_histos[2] = {very_sig, very_bg};
std::vector<TH1F*> plot_histos_vector (plot_histos, plot_histos + sizeof(plot_histos) / sizeof(plot_histos[0]));
TH1F* max_histo = HistoPlot::get_max_histo(plot_histos_vector);
very_bg->SetMaximum(HistoPlot::get_histo_y_max(max_histo)*1.1);
HistoPlot::draw_subtitle(variable, NULL, true, combined_output, final_cuts);
p3->cd();
TH1F* data_bg_ratio_histo = HistoPlot::data_to_bg_ratio_histo(plot_histos[0], plot_histos[1]);
data_bg_ratio_histo->Draw("e1");
HistoPlot::style_ratio_histo(data_bg_ratio_histo, variable->name_styled);
HistoPlot::draw_yline_on_plot(variable, true, 1.0);
p1->cd();
HistoPlot::draw_title((combined_output->extra_label).c_str());
c1->SaveAs("output_test.png");
c1->Close();
}
<file_sep>/include/mva_analysis.h
#ifndef Mva_Analysis_h
#define Mva_Analysis_h
#include "roc_curves.h"
#include "classifier_outputs.h"
class MVAAnalysis
{
public:
static TH1F* plot_output(DataChain* combined_data);
static std::vector<double> get_categories(TH1F* output_histo);
static std::vector<std::string> get_category_strs(std::vector<double> categories);
static TH1F* build_histo(DataChain* combined_output, std::string selection_str, Variable* variable, std::string histo_label);
static std::string build_output_sel_str(std::string category, std::string final_cuts);
static TH1F* draw_signal(DataChain* combined_output, std::string category, std::string final_cuts, Variable* variable);
static TH1F* draw_background(DataChain* combined_output, std::string category, std::string final_cuts, Variable* variable);
static void style_histo(TH1F* histo);
static void draw_histo(DataChain* combined_output, std::string final_cuts, Variable* variable);
static std::vector<const char*> vary_parameters(std::vector<DataChain*> bg_chains, int bg_to_train, DataChain* signal_chain, DataChain* data_chain, SuperVars* super_vars,
std::string method_name, std::string dir_name, std::vector<const char*> NTrees, std::vector<const char*> BoostType,
std::vector<const char*> AdaBoostBeta, std::vector<const char*> SeparationType, std::vector<const char*> nCuts,
std::vector<const char*> NeuronType, std::vector<const char*> NCycles, std::vector<const char*> HiddenLayers,
std::vector<const char*> LearningRate, bool unique_output_files = false,
bool create_cards = false, std::string job_name = "1");
static void get_plots_varying_params(std::vector<DataChain*> bg_chains, int bg_to_train, DataChain* signal_chain, DataChain* data_chain, SuperVars* super_vars,
std::string method_name, std::string dir_name, std::vector<const char*> NTrees, std::vector<const char*> BoostType,
std::vector<const char*> AdaBoostBeta, std::vector<const char*> SeparationType, std::vector<const char*> nCuts,
std::vector<const char*> NeuronType, std::vector<const char*> NCycles, std::vector<const char*> HiddenLayers,
std::vector<const char*> LearningRate,
bool unique_output_files = false, bool create_cards = false, std::string job_name = "1");
static std::vector<TFile*> get_files_from_paths(std::vector<const char*> file_paths);
static std::string get_app_filename_for_chain(std::string app_output_name, const char* trained_bg_label, const char* app_label);
static TFile* get_mva_results(std::vector<DataChain*> bg_chains, int bg_to_train, DataChain* signal_chain, DataChain* data_chain,
SuperVars* super_vars, std::string folder_name, std::string method_name, const char* NTrees = "800",
const char* BoostType = "AdaBoost", const char* AdaBoostBeta = "0.2", const char* SeparationType = "GiniIndex",
const char* nCuts = "30", const char* NeuronType = "sigmoid", const char* NCycles = "500",
const char* HiddenLayers = "5,5,5,5", const char* LearningRate = "0.02",
bool unique_output_files = true, bool create_cards = true,
std::string job_name = "1", std::string mva_cut = "");
static void create_datacards(DataChain* output_data_chain, DataChain* output_signal_chain, std::vector<DataChain*> output_bg_chains,
Variable* mva_output, bool with_cut, std::vector<Variable*>* variables, TFile* trained_output,
std::string method_name);
static std::vector<DataChain*> get_output_bg_chains(std::vector<DataChain*> bg_chains, std::vector<Variable*> vars, std::string method_name,
std::string app_output_name, std::string job_name, const char* trained_bg_label,
bool unique_output_files);
static DataChain* get_output_signal_chain(DataChain* signal_chain, std::vector<Variable*> vars, std::string method_name,
std::string app_output_name, std::string job_name, const char* trained_bg_label,
bool unique_output_files);
static std::string build_output_graph_name(TFile* trained_output, std::string mva_cut = "");
};
#endif
<file_sep>/src/main.cpp
#include <initializer_list>
#include <cmath>
#include "../include/mva_analysis.h"
//#include "../include/mlp_analysis.h"
void produce_graphs(bool with_cut) {
SuperVars* super_vars = new SuperVars();
std::vector<Variable*> vars = super_vars->get_discriminating_vars();
std::vector<Variable*> cut_vars = super_vars->get_signal_cut_vars();
SuperChains* super_chains = new SuperChains();
std::vector<DataChain*> bg_chains = super_chains->get_bg_chains();
DataChain* signal_chain = super_chains->signal_chain;
DataChain* data_chain = super_chains->data_chain;
const char* mva_type = "BDT";
// the topmost folder for all root files so gitignore ignores properly
std::string top_folder_name = "analysis";
//const char* varying_params[] = {"NTrees", "AdaBoostBeta", "nCuts", "SeparationType"};
const char* varying_params[] = {"HiddenLayers", "NCycles", "LearningRate"};
// boolean is for whether or not to create separate output app files
bool unique_output_files = false;
// boolean is for whether or not to create datacards
bool create_cards = false;
MVAAnalysis::get_mva_results(bg_chains, 6, signal_chain, data_chain, super_vars, "test", "BDT", NTrees[0], BoostType[0], AdaBoostBeta[0],
SeparationType[0], nCuts[0], NeuronType[0], NCycles[0],
HiddenLayers[0], LearningRate[0], unique_output_files, create_cards, "1", "");
/*
for (int i = 6; i < bg_chains.size(); i++)
{
for (int j = 0; j < 3; j++)
{
MVAAnalysis::get_plots_varying_params(bg_chains, i, signal_chain, data_chain, super_vars, "MLP", varying_params[j],
NTrees, BoostType, AdaBoostBeta, SeparationType, nCuts, NeuronType, NCycles,
HiddenLayers, LearningRate, unique_output_files, create_cards, "1");
const char* NeuronType2_arr[] = {"tanh","sigmoid"};
std::vector<const char*> NeuronType2 (NeuronType2_arr, NeuronType2_arr +
sizeof(NeuronType2_arr)/sizeof(const char*));
MVAAnalysis::get_plots_varying_params(bg_chains, i, signal_chain, data_chain, super_vars, "MLP", varying_params[j],
NTrees, BoostType, AdaBoostBeta, SeparationType, nCuts, NeuronType2, NCycles,
HiddenLayers, LearningRate, unique_output_files, create_cards, "1");
}
}*/
}
int main(int argc, char** argv) {
TApplication theApp("tapp", &argc, argv);
produce_graphs(true);
theApp.Run();
return 0;
}
<file_sep>/create_BDT_directory_tree.sh
#!/bin/bash
declare -a NTrees=("NTrees=10" "NTrees=20" "NTrees=40" "NTrees=60" "NTrees=80" "NTrees=100")
declare -a BGs=("bg_qcd" "bg_zll" "bg_wjets_ev" "bg_wjets_muv" "bg_wjets_tauv" "bg_top" "bg_vv" "bg_zjets_vv")
declare -a SeparationType=("SeparationType=GiniIndex" "SeparationType=CrossEntropy"
"SeparationType=MisClassificationError" "SeparationType=SDivSqrtSPlusB")
declare -a AdaBoostBeta=("AdaBoostBeta=0.1" "AdaBoostBeta=0.2" "AdaBoostBeta=0.4"
"AdaBoostBeta=0.5" "AdaBoostBeta=0.6" "AdaBoostBeta=0.8")
declare -a nCuts=("nCuts=5" "nCuts=7" "nCuts=10" "nCuts=12" "nCuts=15" "nCuts=20")
declare -a params=("NTrees" "SeparationType" "AdaBoostBeta" "nCuts")
# Create directory "analysis" if it doesn't exist
if [ ! -d "$analysis" ]; then
echo "Creating directory analysis..."
mkdir analysis
fi
# Loop through params, create directories in analysis
for i in "${params[@]}"
do
if [ ! -d "analysis/BDT_varying_$i" ]; then
echo "Creating directory analysis/BDT_varying_$i..."
mkdir analysis/BDT_varying_$i
else
echo "Directory $i already exists."
fi
for j in "${BGs[@]}"
do
if [ ! -d "analysis/BDT_varying_$i/$j" ]; then
echo "Creating directory analysis/BDT_varying_$i/$j..."
mkdir analysis/BDT_varying_$i/$j
else
echo "Directory analysis/BDT_varying_$i/$j already exists."
fi
done
done<file_sep>/create_MLP_directory_tree.sh
#!/bin/bash
declare -a BGs=("bg_qcd" "bg_zll" "bg_wjets_ev" "bg_wjets_muv" "bg_wjets_tauv" "bg_top" "bg_vv" "bg_zjets_vv")
declare -a params=("HiddenLayers" "NCycles" "LearningRate")
# Create directory "analysis" if it doesn't exist
if [ ! -d "$analysis" ]; then
echo "Creating directory analysis..."
mkdir analysis
fi
# Loop through params, create directories in analysis
for i in "${params[@]}"
do
if [ ! -d "analysis/MLP_varying_$i" ]; then
echo "Creating directory analysis/MLP_varying_$i..."
mkdir analysis/MLP_varying_$i
else
echo "Directory $i already exists."
fi
for j in "${BGs[@]}"
do
if [ ! -d "analysis/MLP_varying_$i/$j" ]; then
echo "Creating directory analysis/MLP_varying_$i/$j..."
mkdir analysis/MLP_varying_$i/$j
else
echo "Directory analysis/MLP_varying_$i/$j already exists."
fi
done
done<file_sep>/src/mc_weights.cpp
#include "../include/mc_weights.h"
std::string MCWeights::get_mc_selection_str(DataChain* bg_chain, Variable* variable,
std::vector<Variable*>* variables, std::string mva_cut)
{
std::string selection_str = variable->build_multicut_selection(false, variables);
if (bg_chain->lep_sel != "")
{
selection_str.insert(selection_str.find("(") + 1, bg_chain->lep_sel);
}
if (selection_str.find("(&&", 0) == 0)
{
selection_str.erase(1, 2);
}
// This function below checks to see if mva_cut != ""
selection_str = HistoPlot::add_mva_cut_to_selection(selection_str, mva_cut);
std::cout << "Selection str in get_mc_select_str: " << selection_str << std::endl;
return selection_str;
}
double MCWeights::get_nevents(DataChain* data_chain, Variable* var, bool with_cut, std::vector<Variable*>* variables,
std::string selection)
{
return HistoPlot::get_histo_integral(HistoPlot::build_1d_histo(data_chain, var, with_cut, false, "goff", variables,
selection), with_cut, var);
}
double MCWeights::get_all_bg_in_ctrl(std::vector<DataChain*> bg_chains, Variable* var, bool with_cut,
std::vector<Variable*>* variables, std::string selection)
{
double total_integral = 0.0;
for (int i = 0; i < bg_chains.size(); i++)
{
total_integral += get_nevents(bg_chains[i], var, with_cut, variables, selection);
}
return total_integral;
}
double MCWeights::calc_mc_weight(DataChain* data, std::vector<DataChain*> bg_chains, DataChain* bg_chain,
Variable* var, bool with_cut, std::vector<Variable*>* variables, std::string mva_cut)
{
std::string selection = get_mc_selection_str(bg_chain, var, variables, mva_cut);
double data_in_ctrl = get_nevents(data, var, with_cut, variables, selection);
double ctrl_mc_in_ctrl = get_nevents(bg_chain, var, with_cut, variables, selection);
double other_bg_in_ctrl = get_all_bg_in_ctrl(bg_chains, var, with_cut, variables, selection) - ctrl_mc_in_ctrl;
return (data_in_ctrl - other_bg_in_ctrl) / ctrl_mc_in_ctrl;
}
double MCWeights::calc_weight_error(DataChain* data, std::vector<DataChain*> bg_chains, DataChain* bg_chain,
Variable* var, bool with_cut, std::vector<Variable*>* variables, std::string mva_cut)
{
std::string selection = get_mc_selection_str(bg_chain, var, variables, mva_cut);
double data_N_C = get_nevents(data, var, with_cut, variables, selection);
double MC_N_C = get_nevents(bg_chain, var, with_cut, variables, selection);
double bg_N_C = get_all_bg_in_ctrl(bg_chains, var, with_cut, variables, selection) - MC_N_C;
double sigma_data_N_C = std::pow(data_N_C, 0.5);
double sigma_MC_N_C = std::pow(MC_N_C, 0.5);
double sigma_bg_N_C = std::pow(bg_N_C, 0.5);
double err1 = sigma_data_N_C/MC_N_C;
double err2 = sigma_bg_N_C/MC_N_C;
double err3 = (data_N_C- bg_N_C)/(pow(MC_N_C,1.5));
double error_sq = std::pow(err1,2) + std::pow(err2,2) + std::pow(err3,2);
double weight_error = std::pow(error_sq, 0.5);
return weight_error;
}
| bbc3b38782da8c71db3c5e152ea1a65755501b1a | [
"C++",
"Shell"
] | 8 | C++ | annikamonari/ICMSciThesisHiggsInv-2 | 1d1b2e62f2fec2105b6ccdaacf34bb0a126676ae | dd08d4b1709d0504b761ee6e37af690e94339be6 |
refs/heads/master | <repo_name>Patrick-Libardo/Patrick-Libardo.github.io<file_sep>/calculadora/js/main.js
var numero = "";
var displayBuffer = "";
var termos = [undefined,undefined,undefined];
var resultado = undefined;
function pressNum (num) {
numero = numero.concat(num.innerHTML);
mostrarDisplay(num.innerHTML);
}
function pressOperador (op) {
if(termos[1] == undefined) {
termos[0] = numero;
termos[1] = op.innerHTML;
mostrarDisplay(op.innerHTML);
numero = "";
}
}
function pressEqual () {
if(termos[0] != undefined && termos[1] != undefined && numero != "") {
var esperarResultado;
termos[2] = numero;
switch(termos[1]) {
case ' + ':
resultado = Number(termos[0]) + Number(termos[2]);
break;
case ' - ':
resultado = Number(termos[0]) - Number(termos[2]);
break;
case ' * ':
resultado = Number(termos[0]) * Number(termos[2]);
break;
case ' / ':
resultado = Number(termos[0]) / Number(termos[2]);
break;
}
esperarResultado = resultado;
limparDisplay();
mostrarDisplay(resultado);
limparMemoria();
numero = esperarResultado.toString();
}
}
function limparMemoria() {
numero = "";
termos = [undefined, undefined, undefined];
resultado = undefined;
}
function limparDisplay() {
displayBuffer = "";
var tela = document.getElementById('display');
tela.value = displayBuffer;
}
function limparTudo() {
limparDisplay();
limparMemoria();
}
function mostrarDisplay (conteudo) {
displayBuffer = displayBuffer.concat(conteudo);
var tela = document.getElementById('display');
tela.value = displayBuffer;
}<file_sep>/README.md
# Patrick-Libardo.github.io
WebSite didático de treinamento em WebDesign
| 9af2698ce5b84e057f08faa90420370218c463a9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Patrick-Libardo/Patrick-Libardo.github.io | 1ab56c7f93815b1cbaab88fabe9eff9eba5bae4a | c4357d84102f0e176c22b92ac5d70b96e04ef215 |
refs/heads/master | <file_sep>package leetcode;
import org.junit.Test;
/**
* @author luochong
* @date 2019/8/5 13:34
*/
public class Dome4 {
@Test
public void test() {
int[] nums1 = {};
int[] nums2 = {1, 2, 3, 4};
double response = new Solution().findMedianSortedArrays(nums1, nums2);
System.out.println(response);
}
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// 让长数组在前面
if (nums1.length < nums2.length) {
// return this.findMedianSortedArrays(nums2, nums1);
int[] tem = nums1;
nums1 = nums2;
nums2 = tem;
}
int m = nums1.length, n = nums2.length;
int h = (m + n + 1) / 2, i = 0, j = h - i, li = 0, ri = n;
while (li < ri) {
i = (ri + li) / 2;
j = h - i;
if (nums2[i] < nums1[j - 1]) {
j = h - (li = ++i);
} else {
ri = i;
}
}
double leftValue = Math.max(i <= 0 ? 0 : nums2[i - 1], j <= 0 ? 0 : nums1[j - 1]);
if ((m + n) % 2 == 1) {
return leftValue;
}
double rightValue = Math.min(i >= n ? nums1[j] : nums2[i], j >= m ? nums2[i] : nums1[j]);
return (leftValue + rightValue) / 2;
}
}
}
<file_sep>package leetcode;
import java.util.Arrays;
/**
* @author luochong
* @date 2019/8/2 10:59
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
*/
public class Dome1 {
public static void main(String[] args) {
int[] nums = new int[]{230,863,916,585,981,404,316,785,88,12,70,435,384,778,887,755,740,337,86,92,325,422,815,650,920,125,277,336,221,847,168,23,677,61,400,136,874,363,394,199,863,997,794,587,124,321,212,957,764,173,314,422,927,783,930,282,306,506,44,926,691,568,68,730,933,737,531,180,414,751,28,546,60,371,493,370,527,387,43,541,13,457,328,227,652,365,430,803,59,858,538,427,583,368,375,173,809,896,370,789};
int target = 542;
System.out.println(Arrays.toString(new Solution().twoSum(nums, target)));
}
static class Solution {
public int[] twoSum(int[] nums, int target) {
int indexArrayMax = 2047;
int[] indexArray = new int[indexArrayMax + 1];
int diff;
for (int i=0; i<nums.length; i++) {
diff = target - nums[i];
if (indexArray[diff & indexArrayMax] != 0) {
return new int[]{indexArray[diff & indexArrayMax] - 1, i};
}
indexArray[nums[i] & indexArrayMax] = i + 1;
}
return null;
}
}
}
| e35d408a8016fb61bcf480f84aca6fb5747c3a2b | [
"Java"
] | 2 | Java | herding-wolf/Leetcode | 5dead455a42013fa02914e6b5807a9c800fb0c36 | 740e742a5c7dc3e819de96fbec2be574a47a14f2 |
refs/heads/master | <repo_name>Cliff-Hsieh/Spider<file_sep>/README.md
# Spider
## use python crawler get MLB player data
<file_sep>/build/lib/players/spiders/player.py
# -*- coding: utf-8 -*-
import scrapy
import urlparse
from scrapy.http.request import Request
from scrapy.selector import Selector
class PlayerSpider(scrapy.Spider):
name = "player"
allowed_domains = ["sports.yahoo.com"]
start_urls = ['http://sports.yahoo.com/mlb/teams/chc/roster/']
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//div[@class="D(ib) Va(m) Py(cell-padding-y)"]/a/@href').extract()
for site in sites:
if 'http://' not in site:
site = response.urljoin(site)
yield Request( site, callback=self.parse_detail_page)
def parse_detail_page(self, response):
item = playerProp()
item['name'] = response.xpath('//span[@data-reactid="10"]/text()').extract()
item['team'] = response.xpath('//div[@data-reactid="21"]/a[@data-reactid="22"]/text()').extract()
item['num'] = response.xpath('//span[@data-reactid="16"]/text()').extract()[0].split("#")[1]
item['pos'] = response.xpath('//span[@data-reactid="18"]/text()').extract()[0]
pitcher = ["SP", "RP"]
if item['pos'] not in pitcher:
item['avg'] = response.xpath('//div[@data-reactid="26"]/text()').extract()
item['hr'] = response.xpath('//div[@data-reactid="29"]/text()').extract()
item['rbi'] = response.xpath('//div[@data-reactid="32"]/text()').extract()
item['run'] = response.xpath('//div[@data-reactid="35"]/text()').extract()
else:
item['win'] = response.xpath('//div[@data-reactid="26"]/text()').extract()
item['era'] = response.xpath('//div[@data-reactid="32"]/text()').extract()
item['so'] = response.xpath('//div[@data-reactid="35"]/text()').extract()
item['bb'] = response.xpath('//div[@data-reactid="38"]/text()').extract()
yield item
class playerProp(scrapy.Item):
name = scrapy.Field()
team = scrapy.Field()
num = scrapy.Field()
pos = scrapy.Field()
avg = scrapy.Field()
hr = scrapy.Field()
rbi = scrapy.Field()
run = scrapy.Field()
win = scrapy.Field()
era = scrapy.Field()
so = scrapy.Field()
bb = scrapy.Field()
| 5327fc2a58d6a385a403936bbe0025511ee1ced9 | [
"Markdown",
"Python"
] | 2 | Markdown | Cliff-Hsieh/Spider | 2552c957ed808ec6c43b1a579db4120efc2b372e | dd981980a5f43080b6d96f640194e10b803be8dc |
refs/heads/master | <file_sep>#' List files/folders
#'
#' @export
#' @param route Route to a FTP folder on the CMIP site
#' @return A \code{tibble}
#' @examples \dontrun{
#' cmip_list_files()
#' cmip_list_files('bcsd')
#' cmip_list_files('bcsd/yearly')
#' cmip_list_files('bcsd/yearly/cccma_cgcm3_1.1')
#' cmip_list_files('cmip5')
#' cmip_list_files('cmip5/bcsd')
#' cmip_list_files('cmip5/bcsd/regrid')
#' cmip_list_files('cmip5/bcsd/regrid/ccsm4')
#' cmip_list_files('cmip5/bcsd/regrid/ccsm4/rcp26')
#' cmip_list_files('cmip5/bcsd/regrid/ccsm4/rcp26/mon')
#' cmip_list_files('cmip5/bcsd/regrid/ccsm4/rcp26/mon/r3i1p1')
#' cmip_list_files('cmip5/bcsd/regrid/ccsm4/rcp26/mon/r3i1p1/tas')
#' cmip_list_files('wwcra/monthly/riog/')
#' cmip_list_files('wwcra/monthly/riog/sresb1.mpi_echam5.3/tmax')
#' }
cmip_list_files <- function(route = NULL) {
assert(route, "character")
res <- cmip_GET_list(make_path(route))
parse_file(res)
}
cmip_GET_list <- function(route) {
x <- curl::curl(route)
on.exit(close(x))
readLines(x)
}
parse_file <- function(x) {
tt <- utils::read.delim(text = paste0(x, collapse = "\n"), sep = "",
header = FALSE, skip = 1, stringsAsFactors = FALSE)
as_tbl(data.frame(
date = as.Date(unname(apply(tt[,6:8], 1, paste0, collapse = "-")),
"%b-%d-%Y"),
file = tt[,NCOL(tt)],
stringsAsFactors = FALSE
))
}
<file_sep>cmip_cache <- NULL
.onLoad <- function(libname, pkgname){
x <- hoardr::hoard()
x$cache_path_set("cmipr")
cmip_cache <<- x
}
<file_sep>#' cmipr
#'
#' R client for CMIP (Coupled Model Intercomparison Project) data
#'
#' @name cmipr-package
#' @aliases cmipr
#' @docType package
#' @author <NAME> \email{<EMAIL>}
#' @keywords package
NULL
<file_sep>#' Fetch data
#'
#' @export
#' @param route Route to a folder, a character string
#' @param overwrite (logical) Whether to overwrite files if they already
#' exist on your machine. Default: \code{FALSE}
#' @details Note that data is not read into R as data can be very large.
#' See \code{\link{cmip_read}}
#' @return A character vector of full file paths. A print method makes a tidy
#' return object
#' @examples \dontrun{
#' key <- "<KEY>"
#' (res <- cmip_fetch(key))
#' cmip_read(res)
#' }
cmip_fetch <- function(route, overwrite = FALSE) {
assert(overwrite, "logical")
res <- cache_data(route, cache = TRUE, overwrite = overwrite)
structure(res, class = "cmip_file")
}
#' @export
print.cmip_file <- function(x, ...) {
cat("<CMIP file>", sep = "\n")
cat(paste0(" File: ", x[1]), sep = "\n")
cat(sprintf(" File size: %s MB", file.info(x)$size / 1000000L), sep = "\n")
}
<file_sep>#' Manage cached CMIP files
#'
#' @export
#' @name cmip_cache
#'
#' @details \code{cache_delete} only accepts 1 file name, while
#' \code{cache_delete_all} doesn't accept any names, but deletes all files.
#' For deleting many specific files,
#' use \code{cache_delete} in a \code{\link{lapply}} type call
#'
#' We cache using \pkg{hoardr} for managing cached files. Find where
#' files are being cached with \code{cmip_cache$cache_path_get()}
#'
#' @section Functions:
#' \itemize{
#' \item \code{cmip_cache$list()} returns a character vector of full path file
#' names
#' \item \code{cmip_cache$delete()} deletes one or more files, returns nothing
#' \item \code{cmip_cache$delete_all()} delete all files, returns nothing
#' \item \code{cmip_cache$details()} prints file name and file size for each
#' file, supply with one or more files, or no files (and get details for
#' all available)
#' }
#'
#' @examples \dontrun{
#' cmip_cache
#'
#' # list files in cache
#' cmip_cache$list()
#'
#' # List info for single files
#' allfiles <- cmip_cache$list()
#' cmip_cache$details(files = allfiles[1])
#' cmip_cache$details(files = allfiles[2])
#'
#' # List info for all files
#' cmip_cache$details()
#'
#' # delete files by name in cache
#' # cmip_cache$delete(files = allfiles[1])
#' # cmip_cache$list()
#'
#' # delete all files in cache
#' # cmip_cache$delete_all()
#' # cmip_cache$list()
#' }
NULL
<file_sep>#' Manage cached CMIP files
#'
#' @export
#' @name cmip_cache
#' @param files (character) one or more complete file names
#' @param force (logical) Should files be force deleted? Default: \code{TRUE}
#'
#' @details \code{cache_delete} only accepts 1 file name, while
#' \code{cache_delete_all} doesn't accept any names, but deletes all files.
#' For deleting many specific files,
#' use \code{cache_delete} in a \code{\link{lapply}} type call
#'
#' We cache using \code{\link[rappdirs]{user_cache_dir}}, find your
#' cache folder by executing \code{rappdirs::user_cache_dir("cmip")}
#'
#' @section Functions:
#' \itemize{
#' \item \code{cmip_cache_list()} returns a character vector of full path file
#' names
#' \item \code{cmip_cache_delete()} deletes one or more files, returns nothing
#' \item \code{cmip_cache_delete_all()} delete all files, returns nothing
#' \item \code{cmip_cache_details()} prints file name and file size for each
#' file, supply with one or more files, or no files (and get details for
#' all available)
#' }
#'
#' @examples \dontrun{
#' # list files in cache
#' cmip_cache_list()
#'
#' # List info for single files
#' cmip_cache_details(files = cmip_cache_list()[1])
#' cmip_cache_details(files = cmip_cache_list()[2])
#'
#' # List info for all files
#' cmip_cache_details()
#'
#' # delete files by name in cache
#' # cmip_cache_delete(files = cmip_cache_list()[1])
#'
#' # delete all files in cache
#' # cmip_cache_delete_all()
#' }
#' @export
#' @rdname cmip_cache
cmip_cache_list <- function() {
list.files(cmip_cache_path(), ignore.case = TRUE, include.dirs = TRUE,
recursive = TRUE, full.names = TRUE)
}
#' @export
#' @rdname cmip_cache
cmip_cache_delete <- function(files, force = TRUE) {
if (!all(file.exists(files))) {
stop("These files don't exist or can't be found: \n",
strwrap(files[!file.exists(files)], indent = 5), call. = FALSE)
}
unlink(files, force = force, recursive = TRUE)
}
#' @export
#' @rdname cmip_cache
cmip_cache_delete_all <- function(force = TRUE) {
files <- list.files(cmip_cache_path(), ignore.case = TRUE,
include.dirs = TRUE, full.names = TRUE, recursive = TRUE)
unlink(files, force = force, recursive = TRUE)
}
#' @export
#' @rdname cmip_cache
cmip_cache_details <- function(files = NULL) {
if (is.null(files)) {
files <- list.files(cmip_cache_path(), ignore.case = TRUE,
include.dirs = TRUE, full.names = TRUE,
recursive = TRUE)
structure(lapply(files, file_info_), class = "cmip_cache_info")
} else {
structure(lapply(files, file_info_), class = "cmip_cache_info")
}
}
file_info_ <- function(x) {
if (file.exists(x)) {
fs <- file.size(x)
} else {
fs <- type <- NA
x <- paste0(x, " - does not exist")
}
list(file = x,
type = "nc",
size = if (!is.na(fs)) getsize(fs) else NA
)
}
getsize <- function(x) {
round(x/10 ^ 6, 3)
}
#' @export
print.cmip_cache_info <- function(x, ...) {
cat("<cmip cached files>", sep = "\n")
cat(sprintf(" directory: %s\n", cmip_cache_path()), sep = "\n")
for (i in seq_along(x)) {
cat(paste0(" file: ", sub(cmip_cache_path(), "", x[[i]]$file)), sep = "\n")
cat(paste0(" size: ", x[[i]]$size, if (is.na(x[[i]]$size)) "" else " mb"),
sep = "\n")
cat("\n")
}
}
<file_sep>#' Read data into R
#'
#' @export
#' @param x A \code{ccafs_files} object, the output from a call to
#' \code{\link{cmip_fetch}}
#' @return \code{RasterLayer} or \code{RasterBrick} class object
#' @examples \dontrun{
#' key <- "<KEY>"
#' res <- cmip_fetch(key)
#'
#' # a single file
#' cmip_read(res)
#'
#' # character path input
#' ## you can also pass in a path to a file(s)
#' cmip_read(res[1])
#'
#' # plot data
#' plot(cmip_read(res))
#' }
cmip_read <- function(x) {
UseMethod("cmip_read")
}
#' @export
cmip_read.default <- function(x) {
stop("no 'cmip_read' method for class ", class(x), call. = FALSE)
}
#' @export
cmip_read.cmip_file <- function(x) {
cmip_read(unclass(x))
}
#' @export
cmip_read.character <- function(x) {
stopifnot(all(file.exists(c(x, x))))
if (length(x) == 1) {
raster::raster(x)
} else if (length(x) > 1) {
raster::brick(as.list(x))
} else {
stop("input had length zero", call. = FALSE)
}
}
<file_sep># cache data
cache_data <- function(key, cache = TRUE, overwrite = FALSE) {
cmip_cache$mkdir()
file <- file.path(cmip_cache$cache_path_get(), basename(key))
if (!file.exists(file)) {
suppressMessages(cmip_GET_write(sub("/$", "", make_path(key)),
file, overwrite))
}
return(file)
}
<file_sep>#' raster::plot
#'
#' re-exported \code{plot} method from \code{raster} package to avoid failing
#' when trying to plot raster objects without having \code{raster} loaded
#' first.
#'
#' @name plot
#' @rdname plot
#' @keywords internal
#' @export
#' @importFrom raster plot
NULL
<file_sep><!--
%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{cmipr introduction}
%\VignetteEncoding{UTF-8}
-->
cmipr introduction
==================
`cmipr` - Client to work with CMIP data - downscaled climate and hydrology
projections. Package lists avail. files, downloads and caches, and reads
into raster objects.
## Install
Dev version
```r
devtools::install_github("ropenscilabs/cmipr")
```
```r
library("cmipr")
```
## List files
List files in their FTP directory
```r
cmip_list_files()
#> # A tibble: 9 × 2
#> date file
#> <date> <chr>
#> 1 2014-04-02 bcsd/1950-2099
#> 2 2014-04-02 bcsd/2deg
#> 3 2015-06-02
#> 4 2014-04-02
#> 5 2011-08-23
#> 6 0016-08-26
#> 7 2014-06-20
#> 8 2014-06-17
#> 9 2014-04-02 bcsd/yearly
```
```r
cmip_list_files('cmip5/bcsd')
#> # A tibble: 4 × 2
#> date file
#> <date> <chr>
#> 1 2014-03-28 BC
#> 2 2014-03-28 BCSD
#> 3 2014-03-28 SD_noBC
#> 4 2014-03-28 regrid
```
## Fetch data
Define a path to a file.
```r
key <- "<KEY>_cm3.1.sresa1b.monthly.Prcp.2034.nc"
```
Fetch the file
```r
(res <- cmip_fetch(key))
#> <CMIP file>
#> File: /Users/sacmac/Library/Caches/cmipr/cnrm_cm3.1.sresa1b.monthly.Prcp.2034.nc
#> File size: 4.93842 MB
```
### Caching
When requesting data, we first check if you already have that data cached.
You'll know when this happens as the request will finish much faster when
you have data cached already.
We use the package `hoardr` to manage cached files.
On package load, a hoardr object is created, it's an R6 object.
```r
cmip_cache
#> <hoard>
#> path: cmipr
#> cache path: /Users/sacmac/Library/Caches/cmipr
```
See `?cmip_cache` for all cache management help.
The `cmip_cache` object has variables and functions on it. For example,
we can get the cache path
```r
cmip_cache$cache_path_get()
#> [1] "/Users/sacmac/Library/Caches/cmipr"
```
Or list all files in the cache
```r
cmip_cache$list()
#> [1] "/Users/sacmac/Library/Caches/cmipr/cnrm_cm3.1.sresa1b.monthly.Prcp.2034.nc"
```
Or delete all files (won't run this here though)
```r
cmip_cache$delete_all()
```
## Read data
After fetching data, you need to read the data into a `RasterLayer` or
`RasterBrick` object
Get some data first
```r
keys <- c(
"bcsd/yearly/cnrm_cm3.1/cnrm_cm3.1.sresa1b.monthly.Prcp.2039.nc",
"bcsd/yearly/gfdl_cm2_1.1/gfdl_cm2_1.1.sresa1b.monthly.Prcp.2033.nc"
)
res <- lapply(keys, cmip_fetch)
```
You can read a single file
```r
cmip_read(res[[1]])
#> class : RasterLayer
#> band : 1 (of 12 bands)
#> dimensions : 222, 462, 102564 (nrow, ncol, ncell)
#> resolution : 0.125, 0.125 (x, y)
#> extent : -124.75, -67, 25.125, 52.875 (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#> data source : /Users/sacmac/Library/Caches/cmipr/cnrm_cm3.1.sresa1b.monthly.Prcp.2039.nc
#> names : Prcp
#> z-value : 2039-01-16
#> zvar : Prcp
```
many files
```r
cmip_read(unlist(res))
#> class : RasterBrick
#> dimensions : 222, 462, 102564, 24 (nrow, ncol, ncell, nlayers)
#> resolution : 0.125, 0.125 (x, y)
#> extent : -124.75, -67, 25.125, 52.875 (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#> data source : in memory
#> names : Prcp.1, Prcp.2, Prcp.3, Prcp.4, Prcp.5, Prcp.6, Prcp.7, Prcp.8, Prcp.9, Prcp.10, Prcp.11, Prcp.12, Prcp.13, Prcp.14, Prcp.15, ...
#> min values : 0.0000000000, 0.0014285714, 0.0000000000, 0.0000000000, 0.0000000000, 0.0000000000, 0.0000000000, 0.0010645161, 0.0000000000, 0.0000000000, 0.0000000000, 0.0018709678, 0.0648709685, 0.0221071430, 0.0000000000, ...
#> max values : 36.971066, 16.024536, 30.073355, 18.687033, 19.824322, 11.378433, 8.971000, 13.397967, 12.315033, 53.819515, 43.141335, 38.081871, 29.059355, 24.486929, 24.351355, ...
```
## Visualize
```r
library("raster")
plot(cmip_read(res[[1]]))
```

<file_sep><!--
%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{cmipr introduction}
%\VignetteEncoding{UTF-8}
-->
```{r echo=FALSE}
knitr::opts_chunk$set(
comment = "#>",
collapse = TRUE,
warning = FALSE,
message = FALSE,
fig.path = "img/"
)
```
cmipr introduction
==================
`cmipr` - Client to work with CMIP data - downscaled climate and hydrology
projections. Package lists avail. files, downloads and caches, and reads
into raster objects.
## Install
Dev version
```{r eval=FALSE}
devtools::install_github("ropenscilabs/cmipr")
```
```{r}
library("cmipr")
```
```{r echo=FALSE}
cmip_cache$delete_all()
```
## List files
List files in their FTP directory
```{r}
cmip_list_files()
```
```{r}
cmip_list_files('cmip5/bcsd')
```
## Fetch data
Define a path to a file.
```{r}
key <- "<KEY>"
```
Fetch the file
```{r}
(res <- cmip_fetch(key))
```
### Caching
When requesting data, we first check if you already have that data cached.
You'll know when this happens as the request will finish much faster when
you have data cached already.
We use the package `hoardr` to manage cached files.
On package load, a hoardr object is created, it's an R6 object.
```{r}
cmip_cache
```
See `?cmip_cache` for all cache management help.
The `cmip_cache` object has variables and functions on it. For example,
we can get the cache path
```{r}
cmip_cache$cache_path_get()
```
Or list all files in the cache
```{r}
cmip_cache$list()
```
Or delete all files (won't run this here though)
```{r eval=FALSE}
cmip_cache$delete_all()
```
## Read data
After fetching data, you need to read the data into a `RasterLayer` or
`RasterBrick` object
Get some data first
```{r}
keys <- c(
"bcsd/yearly/cnrm_cm3.1/cnrm_cm3.1.sresa1b.monthly.Prcp.2039.nc",
"bcsd/yearly/gfdl_cm2_1.1/gfdl_cm2_1.1.sresa1b.monthly.Prcp.2033.nc"
)
res <- lapply(keys, cmip_fetch)
```
You can read a single file
```{r}
cmip_read(res[[1]])
```
many files
```{r}
cmip_read(unlist(res))
```
## Visualize
```{r fig.width=10, fig.height=8}
library("raster")
plot(cmip_read(res[[1]]))
```
<file_sep>cmipr
=====
[](https://www.repostatus.org/#abandoned)
R client for CMIP (Coupled Model Intercomparison Project) data
> Under the [World Climate Research Programme (WCRP)](https://www.wcrp-climate.org/) the Working Group on Coupled Modelling (WGCM) established the Coupled Model Intercomparison Project (CMIP) as a standard experimental protocol for studying the output of coupled atmosphere-ocean general circulation models (AOGCMs). Virtually the entire international climate modeling community has participated in this project since its inception in 1995.
<file_sep>cmipr
=====
```{r echo=FALSE}
knitr::opts_chunk$set(
comment = "#>",
collapse = TRUE,
warning = FALSE,
message = FALSE,
fig.path = "inst/img/",
fig.width = 10,
fig.height = 6
)
```
[](https://travis-ci.org/ropenscilabs/cmipr)
[](https://codecov.io/gh/ropenscilabs/cmipr)
[](https://github.com/ropensci/onboarding/issues/99)
R client for CMIP (Coupled Model Intercomparison Project) data
> Under the [World Climate Research Programme (WCRP)](https://www.wcrp-climate.org/) the Working Group on Coupled Modelling (WGCM) established the Coupled Model Intercomparison Project (CMIP) as a standard experimental protocol for studying the output of coupled atmosphere-ocean general circulation models (AOGCMs). Virtually the entire international climate modeling community has participated in this project since its inception in 1995.
Links:
* CMIP (http://cmip-pcmdi.llnl.gov/)
* [CMIP Data available via FTP](http://gdo-dcp.ucllnl.org/downscaled_cmip_projections/dcpInterface.html#Projections:%20Complete%20Archives)
## Install
Development version
```{r eval=FALSE}
devtools::install_github("ropenscilabs/cmipr")
```
```{r}
library("cmipr")
```
## List files
```{r}
cmip_list_files('bcsd/yearly')
cmip_list_files('bcsd/yearly/cccma_cgcm3_1.1')
```
## Download data
```{r}
key <- "<KEY>"
(res <- cmip_fetch(key))
```
## Read data into R
Can load in a single file (gives `RasterLayer`), or many (gives `RasterBrick`)
```{r}
out <- cmip_read(res)
```
## Plot
```{r fig.cap=""}
plot(out)
```
## Meta
* Please [report any issues or bugs](https://github.com/ropenscilabs/cmipr/issues).
* License: MIT
* Get citation information for `cmipr` in R doing `citation(package = 'cmipr')`
* Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
[](https://ropensci.org)
<file_sep>context("cmip_fetch")
# key <- "<KEY>.1.sresa1b.monthly.Prcp.2035.nc"
key <- "bcsd/2deg/1950-2099/sresb1/sresb1.miub_echo_g.1.monthly.Tavg.RAW.1950-2099.nc" # nolint
test_that("cmip_fetch works", {
skip_on_cran()
cmip_cache$delete_all()
aa <- cmip_fetch(route = key)
expect_is(aa, "cmip_file")
expect_match(aa, ".nc")
expect_match(aa, "cmip")
expect_match(aa, "monthly")
})
test_that("cmip_fetch - fails well", {
skip_on_cran()
expect_error(cmip_fetch(), "argument \"route\" is missing")
expect_error(cmip_fetch("aasdf", overwrite = 5),
"overwrite must be of class logical")
})
<file_sep>context("cmip_list_files")
key <- "<KEY>"
test_that("cmip_list_files works", {
skip_on_cran()
res <- cmip_list_files()
expect_is(res, "tbl_df")
expect_is(res, "data.frame")
expect_named(res, c('date', 'file'))
aa <- cmip_list_files('bcsd/yearly')
bb <- cmip_list_files('cmip5/bcsd/regrid/ccsm4')
expect_is(aa, "tbl_df")
expect_is(aa, "data.frame")
expect_named(aa, c('date', 'file'))
expect_is(bb, "tbl_df")
expect_is(bb, "data.frame")
expect_named(bb, c('date', 'file'))
expect_gt(NROW(aa), NROW(bb))
})
test_that("cmip_list_files - fails well", {
skip_on_cran()
expect_error(cmip_list_files(5), "route must be of class character")
expect_error(cmip_list_files(mtcars), "route must be of class character")
})
<file_sep>cp <- function(x) Filter(Negate(is.null), x)
cmip_base <- function() "ftp://gdo-dcp.ucllnl.org/pub/dcp/archive/"
make_path <- function(x) {
tt <- paste0(cmip_base(), x)
if (!grepl("/$", tt)) paste0(tt, "/") else tt
}
last <- function(x) {
x[length(x)]
}
cmip_GET_write <- function(url, path, overwrite = TRUE, ...) {
cli <- crul::HttpClient$new(
url = url,
headers = list(Authorization = "Basic anonymous:<EMAIL>")
)
if (!overwrite) {
if (file.exists(path)) {
stop("file exists and ovewrite != TRUE", call. = FALSE)
}
}
res <- tryCatch(
cli$get(disk = path),
error = function(e) e
)
if (inherits(res, "error")) {
unlink(path)
stop(res$message, call. = FALSE)
}
return(res)
}
as_tbl <- function(x) tibble::as_tibble(x)
assert <- function(x, y) {
if (!is.null(x)) {
if (!class(x) %in% y) {
stop(deparse(substitute(x)), " must be of class ",
paste0(y, collapse = ", "), call. = FALSE)
}
}
}
<file_sep>context("cmip_cache")
key <- "<KEY>"
test_that("cmip_cache works", {
skip_on_cran()
expect_is(cmip_cache, "HoardClient")
expect_is(cmip_cache$cache_path_get, "function")
expect_is(cmip_cache$cache_path_set, "function")
expect_is(cmip_cache$cache_path_get(), 'character')
expect_is(cmip_cache$list(), 'character')
})
<file_sep>all: move rmd2md
move:
cp inst/vign/cmipr_vignette.md vignettes;\
cp -r inst/vign/img/ vignettes/img/
rmd2md:
cd vignettes;\
mv cmipr_vignette.md cmipr_vignette.Rmd
<file_sep>context("cmip_read")
#key <- "<KEY>"
key <- "bcsd/2deg/1950-2099/sresb1/sresb1.miub_echo_g.1.monthly.Tavg.RAW.1950-2099.nc" # nolint
test_that("cmip_read works", {
skip_on_cran()
cmip_cache$delete_all()
res <- cmip_fetch(key)
# cmip_file class
aa <- cmip_read(res)
expect_is(aa, "RasterLayer")
# character string, a path
bb <- cmip_read(res[[1]])
expect_is(bb, "RasterLayer")
expect_identical(cmip_read(res), cmip_read(res[[1]]))
})
test_that("cmip_read - fails well", {
skip_on_cran()
expect_error(cmip_read(), "argument \"x\" is missing")
expect_error(cmip_read("Adfadfs"), "is not TRUE")
})
<file_sep>library("testthat")
test_check("cmipr")
| c8d607bda83b28bac63e93d6aa3c0c60de26eb29 | [
"Markdown",
"R",
"RMarkdown",
"Makefile"
] | 20 | R | ropenscilabs/cmip | 4a9c8ac3b55eb16465d9497aa9c7fefe7cec363e | 16f3b6b1450afe1296291a830b21739553a47a2c |
refs/heads/master | <file_sep>using Microsoft.Win32;
using System;
using System.Windows;
namespace NetRunner2.ui
{
/// <summary>
/// Interaction logic for EditUserApplication.xaml
/// </summary>
public partial class EditUserApplication : Window
{
#warning TODO: Implement hotkey
OpenFileDialog openFileDialog;
string appID;
public EditUserApplication()
{
InitializeComponent();
}
//protected override void OnDeactivated(EventArgs e)
//{
// base.OnDeactivated(e);
// this.Close();
//}
public EditUserApplication(string appID)
{
InitializeComponent();
this.appID = appID;
UserApplication userApplication = Settings.instance.applications.Find(e => e.id == appID);
textboxName.Text = userApplication.name;
textboxPath.Text = userApplication.filepath;
textboxArguments.Text = userApplication.arguments;
}
private void buttonOpenFileDialog_Click(object sender, RoutedEventArgs e)
{
openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Executables |*.exe|Batch files|*.bat";
openFileDialog.DefaultExt = ".exe";
openFileDialog.InitialDirectory = Settings.instance.DefaultFileDialogPath;
openFileDialog.FileOk += OpenFileDialog_FileOk;
openFileDialog.ShowDialog();
}
private void OpenFileDialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
textboxPath.Text = openFileDialog.FileName;
if (String.IsNullOrEmpty(textboxPath.Text))
textboxPath.Text = openFileDialog.SafeFileName;
}
private void buttonAddApplication_Click(object sender, RoutedEventArgs e)
{
if (appID != null)
{
UserApplication userApplication = Settings.instance.applications.Find(a => a.id == appID);
userApplication.name = textboxName.Text;
userApplication.filepath = textboxPath.Text;
userApplication.arguments = textboxArguments.Text;
}
else
{
Settings.instance.applications.Add(new UserApplication(
textboxName.Text,
textboxPath.Text,
textboxArguments.Text,
""
));
}
Settings.Save();
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NetRunner2
{
class Settings
{
public static string settingsfilepath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "settings.ini";
public static GlobalSettings instance = new GlobalSettings();
public static event EventHandler SettingsChanged = delegate { };
public static void Save() { SaveSettings(instance, settingsfilepath); }
public static void Load() { LoadSettings(ref instance, settingsfilepath); }
private static bool SaveSettings(GlobalSettings settings, string filepath)
{
try
{
string xml = string.Empty;
var xs = new XmlSerializer(typeof(GlobalSettings));
using (var writer = new StringWriter())
{
xs.Serialize(writer, settings);
writer.Flush();
xml = writer.ToString();
}
File.WriteAllText(filepath, xml);
SettingsChanged(null, EventArgs.Empty);
return true;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while saving settings to disk: " + ex.Message, "NetRunner2");
return false;
}
}
private static bool LoadSettings(ref GlobalSettings settings, string filepath)
{
try
{
if (!File.Exists(filepath))
{
return false;
}
string xml = File.ReadAllText(filepath);
var xs = new XmlSerializer(settings.GetType());
GlobalSettings ret = (GlobalSettings)xs.Deserialize(new StringReader(xml));
settings = ret;
return true;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while loading settings from disk: " + ex.Message, "NetRunner2");
return false;
}
}
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace NetRunner2
{
public static class Impersonator
{
#region Public Methods
public static int CreateProcessWithNetCredentials(UserCredentials creds, UserApplication app) // string username, string domain, string password, string path, string command)
{
int ret = 0;
StartupInfo si = new StartupInfo();
ProcessInformation pi;
CreateProcessWithLogonW(creds.username, creds.domain, creds.password, LogonFlags.LOGON_NETCREDENTIALS_ONLY,
app.filepath, " " + app.arguments,
CreationFlags.CREATE_UNICODE_ENVIRONMENT,
(UInt32)0,
System.IO.Directory.GetCurrentDirectory(),
ref si,
out pi);
return ret;
}
#endregion
[StructLayout(LayoutKind.Sequential)]
private struct ProcessInformation
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct StartupInfo
{
public int cb;
public String reserved;
public String desktop;
public String title;
public int x;
public int y;
public int xSize;
public int ySize;
public int xCountChars;
public int yCountChars;
public int fillAttribute;
public int flags;
public UInt16 showWindow;
public UInt16 reserved2;
public byte reserved3;
public IntPtr stdInput;
public IntPtr stdOutput;
public IntPtr stdError;
}
[Flags]
private enum CreationFlags
{
CREATE_SUSPENDED = 0x00000004,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
}
[Flags]
private enum LogonFlags
{
LOGON_WITH_PROFILE = 0x00000001,
LOGON_NETCREDENTIALS_ONLY = 0x00000002
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool CreateProcessWithLogonW(
String userName,
String domain,
String password,
LogonFlags logonFlags,
String applicationName,
String commandLine,
CreationFlags creationFlags,
UInt32 environment,
String currentDirectory,
ref StartupInfo startupInfo,
out ProcessInformation processInformation);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Xml.Serialization;
namespace NetRunner2
{
[Serializable]
public class GlobalSettings
{
public bool RunOnStartup = true;
public string DefaultFileDialogPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
public List<UserCredentials> credentials = new List<UserCredentials>();
public List<UserApplication> applications = new List<UserApplication>();
}
[Serializable]
public class UserCredentials
{
public string domain, username, password;
public bool IsSelected = false;
public UserCredentials() { domain = ""; username = ""; password = "";}
public UserCredentials(string domain, string username, string password) { this.domain = domain; this.username = username; this.password = <PASSWORD>; }
public string credentialId { get { return String.Join("/", domain, username); } }
public override string ToString()
{
return String.Join(" @ ", username, domain);
}
}
[Serializable]
public class KeyboardHotkey
{
public Key AN = Key.None;
public ModifierKeys Mod1 = ModifierKeys.None, Mod2 = ModifierKeys.None;
[XmlIgnore]
public List<string> HotKeyKeyNames
{
get
{
List<string> tmp = new List<string>();
if (Mod1 != ModifierKeys.None) tmp.Add(Mod1.ToString());
if (Mod2 != ModifierKeys.None) tmp.Add(Mod2.ToString());
if (AN != Key.None) tmp.Add(AN.ToString());
return tmp;
}
}
}
[Serializable]
public class UserApplication
{
public string id, name, filepath, arguments, icon_filepath;
public int list_order = 0;
public KeyboardHotkey hotkey = new KeyboardHotkey();
public UserApplication()
{
id = GenerateID();
name = ""; filepath = ""; arguments = ""; icon_filepath = "";
}
public UserApplication(string name, string filepath, string arguments, string icon_filepath)
{
id = GenerateID();
this.name = name; this.filepath = filepath; this.arguments = arguments; this.icon_filepath = icon_filepath;
}
private string GenerateID()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
namespace NetRunner
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
bool IsEditModeOn = false;
AddProgram addform;
public MainWindow()
{
InitializeComponent();
AppManager.SettingsChanged += AppManager_SettingsChanged;
Refresh();
}
private void AppManager_SettingsChanged(object sender, EventArgs e)
{
Refresh();
}
public void Refresh()
{
panelApps.Children.Clear();
foreach (var app in AppManager.settings.appList)
{
Button btn = GenerateButton(app.id, app.name, app.prog_path, app.prog_args, false);
panelApps.Children.Add(btn);
}
if (IsEditModeOn)
panelApps.Children.Add(GenerateButton("insert", "Add Program", "", "", true));
}
private Button GenerateButton(string id, string caption, string launchpath, string arguments, bool launchaddform)
{
Button btn = new Button();
StackPanel stk = new StackPanel();
Image img = new Image();
Label lbl = new Label();
try
{
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(launchpath);
img.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions());
}
catch
{
var uriSource = new Uri(@"/NetRunner;component/images/plus.png", UriKind.Relative);
img.Source = new BitmapImage(uriSource);
}
btn.Width = 100;
btn.Height = 100;
btn.Name = "btn" + id;
stk.Height = 100;
stk.Width = 100;
img.Height = 45;
img.Margin = new Thickness(18, 10, 18, 10);
lbl.HorizontalAlignment = HorizontalAlignment.Center;
lbl.VerticalAlignment = VerticalAlignment.Center;
lbl.Content = caption;
stk.Children.Add(img);
stk.Children.Add(lbl);
btn.Content = stk;
if (launchaddform)
{
btn.Click += (s, e) =>
{
if (addform == null || !addform.IsVisible)
{
addform = new AddProgram();
addform.Show();
}
};
}
else
{
btn.Click += (s, e) =>
{
if (IsEditModeOn)
{
if (addform == null || !addform.IsVisible)
{
var app = AppManager.settings.appList.Find(k => k.id == id);
addform = new AddProgram(app.id, app.name, app.prog_path, app.prog_args, app.AN, app.Mod1, app.Mod2);
addform.Show();
}
}
else
{
AppManager.RunProgram(launchpath, arguments);
}
};
}
txtDomain.Text = AppManager.settings.domain;
txtUsername.Text = AppManager.settings.username;
txtPassword.Password = <PASSWORD>;
return btn;
}
private void ToggleEditMode(bool IsEditModeOn)
{
if (IsEditModeOn)
{
panelApps.Children.Add(GenerateButton("insert", "Add Program", "", "", true));
}
else
{
panelApps.Children.RemoveAt(panelApps.Children.Count - 1);
}
}
private void Window_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
IsEditModeOn = !IsEditModeOn;
ToggleEditMode(IsEditModeOn);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Visibility = Visibility.Hidden;
}
private void cbLock_Checked(object sender, RoutedEventArgs e)
{
txtDomain.IsEnabled = false;
txtUsername.IsEnabled = false;
txtPassword.IsEnabled = false;
btnSaveCreds.IsEnabled = false;
}
private void cbLock_Unchecked(object sender, RoutedEventArgs e)
{
txtDomain.IsEnabled = true;
txtUsername.IsEnabled = true;
txtPassword.IsEnabled = true;
btnSaveCreds.IsEnabled = true;
}
private void btnSaveCreds_Click(object sender, RoutedEventArgs e)
{
AppManager.settings.domain = txtDomain.Text;
AppManager.settings.username = txtUsername.Text;
AppManager.settings.password = <PASSWORD>;
AppManager.SaveSettings();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
namespace ShiftTracker
{
public class WorkDay
{
public DateTime Date;
public TimeSpan WorkedHours;
public DateTime StartTime;
public TimeSpan Balance
{
get { return WorkedHours.Subtract(new TimeSpan(8, 0, 0)); }
}
public string DateString
{
get { return Date.ToString("dd/MM/yyyy"); }
}
public string WorkedHoursString
{
get { return WorkedHours.ToString(@"hh\:mm\:ss"); }
}
public string BalanceString
{
get { var tmp = WorkedHours.Subtract(new TimeSpan(8, 0, 0)); return tmp.ToString((tmp < TimeSpan.Zero ? "\\-" : "\\+") + @"hh\:mm\:ss"); }
}
public WorkDay() { }
public WorkDay(DateTime Date) { this.Date = Date; }
}
public static class TimeSpanExtensions
{
public static TimeSpan RoundDownToHalfHour(this TimeSpan input)
{
return new TimeSpan(0, (int)input.TotalMinutes - (int)input.TotalMinutes % 30, 0);
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SolidColorBrush positiveBrush = new SolidColorBrush(Color.FromArgb(255, 28, 141, 33)),
negativeBrush = new SolidColorBrush(Color.FromArgb(255, 149, 53, 53)),
neutralBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
List<WorkDay> workDays = new List<WorkDay>();
public MainWindow()
{
InitializeComponent();
timer.Tick += Timer_Tick;
timer.Interval = new TimeSpan(0, 0, 1);
if (App.Current.Properties["initfile"] != null)
ProcessXLSShiftFile((string)App.Current.Properties["initfile"]);
if (CalculateTime())
{
UpdateTimeLabels();
timer.Start();
}
else
{
UpdateTimeLabels();
}
this.Top = Properties.Settings.Default.Top;
this.Left = Properties.Settings.Default.Left;
ttGrid.ItemsSource = workDays;
}
#region Events
private void Timer_Tick(object sender, EventArgs e)
{
TimeSpan tmptsMonthly = TimeSpan.Parse((string)lblDeltaTimeMonthly.Content).Add(new TimeSpan(0, 0, 1));
TimeSpan tmptsDay = TimeSpan.Parse((string)lblDeltaTimeDay.Content).Add(new TimeSpan(0, 0, 1));
if (tmptsDay > TimeSpan.Zero)
{
TimeSpan tmptsDiff = TimeSpan.Parse(((string)lblDiff.Content).Replace("+", "")).Add(new TimeSpan(0, 0, 1));
lblDiff.Content = tmptsDiff.ToString((tmptsDiff < TimeSpan.Zero ? "\\-" : "\\+") + @"hh\:mm\:ss");
lblDiff.Foreground = ((string)lblDiff.Content) == "00:00:00" ? neutralBrush : ((string)lblDiff.Content)[0] == '-' ? negativeBrush : positiveBrush;
}
lblDeltaTimeMonthly.Content = tmptsMonthly.ToString((tmptsMonthly < TimeSpan.Zero ? "\\-" : "") + @"hh\:mm\:ss");
lblDeltaTimeMonthly.Foreground = ((string)lblDeltaTimeMonthly.Content) == "00:00:00" ? neutralBrush : ((string)lblDeltaTimeMonthly.Content)[0] == '-' ? negativeBrush : positiveBrush;
lblDeltaTimeDay.Content = (bool)App.Current.Properties["suppresstoday"] ? "00:00:00" : tmptsDay.ToString((tmptsDay < TimeSpan.Zero ? "\\-" : "") + @"hh\:mm\:ss");
lblDeltaTimeDay.Foreground = ((string)lblDeltaTimeDay.Content) == "00:00:00" ? neutralBrush : ((string)lblDeltaTimeDay.Content)[0] == '-' ? negativeBrush : positiveBrush;
if ((int)App.Current.Properties["closetimer"] != -10)
{
if ((int)App.Current.Properties["closetimer"] < 0)
Quit();
else
App.Current.Properties["closetimer"] = (int)App.Current.Properties["closetimer"] - 1;
}
}
private void LblDeltaTime_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// if multiple files were dropped get only the first one
string file = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
ProcessXLSShiftFile(file);
}
if (CalculateTime())
{
UpdateTimeLabels();
ttGrid.ItemsSource = null;
ttGrid.ItemsSource = workDays;
#warning TODO: DYNAMIC TTGRID STYLING
timer.Start();
}
else
{
UpdateTimeLabels();
}
}
private void LblDeltaTime_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
}
private void BtnimgClose_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Quit();
}
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
#endregion
#region Inner Workings
private void UpdateTimeLabels()
{
TimeSpan tmptsMonthly = (TimeSpan)App.Current.Properties["monthlybalance"];
TimeSpan tmptsDay = (TimeSpan)App.Current.Properties["dailybalance"];
TimeSpan tmptsDiff = (TimeSpan)App.Current.Properties["monthlyaccumulated"];
//if (tmptsDay > TimeSpan.Zero) { tmptsDiff = tmptsDiff.Add(tmptsDay); }
lblDeltaTimeMonthly.Content = tmptsMonthly.ToString((tmptsMonthly < TimeSpan.Zero ? "\\-" : "") + @"hh\:mm\:ss");
lblDeltaTimeDay.Content = (bool)App.Current.Properties["suppresstoday"] ? "00:00:00" : tmptsDay.ToString((tmptsDay < TimeSpan.Zero ? "\\-" : "") + @"hh\:mm\:ss");
lblDiff.Content = tmptsDiff.ToString((tmptsDiff < TimeSpan.Zero ? "\\-" : "\\+") + @"hh\:mm\:ss");
lblDeltaTimeMonthly.Foreground = ((string)lblDeltaTimeMonthly.Content) == "00:00:00" ? neutralBrush : ((string)lblDeltaTimeMonthly.Content)[0] == '-' ? negativeBrush : positiveBrush;
lblDeltaTimeDay.Foreground = ((string)lblDeltaTimeDay.Content) == "00:00:00" ? neutralBrush : ((string)lblDeltaTimeDay.Content)[0] == '-' ? negativeBrush : positiveBrush;
lblDiff.Foreground = ((string)lblDiff.Content) == "00:00:00" ? neutralBrush : ((string)lblDiff.Content)[0] == '-' ? negativeBrush : positiveBrush;
}
private void Quit()
{
Properties.Settings.Default.Top = this.Top;
Properties.Settings.Default.Left = this.Left;
Properties.Settings.Default.Save();
App.Current.Shutdown();
}
private void ProcessXLSShiftFile(string file)
{
SQLiteConnection con = new SQLiteConnection("Data Source=.\\shift.db;Version=3;");
con.Open();
SQLiteCommand cmd = new SQLiteCommand("DELETE FROM clockdata;DELETE FROM dailyhours;", con);
cmd.ExecuteNonQuery();
foreach (string line in File.ReadAllLines(file, Encoding.Unicode).Skip(1))
{
if (line.Trim().Length > 0)
{
string[] cols = line.Split('\t');
DateTime timestamp = DateTime.ParseExact(cols[0] + "T" + cols[1], "dd/MM/yyyyTHH:mm:ss", null);
bool is_entry = cols[2] == "E" ? true : false;
string exit_reason = cols[3].Trim();
cmd.CommandText = "INSERT INTO clockdata (clock_timestamp, is_entry, exit_reason) VALUES ('" + timestamp.ToString("yyyy-MM-dd HH:mm:ss") + "', " + is_entry + ", '" + exit_reason + "');";
cmd.ExecuteNonQuery();
}
}
con.Close();
}
private bool CalculateTime()
{
SQLiteConnection con = new SQLiteConnection("Data Source=.\\shift.db;Version=3;");
con.Open();
SQLiteCommand cmd = new SQLiteCommand("SELECT clock_timestamp, is_entry, exit_reason FROM clockdata WHERE SUBSTR(clock_timestamp, 0, 8) = (SELECT MAX(SUBSTR(clock_timestamp, 0, 8)) FROM clockdata) ORDER BY clock_timestamp;", con),
cmdi = new SQLiteCommand("INSERT INTO dailyhours (date, worked_minutes, worked_minutes_rounded) VALUES (?, ?, ?)", con);
workDays = new List<WorkDay>();
//
DateTime openshiftstart = DateTime.MinValue;
DateTime lastshiftend = DateTime.MinValue;
TimeSpan dailyworkedhours = new TimeSpan();
TimeSpan dailybalance = new TimeSpan();
TimeSpan monthlybalance = new TimeSpan();
TimeSpan monthlyaccumulated = new TimeSpan();
TimeSpan dailymaxbreaktime = new TimeSpan();
bool trackopenshift = false;
bool skipnextrow = false;
WorkDay wd = new WorkDay();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var tmpdt = reader.GetDateTime(0);
var tmpentry = reader.GetBoolean(1);
var tmpreason = reader.GetString(2);
// ignorar saídas em serviço
if (tmpreason.Length != 0 || skipnextrow)
{
skipnextrow = !skipnextrow;
continue;
}
if (openshiftstart != DateTime.MinValue && tmpdt.Date != openshiftstart.Date) // novo dia
{
// cobrar hora de almoço ---- se existir uma saída inferior a 1h ou se saiu só depois das 15, mas apenas se entrou antes das 11
if (wd.StartTime.Hour < 11 && lastshiftend.Hour >= 15 && dailymaxbreaktime.TotalHours < 1)
{
wd.WorkedHours = dailyworkedhours.Add(dailymaxbreaktime.Subtract(new TimeSpan(1, 0, 0)));
}
else
{
wd.WorkedHours = dailyworkedhours;
}
workDays.Add(wd);
lastshiftend = DateTime.MinValue;
dailyworkedhours = new TimeSpan();
dailymaxbreaktime = new TimeSpan();
}
if (tmpentry) // entrada
{
if (lastshiftend != DateTime.MinValue) // saiu e entrou no mesmo dia
{
if (dailymaxbreaktime == TimeSpan.Zero)
{
dailymaxbreaktime = tmpdt.Subtract(lastshiftend);
}
}
else
{
wd = new WorkDay(tmpdt.Date);
wd.StartTime = tmpdt;
}
openshiftstart = tmpdt;
trackopenshift = true;
}
else // saída
{
lastshiftend = tmpdt;
dailyworkedhours = dailyworkedhours.Add(tmpdt.Subtract(openshiftstart));
trackopenshift = false;
}
}
reader.Close();
if (openshiftstart != DateTime.MinValue)
{
// add up final day
if (trackopenshift) // open day
{
dailyworkedhours = dailyworkedhours.Add(DateTime.Now.Subtract(openshiftstart));
// cobrar hora de almoço ---- se existir uma saída inferior a 1h, mas apenas se entrou antes das 11
if (wd.StartTime.Hour < 11 && dailymaxbreaktime.TotalHours < 1 && (dailymaxbreaktime.TotalHours > 0 || DateTime.Now.Hour >= 15))
{
dailyworkedhours = dailyworkedhours.Add(dailymaxbreaktime.Subtract(new TimeSpan(1, 0, 0)));
}
}
else
{
// cobrar hora de almoço ---- se existir uma saída inferior a 1h ou se saiu só depois das 15, mas apenas se entrou antes das 11
if (wd.StartTime.Hour < 11 && lastshiftend.Hour >= 15 && dailymaxbreaktime.TotalHours < 1)
{
dailyworkedhours = dailyworkedhours.Add(dailymaxbreaktime.Subtract(new TimeSpan(1, 0, 0)));
}
}
wd.WorkedHours = dailyworkedhours;
workDays.Add(wd);
}
if (workDays.Count > 0)
{
foreach (WorkDay w in workDays)
{
cmdi.Parameters.Clear();
cmdi.Parameters.AddWithValue("date", w.Date.ToString("yyyy-MM-dd HH:mm:ss"));
cmdi.Parameters.AddWithValue("workedminutes", Math.Round(w.WorkedHours.TotalMinutes, 6));
cmdi.Parameters.AddWithValue("workedminutesrounded", w.WorkedHours.RoundDownToHalfHour().TotalMinutes);
cmdi.ExecuteNonQuery();
}
con.Close();
monthlybalance = TimeSpan.FromMilliseconds(workDays.Sum(e => e.Balance.TotalMilliseconds));
WorkDay currentDay = workDays.SingleOrDefault(e => e.Date == DateTime.Now.Date);
dailybalance = currentDay?.Balance ?? TimeSpan.Zero;
monthlyaccumulated = TimeSpan.FromMilliseconds(workDays.Take(workDays.Count - 1).Sum(e => e.Balance.TotalMilliseconds)).Add(workDays.Last().Balance > TimeSpan.Zero ? workDays.Last().Balance : TimeSpan.Zero);
}
App.Current.Properties["monthlybalance"] = monthlybalance;
App.Current.Properties["dailybalance"] = dailybalance;
App.Current.Properties["monthlyaccumulated"] = monthlyaccumulated;
App.Current.Properties["suppresstoday"] = dailybalance == TimeSpan.Zero;
return dailybalance != TimeSpan.Zero;
}
#endregion
}
}<file_sep>using NetRunner2.src;
using NetRunner2.ui;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace NetRunner2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#warning TODO: custom scrollbar
public MainWindow()
{
InitializeComponent();
RefreshUI();
}
//protected override void OnDeactivated(EventArgs e)
//{
// base.OnDeactivated(e);
// if (GlobalState.Instance.editUserApplicationWindow == null)
// this.Close();
//}
private void RefreshUI()
{
Settings.Load();
cmbCredentials.ItemsSource = Settings.instance.credentials;
cmbCredentials.SelectedItem = Settings.instance.credentials.Where(e => e.IsSelected).DefaultIfEmpty(new UserCredentials()).First();
if (Settings.instance.applications.Count == 0)
{
textboxEmptyAppList.Visibility = Visibility.Visible;
stackApps.Visibility = Visibility.Hidden;
}
else
{
textboxEmptyAppList.Visibility = Visibility.Hidden;
stackApps.Visibility = Visibility.Visible;
stackApps.Children.Clear();
foreach (var app in Settings.instance.applications)
{
stackApps.Children.Add(new UserApplicationUI(app));
}
}
}
private void buttonAddApplication_Click(object sender, RoutedEventArgs e)
{
}
private void buttonMinimize_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void buttonOptions_Click(object sender, RoutedEventArgs e)
{
}
private void cmbCredentials_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
lblSelectedCredentials.Content = cmbCredentials.SelectedItem.ToString();
Settings.instance.credentials.ForEach(k => k.IsSelected = false);
Settings.instance.credentials.Where(j => j.credentialId == ((UserCredentials)cmbCredentials.SelectedItem).credentialId).DefaultIfEmpty(new UserCredentials()).First().IsSelected = true;
Settings.Save();
}
private void lblSelectedCredentials_MouseEnter(object sender, MouseEventArgs e)
{
lblSelectedCredentials.BorderBrush = System.Windows.Media.Brushes.LightGray;
}
private void lblSelectedCredentials_MouseLeave(object sender, MouseEventArgs e)
{
lblSelectedCredentials.BorderBrush = System.Windows.Media.Brushes.Transparent;
}
private void lblSelectedCredentials_MouseDown(object sender, MouseButtonEventArgs e)
{
cmbCredentials.IsDropDownOpen = true;
}
}
}
<file_sep>using System;
using System.Windows;
using System.Windows.Input;
namespace NetRunner
{
/// <summary>
/// Interaction logic for AddProgram.xaml
/// </summary>
public partial class AddProgram : Window
{
bool IsEditMode = false;
string appid = "";
Key AN = Key.None;
ModifierKeys Mod1 = ModifierKeys.None;
ModifierKeys Mod2 = ModifierKeys.None;
public AddProgram()
{
InitializeComponent();
}
public AddProgram(string id, string ProgramName, string ProgramPath, string ProgramArgs, Key AN, ModifierKeys Mod1, ModifierKeys Mod2)
{
InitializeComponent();
IsEditMode = true;
appid = id;
btnDelete.IsEnabled = true;
this.Title = "Edit";
txtProgramName.Text = ProgramName;
txtProgramPath.Text = ProgramPath;
txtProgramArgs.Text = ProgramArgs;
this.AN = AN;
txtANKey.Text = AN.ToString();
this.Mod1 = Mod1;
txtModKey1.Text = Mod1.ToString();
this.Mod2 = Mod2;
txtModKey2.Text = Mod2.ToString();
}
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
fd.Filter = "Executables |*.exe|Batch files|*.bat";
fd.DefaultExt = ".exe";
fd.InitialDirectory = "C:\\";
fd.FileOk += Fd_FileOk;
fd.ShowDialog();
}
private void Fd_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
txtProgramPath.Text = fd.FileName;
if (String.IsNullOrEmpty(txtProgramName.Text))
txtProgramName.Text = fd.SafeFileName;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (AN == Key.None || Mod1 == Mod2)
{
AN = Key.None; Mod1 = ModifierKeys.None; Mod2 = ModifierKeys.None;
}
if (IsEditMode)
{
AppManager.EditProgram(appid, txtProgramName.Text, txtProgramPath.Text, txtProgramArgs.Text, "", AN, Mod1, Mod2);
}
else
{
AppManager.AddProgram(txtProgramName.Text, txtProgramPath.Text, txtProgramArgs.Text, "", AN, Mod1, Mod2);
}
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
AppManager.DeleteProgram(appid);
this.Close();
}
private void txtModKey1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key == Key.System ? e.SystemKey : e.Key)
{
case Key.LeftCtrl:
case Key.RightCtrl:
txtModKey1.Text = ModifierKeys.Control.ToString();
Mod1 = ModifierKeys.Control;
break;
case Key.LeftShift:
case Key.RightShift:
txtModKey1.Text = ModifierKeys.Shift.ToString();
Mod1 = ModifierKeys.Shift;
break;
case Key.LeftAlt:
case Key.RightAlt:
txtModKey1.Text = ModifierKeys.Alt.ToString();
Mod1 = ModifierKeys.Alt;
break;
default:
txtModKey1.Text = "";
Mod1 = ModifierKeys.None;
break;
}
if (txtModKey1.Text == txtModKey2.Text)
{
txtModKey2.Text = "";
Mod2 = ModifierKeys.None;
}
txtModKey2.Focus();
e.Handled = true;
}
private void txtModKey2_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key == Key.System ? e.SystemKey : e.Key)
{
case Key.LeftCtrl:
case Key.RightCtrl:
txtModKey2.Text = ModifierKeys.Control.ToString();
Mod2 = ModifierKeys.Control;
break;
case Key.LeftShift:
case Key.RightShift:
txtModKey2.Text = ModifierKeys.Shift.ToString();
Mod2 = ModifierKeys.Shift;
break;
case Key.LeftAlt:
case Key.RightAlt:
txtModKey2.Text = ModifierKeys.Alt.ToString();
Mod2 = ModifierKeys.Alt;
break;
default:
txtModKey2.Text = "";
Mod2 = ModifierKeys.None;
break;
}
if (txtModKey1.Text == txtModKey2.Text)
{
txtModKey2.Text = "";
Mod2 = ModifierKeys.None;
}
txtANKey.Focus();
e.Handled = true;
}
private void txtANKey_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key >= Key.A && e.Key <= Key.Z)
{
txtANKey.Text = Enum.GetName(typeof(Key), e.Key).ToUpper();
AN = e.Key;
}
e.Handled = true;
}
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NetRunner
{
class KeyboardHook
{
#region Windows API Types And Consts
private const int WH_KEYBOARD_LL = 13;
private const uint MAPVK_VK_TO_CHAR = 0x02;
private const uint WM_KEYDOWN = 0x100;
private const uint VK_SHIFT = 0x10;
private const uint VK_CAPITAL = 0x14;
private const uint VK_LCONTROL = 0xA2;
private const uint VK_SPACE = 0x20;
private const int KEY_PRESSED = 0x1000;
private const int KEY_TOGGLED = 0x8000;
public const int WM_HOTKEY = 0x312;
delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
[Flags]
public enum KBDLLHOOKSTRUCTFlags : uint
{
LLKHF_EXTENDED = 0x01,
LLKHF_INJECTED = 0x10,
LLKHF_ALTDOWN = 0x20,
LLKHF_UP = 0x80,
}
[Flags]
public enum Modifiers : uint
{
MOD_ALT = 0x1,
MOD_CONTROL = 0x2,
MOD_SHIFT = 0x4,
MOD_WIN = 0x8
}
[StructLayout(LayoutKind.Sequential)]
public class KBDLLHOOKSTRUCT
{
public uint vkCode;
public uint scanCode;
public KBDLLHOOKSTRUCTFlags flags;
public uint time;
public UIntPtr dwExtraInfo;
}
#endregion
#region Windows API Functions
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int hookType, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPArray)] char[] pwszBuff, int cchBuff, uint wFlags);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
static extern short GetKeyState(uint nVirtKey);
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
#endregion
public event KeyPressEventHandler KeyPressed;
public event EventHandler HotKeyPressed;
private bool _hookOn = false;
public bool hookOn { get { return _hookOn; } }
private HookProc callbackDelegate;
private WindowsMessageListener wmListener;
public KeyboardHook()
{
callbackDelegate = new HookProc(KeyboardEventHandler);
IntPtr modlib = LoadLibrary("user32.dll"); // get a module to bypass SetWindowsHookEx's check on Windows versions earlier than 7
SetWindowsHookEx(WH_KEYBOARD_LL, callbackDelegate, modlib, 0);
//_hookOn = true;
wmListener = new WindowsMessageListener(this);
}
public bool ToggleHook()
{
_hookOn = !_hookOn;
return _hookOn;
}
private int KeyboardEventHandler(int code, IntPtr wParam, IntPtr lParam)
{
bool handled = false;
if (code >= 0 && (uint)wParam == WM_KEYDOWN && KeyPressed != null && _hookOn)
{
KBDLLHOOKSTRUCT kbdstruct = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
byte[] state = new byte[256];
char[] outchar = new char[1];
// calling GetKeyState before GetKeyboardState ensures an updated state buffer
bool ShiftPressed = Convert.ToBoolean(GetKeyState(VK_SHIFT) & KEY_PRESSED);
bool CapsLockToggled = Convert.ToBoolean(GetKeyState(VK_CAPITAL) & KEY_TOGGLED);
GetKeyboardState(state);
// avoid calling ToUnicode on dead keys
if (MapVirtualKey((uint)kbdstruct.vkCode, MAPVK_VK_TO_CHAR) >> sizeof(uint) * 8 - 1 == 0)
{
if (ToUnicode(kbdstruct.vkCode, kbdstruct.scanCode, state, outchar, outchar.Length, (uint)kbdstruct.flags) == 1)
{
outchar[0] = ShiftPressed || CapsLockToggled ? Char.ToUpper(outchar[0]) : outchar[0];
System.Windows.Forms.KeyPressEventArgs e = new System.Windows.Forms.KeyPressEventArgs(outchar[0]);
KeyPressed(this, e);
handled = e.Handled;
}
}
}
return handled ? 1 : CallNextHookEx(IntPtr.Zero, code, wParam, lParam);
}
public void RegHotKey(Modifiers modifiers, uint key, IntPtr formHandle, int keyID)
{
RegisterHotKey(formHandle, keyID, (uint)modifiers, key);
}
public void UnregHotKey(IntPtr formHandle, int keyID)
{
if (keyID > 0)
{
UnregisterHotKey(formHandle, keyID);
}
}
public void ThrowHotKeyEvent()
{
HotKeyPressed?.Invoke(this, null);
}
}
partial class WindowsMessageListener : Form, IDisposable
{
KeyboardHook kbHook;
public WindowsMessageListener(KeyboardHook kbHook)
{
this.kbHook = kbHook;
KeyboardHook.Modifiers modifiers = 0;
Keys k = Keys.Space | Keys.Control;
if ((k & Keys.Alt) == Keys.Alt)
modifiers = modifiers | KeyboardHook.Modifiers.MOD_ALT;
if ((k & Keys.Control) == Keys.Control)
modifiers = modifiers | KeyboardHook.Modifiers.MOD_CONTROL;
if ((k & Keys.Shift) == Keys.Shift)
modifiers = modifiers | KeyboardHook.Modifiers.MOD_SHIFT;
k = k & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;
kbHook.RegHotKey(modifiers, (uint)k, this.Handle, this.GetHashCode());
}
// CF Note: The WndProc is not present in the Compact Framework (as of vers. 3.5)! please derive from the MessageWindow class in order to handle WM_HOTKEY
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == KeyboardHook.WM_HOTKEY)
kbHook.ThrowHotKeyEvent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
kbHook.UnregHotKey(this.Handle, this.GetHashCode());
}
}
}
<file_sep>using NetRunner2.ui;
namespace NetRunner2.src
{
public sealed class GlobalState
{
private static readonly GlobalState instance = new GlobalState();
static GlobalState() { }
private GlobalState() { }
public static GlobalState Instance { get { return instance; } }
public void InvokeSettingsWindow()
{
}
public void InvokeEditUserApplicationWindow()
{
}
public void InvokeEditUserApplicationWindow(string applicationId)
{
}
}
}
<file_sep>using NetRunner2.src;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace NetRunner2.ui
{
/// <summary>
/// Interaction logic for UserApplicationUI.xaml
/// </summary>
public partial class UserApplicationUI : UserControl
{
UserApplication application;
public UserApplicationUI(UserApplication application)
{
InitializeComponent();
this.application = application;
textboxName.Content = application.name;
System.Drawing.Icon icon = System.Drawing.SystemIcons.Application;
if (File.Exists(application.filepath))
{
icon = System.Drawing.Icon.ExtractAssociatedIcon(application.filepath);
}
System.Drawing.Bitmap imgtest = new Icon(icon, 96, 96).ToBitmap();
imageIcon.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(imgtest.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
textboxHotkey.Content = String.Join(" + ", application.hotkey.HotKeyKeyNames);
}
private void OpenAppSettings()
{
GlobalState.Instance.InvokeEditUserApplicationWindow(application.id);
}
private void LaunchApp()
{
Impersonator.CreateProcessWithNetCredentials(Settings.instance.credentials.Where(e => e.IsSelected).DefaultIfEmpty(new UserCredentials()).First(), application);
}
#region Event Handlers
private void lblEllipsis_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
OpenAppSettings();
}
private void imageIcon_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
LaunchApp();
}
private void textboxName_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
LaunchApp();
}
private void textboxHotkey_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
LaunchApp();
}
private void lblEllipsis_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
lblEllipsis.Background = System.Windows.Media.Brushes.Transparent;
}
private void lblEllipsis_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
lblEllipsis.Background = System.Windows.Media.Brushes.LightGray;
}
private void gridMain_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
gridMain.Background = System.Windows.Media.Brushes.Beige;
}
private void gridMain_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
gridMain.Background = System.Windows.Media.Brushes.Transparent;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Input;
namespace NetRunner2
{
public sealed class HotkeyManager : NativeWindow
{
class RegisteredHotkey
{
public int Win32_ID;
public Keys Key;
public ModifierKeys Modifiers;
}
private static readonly HotkeyManager instance = new HotkeyManager();
static HotkeyManager() { }
private HotkeyManager()
{
this.CreateHandle(new CreateParams());
}
public static HotkeyManager Instance { get { return instance; } }
#region System calls and definitions
private const int WM_HOTKEY = 0x0312;
private int system_id_current_max = 1000;
private static readonly Dictionary<string, int> registeredHotkeyDict = new Dictionary<string, int>();
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, ModifierKeys fsModifiers, uint vk);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool UnregisterHotKey(IntPtr hWnd, int id);
#endregion
public event EventHandler<HotKeyEventArgs> HotKeyPressed;
public bool RegisterHotKey(string id, KeyboardHotkey hotkey)
{
if (registeredHotkeyDict.ContainsKey(id))
return false;
int tmp_id = ++system_id_current_max;
bool ret = RegisterHotKey(this.Handle, tmp_id, hotkey.Mod1 | hotkey.Mod2, (uint)KeyInterop.VirtualKeyFromKey(hotkey.AN));
if (ret)
{
registeredHotkeyDict.Add(id, tmp_id);
return true;
}
else
return false;
}
public bool UnregisterHotKey(string id)
{
if (registeredHotkeyDict.ContainsKey(id))
{
int tmp_id;
if (registeredHotkeyDict.TryGetValue(id, out tmp_id) && UnregisterHotKey(IntPtr.Zero, tmp_id))
return true;
}
return false;
}
public void UnregisterAllHotKeys()
{
foreach(var id in registeredHotkeyDict.Values)
{
UnregisterHotKey(this.Handle, id);
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_HOTKEY)
{
int val = (int)m.WParam;
if (registeredHotkeyDict.ContainsValue(val))
{
string key = registeredHotkeyDict.Where(e => e.Value == val).Select(e => e.Key).First();
if (HotKeyPressed != null)
HotKeyPressed(this, new HotKeyEventArgs(key));
}
}
}
}
public class HotKeyEventArgs
{
private string _id;
public string id { get { return _id; } }
public HotKeyEventArgs(string id)
{
_id = id;
}
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using Microsoft.Win32;
using Application = System.Windows.Forms.Application;
using System.Linq;
namespace NetRunner2
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
private NotifyIcon ni;
private MainWindow mainwindow;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Settings.Load();
Settings.Save();
#region Register Hotkeys
Settings.instance.applications.Where(k=> k.hotkey.AN != System.Windows.Input.Key.None).ToList().ForEach(k => HotkeyManager.Instance.RegisterHotKey(k.id, k.hotkey));
HotkeyManager.Instance.HotKeyPressed += Handle_HotKeyPressed;
#endregion
#region Create Tray Icon
ni = new NotifyIcon();
ni.MouseUp += (s, a) => { if (a.Button == MouseButtons.Left) ToggleMainWindow(); };
ni.Icon = System.Drawing.SystemIcons.Application;
ni.Visible = true;
ni.ContextMenuStrip = new ContextMenuStrip();
ni.ContextMenuStrip.Items.Add("Open").Click += (s, a) => ToggleMainWindow();
ni.ContextMenuStrip.Items.Add($"Run on Startup: {(CheckRunOnStartup() ? "ON" : "OFF")}").Click += (s, a) => ToggleRunOnStartup();
ni.ContextMenuStrip.Items.Add("Close").Click += (s, a) => ShutdownApplication();
#endregion
if (e.Args.Length > 0 && e.Args[0] == "/show")
ToggleMainWindow();
}
private void Handle_HotKeyPressed(object sender, HotKeyEventArgs e)
{
var application = Settings.instance.applications.Where(a => a.id == e.id).FirstOrDefault();
var credentials = Settings.instance.credentials.Where(c => c.IsSelected).DefaultIfEmpty(new UserCredentials()).First();
if (application != null)
Impersonator.CreateProcessWithNetCredentials(credentials, application);
}
private void ToggleMainWindow()
{
if (mainwindow != null && mainwindow.WindowState == WindowState.Normal && mainwindow.IsLoaded)
{
mainwindow.Close();
}
else
{
mainwindow = new MainWindow();
mainwindow.WindowStartupLocation = WindowStartupLocation.Manual;
// Find screen dpi and unitsize in case the display is scaled
IntPtr dDC = GetDC(IntPtr.Zero);
int dpi = GetDeviceCaps(dDC, 88);
bool rv = ReleaseDC(IntPtr.Zero, dDC);
double physicalUnitSize = (1d / 96d) * (double)dpi;
var mousepos = Control.MousePosition;
mainwindow.Show();
var screenheight = Screen.FromPoint(mousepos).WorkingArea.Height;
double X = mousepos.X / physicalUnitSize - mainwindow.ActualWidth / 2;
double Y = Math.Min(mousepos.Y, screenheight) / physicalUnitSize - mainwindow.ActualHeight;
mainwindow.Left = X;
mainwindow.Top = Y;
}
}
private bool CheckRunOnStartup()
{
RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
if (regkey.GetValue(Application.ProductName) != null)
return true;
else
return false;
}
private void ToggleRunOnStartup()
{
RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (CheckRunOnStartup())
{
regkey.DeleteValue(Application.ProductName);
ni.ContextMenuStrip.Items[1].Text = "Run on Startup: OFF";
}
else
{
regkey.SetValue(Application.ProductName, Application.ExecutablePath);
ni.ContextMenuStrip.Items[1].Text = "Run on Startup: ON";
}
}
private void ShutdownApplication()
{
ni.Dispose();
ni = null;
HotkeyManager.Instance.UnregisterAllHotKeys();
App.Current.Shutdown();
}
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
}
}
<file_sep>using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Timers;
using System.ComponentModel;
using System.Windows.Media.Animation;
using System.Media;
namespace Timer
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private TimeSpan countdownSpan;
private System.Timers.Timer timer;
private DateTime startTime;
private string _timeLeft;
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
TimeLeft = "003000";
timer = new System.Timers.Timer(1000);
timer.Start();
}
#region Timer
public string TimeLeft
{
get { return _timeLeft; }
set { _timeLeft = value; OnPropertyChanged("TimeLeft"); }
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
protected void StartTimer()
{
int hours = int.Parse(TimerCount.Text.Substring(0, 2)),
minutes = int.Parse(TimerCount.Text.Substring(3, 2)),
seconds = int.Parse(TimerCount.Text.Substring(6, 2));
if (hours < 0 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60)
{
TimeLeft = "000000";
return;
}
countdownSpan = new TimeSpan(hours, minutes, seconds);
startTime = DateTime.Now;
timer.Elapsed += Timer_Elapsed;
TimerCount.IsReadOnly = true;
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
var ts = countdownSpan - (DateTime.Now - startTime);
TimeLeft = ts.ToString("hhmmss");
if (ts <= TimeSpan.Zero)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
StopTimer(false);
}));
}
}
private void StopTimer(bool WasCanceled)
{
if (!WasCanceled)
{
PartyUp();
}
timer.Elapsed -= Timer_Elapsed;
TimeLeft = "000000";
TimerCount.IsReadOnly = false;
}
private void PartyUp()
{
Container.Topmost = true;
Container.Topmost = checkBox.IsChecked ?? true;
ColorAnimation colorChangeAnimation = new ColorAnimation() { From = (Color)ColorConverter.ConvertFromString("#ff0800"), To = (Color)ColorConverter.ConvertFromString("#FF9B9B9B"), Duration = new TimeSpan(0, 0, 5) };
TimerCount.Background.BeginAnimation(SolidColorBrush.ColorProperty, colorChangeAnimation);
SystemSounds.Exclamation.Play();
}
#endregion
#region UIEventHandlers
private void close_Click(object sender, RoutedEventArgs e)
{
timer.Stop();
this.Close();
}
private void _404Button_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://404vault.tumblr.com/");
}
private void TimerCount_PreviewKeyDown(object sender, KeyEventArgs e)
{
TimerCount.SelectionLength = 0;
if (e.Key == Key.Back)
{
e.Handled = true;
}
}
private void TimerCount_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var asdf = e.Text;
if (!char.IsDigit(e.Text[0]))
{
e.Handled = true;
}
}
private void TimerCount_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
StartTimer();
}
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
Container.Topmost = true;
}
private void checkBox_Unchecked(object sender, RoutedEventArgs e)
{
Container.Topmost = false;
}
private void stop_Click(object sender, RoutedEventArgs e)
{
StopTimer(true);
}
private void start_Click(object sender, RoutedEventArgs e)
{
StartTimer();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
#endregion
}
}
<file_sep># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys, os, os.path, time, subprocess
#####
# get credentials from config file in APPDATA
exists = os.path.isfile(os.getenv('APPDATA') + "\\shifttracker-settings.xml")
if exists:
f = open(os.getenv('APPDATA') + "\\shifttracker-settings.xml", "r")
username = f.readline().strip()
password = f.readline().strip()
else:
sys.exit(0)
#####
# clear destination folder
dlpath = os.getcwd() + "\\picagens\\"
for root, dirs, files in os.walk(dlpath):
for file in files:
os.remove(os.path.join(root, file))
#####
# fetch file
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument("--headless")
prefs = {"download.default_directory": dlpath}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(".\chromedriver.exe", options=chrome_options)
driver.get("https://intranet.tap.pt/Pages/SistemaPonto.aspx")
assert "login.tap.pt" in driver.title
usrel = driver.find_element_by_id("input_1")
usrpw = driver.find_element_by_id("input_2")
usrel.send_keys(username)
usrpw.send_keys(<PASSWORD>)
usrpw.submit()
assert "TAP Intranet > Sistema de Ponto" in driver.title
#btnexp = driver.find_element_by_id("ctl00_ctl66_g_150d8a4a_91fb_428e_a279_e971347020e2_ctl00_PicagensControl_ExportBtn")
btnexp = driver.find_element_by_class_name("export")
btnexp.click()
time.sleep(3)
driver.close()
driver.quit()
#####
# run ShiftTracker with the given file
#os.chdir(r"shifttracker")
subprocess.Popen([r'shifttracker', r'/keepopen', r'.\picagens\Picagens.xls'])
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NHotkey;
using NHotkey.Wpf;
using System.Xml.Serialization;
using System.Windows.Input;
using System.Diagnostics;
namespace NetRunner
{
public static class AppManager
{
public static event EventHandler SettingsChanged = delegate { };
public static int NextAvailablePosition
{
get { return settings.appList.Count > 0 ? settings.appList.Max(e => e.order) + 1 : 0; }
}
private static string settingsPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\netrunner-settings.xml";
private static string shifttrackerSettingsPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\shifttracker-settings.xml";
public static UserSettings settings;
public static void SaveSettings()
{
try
{
string xml = string.Empty;
var xs = new XmlSerializer(typeof(UserSettings));
using (var writer = new StringWriter())
{
xs.Serialize(writer, settings);
writer.Flush();
xml = writer.ToString();
}
File.WriteAllText(settingsPath, xml);
File.WriteAllText(shifttrackerSettingsPath, String.Join("\n", settings.username, settings.password));
UnregisterAllHotkeys(settings.appList);
RegisterAllHotkeys(settings.appList);
SettingsChanged(null, EventArgs.Empty);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while saving settings to disk: " + ex.Message, "NetRunner");
}
}
public static void LoadSettings()
{
try
{
if (!File.Exists(settingsPath))
{
settings = new UserSettings() { domain = "domain", username = "user", password = "<PASSWORD>" };
return;
}
string xml = File.ReadAllText(settingsPath);
var xs = new XmlSerializer(typeof(UserSettings));
UserSettings ret = (UserSettings)xs.Deserialize(new StringReader(xml));
UnregisterAllHotkeys(ret.appList);
RegisterAllHotkeys(ret.appList);
settings = ret;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while loading settings from disk: " + ex.Message, "NetRunner");
}
}
private static void RegisterAllHotkeys(List<Program> appList)
{
try
{
appList.ForEach(e => RegisterHotkey(e.id, e.AN, e.Mod1, e.Mod2));
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while registering one or more hotkeys: " + ex.Message, "NetRunner");
}
}
private static void RegisterHotkey(String id, Key AN, ModifierKeys Mod1, ModifierKeys Mod2)
{
try
{
if (AN != Key.None)
HotkeyManager.Current.AddOrReplace(id, AN, Mod1 | Mod2, HandleHotkeyEvent);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while registering a hotkey: " + ex.Message, "NetRunner");
}
}
public static void UnregisterAllHotkeys(List<Program> appList)
{
try
{
foreach (var id in appList.Select(e => e.id).ToList())
{
HotkeyManager.Current.Remove(id);
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while unregistering one or more hotkeys: " + ex.Message, "NetRunner");
}
}
private static void UnregisterHotkey(string id)
{
try
{
HotkeyManager.Current.Remove(id);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("An exception has occurred while unregistering a hotkey: " + ex.Message, "NetRunner");
}
}
public static void HandleHotkeyEvent(object sender, HotkeyEventArgs e)
{
var app = settings.appList.Find(k => k.id == e.Name);
RunProgram(app.prog_path, app.prog_args);
}
public static void RunProgram(string launchpath, string arguments)
{
Impersonator.CreateProcessWithNetCredentials(settings.username, settings.domain, settings.password, launchpath, arguments);
}
public static void RunProgramCPAU(string launchpath, string arguments)
{
string path = Path.Combine(Path.GetTempPath(), "queres_e_pau.exe");
try
{
if (File.Exists(path))
File.Delete(path);
File.WriteAllBytes(path, Properties.Resources.CPAU);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("A fatal exception has occurred while unpacking CPAU to \"" + Path.GetTempPath() + "\" : \n" + ex.Message, "NetRunner");
throw ex;
}
try
{
Process p = new Process();
p.StartInfo.FileName = path;
p.StartInfo.Arguments = "-u " + settings.domain + "\\" + settings.username + " -p " + settings.password + " -ex \"" + launchpath + (arguments.Length > 0 ? " \"" + arguments + "\"" : "\"");
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(launchpath);
p.Start();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("A fatal exception has occurred while invoking CPAU: " + ex.Message, "NetRunner");
throw ex;
}
}
public static void AddProgram(string name, string prog_path, string prog_args, string icon_path, Key AN, ModifierKeys Mod1, ModifierKeys Mod2)
{
settings.appList.Add(new Program(name, prog_path, prog_args, icon_path, NextAvailablePosition, AN, Mod1, Mod2));
SaveSettings();
}
public static void EditProgram(string id, string name, string prog_path, string prog_args, string icon_path, Key AN, ModifierKeys Mod1, ModifierKeys Mod2)
{
var app = settings.appList.Single(e => e.id == id);
app.name = name;
app.prog_path = prog_path;
app.prog_args = prog_args;
app.icon_path = icon_path;
app.AN = AN;
app.Mod1 = Mod1;
app.Mod2 = Mod2;
SaveSettings();
}
public static void DeleteProgram(string id)
{
var app = settings.appList.Single(e => e.id == id);
UnregisterHotkey(app.id);
settings.appList.Remove(app);
SaveSettings();
}
}
[Serializable]
public class UserSettings
{
public string username = "", password = "", domain = "";
public List<Program> appList;
public UserSettings()
{
appList = new List<NetRunner.Program>();
}
}
[Serializable]
public class Program
{
public string id;
public string name = "", prog_path = "", prog_args = "", icon_path = "";
public int order = 0;
public Key AN = Key.None;
public ModifierKeys Mod1 = ModifierKeys.None, Mod2 = ModifierKeys.None;
public Program()
{
id = GenerateID();
}
public Program(string name, string prog_path, string prog_args, string icon_path, int order, Key AN, ModifierKeys Mod1, ModifierKeys Mod2)
{
id = GenerateID();
this.name = name; this.prog_path = prog_path; this.prog_args = prog_args; this.icon_path = icon_path; this.order = order;
this.AN = AN; this.Mod1 = Mod1; this.Mod2 = Mod2;
}
private string GenerateID()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
namespace NetRunner
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
private NotifyIcon ni;
private MainWindow main;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
AppManager.LoadSettings();
main = new MainWindow();
ni = new NotifyIcon();
ni.DoubleClick += (s, a) => main.Show();
ni.Icon = System.Drawing.SystemIcons.Application;
ni.Visible = true;
ni.ContextMenuStrip = new ContextMenuStrip();
ni.ContextMenuStrip.Items.Add("Open").Click += (s, a) => OpenMain();
ni.ContextMenuStrip.Items.Add("Close").Click += (s, a) => CloseApp();
if (e.Args.Length > 0 && e.Args[0] == "/max")
{
main.Show();
}
}
private void OpenMain()
{
if (main.IsVisible)
{
if (main.WindowState == WindowState.Minimized)
main.WindowState = WindowState.Normal;
main.Activate();
}
else
main.Show();
}
private void CloseApp()
{
ni.Dispose();
ni = null;
AppManager.UnregisterAllHotkeys(AppManager.settings.appList);
App.Current.Shutdown();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace ShiftTracker
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
App.Current.Properties["closetimer"] = 4;
if (e.Args.Length > 0)
{
if (e.Args[0] == "/keepopen")
App.Current.Properties["closetimer"] = -10;
}
if (e.Args.Length == 2)
App.Current.Properties["initfile"] = e.Args[1];
MainWindow wnd = new MainWindow();
wnd.Show();
}
}
}
| 59e6814341305a3424cdeb041b6232e2afca4397 | [
"C#",
"Python"
] | 18 | C# | rdmachado/microutilities | b2a45dea8aedb09ede0fa00f1dfc51362587195d | 01aac174f7300227e90fd00b88fe3816baf4ce5c |
refs/heads/master | <repo_name>connor-klopfer/animal_response_nets<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/libraries.R
library(adehabitatHR)
library(adehabitatLT)
library(changepoint)
library(e1071)
library(igraph)
library(gtools)
library(Rcpp)
library(survival)<file_sep>/data_prep_scripts/import_beetle.py
#!/usr/bin/env python
# coding: utf-8
"""
Taking the association networks from the beetle data and saving to a friendlier format type, for easier use.
Used VThorsethief's code as a template
"""
from os.path import join
import pandas as pd
import networkx as nx
def get_beetle_networks():
"""Import the beetle encounters as an edgelist, partitioned into the components.
"""
filename = "SRI_edgelist.csv"
df = pd.read_csv(join(filename))
all_nets = {}
# For all treatement levels
for treatment in df['Group.ID.Populations'].unique():
all_nets[treatment] = {}
# For 'before' and 'after' injection
for treatment_period in df['Treatment.Period'].unique():
all_nets[treatment][treatment_period] = []
treatment_subset = df.loc[(df['Treatment.Period'] == treatment_period) & (df['Group.ID.Populations'] == treatment)]
# Append network from pandas dataframe into master dictionary
all_nets[treatment][treatment_period].append(nx.from_pandas_edgelist(treatment_subset,"Focal.Letter","Social.Partner", edge_attr=True))
return all_nets
<file_sep>/visualizations/vis_params.py
from matplotlib import rcParams
rcParams['axes.titlesize'] = 18
rcParams['axes.labelsize'] = 18
rcParams['legend.fontsize'] = 14
ANALYSIS_FOLDER = '../analysis_results/'
IMAGES_FOLDER = './images/'<file_sep>/data_prep_scripts/fairywren_cleaning.R
#' Cleaning the grate_tits data into a clean edgelist from the simplical
#' #' edgelist version.
reformat_fairywrens_dataset <- function(original){
#' Should give all the permutations seen in the dataset into a long, edgelist format.
bird_data <- original %>% select(contains("Bird"))
id_data <- original %>% select(-contains("Bird"))
bird_combos <- combn(bird_data, 2, simplify = FALSE)
all_dfs <- list()
for(x in 1:length(bird_combos)){
temp_dataset <- cbind(id_data, bird_combos[[x]])
n_cols <- ncol(temp_dataset)
names(temp_dataset)[(n_cols - 1):n_cols] <- c("Bird1", "Bird2")
all_dfs[[x]] <- temp_dataset
}
final <- do.call(rbind, all_dfs) %>% filter(!is.na(Bird1), !is.na(Bird2))
write.csv(final, "data/Fairywrens_LantzAndKarubian2017/fairwren_edgelist.csv", row.names = F)
return(final)
}
reformatted_fairywrens <- reformat_fairywrens_dataset(S1Table)
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/9_interaction_detection.R
######9_interaction_detection.R
### Calls C++ functions interaction_close_front_contacts and filter_interactions_cut_immobile (https://github.com/laurentkeller/anttrackingUNIL)
### interaction_close_front_contacts takes datfile and tagfile as an input and returns the list of all pairs of interacting ants on each frame
### filter_interactions_cut_immobile takes the output from interaction_close_front_contacts, checks whether subsequent interactions between the same pair of ants belong to the same interaction event or 2 distinct events, and returns the list of all interaction events
###Created by <NAME>
###########################################################################################
####get dat list #####
input_dat <- paste(data_path,"intermediary_analysis_steps/dat_files",sep="/")
setwd(input_dat)
dat_list <- paste(input_dat,list.files(pattern="dat"),sep="/")
####output folders
output_unfiltered <- paste(data_path,"/intermediary_analysis_steps/unfiltered_interactions",sep=""); if (!file.exists(output_unfiltered)){dir.create(output_unfiltered,recursive=T)}
output_filtered <- paste(data_path,"/intermediary_analysis_steps/filtered_interactions",sep=""); if (!file.exists(output_filtered)){dir.create(output_filtered,recursive=T)}
######### parameter values for detect interactions
distance <- 60 #####considers only ants who are distant by tl1/2+tl2/2+distance (speeds process up)
delta_angle <- 0 ####tests points along an arc with angle = -delta_angle,+delta_angle to tag orientation
angle_interval <- 0 ####tests points on that arc every angle_interval degrees
angle_parallel <- 0 #####will use all contacts, even back to front (because all contact can lead to transmission event)
####filter interaction parameters
width_ratio <- 0.7584637
width_factor <-0.7645475
filter_arguments <- " -t 20 -m 240 -d 25 -a 6 "
#### t: maximum time gap, in frames (10 sec); after this is considered a new interaction
#### m: maximum asleep duration, in frames . After that the interaction is either cut short, or if the ants move again, a new interaction is declared
#### d: maximum movement distance (25 pixels) for an interaction to be considered the same
#### a: asleep maximum movement. If movement less than that between successive frames then ant is considered asleep
for (datfile in dat_list){
dat_root <- gsub("\\.dat","",unlist(strsplit(datfile,split="/"))[grepl("\\.dat",unlist(strsplit(datfile,split="/")))])
colony <- unlist(strsplit(dat_root,split="_"))[grepl("colony",unlist(strsplit(dat_root,split="_")))]
tagfile <- tag_list[which(grepl(colony,tag_list))]
if (length(tagfile)>1){
tagfile <- tagfile[grepl(unlist(strsplit(dat_root,"_"))[grepl("Treatment",unlist(strsplit(dat_root,"_")))],tagfile)]
}
###detect interactions
command <- paste(executables_path,"/interaction_close_front_contacts ",datfile," ",tagfile," ",output_unfiltered,"/",dat_root,".txt ",distance," ",angle_parallel," ",width_factor," ",width_ratio," ",delta_angle," ",angle_interval,";",sep="")
print(command)
system(command)
###filter interactions
command <- paste(executables_path,"/filter_interactions_cut_immobile -i ",output_unfiltered,"/",dat_root,".txt -o ",output_filtered,"/",dat_root,".txt",filter_arguments, tagfile,sep="")
print(command)
system(command)
}<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/13_network_analysis.R
####13_network_analysis.R#####
#### Takes an interaction list as an input, builds a network, and analyse its properties
###Created by <NAME>
####################################
to_keep_ori <- to_keep
#################################
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
###remove output file
if (file.exists(paste(data_path,"/processed_data/individual_behaviour/post_treatment/interactions_with_treated.txt",sep=""))){
file.remove(paste(data_path,"/processed_data/individual_behaviour/post_treatment/interactions_with_treated.txt",sep=""))
}
#### get input file list
if (!grepl("survival",data_path)){
input_path <- paste(data_path,"/intermediary_analysis_steps/binned_interaction_lists",sep="")
setwd(input_path)
input_folders <- list.dirs(recursive=T,path="PreTreatment",full.names=F)
input_folders <- input_folders[which(input_folders!="")]
}else{
input_path <- paste(data_path,"/intermediary_analysis_steps/full_interaction_lists",sep="")
setwd(input_path)
input_folders <- list.dirs(recursive=T,path="PostTreatment",full.names=F)
input_folders <- input_folders[which(input_folders!="")]
}
queen_community_summary <- NULL
to_keep <- c(ls(),"to_keep","input_folder","network_files","options","option","summary_collective","summary_individual","outputfolder","network_file")
for (input_folder in input_folders){
print(input_folder)
setwd(input_path)
network_files <- list.files(path=paste("PreTreatment/",input_folder,sep=""),full.names=T)
if (input_folder=="observed"){
network_files <- c(network_files,list.files(path=paste("PostTreatment/",input_folder,sep=""),full.names=T))
if(grepl("main",data_path)){
options <- c("all_workers","untreated_only")
}else{
options <- c("all_workers")
}
}else{
options <- c("all_workers")
}
for (option in options){
print(option)
outputfolder <- paste(data_path,"/processed_data/network_properties",sep="")
summary_collective <- NULL
summary_individual <- NULL
for (network_file in network_files){
print(network_file)
####get file metadata
root_name <- gsub("_interactions.txt","",unlist(strsplit(network_file,split="/"))[grepl("colony",unlist(strsplit(network_file,split="/")))])
components <- unlist(strsplit(root_name,split="_"))
colony <- components[grepl("colony",components)]
colony_number <- as.numeric(gsub("colony","",colony))
treatment <- info[which(info$colony==colony_number),"treatment"]
colony_size <- info[which(info$colony==colony_number),"colony_size"]
if (!all(!grepl("PreTreatment",components))){period <- "before"}else{period <- "after"}
if(!grepl("survival",data_path)){
time_hours <- as.numeric(gsub("TH","",components[which(grepl("TH",components))]))
time_of_day <- as.numeric(gsub("TD","",components[which(grepl("TD",components))]))
}else{
if (period=="after"){
time_hours <- 0
time_of_day <- 12
}else{
time_hours <- -30
time_of_day <- 6
}
}
####get appropriate task_group list, treated list and tag
colony_treated <- treated[which(treated$colony==colony_number),"tag"]
colony_task_group <- task_groups[which(task_groups$colony==colony),]
tagfile <- tag_list[which(grepl(colony,tag_list))]
if (length(tagfile)>1){
tagfile <- tagfile[grepl(unlist(strsplit(gsub("\\.txt","",root_name),"_"))[grepl("Treatment",unlist(strsplit(gsub("\\.txt","",root_name),"_")))],tagfile)]
}
####read interactions
interactions <- read.table(network_file,header=T,stringsAsFactors = F)
tag <- read.tag(tagfile)$tag
names(tag)[names(tag)=="#tag"] <- "tag"; tag <- tag[which(tag$tag!="#tag"),]
tag[which(tag$age==0),"age"] <- NA ###unknown ages are coded as 0 in the tag file
if (!grepl("survival",data_path)){
alive <- tag[which(tag$final_status=="alive"),"tag"]
}else{
alive <- tag[which(as.numeric(tag$death)==0|as.numeric(tag$death)>=max(interactions$Stopframe,na.rm=T)),"tag"]
}
tag <-tag[which(tag$tag%in%alive),] ###remove dead ants from tag file
####if untreated only, reduce tag , colony_task_group, and interactions
if (option=="untreated_only"){
colony_task_group <- colony_task_group[which(!colony_task_group$tag%in%colony_treated),]
tag <- tag[which(!tag$tag%in%colony_treated),]
interactions <- interactions[which(!((interactions$Tag1%in%colony_treated)|(interactions$Tag2%in%colony_treated))),]
}
actors <- data.frame(name=as.character(tag$tag))
#### add a column contaning interaction duration in min
interactions["duration_min"] <- (interactions$Stoptime - interactions$Starttime + 0.5) /60 ###duration in minutes (one frame = 0.5 second)
#### add a column containing the status of tag 1 and the status of tag2
interactions[c("status_Tag1","status_Tag2")] <- "untreated"
interactions[which(interactions$Tag1%in%colony_treated),"status_Tag1"] <- "treated"
interactions[which(interactions$Tag2%in%colony_treated),"status_Tag2"] <- "treated"
#### use this information to calculate, for each worker, the cumulated duration of interaction with treated workers
if (input_folder=="observed"&option=="all_workers"){
aggregated1 <- aggregate(na.rm=T,na.action="na.pass",duration_min~Tag1+status_Tag2,FUN=sum,data=interactions[which(interactions$status_Tag2=="treated"),])
names(aggregated1) <- c("tag","partner_status","duration_min")
aggregated2 <- aggregate(na.rm=T,na.action="na.pass",duration_min~Tag2+status_Tag1,FUN=sum,data=interactions[which(interactions$status_Tag1=="treated"),])
names(aggregated2) <- c("tag","partner_status","duration_min")
aggregated <- rbind(aggregated1,aggregated2)
aggregated <- aggregate(na.rm=T,na.action="na.pass",duration_min~tag+partner_status,FUN=sum,data=aggregated)
interactions_with_treated <- merge(data.frame(tag=tag[which(tag$tag%in%alive),"tag"],stringsAsFactors = F),aggregated[c("tag","duration_min")],all.x=T)
interactions_with_treated[is.na(interactions_with_treated$duration_min),"duration_min"] <- 0
names(interactions_with_treated) <- c("tag","duration_of_contact_with_treated_min")
interactions_with_treated["colony"] <- colony
interactions_with_treated["time_hours"] <- time_hours
###write results
###individual behaviour: pre_vs_post treatment
if (grepl("main",data_path)){
behav <- read.table(paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""),header=T,stringsAsFactors = F)
if (!"duration_of_contact_with_treated_min"%in%names(behav)){
behav[c("duration_of_contact_with_treated_min")] <- NA
}
behav[match(as.character(interaction(interactions_with_treated$colony,interactions_with_treated$tag,interactions_with_treated$time_hours)),as.character(interaction(behav$colony,behav$tag,behav$time_hours))),c("duration_of_contact_with_treated_min")] <- interactions_with_treated$duration_of_contact_with_treated_min
options(digits=3)
write.table(behav,file=paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""), row.names=F, col.names=T,append=F,quote=F)
options(digits=16)
}
###interactions with treated: post-treatment
if (period=="after"){
outputfoldy <- paste(data_path,"/processed_data/individual_behaviour/post_treatment",sep="")
if(!file.exists(outputfoldy)){dir.create(outputfoldy,recursive=T)}
int_with_treated <- data.frame(colony_size=colony_size,treatment=treatment,period=period,time_of_day=time_of_day,
interactions_with_treated,stringsAsFactors = F)
if (!file.exists(paste(data_path,"/processed_data/individual_behaviour/post_treatment/interactions_with_treated.txt",sep=""))){
write.table(int_with_treated,file=paste(outputfoldy,"/interactions_with_treated.txt",sep=""),col.names=T,row.names=F,quote=F,append=F)
}else{
write.table(int_with_treated,file=paste(outputfoldy,"/interactions_with_treated.txt",sep=""),col.names=F,row.names=F,quote=F,append=T)
}
}
}
###build NETWORK
if (!grepl("survival",data_path)){
net <- graph.data.frame(interactions[c("Tag1","Tag2")],directed=F,vertices=actors)
### add edge weights
E(net)$weight <- interactions[,"duration_min"]
###simplify graph (merge all edges involving the same pair of ants into a single one whose weight = sum of these weights)
net <- simplify(net,remove.multiple=TRUE,remove.loop=TRUE,edge.attr.comb="sum")
##################remove unconnected nodes
unconnected <- actors[degree(net)==0,]
net <- net - as.character(unconnected)
##################update actor list
actors <- get.vertex.attribute(net,"name")
####Part 1: collective network properties ####
##Assortativity - Age
####if age experiment, get colony ages
if (grepl("age",data_path)){
colony_ages <- ages [which(ages$colony==colony),]
####set queen age to NA as this would bias the result (the queen is the oldest individual and interacts mostly with the young nurses)
colony_ages[which(colony_ages$tag==queenid),"age"] <- NA
####order the age acording to the order of the network's vertices
ordered_ages <- colony_ages[match(V(net)$name,as.character(colony_ages$tag)),"age"]
#### calculate age assortativity
age_assortativity <- assortativity(net-V(net)$name[is.na(ordered_ages)],types1=ordered_ages[!is.na(ordered_ages)],directed=F)
}else{
age_assortativity <- NA
}
## Assortativity - Task
ordered_task_groups <- colony_task_group[match(actors,as.character(colony_task_group$tag)),"task_group"]
ordered_task_groups <- as.numeric(as.factor(ordered_task_groups))
task_assortativity <- assortativity_nominal(net,types=ordered_task_groups,directed=F)
##Clustering
clustering <- mean(transitivity(net,type="barrat",weights=E(net)$weight,isolates = c("NaN")),na.rm=T)
##Degree mean and max
degrees <- degree(net,mode="all")
degree_mean <- mean(degrees,na.rm=T)
degree_maximum <- max(degrees,na.rm=T)
##Density
density <- igraph::edge_density(net)
##Diameter
diameter <- igraph::diameter(net,directed=F,unconnected=TRUE,weights=(1/E(net)$weight)) ###here use the inverse of the weights, because the algorithm considers weights as distances rather than strengths of connexion
##Efficiency
net_dist <- shortest.paths(net, weights=1/E(net)$weight, mode="all") ##again use the inverse of the weights, because the algorithm considers weights as distances rather than strengths of connexion
net_dist[net_dist==0] <- NA ##remove distances to self
efficiency <- 1/net_dist ##transform each distance into an efficiency
efficiency <- (1/((vcount(net)*(vcount(net)-1))))*(sum(efficiency,na.rm=TRUE))
## Modularity
communities <- cluster_louvain(net, weights = E(net)$weight)
community_membership <- communities$membership
modularity <- modularity(net,community_membership,weights=E(net)$weight)
###Add to data
summary_collective <- rbind(summary_collective,data.frame(randy=input_folder,colony=colony,colony_size=colony_size,treatment=treatment,period=period,time_hours=time_hours,time_of_day=time_of_day,
age_assortativity=age_assortativity,
task_assortativity=task_assortativity,
clustering=clustering,
degree_mean=degree_mean,
degree_maximum=degree_maximum,
density=density,
diameter=diameter,
efficiency=efficiency,
modularity=modularity,stringsAsFactors = F))
####Part 2: individual network properties ####
###prepare table
tag["status"] <- "untreated"; tag[which(tag$tag%in%colony_treated),"status"] <- "treated"
individual <- data.frame(randy=input_folder,colony=colony,colony_size=colony_size,treatment=treatment,tag=tag$tag,age=tag$age,status=tag$group,period=period,time_hours=time_hours,time_of_day=time_of_day,
degree=NA,
aggregated_distance_to_queen=NA,
mean_aggregated_distance_to_treated=NA,
same_community_as_queen=NA)
##degree
individual[match(names(degrees),individual$tag),"degree"] <- degrees
##same community as queen
queen_comm <- community_membership[which(V(net)$name==queenid)]
community_membership <- community_membership==queen_comm
individual[match(V(net)$name,individual$tag),"same_community_as_queen"] <- community_membership
##path length to queen
if (queenid%in%actors){
path_length_to_queen <- t(shortest.paths(net,v=actors,to="665",weights=1/E(net)$weight))
individual[match(colnames(path_length_to_queen),individual$tag),"aggregated_distance_to_queen"] <- as.numeric(path_length_to_queen )
}
########Mean path length to treated; aggregated_network
if(option!="untreated_only"){
path_length_to_treated <- as.data.frame(as.matrix(shortest.paths(net,v=actors,to=as.character(colony_treated)[as.character(colony_treated)%in%V(net)$name],weights=1/E(net)$weight)))
path_length_to_treated["mean_distance_to_treated"] <- NA
path_length_to_treated$mean_distance_to_treated <- as.numeric(rowMeans(path_length_to_treated,na.rm=T))
individual[match(rownames(path_length_to_treated),individual$tag),"mean_aggregated_distance_to_treated"] <- path_length_to_treated[,"mean_distance_to_treated"]
}
###Add data to main data table
summary_individual <- rbind(summary_individual,individual)
}
clean()
}
#####write #####
if (!grepl("survival",data_path)){
if (input_folder=="observed"){
####Main experiment: write pre_vs_post_treatment data
if (!grepl("age",data_path)){
outputfolder2 <- paste(outputfolder,"pre_vs_post_treatment",option,sep="/")
if(!file.exists(outputfolder2)){dir.create(outputfolder2,recursive=T)}
write.table(summary_collective[,names(summary_collective)!="randy"],file=paste(outputfolder2,"/colony_data.txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
write.table(summary_individual[,names(summary_individual)!="randy"],file=paste(outputfolder2,"/individual_data.txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
}
####All workers: write pre_treatment data into random_vs_observed folder
if (option=="all_workers"){
outputfolder3 <- paste(outputfolder,"random_vs_observed",sep="/")
if(!file.exists(outputfolder3)){dir.create(outputfolder3,recursive=T)}
write.table(summary_collective[which(summary_collective$period=="before"),],file=paste(outputfolder3,"/network_properties_",input_folder,".txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
write.table(summary_individual[which(summary_individual$period=="before"),],file=paste(outputfolder3,"/node_properties_",input_folder,".txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
outputfolder4 <- paste(outputfolder,"post_treatment",sep="/")
if(!file.exists(outputfolder4)){dir.create(outputfolder4,recursive=T)}
write.table(summary_collective[which(summary_collective$period=="after"),],file=paste(outputfolder4,"/network_properties_",input_folder,".txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
write.table(summary_individual[which(summary_individual$period=="after"),],file=paste(outputfolder4,"/node_properties_",input_folder,".txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
}
######Main experiment, All workers: add pre_treatment node_properties information to pre_treatment behaviour file
if (!grepl("age",data_path)&option=="all_workers"){
pre_treatment_behav_file <- paste(data_path,"/processed_data/individual_behaviour/pre_treatment/network_position_vs_time_outside.dat",sep="")
pre_treatment_behav <- read.table(pre_treatment_behav_file,header=T,stringsAsFactors = F)
pre_treatment_behav <- merge(pre_treatment_behav,summary_individual[which(summary_individual$period=="before"),c("colony","tag","time_hours","degree","aggregated_distance_to_queen")],all.x=T,all.y=T)
pre_treatment_behav <- pre_treatment_behav[order(pre_treatment_behav$colony,pre_treatment_behav$tag,pre_treatment_behav$time_hours),]
write.table(pre_treatment_behav, file=pre_treatment_behav_file,col.names=T,row.names=F,quote=F,append=F)
}
}else{
outputfolder3 <- paste(outputfolder,"random_vs_observed",sep="/")
if(!file.exists(outputfolder3)){dir.create(outputfolder3,recursive=T)}
write.table(summary_collective[which(summary_collective$period=="before"),],file=paste(outputfolder3,"/network_properties_",input_folder,".txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
write.table(summary_individual[which(summary_individual$period=="before"),],file=paste(outputfolder3,"/node_properties_",input_folder,".txt",sep=""),col.names = T,row.names=F,append=F,quote=F)
}
}
###Get characteristics of queen community vs. other communities (worker age, prop. of foragers)
if (!grepl("survival",data_path)&option=="all_workers"){
summary_individual_before <- read.table(paste(outputfolder,"/random_vs_observed/node_properties_",input_folder,".txt",sep=""),header = T,stringsAsFactors = F)
summary_individual_before <- summary_individual_before[which(summary_individual_before$period=="before"),]
####if necessary: add age
if (grepl("age",data_path)){
summary_individual_before <- merge(summary_individual_before[,which(names(summary_individual_before)!="age")],ages,all.x=T,all.y=F)
}else{
summary_individual_before$age <- NA
}
####add task_group
summary_individual_before <- merge(summary_individual_before,task_groups,all.x=T,all.y=F)
###remove queen
summary_individual_before <- summary_individual_before[which(summary_individual_before$tag!=queenid),]
###1. calculate mean proportion of foragers depending on with vs without queen
summary_individual_before["forager"] <- 0
summary_individual_before[which(summary_individual_before$task_group=="forager"),"forager"] <- 1
prop_foragers <- aggregate(na.rm=T,na.action="na.pass",forager~colony+randy+colony_size+treatment+period+time_hours+same_community_as_queen,FUN=mean,data=summary_individual_before)
prop_foragers <- aggregate(na.rm=T,na.action="na.pass",forager~colony+randy+colony_size+treatment+period+same_community_as_queen,FUN=mean,data=prop_foragers)
names(prop_foragers)[names(prop_foragers)=="same_community_as_queen"] <- "in_queen_comm";names(prop_foragers)[names(prop_foragers)=="forager"] <- "proportion_of_foragers"
###2. calculate mean age of workers depending on with vs without queen
if (grepl("age",data_path)){
mean_age <- aggregate(na.rm=T,na.action="na.pass",age~colony+randy+colony_size+treatment+period+time_hours+same_community_as_queen,FUN=mean,data=summary_individual_before)
mean_age <- aggregate(na.rm=T,na.action="na.pass",age~colony+randy+colony_size+treatment+period+same_community_as_queen,FUN=mean,data=mean_age)
names(mean_age)[names(mean_age)=="same_community_as_queen"] <- "in_queen_comm"
prop_foragers <- merge(prop_foragers,mean_age,all.x=T)
}else{
prop_foragers$age <- NA
}
prop_foragers[which(prop_foragers$in_queen_comm=="FALSE"),"in_queen_comm"] <- "not_with_queen"
prop_foragers[which(prop_foragers$in_queen_comm=="TRUE"),"in_queen_comm"] <- "with_queen"
if (grepl("random",input_folder)){
prop_foragers["randy"] <- "random"
}
queen_community_summary <- rbind(queen_community_summary,prop_foragers)
}
}
}
if (!grepl("survival",data_path)){
queen_community_summary <- aggregate(na.rm=T,na.action="na.pass",cbind(proportion_of_foragers,age)~.,FUN=mean,data=queen_community_summary)
queen_community_summary <- queen_community_summary[order(queen_community_summary$randy,queen_community_summary$colony),]
queen_community_summary$treatment <- queen_community_summary$randy
if (!file.exists(paste(data_path,"/processed_data/network_properties/random_vs_observed",sep=""))){dir.create(paste(data_path,"/processed_data/network_properties/random_vs_observed",sep=""),recursive=T)}
write.table(queen_community_summary,file=paste(data_path,"/processed_data/network_properties/random_vs_observed/queen_community.dat",sep=""),append=F,quote=F,row.names=F,col.names=T)
}
to_keep <- to_keep_ori
<file_sep>/pre_made_scripts/LPS_belize_effect_size08.R
# Plot changes in effect sizes of LPS on Belize vampire bat social networks
# <NAME> and <NAME>
# clear workspace
rm(list=ls())
# set directory
setwd("~/Dropbox/Dropbox/_working/_ACTIVE/belize_LPS/2018_Belize_analysis")
setwd("C:/Users/simon.ripperger/Dropbox/2018_Belize_analysis")
.libPaths("C:/R libraries")
# load packages
library(tidyverse)
library(boot)
library(lubridate)
library(lme4)
library(lmerTest)
library(igraph)
library(cowplot)
# run simulations to get new data or plot existing data??
GET_NEW_DATA <- F
GET_NEW_DATA <- T
# or load simulation data or run simulations----
if(GET_NEW_DATA==F){
load('simulation_results_2020-03-06_08_23.Rdata')
}else{
# load data from main R script
load('results_2020-09-15_21_02.Rdata')
# EFFECT OF NUMBER OF MEETINGS ON LPS EFFECT SIZE -----
# define association using MANY RSSI values ----
thresholds <-
quantile(Belize$RSSI, probs = seq(from = 76, to = 98, by = 2)/100)
thresholds
# create df to store effect sizes
effect_sizes <- tibble(RSSI= names(thresholds), effect_size_degree= NA, n.meetings= NA, p=NA)
# for loop ----
start <- Sys.time()
options(dplyr.show_progress = T)
for (i in 1:length(thresholds)) {
RSSI_threshold = thresholds[i] #set RSSI threshold
#threshold for Current Biology paper was -26dmb at 90%; here -27dbm at 85%
# clean data
df <-
Belize %>%
filter(RSSI > RSSI_threshold) %>%
filter(SenderID %in% BatIDs ) %>%
filter(EncounteredID %in% BatIDs ) %>%
select(- PacketID, -ChunkID) %>%
mutate(dyad= if_else(SenderID<EncounteredID,
paste(SenderID,EncounteredID, sep="_"),
paste(EncounteredID,SenderID, sep="_"))) %>%
mutate(EndOfMeeting = StartOfMeeting + MeetingDuration) %>%
group_by(dyad) %>%
arrange(StartOfMeeting) %>%
mutate(indx = c(0, cumsum(as.numeric(lead(StartOfMeeting)) >
cummax(as.numeric(EndOfMeeting)))[-n()])) %>%
group_by(dyad, indx) %>%
summarise(StartOfMeeting = min(StartOfMeeting),
EndOfMeeting = max(EndOfMeeting),
duration = difftime(EndOfMeeting, StartOfMeeting,unit = "secs"),
RSSI = max(RSSI)) %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(duration = as.numeric(duration, unit = "secs"))
# count meetings
n.meetings <- nrow(df)
# insert hour breaks
# convert start and end times to interval
df$interval <- interval(df$StartOfMeeting, df$EndOfMeeting)
#insert "event" column with series of numbers
df$event <- c(1:nrow(df))
# create function to get hours within a time interval
get_hours <- function(event, StartOfMeeting, EndOfMeeting){
hours <- seq(StartOfMeeting-minute(StartOfMeeting)*60-second(StartOfMeeting),
EndOfMeeting-minute(EndOfMeeting)*60-second(EndOfMeeting),
"hour")
dateseq <- hours
dateseq[1] <- StartOfMeeting
r <- c(dateseq, EndOfMeeting)
dur <- as.numeric(difftime(r[-1], r[-length(r)], unit = 'secs'))
data.frame(event, hour = hours, duration = dur)}
# create new events with event durations within each hour
df2 <-
df %>%
rowwise %>%
do(get_hours(.$event, .$StartOfMeeting, .$EndOfMeeting)) %>%
ungroup() %>%
group_by(event, hour) %>%
summarize(duration = sum(duration)) %>%
as.data.frame()
# match original start time back into new events
df2$StartOfMeeting <- df$StartOfMeeting[match(df2$event, df$event)]
# if start time is past the hour use that start time, otherwise use the hour slot as the start time
df2$StartOfMeeting <- if_else(df2$StartOfMeeting>df2$hour, df2$StartOfMeeting, df2$hour)
# match original end time back into new events
df2$EndOfMeeting <- df$EndOfMeeting[match(df2$event, df$event)]
# if end time is before the next hour (start hour+ 1 hour), use that end time, otherwise use the next hour
df2$EndOfMeeting <- if_else(df2$EndOfMeeting<(df2$hour+3600), df2$EndOfMeeting, df2$hour+3600)
# match other data back in
df2$dyad <- df$dyad[match(df2$event, df$event)]
df2$RSSI <- df$RSSI[match(df2$event, df$event)]
# set end of meeting
# set timezone to BelizeTime
# set start of study to 3pm on 25th
df <-
df2 %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(StartBelizeTime = force_tz(StartOfMeeting, tzone = "CST6CDT")) %>%
mutate(EndBelizeTime = force_tz(EndOfMeeting, tzone = "CST6CDT")) %>%
mutate(StartBelizeTime= StartBelizeTime - hours(8), EndBelizeTime=EndBelizeTime - hours(8)) %>%
filter(StartBelizeTime >= as.POSIXct("2018-04-25 15:00:00", tz = "CST6CDT")) %>%
select(StartBelizeTime,bat1,bat2,duration, RSSI)
# match treatment from bats table into df
df$treatment_bat1 <- bats$treatment[match(df$bat1, bats$sensor_node)]
df$treatment_bat2 <- bats$treatment[match(df$bat2, bats$sensor_node)]
# remove other dataframe
rm(df2)
# define treatment and post-treatment periods
d <-
df %>%
mutate(datetime= as.POSIXct(StartBelizeTime,tz = "CST6CDT")) %>%
mutate(treatment_period= datetime >= treatment_start & datetime < treatment_stop) %>%
mutate(post24_period= datetime >= post24_start & datetime < post24_stop) %>%
mutate(post48_period= datetime >= post48_start & datetime < post48_stop) %>%
mutate(hour= substring(datetime, 1,13))
# get treated bats
treated.bats <-
d %>%
mutate(treated= ifelse(treatment_bat1=="LPS", bat1,
ifelse(treatment_bat2=="LPS", bat2, NA))) %>%
filter(!is.na(treated)) %>%
pull(treated) %>%
unique()
# make six-hour network for each period----
network.treatment <-
d %>%
filter(treatment_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F)
network.post24 <-
d %>%
filter(post24_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
network.post48 <-
d %>%
filter(post48_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
# compare network centrality by treatment period
centrality.treatment <-
tibble(bat= names(degree(network.treatment)),
degree= degree(network.treatment),
strength= strength(network.treatment),
eigenvector= eigen_centrality(network.treatment)$vector,
period= "during treatment")
centrality.post24 <-
tibble(bat= names(degree(network.post24)),
degree= degree(network.post24),
strength= strength(network.post24),
eigenvector= eigen_centrality(network.post24)$vector,
period= "post-treatment") %>%
# define two post-treatment periods or one
mutate(period= paste(period, "24 hours later")) %>%
ungroup()
centrality.post48 <-
tibble(bat= names(degree(network.post48)),
degree= degree(network.post48),
strength= strength(network.post48),
eigenvector= eigen_centrality(network.post48)$vector,
period= "post-treatment") %>%
# define two post periods or one
mutate(period= paste(period, "48 hours later")) %>%
ungroup()
# get centrality data per period and bat
data <-
rbind(centrality.treatment, centrality.post24, centrality.post48) %>%
mutate(treated= bat %in% treated.bats) %>%
mutate(treatment= ifelse(treated, "LPS", "saline"))
# get effect sizes (slope)
effect_sizes$effect_size_degree[i] <-
summary(lm(degree~ treated, data= data[which(data$period=="during treatment"),]))$coefficients[2,1] #effect during treatment
# p-values
effect_sizes$p[i] <-
summary(lm(degree~ treated, data= data[which(data$period=="during treatment"),]))$coefficients[2,4]
# store number of meetings
effect_sizes$n.meetings[i] <- n.meetings
# print progress
print(paste(i, "of", length(thresholds)))
}
stop <- Sys.time()
loop1time <- stop-start
loop1time
# EFFECT OF MEETING DURATION ON LPS EFFECT SIZE-----
# define association using one RSSI value ----
thresholds <- quantile(Belize$RSSI, probs = c(85)/100)
# define minimum duration using many values----
min.durations <- seq(from=0, to= 1200, by= 60)
# create df to store effect sizes
effect_sizes2 <- tibble(duration= min.durations, effect_size_degree= NA, n.meetings= NA, p=NA)
# for loop ----
start <- Sys.time()
for (i in 1:length(min.durations)) {
RSSI_threshold = thresholds[1] #set RSSI threshold
# clean data and filter by duration
df <-
Belize %>%
filter(RSSI > RSSI_threshold) %>%
filter(SenderID %in% BatIDs ) %>%
filter(EncounteredID %in% BatIDs ) %>%
select(- PacketID, -ChunkID) %>%
mutate(dyad= if_else(SenderID<EncounteredID,
paste(SenderID,EncounteredID, sep="_"),
paste(EncounteredID,SenderID, sep="_"))) %>%
mutate(EndOfMeeting = StartOfMeeting + MeetingDuration) %>%
group_by(dyad) %>%
arrange(StartOfMeeting) %>%
mutate(indx = c(0, cumsum(as.numeric(lead(StartOfMeeting)) >
cummax(as.numeric(EndOfMeeting)))[-n()])) %>%
group_by(dyad, indx) %>%
summarise(StartOfMeeting = min(StartOfMeeting),
EndOfMeeting = max(EndOfMeeting),
duration = difftime(EndOfMeeting, StartOfMeeting,unit = "secs"),
RSSI = max(RSSI)) %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(duration = as.numeric(duration, unit = "secs")) %>%
filter(duration > min.durations[i]) %>%
ungroup()
# count meetings
n.meetings <- nrow(df)
# insert hour breaks
# convert start and end times to interval
df$interval <- interval(df$StartOfMeeting, df$EndOfMeeting)
#insert "event" column with series of numbers
df$event <- c(1:nrow(df))
# create function to get hours within a time interval
get_hours <- function(event, StartOfMeeting, EndOfMeeting){
hours <- seq(StartOfMeeting-minute(StartOfMeeting)*60-second(StartOfMeeting),
EndOfMeeting-minute(EndOfMeeting)*60-second(EndOfMeeting),
"hour")
dateseq <- hours
dateseq[1] <- StartOfMeeting
r <- c(dateseq, EndOfMeeting)
dur <- as.numeric(difftime(r[-1], r[-length(r)], unit = 'secs'))
data.frame(event, hour = hours, duration = dur)}
# create new events with event durations within each hour
df2 <-
df %>%
rowwise %>%
do(get_hours(.$event, .$StartOfMeeting, .$EndOfMeeting)) %>%
ungroup() %>%
group_by(event, hour) %>%
summarize(duration = sum(duration)) %>%
as.data.frame()
# match original start time back into new events
df2$StartOfMeeting <- df$StartOfMeeting[match(df2$event, df$event)]
# if start time is past the hour use that start time, otherwise use the hour slot as the start time
df2$StartOfMeeting <- if_else(df2$StartOfMeeting>df2$hour, df2$StartOfMeeting, df2$hour)
# match original end time back into new events
df2$EndOfMeeting <- df$EndOfMeeting[match(df2$event, df$event)]
# if end time is before the next hour (start hour+ 1 hour), use that end time, otherwise use the next hour
df2$EndOfMeeting <- if_else(df2$EndOfMeeting<(df2$hour+3600), df2$EndOfMeeting, df2$hour+3600)
# match other data back in
df2$dyad <- df$dyad[match(df2$event, df$event)]
df2$RSSI <- df$RSSI[match(df2$event, df$event)]
# set end of meeting
# set timezone to BelizeTime
# set start of study to 3pm on 25th
df <-
df2 %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(StartBelizeTime = force_tz(StartOfMeeting, tzone = "CST6CDT")) %>%
mutate(EndBelizeTime = force_tz(EndOfMeeting, tzone = "CST6CDT")) %>%
mutate(StartBelizeTime= StartBelizeTime - hours(8), EndBelizeTime=EndBelizeTime - hours(8)) %>%
filter(StartBelizeTime >= as.POSIXct("2018-04-25 15:00:00", tz = "CST6CDT")) %>%
select(StartBelizeTime,bat1,bat2,duration, RSSI)
# match treatment from bats table into df
df$treatment_bat1 <- bats$treatment[match(df$bat1, bats$sensor_node)]
df$treatment_bat2 <- bats$treatment[match(df$bat2, bats$sensor_node)]
# remove other dataframe
rm(df2)
# define treatment and post-treatment periods
d <-
df %>%
mutate(datetime= as.POSIXct(StartBelizeTime,tz = "CST6CDT")) %>%
mutate(treatment_period= datetime >= treatment_start & datetime < treatment_stop) %>%
mutate(post24_period= datetime >= post24_start & datetime < post24_stop) %>%
mutate(post48_period= datetime >= post48_start & datetime < post48_stop) %>%
mutate(hour= substring(datetime, 1,13))
# get treated bats
treated.bats <-
d %>%
mutate(treated= ifelse(treatment_bat1=="LPS", bat1,
ifelse(treatment_bat2=="LPS", bat2, NA))) %>%
filter(!is.na(treated)) %>%
pull(treated) %>%
unique()
# make six-hour network for each period----
network.treatment <-
d %>%
filter(treatment_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F)
network.post24 <-
d %>%
filter(post24_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
network.post48 <-
d %>%
filter(post48_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
# compare network centrality by treatment period
centrality.treatment <-
tibble(bat= names(degree(network.treatment)),
degree= degree(network.treatment),
strength= strength(network.treatment),
eigenvector= eigen_centrality(network.treatment)$vector,
period= "during treatment")
centrality.post24 <-
tibble(bat= names(degree(network.post24)),
degree= degree(network.post24),
strength= strength(network.post24),
eigenvector= eigen_centrality(network.post24)$vector,
period= "post-treatment") %>%
# define two post-treatment periods or one
mutate(period= paste(period, "24 hours later")) %>%
ungroup()
centrality.post48 <-
tibble(bat= names(degree(network.post48)),
degree= degree(network.post48),
strength= strength(network.post48),
eigenvector= eigen_centrality(network.post48)$vector,
period= "post-treatment") %>%
# define two post periods or one
mutate(period= paste(period, "48 hours later")) %>%
ungroup()
# get centrality data per period and bat
data <-
rbind(centrality.post24, centrality.post48, centrality.treatment) %>%
mutate(treated= bat %in% treated.bats) %>%
mutate(treatment= ifelse(treated, "LPS", "saline")) %>%
# combine post periods
mutate(period= ifelse(period=="during treatment", period, "post-treatment"))
# get effect sizes (slope)
effect_sizes2$effect_size_degree[i] <-
summary(lm(degree~ treated, data= data[which(data$period=="during treatment"),]))$coefficients[2,1] #effect during treatment
# p-values
effect_sizes2$p[i] <- summary(lm(degree~ treated, data= data[which(data$period=="during treatment"),]))$coefficients[2,4]
# store number of meetings
effect_sizes2$n.meetings[i] <- n.meetings
# print progress
print(paste(i, "of", length(min.durations)))
}
stop <- Sys.time()
loop2time <- stop-start
loop2time
# EFFECT OF RSSI ON LPS EFFECT SIZE (AT CONSTANT SAMPLE SIZE)-----
# choose number of effect sizes to sample at each RSSI level
replicates <- 200
# define association using MANY RSSI values ----
thresholds <-
quantile(Belize$RSSI, probs = rep(seq(from = 76, to = 94, by = 2)/100, each=replicates) )
thresholds
unique(thresholds)
# choose number of meetings to randomly sample
# set number to be 95% of the number of meetings at the largest RSSI quantile
random_N <-
Belize %>%
filter(RSSI > thresholds[length(thresholds)]) %>%
filter(SenderID %in% BatIDs ) %>%
filter(EncounteredID %in% BatIDs ) %>%
select(- PacketID, -ChunkID) %>%
mutate(dyad= if_else(SenderID<EncounteredID,
paste(SenderID,EncounteredID, sep="_"),
paste(EncounteredID,SenderID, sep="_"))) %>%
mutate(EndOfMeeting = StartOfMeeting + MeetingDuration) %>%
group_by(dyad) %>%
arrange(StartOfMeeting) %>%
mutate(indx = c(0, cumsum(as.numeric(lead(StartOfMeeting)) >
cummax(as.numeric(EndOfMeeting)))[-n()])) %>%
group_by(dyad, indx) %>%
summarise(StartOfMeeting = min(StartOfMeeting),
EndOfMeeting = max(EndOfMeeting),
duration = difftime(EndOfMeeting, StartOfMeeting,unit = "secs"),
RSSI = max(RSSI)) %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(duration = as.numeric(duration, unit = "secs")) %>%
ungroup() %>%
sample_frac(size=0.95) %>%
nrow()
random_N
# define minimum duration
min.durations <- 0
# create df to store effect sizes
effect_sizes3 <- tibble(RSSI= names(thresholds), effect_size_degree= NA, n.meetings= NA, p=NA)
# for loop ----
start <- Sys.time()
options(dplyr.show_progress = F)
for (i in 1:length(thresholds)) {
RSSI_threshold = thresholds[i] #set RSSI threshold
# clean data and filter by duration
df <-
Belize %>%
filter(RSSI > RSSI_threshold) %>% ###
filter(SenderID %in% BatIDs ) %>%
filter(EncounteredID %in% BatIDs ) %>%
select(- PacketID, -ChunkID) %>%
mutate(dyad= if_else(SenderID<EncounteredID,
paste(SenderID,EncounteredID, sep="_"),
paste(EncounteredID,SenderID, sep="_"))) %>%
mutate(EndOfMeeting = StartOfMeeting + MeetingDuration) %>%
group_by(dyad) %>%
arrange(StartOfMeeting) %>%
mutate(indx = c(0, cumsum(as.numeric(lead(StartOfMeeting)) >
cummax(as.numeric(EndOfMeeting)))[-n()])) %>%
group_by(dyad, indx) %>%
summarise(StartOfMeeting = min(StartOfMeeting),
EndOfMeeting = max(EndOfMeeting),
duration = difftime(EndOfMeeting, StartOfMeeting,unit = "secs"),
RSSI = max(RSSI)) %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(duration = as.numeric(duration, unit = "secs")) %>%
ungroup() %>%
sample_n(size= random_N, replace = F)
# count meetings
n.meetings <- nrow(df)
# insert hour breaks
# convert start and end times to interval
df$interval <- interval(df$StartOfMeeting, df$EndOfMeeting)
#insert "event" column with series of numbers
df$event <- c(1:nrow(df))
# create function to get hours within a time interval
get_hours <- function(event, StartOfMeeting, EndOfMeeting){
hours <- seq(StartOfMeeting-minute(StartOfMeeting)*60-second(StartOfMeeting),
EndOfMeeting-minute(EndOfMeeting)*60-second(EndOfMeeting),
"hour")
dateseq <- hours
dateseq[1] <- StartOfMeeting
r <- c(dateseq, EndOfMeeting)
dur <- as.numeric(difftime(r[-1], r[-length(r)], unit = 'secs'))
data.frame(event, hour = hours, duration = dur)}
# create new events with event durations within each hour
df2 <-
df %>%
rowwise %>%
do(get_hours(.$event, .$StartOfMeeting, .$EndOfMeeting)) %>%
ungroup() %>%
group_by(event, hour) %>%
summarize(duration = sum(duration)) %>%
as.data.frame()
# match original start time back into new events
df2$StartOfMeeting <- df$StartOfMeeting[match(df2$event, df$event)]
# if start time is past the hour use that start time, otherwise use the hour slot as the start time
df2$StartOfMeeting <- if_else(df2$StartOfMeeting>df2$hour, df2$StartOfMeeting, df2$hour)
# match original end time back into new events
df2$EndOfMeeting <- df$EndOfMeeting[match(df2$event, df$event)]
# if end time is before the next hour (start hour+ 1 hour), use that end time, otherwise use the next hour
df2$EndOfMeeting <- if_else(df2$EndOfMeeting<(df2$hour+3600), df2$EndOfMeeting, df2$hour+3600)
# match other data back in
df2$dyad <- df$dyad[match(df2$event, df$event)]
df2$RSSI <- df$RSSI[match(df2$event, df$event)]
# set end of meeting
# set timezone to BelizeTime
# set start of study to 3pm on 25th
df <-
df2 %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(StartBelizeTime = force_tz(StartOfMeeting, tzone = "CST6CDT")) %>%
mutate(EndBelizeTime = force_tz(EndOfMeeting, tzone = "CST6CDT")) %>%
mutate(StartBelizeTime= StartBelizeTime - hours(8), EndBelizeTime=EndBelizeTime - hours(8)) %>%
filter(StartBelizeTime >= as.POSIXct("2018-04-25 15:00:00", tz = "CST6CDT")) %>%
select(StartBelizeTime,bat1,bat2,duration, RSSI)
# match treatment from bats table into df
df$treatment_bat1 <- bats$treatment[match(df$bat1, bats$sensor_node)]
df$treatment_bat2 <- bats$treatment[match(df$bat2, bats$sensor_node)]
# remove other dataframe
rm(df2)
# define treatment and post-treatment periods
d <-
df %>%
mutate(datetime= as.POSIXct(StartBelizeTime,tz = "CST6CDT")) %>%
mutate(treatment_period= datetime >= treatment_start & datetime < treatment_stop) %>%
mutate(post24_period= datetime >= post24_start & datetime < post24_stop) %>%
mutate(post48_period= datetime >= post48_start & datetime < post48_stop) %>%
mutate(hour= substring(datetime, 1,13))
# get treated bats
treated.bats <-
d %>%
mutate(treated= ifelse(treatment_bat1=="LPS", bat1,
ifelse(treatment_bat2=="LPS", bat2, NA))) %>%
filter(!is.na(treated)) %>%
pull(treated) %>%
unique()
# make six-hour network for each period----
network.treatment <-
d %>%
filter(treatment_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F)
network.post24 <-
d %>%
filter(post24_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
network.post48 <-
d %>%
filter(post48_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
# compare network centrality by treatment period
centrality.treatment <-
tibble(bat= names(degree(network.treatment)),
degree= degree(network.treatment),
strength= strength(network.treatment),
eigenvector= eigen_centrality(network.treatment)$vector,
period= "during treatment")
centrality.post24 <-
tibble(bat= names(degree(network.post24)),
degree= degree(network.post24),
strength= strength(network.post24),
eigenvector= eigen_centrality(network.post24)$vector,
period= "post-treatment") %>%
# define two post-treatment periods or one
mutate(period= paste(period, "24 hours later")) %>%
ungroup()
centrality.post48 <-
tibble(bat= names(degree(network.post48)),
degree= degree(network.post48),
strength= strength(network.post48),
eigenvector= eigen_centrality(network.post48)$vector,
period= "post-treatment") %>%
# define two post periods or one
mutate(period= paste(period, "48 hours later")) %>%
ungroup()
# get centrality data per period and bat
data <-
rbind(centrality.post24, centrality.post48, centrality.treatment) %>%
mutate(treated= bat %in% treated.bats) %>%
mutate(treatment= ifelse(treated, "LPS", "saline")) %>%
# combine post periods
mutate(period= ifelse(period=="during treatment", period, "post-treatment"))
# get effect sizes (slope)
effect_sizes3$effect_size_degree[i] <-
summary(lm(degree~ treated, data= data[which(data$period=="during treatment"),]))$coefficients[2,1] #effect during treatment
# p-values
effect_sizes3$p[i] <- summary(lm(degree~ treated, data= data[which(data$period=="during treatment"),]))$coefficients[2,4]
# store number of meetings
effect_sizes3$n.meetings[i] <- n.meetings
# print progress
print(paste(i, "of", length(thresholds)))
}
stop <- Sys.time()
loop3time <- stop-start
loop3time
# save output with timestamp-----
timestamp <- substr(gsub(x=gsub(":","_",Sys.time()),
pattern=" ", replace="_"), start=1, stop=16)
save.image(file= paste("sim_results_", timestamp, ".Rdata", sep=""))
# reset these options
options(dplyr.show_progress = T)
GET_NEW_DATA <- F #this is important
}
# time to run for loop code
loop1time # 8 min
loop2time # 13 min
loop3time # 11 hours
# plot LPS effect sizes with number of meetings----
N_meetings_plot <-
effect_sizes %>%
mutate(effect_size_degree= effect_size_degree*-1) %>%
mutate(pvalue= ifelse(p>0.05, 0.05, p)) %>%
mutate(significance= ifelse(p>0.05, "NS", "p<0.05")) %>%
select(-p) %>%
pivot_longer(cols= c(effect_size_degree, pvalue, n.meetings), names_to = "measure", values_to = "value") %>%
mutate(measure= case_when(
measure == "effect_size_degree" ~ "LPS treatment coefficient",
measure == "n.meetings" ~ "number of dyadic encounters",
measure == "pvalue" ~ "p-value (if < 0.05)")) %>%
ggplot(aes(x=RSSI, y=value, group= 1))+
facet_wrap(~measure, scales= "free", ncol=1,
strip.position = "left")+
geom_point(aes(shape=significance, color= significance), size=3) +
geom_line()+
geom_vline(xintercept = 5.5, color= 'blue', linetype='dashed', size=1)+
xlab("minimum proximity index to define an encounter")+
ylab("")+
scale_color_manual(values= c("grey", "black"))+
scale_shape_manual(values= c("triangle","circle"))+
theme_cowplot()+
theme(strip.background = element_blank(),
strip.placement = "outside")
N_meetings_plot
# plot effect sizes with meeting duration----
duration_plot <-
effect_sizes2 %>%
mutate(effect_size_degree= effect_size_degree*-1) %>%
mutate(pvalue= ifelse(p>0.05, 0.05, p)) %>%
mutate(significance= ifelse(p>0.05, "NS", "p<0.05")) %>%
select(-p) %>%
pivot_longer(cols= c(effect_size_degree, pvalue, n.meetings), names_to = "measure", values_to = "value") %>%
mutate(measure= case_when(
measure == "effect_size_degree" ~ "LPS treatment coefficient",
measure == "n.meetings" ~ "number of dyadic encounters",
measure == "pvalue" ~ "p-value (if < 0.05)")) %>%
ggplot(aes(x=duration, y=value, group= 1))+
facet_wrap(~measure, scales= "free", ncol=1,
strip.position = "left")+
geom_point(aes(shape=significance, color= significance), size=3) +
geom_line()+
geom_vline(xintercept = 1, color= 'blue', linetype='dashed', size=1)+
xlab("minimum seconds to define an encounter")+
ylab("")+
scale_color_manual(values= c("grey", "black"))+
scale_shape_manual(values= c("triangle","circle"))+
theme_cowplot()+
theme(strip.background = element_blank(),
strip.placement = "outside")
duration_plot
# plot effect sizes with RSSI at smallest sample size bin----
# get absolute effect size
effect_sizes3 <-
effect_sizes3 %>%
mutate(effect_size= effect_size_degree*-1)
# get means and 95% CI
means_ci <-
effect_sizes3 %>%
select(RSSI, effect_size) %>%
boot_ci2(y= .$effect_size, x=.$RSSI)
RSSI_plot <-
effect_sizes3 %>%
ggplot(aes(x=RSSI, y=effect_size))+
geom_jitter(alpha=0.2, width=0.1, color= "grey")+
geom_violin(width=1, fill=NA)+
geom_point(data= means_ci, aes(x=effect, y=mean), size=1)+
geom_errorbar(data= means_ci, aes(ymin=low, ymax=high, width=.2, x=effect, y=mean), size=1)+
ylim(c(0,5))+
ylab("LPS treatment coefficient")+
xlab("minimum proximity index to define an encounter")+
ggtitle(paste("LPS effect size with", random_N, "encounters"))+
theme_cowplot()
RSSI_plot
# combine plots
plot1 <-
duration_plot+
theme(legend.position= 'none')
plot2 <-
N_meetings_plot+
theme(legend.position= 'none')
plot3 <-
RSSI_plot+
theme(plot.title = element_blank())
# make figure 3
(sim1 <- plot_grid(plot1,plot2, ncol=2, labels= 'AUTO'))
ggsave("simulation1_results.pdf", width= 14, height= 8, units="in", dpi=1200)
(sim2 <- plot3)
ggsave("simulation2_results.pdf", width= 14, height= 7, units="in", dpi=1200)
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/B_Age_experiment.R
rm(list=ls())
########################################################################
### INPUT TO DEFINE BY USER############################################
####Please fill in the path to the data folder, the code folder, and the c++ executables folder, as in the exemple below
data_path <- "~/Repositories/Data_Repository/age_experiment"
code_path <- "~/Repositories/Code_Repository/1_data_post_processing/source"
executables_path <- "~/executables"
########################################################################
### END INPUT ########################################################
########################################################################
source(paste(code_path,"/libraries.R",sep=""))
source(paste(code_path,"/functions_and_parameters.R",sep=""))
to_keep <- c(ls(),"to_keep")
# #####Run analysis programs ####
source(paste(code_path,"/1_trackconverter.R",sep=""))
clean()
source(paste(code_path,"/2_define_deaths.R",sep=""))
clean()
source(paste(code_path,"/3_apply_rotation_to_datfiles.R",sep=""))
clean()
source(paste(code_path,"/5_zoneconverter_nest.R",sep=""))
clean()
source(paste(code_path,"/6_time_investment.R",sep=""))
clean()
source(paste(code_path,"/9_interaction_detection.R",sep=""))
clean()
source(paste(code_path,"/10_process_interaction_files.R",sep=""))
clean()
source(paste(code_path,"/11_randomise_interactions.R",sep=""))
clean()
source(paste(code_path,"/13_network_analysis.R",sep=""))
clean()
source(paste(code_path,"/14_summarise_interactions.R",sep=""))
clean()<file_sep>/tracking_scripts/visualize.py
import ant_tracking as a_t
from matplotlib import pyplot
import numpy as np
################
#
# Goal: Make an animation of the ants over time.
#
# <NAME> (<EMAIL>)
#
timegroups = a_t.df.groupby('t')
times_dict = timegroups.groups
times = list(times_dict.keys()) # list of time stamps
freq = 1/0.5 # readme says sampling rate is half of a second
plot_rate = 60 # seconds
######
all_ant_ids = np.unique(a_t.df['id'].values) # how many ants?
colors = pyplot.cm.rainbow(np.linspace(0,1,len(all_ant_ids)))
ant_cmap = {aid: colors[i] for i,aid in enumerate(all_ant_ids) }
box = [-100,3200,-100,4500] # x0,x1,y0,y1
fig,ax = pyplot.subplots(1,1,
constrained_layout=True,
figsize=(9.2,6.6)
)
t = -999
pic_idx = 0
for ti in times:
if ti >= t + plot_rate*freq:
t = ti
dfs = timegroups.get_group(t)
x,y = dfs['x'].values, dfs['y'].values
u,v = np.cos(dfs['theta'].values), np.sin(dfs['theta'].values)
colors = [ant_cmap[ai] for ai in dfs['id'].values]
ant_ids = dfs['id'].values
ax.cla()
ax.quiver( x,y,u,v , color=colors)
ax.axis('square')
ax.set_xlim(box[0],box[1])
ax.set_ylim(box[2],box[3])
ax.set_title('Timestamp: %i'%t)
fig.savefig('frames/ants_colony_%s.png'%str(pic_idx).zfill(5))
pic_idx += 1
#<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/3_apply_rotation_to_datfiles.R
####1_apply_rotation_to_datfiles.R#####
### Calls C++ functions datcorr created when compiling anttrackingUNIL/Antorient (https://github.com/laurentkeller/anttrackingUNIL)
### Takes tracking datfile and tagfile as an input and returns an oriented datfile
### Note that the tag files used as an input must have been oriented using Antorient (https://github.com/laurentkeller/anttrackingUNIL),
### had false detections removed,
### and include the frame of death / tag loss information
### The final processed tag files are provided in the subfolder original_data/tag_files and will be used in all later steps of the analysis
###Created by <NAME>
###################################
### define directories
tag_path <- paste(data_path,"original_data/tag_files",sep="/")
input_path <- paste(data_path,"intermediary_analysis_steps/datfiles_uncorrected",sep="/")
output_path <- paste(data_path,"intermediary_analysis_steps/dat_files",sep="/")
####If necessary, create output folder
if(!exists(output_path)){
dir.create(output_path,recursive = T,showWarnings = F)
}
####Navigate to input folder and list datfiles
setwd(input_path)
dat_list <- paste(input_path,list.files(pattern="\\.dat"),sep="/")
####Navigate to tag folder and list tagfiles
setwd(tag_path)
tag_list <- paste(tag_path,list.files(pattern="\\.tags"),sep="/")
for (dat_file in dat_list){
name_root <- gsub("\\.dat","",unlist(strsplit(dat_file,split="\\/"))[grepl("\\.dat",unlist(strsplit(dat_file,split="\\/")))])
tag_file <- paste(unlist(strsplit(name_root,"_"))[!grepl("Treatment",unlist(strsplit(name_root,"_")))],collapse="_")
tag_file <- tag_list[grepl(tag_file,tag_list)]
if (length(tag_file)>1){
tag_file <- tag_file[grepl(unlist(strsplit(name_root,"_"))[grepl("Treatment",unlist(strsplit(name_root,"_")))],tag_file)]
}
new_dat_file <- paste(output_path,"/",name_root,".dat",sep="")
log_file <- paste(input_path,"/",name_root,".log",sep="")
command_line <- paste(paste(executables_path,"/datcorr",sep=""),dat_file,tag_file,new_dat_file,log_file,sep=" ")
print(command_line)
system(command_line)
}<file_sep>/tracking_scripts/ant_tracking.py
#
# Script for loading one ant tracking file
# Loads a single csv from main_experiment/original_data/tracking/
# and puts it into a "flat" pandas DataFrame.
#
# It's expected to use df.groupby(...) to later analyze
# a single ant (with df.groupby('id') ) or by timestamp
# (with df.groupby('t') )
#
# Resulting dataframe has a large number of rows with
# five columns: ['t', 'id', 'x', 'y', 'theta']
# corresponding to integer timestamp, ant tag ID,
# x and y coordinates, and ant orientation theta (IN DEGREES).
#
# Author: <NAME>
#
import csv
import pandas
import numpy as np
#
FOLDER = "C:/Users/maminian/Desktop/ANTS/main_experiment/original_data/tracking/"
FILENAME = "colony020_pathogen_PreTreatment.csv"
# pre-analysis just to figure out how many ants at how many time points we have.
nrows = 0
with open(FOLDER+FILENAME, 'r') as f:
csvr = csv.reader(f)
for line in csvr:
nants = int( line[3] )
nrows += nants
#
shft = 4 # column number for start of ant records
ants = np.zeros( (nrows,5), dtype=int )
#ants = []
rownum = 0
with open(FOLDER+FILENAME, 'r') as f:
csvr = csv.reader(f)
for j,line in enumerate(csvr):
# unix = float( line[0] )
tidx = int( line[1] )
na = int( line[3] )
for k in range(na): # loop over all ants; get information.
aidx = int( line[shft + 4*k + 0] )
x = int( line[shft + 4*k + 1] )
y = int( line[shft + 4*k + 2] )
theta = int(float( line[shft + 4*k + 3] ))
# ants.append( [tidx,aidx,x,y,theta] )
ants[rownum] = [tidx,aidx,x,y,theta]
rownum += 1
#
#
df = pandas.DataFrame(data=ants, columns=['t','id','x','y','theta'])
if False:
def plot_ants(dfin,t,ax=None):
if ax is not None:
fig,ax = pyplot.subplots(1,1)
x,y = dfs['x'].values, dfs['y'].values
u,v = np.cos(np.pi/180*dfs['theta'].values), np.sin(np.pi/180*dfs['theta'].values)
colors = [ant_cmap[ai] for ai in dfs['id'].values]
ant_ids = dfs['id'].values
ax.cla()
ax.quiver( x,y,u,v , color=colors)
<file_sep>/data_prep_scripts/import_woodants_networks.Rmd
---
title: "import_networks"
author: "<NAME>"
date: "11/01/2021"
output: html_document
---
```{r setup, include=FALSE}
library(readr)
library(dplyr)
library(igraph)
library(ggplot2)
library(einet)
library(EloRating)
library(tidyverse)
```
```{r}
#make matrix function (from dataframe, 1st col with row names)
matrix.please<-function(x) {
m<-as.matrix(x[,-1])
rownames(m)<-x[,1]
m
}
```
# Import wood ants networks
Burns et al. 2020
In this folder there are six csv files that have all of the data for the
exclusion experiment and previous data not used in the analysis:
1. conditions.csv - This file has the conditions that each colony belongs to in the experiment
2. edges.csv - This file has the edges (trail) data for all maps taken for the
experiment and previous work on this system including the two nodes
that the edge connects (undirected), the colony, the date and the
the strength of each connection
3. focal_trees.csv- This file has the focal trees for each colony in the experiment
4. nest_locations.csv - This file has the locations (x/y) for all the nests in the
experiment
5. nests.csv - This file has the nest data for all maps taken in the experiment
and previous work on this system including the node ID, colony,
date and size of nest
6. trees.csv - This file has the tree data for all colonies in the experiment and
previous work on the system including the tree ID, colony, species
and locations of the trees
# import data
```{r wood ants}
#path_in <- "./data/data Burns_ants food removal/"
#path_out <- "./analysis" # where do we want to save the networks?
nests<-read_csv("../data/data Burns_ants food removal/nests.csv")
id_list<-unique(nests$ID)
conditions <- read_csv("../data/data Burns_ants food removal/conditions.csv") # ../ will go one folder back
edges <- readr::read_csv("../data/data Burns_ants food removal/edges.csv")
edges<-left_join(edges, conditions)
View(edges)
head(edges)
glimpse(edges)
unique(levels(as.factor(edges$colony)))
unique(levels(as.factor(edges$condition)))
unique(levels(as.factor(edges$date)))
unique(edges$from)
unique(edges$to)
```
Time points: "For this study we mapped each colony at four time points: (a) before we installed the collars, in August 2016; (b) after we installed the collars, in June 2017; (c) late in the season, in August 2017; and (d) after the first overwinter since the collars were installed, in June 2018. Here we use the August 2016 and August 2017 time points to assess changes to colonies and nests."
Are we using the same time points?
# number of networks (undirected)
- condition (2)
- period (2)
- colony (9)
# get data ready
```{r}
sub_edges<-edges %>% filter(date %in% c("22/08/2016","22/08/2017"))
sub_edges$period[sub_edges$date=="22/08/2016"]<-"before"
sub_edges$period[sub_edges$date=="22/08/2017"]<-"after"
colonies <- unique(levels(as.factor(sub_edges$colony)))
sub_edges$id <- paste0(sub_edges$colony, "-", sub_edges$period)
head(sub_edges)
glimpse(sub_edges)
```
First, try on one network
```{r}
# subset on 1 colony
sub_edges1<-filter(sub_edges, colony=="2b", period=="after")
graph_woodants<-graph_from_data_frame(sub_edges1)
graph_woodants
print(graph_woodants)
plot(graph_woodants)
```
# loop to get network and network metrics
```{r}
colony_timepoint<-unique(sub_edges$id)
all_nets = list() # empty list for networks
#make empty dataframe to fill
node_summary <- data.frame(focal.m=character(),
degree=numeric(),
eigenvector_centrality=numeric(),
betweenness_centrality=numeric())
network_summary <- data.frame(focal.m=character(),
n_nodes=numeric(),
density=numeric(),
normal_ei=numeric())
#apl=numeric(),
#ei=numeric())
#)
i=1
for (i in 1:length(colony_timepoint)) {
# as a check and to know where in the loop we are
focal.m <- colony_timepoint[i]
print(focal.m)
# subset the dataframe per combi
focal.data <- subset(sub_edges, id==focal.m)
head(focal.data)
## convert to network format
graph<-graph_from_data_frame(focal.data, directed = F)
graph
#plot
plot(graph,
edge.width=E(graph)$weight,
#vertex.color="grey",
vertex.label="",
edge.color=alpha("black", 1),
vertex.size=20,
layout=layout_in_circle,
main=focal.m)
#### individual-level : Betweenness Centrality, Eigenvector Centrality, and Degree ###
# degree
degree <- igraph::degree(graph)
# betweenness centrality -> standardized
between <- igraph::betweenness(graph, directed = F,
weights = E(graph)$weight)
betweenness_centrality <- (between-min(between))/(max(between)-min(between))
# eigenvector centrality
eigenvector_centrality<-igraph::eigen_centrality(graph, directed = F)$vector
# pool individual
pool_id <- cbind.data.frame(focal.m,
degree,
betweenness_centrality,
eigenvector_centrality)
node_summary <- rbind(node_summary, pool_id)
#### network level (N Nodes, Density, Effective Information) ####
# number of nodes
n_nodes <- length(V(graph))
# density = number of observed dyads/total possible dyads
#density<-ecount(graph)/(vcount(graph)*(vcount(graph)-1)) #for a directed network
density<-igraph::edge_density(graph)
# average path length
apl <- igraph::mean_distance(graph) #average.path.length(graph.ref.crowd)
# efficiency
library(einet)
ei <- effective_information(graph, effectiveness = FALSE)
normal_ei <- ei/log2(n_nodes) # normalized value to control for network size
# betweenness_centrality <- mean(igraph::betweenness(graph, directed = F, weights = E(graph)$weight))
# eigenvector_centrality<-mean(igraph::eigen_centrality(graph, directed = F)$vector)
#Find proportion unknown relationships, a measure of sparseness
#prunk <- EloRating::prunk(matrix)
#prunk.pu <- as.numeric(prunk[1])
#prunk.dyads <- as.numeric(prunk[2])
## pool network data
pool_network<- cbind.data.frame(focal.m,
n_nodes,
density,
normal_ei)
network_summary <- rbind(network_summary, pool_network)
# pool networks
graph <- as.list(graph)
names(graph) <- focal.m
all_nets[[focal.m]] <- graph
}
all_woodants_networks<-all_nets
```
```{r save output}
# compile node output and save
head(node_summary)
node_output <- node_summary %>%
tibble::rownames_to_column() %>% rename(ID=rowname) %>%
separate(focal.m, c("replicate", "treatment")) %>%
mutate(study="burnsetal2020", species="wood ants") %>%
select(study, species, treatment, replicate, everything())
head(node_output)
write.csv(node_output, file = "../analysis_results/node_output_woodants.csv")
# compile network output and save
head(network_summary)
network_output <- network_summary %>%
#tibble::rownames_to_column() %>% rename(nodeID=rowname)
separate(focal.m, c("replicate", "treatment")) %>%
mutate(study="burnsetal2020", species="wood ants") %>%
select(study, species, treatment, replicate, everything())
head(network_output)
write.csv(network_output, file = "../analysis_results/network_output_woodants.csv")
# save network edgelist or matrix as csv
head(sub_edges)
glimpse(sub_edges)
write.csv(sub_edges, file = "../analysis_results/edgelist_woodants.csv")
```
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/5_zoneconverter_nest.R
####5_zoneconverter_nest.R#####
### Calls C++ functions zoneconverter (https://github.com/laurentkeller/anttrackingUNIL)
### Takes as input a datfile and a plume file created using Plume (https://github.com/laurentkeller/anttrackingUNIL)
### Creates a dat files containing spatial information (nest zone vs. all other zones)
###Created by <NAME>
input_plume <- paste(data_path,"/original_data/plume_files",sep="")
input_dat <- paste(data_path,"/intermediary_analysis_steps/dat_files",sep="")
output_path <- paste(data_path,"/intermediary_analysis_steps/dat_files_nest_zone",sep="")
if (!file.exists(output_path)){
dir.create(output_path,recursive=T)
}
for (dat_file in unique(info_plume$dat_file)){
subset <- info_plume[info_plume$dat_file==dat_file,]
for (line in 1:nrow(subset)){
box <- subset[line,"box"]
plume_file <- subset[line,"plume_file"]
if (line==1){
command <- paste(executables_path,"/zone_converter -d ",input_dat,"/",dat_file," -p ",input_plume,"/", plume_file," -z nest -i 111 -o ",output_path,"/",dat_file," -b ",box, ";",sep="")
system(command)
}else{
command <- paste("mv ",output_path,"/",dat_file," ",output_path,"/",dat_file,"_temp ;",sep="")
system(command)
command <- paste(executables_path,"/zone_converter -d ",output_path,"/",dat_file,"_temp"," -p ",input_plume,"/", plume_file," -z nest -i 111 -o ",output_path,"/",dat_file," -b ",box, ";",sep="")
system(command)
command <- paste("rm ",output_path,"/",dat_file,"_temp ;",sep="")
system(command)
}
}
}#dat_file
<file_sep>/pre_made_scripts/ant_code/2_statistics_and_plotting/Statistics_and_plots.R
rm(list=ls())
#####Overall parameters and functions ##########
####define folders
figurefolder <- "~/figures"
disk_path <- "~/Repositories/Data_Repository"
source_path <- "~/Repositories/Code_Repository/2_statistics_and_plotting/source"
####source programs
source(paste(source_path,"/libraries.R",sep=""))
source(paste(source_path,"/plotting_parameters.R",sep=""))
source(paste(source_path,"/functions.R",sep=""))
source(paste(source_path,"/analysis_parameters.R",sep=""))
############## Figure 1##############
#########Define parameters for Figure 1
figure_height <- page_height/1.8
#####at the top of figure 1 we will have 2 images. I now give their height in inches
image_height <- 1.75
##### parameters defining the height of each plotting row in figure 1
a <- (double_col/2)/figure_height
d <- image_height/figure_height
c <- 0.05
b <- (1 -a -c -d)
to_keep <- c(to_keep,"a","b","c","d")
######Open pdf Figure 1 #####
pdf(file=paste(figurefolder,"/Figure1.pdf",sep=""),family=text_font,font=text_font,bg="white",width=double_col,height=figure_height,pointsize=pointsize_more_than_2row2col)
##### Set-up layout and plot parameters #####
par(pars)
ncoli <- 26
layout(matrix(c(rep(8,ncoli),
rep(1,ncoli/2),rep(2,ncoli/2),####networks at the top
rep(8,ncoli),
rep(7,ncoli/13),rep(3,3*ncoli/13),rep(4,3*ncoli/13), rep(6,3*ncoli/13),rep(5,3*ncoli/13)###second row, first half
), 4, ncoli, byrow = TRUE),heights=c(d,a,c,b))
####First plot networks #######
root_path <- paste(disk_path,"/main_experiment",sep="")######linux laptop
plot_network(case="topology_comparison",which_to_draw=c("PreTreatment_observed","PostTreatment_observed"))
### clean before next step
clean();
Sys.sleep(2)
####Second, plot changes in networks ########
root_path <- paste(disk_path,"/main_experiment/processed_data",sep="")
variable_list <- c("modularity","clustering","task_assortativity","efficiency")
names(variable_list) <- c("modularity","clustering","assortativity","efficiency")
transf_variable_list <- c("none","none","none","none")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.01),c(1.5,-0.02,-0.02,0.25,0.01),c(1.5,-0.02,-0.02,0.25,0.01),c(1.5,-0.02,-0.02,0.25,0.001)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/network_properties/pre_vs_post_treatment/all_workers",sep=""),analysis=analysis,status="collective",collective=T,pool_plot=T,pattern="colony_data.txt")
######## clean before next step###
clean();
Sys.sleep(2)
####Third, add letters #########
par(xpd=NA)
##LETTERS
y_text <- grconvertY((1-1/80), from='ndc')
x_text1 <- grconvertX(0+1/80, from='ndc')
x_text2 <- grconvertX(0.6+1/80, from='ndc')
text(x_text1,y_text,labels=panel_casse("a"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text2,y_text,labels=panel_casse("b"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
x_text1 <- grconvertX(0+1/80, from='ndc'); x_text2 <- grconvertX(1/2+1/80, from='ndc')
y_text <- grconvertY((1-d-1/80), from='ndc')
text(x_text1,y_text,labels=panel_casse("c"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
y_text1 <- grconvertY((1-d-a-c/2-1/80), from='ndc')
text(x_text1,y_text1,labels=panel_casse("d"),font=panel_font, cex=panel_cex,adj=c(0,0),xpd=NA)
par(xpd=F)
####Fourth, Close figure 1 #######
dev.off()
############## ##############
########Extended Data 15: pathogen-induced changes for untreated-only networks########################
pdf(file=paste(figurefolder,"/Extended_Data_15.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height*0.3,pointsize=pointsize_more_than_2row2col)
par(pars)
ncoli <- 26
layout(matrix(c(rep(5,ncoli),
rep(5,ncoli/13),rep(1,3*ncoli/13),rep(2,3*ncoli/13), rep(4,3*ncoli/13),rep(3,3*ncoli/13)###second row, first half
), 2, ncoli, byrow = TRUE)
,heights=c(0.05,0.95)
)
####Plot changes in networks - untreated workers only
root_path <- paste(disk_path,"/main_experiment/processed_data",sep="")
variable_list <- c("modularity","clustering","task_assortativity","efficiency")
names(variable_list) <- c("modularity","clustering","assortativity","efficiency")
transf_variable_list <- c("none","none","none","none")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.01),c(1.5,-0.02,-0.02,0.25,0.01),c(1.5,-0.02,-0.02,0.25,0.01),c(1.5,-0.02,-0.02,0.25,0.001)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/network_properties/pre_vs_post_treatment/untreated_only",sep=""),analysis=analysis,status="collective",collective=T,pool_plot=T,pattern="colony_data.txt")
dev.off()
######## clean before next step###
Sys.sleep(2)
clean();
Sys.sleep(2)
######Open pdf Figure 2 #####
pdf(file=paste(figurefolder,"/Figure2.pdf",sep=""),family=text_font,font=text_font,bg="white",width=double_col,height=page_height*0.25,pointsize=pointsize_less_than_2row2col)
######Plot qPCR data #####
full_statuses_names_ori <- full_statuses_names
full_statuses_names[full_statuses_names%in%c("Foragers","Untreated\nforagers")] <- "Foragers\n"
statuses_colours_ori <- statuses_colours
statuses_colours[names(statuses_colours)%in%c("queen","forager","nurse")] <- "black"
par(pars)
par_mar_ori <- par()$mar
par(mar=par_mar_ori+c(1,0,1,1))
widz <- c(2,1.5)
layout(matrix(c(1,2),nrow=1),widths=widz)
translated_high_threshold <- plot_qpcr(experiments=c("age_experiment","main_experiment"))
to_keep <- c(to_keep,"translated_high_threshold")
####Add letters ####
par(xpd=NA)
x_text1 <- grconvertX(1/80, from='ndc');x_text2 <- grconvertX(widz[1]/sum(widz)+1/80, from='ndc')
y_text <- grconvertY(0.97, from='ndc')
text(x_text1,y_text,labels=panel_casse("a"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text2,y_text,labels=panel_casse("b"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
par(xpd=F)
full_statuses_names <- full_statuses_names_ori
statuses_colours <- statuses_colours_ori
par(mar=par_mar_ori)
####Close figure 2#####
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Open pdf Figure 3 #####
pdf(file=paste(figurefolder,"/Figure3.pdf",sep=""),family=text_font,font=text_font,bg="white",width=double_col,height=page_height*0.45,pointsize=pointsize_more_than_2row2col)
##### Set-up layout and plot parameters #####
par(pars)
ncoli <- 4
heits <- c(5/9,0.05,4/9)
widz <- c(0.075,0.45,0,0.45)
layout(matrix(c(rep(1,ncoli/2),rep(4,ncoli/2),
rep(5,ncoli),
rep(5,ncoli/4),rep(2,ncoli/4),rep(5,ncoli/4),rep(3,ncoli/4)
), 3, ncoli, byrow = TRUE),heights=heits,widths = widz)
######First, plot distribution and threshold identification#######
plot_distribution(experiments="main_experiment",desired_treatments=c("pathogen"))
####Second, individual simulation results - comparison #######
root_path <- paste(disk_path,"/main_experiment",sep="")
queen <- T; treated <- F; nurses <- T; foragers <- T;
unit_ori <- unit; unit <- 24
time_window <- 24
variable_list <- c("probability_high_level","probability_low_level")
names(variable_list) <- c("prob. receiving high load","prob. receiving low load")
transf_variable_list <- c("power3","sqrt")
predictor_list <- c("task_group","task_group")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,0.35,0.11),c(1.5,-0.02,-0.02,0.35,0.11)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/transmission_simulations/pre_vs_post_treatment/experimentally_exposed_seeds",sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="individual_simulation_results_observed",plot_untransformed=T,aligned=T)
unit <- unit_ori
####Third, add survival curve #######
par(pars)
survival_analysis(experiment="survival_experiment",which_to_plot="second_only")
####Fourth, add letters #########
par(xpd=NA)
##LETTERS
x_text1 <- grconvertX(0+1/80, from='ndc'); x_text2 <- grconvertX((sum(widz[1:2]))/(sum(widz))+1/80, from='ndc')
y_text1 <- grconvertY((1-1/80), from='ndc')
y_text2 <- grconvertY((1-heits[1]-1/80), from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text1,y_text2,labels=panel_casse("b"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text2,y_text1,labels=panel_casse("c"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
par(xpd=F)
####Fifth, Close figure 3 #######
dev.off()
######Open pdf Figure 4 #####
pdf(file=paste(figurefolder,"/Figure4.pdf",sep=""),family=text_font,font=text_font,bg="white",width=double_col,height=page_height/2.5,pointsize=pointsize_more_than_2row2col)
Extended <- T
##### Set-up layout and plot parameters #####
par(pars)
ncoli <- 13
layout(matrix(c(rep(5,ncoli),
rep(5,ncoli/13),rep(1,6*ncoli/13),rep(2,6*ncoli/13),
rep(5,ncoli),
rep(5,ncoli/13),rep(3,6*ncoli/13),rep(4,6*ncoli/13)
), 4, ncoli, byrow = TRUE),heights=c(0.05,0.425,0.1,0.425))
####Time spent in nest ##########
root_path <- paste(disk_path,"/main_experiment",sep="")
queen <- F; treated <- T; nurses <- T; foragers <- T
variable_list <- c("prop_time_outside")
names(variable_list) <- c("prop. of time outside")
transf_variable_list <- c("power0.01")
predictor_list <- "task_group"
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,1,0.1)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/processed_data/individual_behaviour/pre_vs_post_treatment",sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="individual_behavioural_data",plot_untransformed = T,boldy=T)
######## clean before next step###
clean();
Sys.sleep(2)
####Distance to colony,Overlap_with_brood####
root_path <- paste(disk_path,"/main_experiment",sep="")
queen <- F; treated <- T; nurses <- T; foragers <- T
level <- "all"
variable_list <- c("distance_antCoG_to_colonyCoG","BA_between_ant_and_brood")
names(variable_list) <- c(paste("distance to colony","_changetomm",sep=""),"overlap with brood")
predictor_list <- c("task_group","task_group")
transf_variable_list <- c("log","none")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list = predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,1,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/processed_data/individual_behaviour/pre_vs_post_treatment",sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="individual_behavioural_data",boldy=T)
######## clean before next step###
clean();
Sys.sleep(2)
####Interactions within vs. between, untreated only #####
root_path <- paste(disk_path,"/main_experiment",sep="")
queen <- F; treated <- F; nurses <- T; foragers <- T
variable_list <- c("inter_caste_contact_duration")
names(variable_list) <- c("Inter-task contact (min)")
transf_variable_list <- c("sqrt")
predictor_list <- "task_group"
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,1,0.25),c(1.5,0,-0.02,1,0.25),c(1.5,0,-0.02,1,0.25),c(1.5,0,-0.02,1,0.25)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/processed_data/individual_behaviour/pre_vs_post_treatment",sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="individual_behavioural_data",boldy=T)
####Fifth, add letters #########
par(xpd=NA)
##LETTERS
x_text1 <- grconvertX(1/13+1/80, from='ndc'); x_text2 <- grconvertX(7/13+1/80, from='ndc')
y_text1 <- grconvertY((1-1/80), from='ndc')
y_text2 <- grconvertY((1-0.5-1/80), from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text1,y_text2,labels=panel_casse("c"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text2,y_text1,labels=panel_casse("b"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text2,y_text2,labels=panel_casse("d"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
par(xpd=F)
####Fifth, Close figure 4 #######
dev.off()
######Open pdf Extended data 2: obs. vs random #####
figure_height <- page_height*0.62
three_col <- conv_unit(165, "mm","inch")
pdf(file=paste(figurefolder,"/Extended_data_2.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=figure_height,pointsize=pointsize_more_than_2row2col)
############## ##############
##### Set-up layout and plot parameters #####
a <- (double_col/2)/figure_height
c <- 0
b <- (1 -a)/2
par(pars)
ncoli <- 6
layout(matrix(c(rep(1,ncoli/2),rep(2,ncoli/2),####networks at the top
rep(3,ncoli/3),rep(4,ncoli/3),rep(5,ncoli/3),
rep(6,ncoli/3),rep(7,ncoli/3),rep(8,ncoli/3)
), 3, ncoli, byrow = TRUE),heights=c(a,b,b))
### clean before next step
clean();
Sys.sleep(2)
####First plot networks #######
#######chosen case: experiment 2, replicate 59, time_hours=9
root_path <- paste(disk_path,"/main_experiment",sep="")######linux laptop
plot_network(case="topology_comparison",which_to_draw=c("PreTreatment_random","PreTreatment_observed"))
### clean before next step
clean();
Sys.sleep(2)
####Second plot random vs observed #######
par_mar_ori <- par()$mar
par_mgp_ori <- par()$mgp
par(mar=par_mar_ori+c(0,1,0,1))
par(mgp=par_mgp_ori+c(0.1,0,0))
variable_list <- c("modularity","density","degree_mean",
"task_assortativity","diameter","degree_maximum")
names(variable_list) <- c("Modularity","Density", "Mean degree",
"Task assortativity","Diameter","Max. degree")
full_statuses_names_ori <- full_statuses_names
full_statuses_names[full_statuses_names%in%c("Rand.","Obs.")] <- c("Random","Observed")
plot_observed_vs_random(experiments="main_experiment",variables=variable_list,pattern="network_properties",data_path="processed_data/network_properties/random_vs_observed")
par(mar=par_mar_ori)
par(mgp=par_mgp_ori)
full_statuses_names <- full_statuses_names_ori
### clean before next step
clean();
Sys.sleep(2)
####Third, add letters #########
par(xpd=NA)
##LETTERS
x_text1 <- grconvertX(0+1/80, from='ndc');
y_text1 <- grconvertY((1-1/80), from='ndc')
y_text2 <- grconvertY((1-a-1/80), from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text1,y_text2,labels=panel_casse("b"),font=panel_font, cex=panel_cex,adj=c(0,0),xpd=NA)
par(xpd=F)
######## clean before next step###
clean();
Sys.sleep(2)
####Fourth, Close Extended Data 2 #######
dev.off()
######Extended data 3: simulation results from different seeds, obs vs. random, COLLECTIVE #####
pdf(file=paste(figurefolder,"/Extended_data_3.pdf",sep=""),family=text_font,font=text_font,bg="white",width= three_col,height=page_height*0.4,pointsize=pointsize_more_than_2row2col)
seeds <- c("random_workers","frequent_foragers","occasional_foragers","nurses","low_degree","high_degree")
names(seeds) <- c("Seeds = random workers","Seeds = frequent foragers","Seeds = occasional foragers","Seeds = nurses","Seeds = low degree workers (LD)","Seeds = high degree workers (HD)" )
seeds <- seeds[c(2,3,4,1)]
nrep <- length(seeds)/2
ncols <- 7
d <- 0.05
variable_list <- c("logistic_r","Mean_load","Load_skewness")
names(variable_list) <- c("Transmission rate","Mean simulated load (W)","Simulated load skewness (W)")
par(pars)
par_mar_ori <- par()$mar
par(mar=par_mar_ori+c(-1,0,0,0))
layout(
matrix(c(
rep(13,ncols),
c(1:3),13,c(4:6),
rep(13,ncols),
c(7:9),13,c(10:12)
)
,
nrow=nrep+2,
ncol=ncols,
byrow = T
)
,widths=c(rep((1-d)/6,3),d,rep((1-d)/6,3))
,heights=c(d,(1-2*d)/2,d,(1-2*d)/2)
)
for (seed in seeds){
full_statuses_names_ori <- full_statuses_names
full_statuses_names[full_statuses_names%in%c("Rand.","Obs.")] <- c("Rd","Obs")
print(seed)
plot_observed_vs_random(experiments="main_experiment",variables=variable_list,data_path = paste("transmission_simulations/random_vs_observed/",seed,sep=""),pattern="collective_simulation_results_")
####plot title
par(xpd=NA)
x_text <- grconvertX(1/4+as.numeric(((which(seed==seeds)/2)-floor((which(seed==seeds)/2)))==0)/2, from='ndc')
y_text <- grconvertY((1 - 2*d/3 - (ceiling((which(seed==seeds)/2))-1)*(d+(1-2*d)/2)), from='ndc')
text(x_text,y_text,labels=names(seeds[seeds==seed]),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
# text(x_text,y_text,labels="The observed pre-exposure networks protect colonies from outside pathogens",font=2, cex=max_cex,adj=0.5,xpd=NA)
##if necessary, plot line
if (is.even(which(seed==seeds))){
x_line <- grconvertX(1/2, from='ndc')
y_line1 <- grconvertY((1 - d - (ceiling((which(seed==seeds)/2))-1)*(d+(1-2*d)/2)), from='ndc') ####lower left = 0-0;top_right=1-1
y_line2 <- grconvertY((1 - d - (1-2*d)/2 - (ceiling((which(seed==seeds)/2))-1)*(d+(1-2*d)/2)), from='ndc')
segments(x_line,y_line1,x_line,y_line2)
}
par(xpd=F)
full_statuses_names <- full_statuses_names_ori
}
par(mar=par_mar_ori)
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Open pdf Extended data 4: degree and distance to queen vs time spent outside in observed networks #####
figure_height <- three_col/2.2
pdf(file=paste(figurefolder,"/Extended_data_4.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=figure_height,pointsize=pointsize_less_than_2row2col)
##### Set-up layout and plot parameters #####
par(pars)
par_mar_ori <- par()$mar
par_mgp_ori <- par()$mgp
par(mar=par_mar_ori+c(0.2,0,0.8,1))
par(mgp=par_mgp_ori+c(0.3,0,0))
ncoli <- 2
layout(matrix(c(1,2
), 1, ncoli, byrow = TRUE))
###read data
data <- read.table(paste(disk_path,"/main_experiment/processed_data/individual_behaviour/pre_treatment/network_position_vs_time_outside.dat",sep=""),header=T,stringsAsFactors = F)
data["antid"] <- as.character(interaction(data$colony,data$tag))
####list desired variables and transformations
variable_list <- c("degree","aggregated_distance_to_queen")
names(variable_list) <- c("degree","path length to queen")
predictor_list <- c("prop_time_outside","prop_time_outside")
names(predictor_list) <- c("Prop. of time outside","Prop. of time outside")
transf_variable_list <- c("none","log")
transf_predictor_list <- c("power2","none")
analysis <- list(variable_list=variable_list,
predictor_list=predictor_list,
transf_variable_list=transf_variable_list,
transf_predictor_list=transf_predictor_list,
violin_plot_param = list(c(1,0,-0.025,0.07,5),c(1,0,-0.025,0.07,0.2)))
####plot
plot_regression(data=data,time_point="before",analysis=analysis,n_cat_horiz=15,n_cat_vertic=30,pool=c(F,F),collective=T)
par(mar=par_mar_ori)
par(mgp=par_mgp_ori)
######## clean before next step###
clean();
Sys.sleep(2)
####Second, add letters #########
par(xpd=NA)
##LETTERS
x_text1 <- grconvertX(0+1/80, from='ndc');
x_text2 <- grconvertX(0.5+1/80, from='ndc');
y_text1 <- grconvertY((1-1/80), from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text2,y_text1,labels=panel_casse("b"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
par(xpd=F)
######## clean before next step###
clean();
Sys.sleep(2)
####Third, Close Extended Data 4 #######
dev.off()
######Extended data 5: simulation results from different seeds, observed #####
seeds <- c("random_workers","low_degree","high_degree","frequent_foragers","occasional_foragers","nurses")
names(seeds) <- c("R","LD","HD","FF","OF","N")
seeds <- seeds[c(2,3,4,5,6,1)]
color_pal <- c(GetColorHex("grey50"),GetColorHex("grey70"),GetColorHex("grey20"),statuses_colours["forager"],statuses_colours["occasional_forager"],statuses_colours["nurse"])
color_pal <- color_pal[c(2,3,4,5,6,1)]
names(color_pal) <- seeds
variables <- c("logistic_r","Prevalence","Mean_load","Load_skewness","Queen_load")
names(variables) <- c("Transmission rate","Prevalence","Mean simulated load (W)","Simulated load skewness (W)","Simulated load (Q)")
transf <- c("none","none","none","none","none")
names(transf) <- variables
pdf(file=paste(figurefolder,"/Extended_data_5.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height*0.49,pointsize=pointsize_more_than_2row2col)
par(pars)
par(mar=c(2.6,2,1,1))
layout(matrix(c(1:(2*ceiling(length(variables)/2))), ceiling(length(variables)/2), 2, byrow = T))
plot_seeds(experiments="main_experiment",seeds=seeds,variables=variables,transf=transf,color_pal=color_pal)
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Extended data 6: age-and-caste organization, main experiment + age-marked experiment #####
full_statuses_names_ori <- full_statuses_names
full_statuses_names[full_statuses_names%in%c("Rand.","Obs.")] <- c("Rd","Obs")
full_statuses_names[full_statuses_names%in%c("Q\ncomm." ,"Other\ncomm." )] <- c("Q","W")
pdf(file=paste(figurefolder,"/Extended_data_6.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height*0.55,pointsize=pointsize_more_than_2row2col)
til <- 0.1
par(pars)
par_mar_ori <- par("mar")
# par(mar=par_mar_ori+c(1,0,0,0))
ncols <- 6
nrows <- 3
heits <- c(til,til,3/4*(1-til),til,1-til,0,3/4*(1-til))
layout(matrix (
c (rep(14,ncols),
rep(14,ncols),
rep(1,ncols/3),rep(8,ncols/6),rep(9,ncols/6),rep(13,ncols/3),
rep(14,ncols),
rep(2,ncols/6),rep(3,ncols/6), rep(4,ncols/6),rep(5,ncols/6), rep(10,ncols/6),rep(11,ncols/6),
rep(14,ncols),
rep(6,ncols/3), rep(7,ncols/3), rep(12,ncols/3)
)
,
nrow=1+2*nrows,
ncol=ncols,
byrow = T
),
heights=heits
)
plot_age_dol(experiments=c("age_experiment","main_experiment"))
par(mar=par_mar_ori)
dev.off()
full_statuses_names <- full_statuses_names_ori
######## clean before next step###
clean();
Sys.sleep(2)
######Extended data 7: simulation results from different seeds, obs vs. random, INDIVIDUAL #####
pdf(file=paste(figurefolder,"/Extended_data_7.pdf",sep=""),family=text_font,font=text_font,bg="white",width= three_col,height=page_height*0.4,pointsize=pointsize_more_than_2row2col)
root_path <- paste(disk_path,"/main_experiment",sep="")######linux laptop
seeds <- c("random_workers","frequent_foragers","occasional_foragers","nurses","low_degree","high_degree")
names(seeds) <- c("Seeds = random workers","Seeds = frequent foragers","Seeds = occasional foragers","Seeds = nurses","Seeds = low degree workers (LD)","Seeds = high degree workers (HD)" )
seeds <- seeds[c(2,3,4,1)]
nrep <- length(seeds)/2
ncols <- 5
d <- 0.04
variable_list <- c("transmission_latency","simulated_load")
names(variable_list) <- c("Contamination latency (h)","Simulated load")
predictor_list <- c("task_group","task_group")
transf_variable_list <- c("none","sqrt")
par(pars)
layout(
matrix(c(
rep(9,ncols),
c(1:2),9,c(3:4),
rep(9,ncols),
c(5:6),9,c(7:8)
)
,
nrow=nrep+2,
ncol=ncols,
byrow = T
)
,widths=c(rep((1-d)/4,2),d,rep((1-d)/4,2))
,heights=c(d,(1-2*d)/2,d,(1-2*d)/2)
)
unit_ori <- unit; unit <- 24
time_window <- 24
full_statuses_names_ori <- full_statuses_names
full_statuses_names[full_statuses_names%in%c("Rand.","Obs.")] <- c("Random","Observed")
full_statuses_names[full_statuses_names%in%c("Queen","Queen\n")] <- "Q"
full_statuses_names[full_statuses_names%in%c("Nurses\n","Untreated\nnurses")] <- "N"
full_statuses_names[full_statuses_names%in%c("Foragers","Untreated\nforagers")] <- "F"
for (seed in seeds){
print(seed)
####then plot, for each of observed and random, the simulated time to infection and simulated mean load of queen, nurses and foragers
queen <- T; treated <- F; nurses <- T; foragers <- T
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/transmission_simulations/random_vs_observed/",seed,sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="summarised_individual_results.dat")
####plot title
par(xpd=NA)
x_text <- grconvertX(1/4+as.numeric(((which(seed==seeds)/2)-floor((which(seed==seeds)/2)))==0)/2, from='ndc')
y_text <- grconvertY((1 - 2*d/3 - (ceiling((which(seed==seeds)/2))-1)*(d+(1-2*d)/2)), from='ndc')
text(x_text,y_text,labels=names(seeds[seeds==seed]),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
# text(x_text,y_text,labels="The observed pre-exposure networks protect colonies from outside pathogens",font=2, cex=max_cex,adj=0.5,xpd=NA)
##if necessary, plot line
if (is.even(which(seed==seeds))){
x_line <- grconvertX(1/2, from='ndc')
y_line1 <- grconvertY((1 - d - (ceiling((which(seed==seeds)/2))-1)*(d+(1-2*d)/2)), from='ndc') ####lower left = 0-0;top_right=1-1
y_line2 <- grconvertY((1 - d - (1-2*d)/2 - (ceiling((which(seed==seeds)/2))-1)*(d+(1-2*d)/2)), from='ndc')
segments(x_line,y_line1,x_line,y_line2)
}
par(xpd=F)
}
unit <- unit_ori
full_statuses_names <- full_statuses_names_ori
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Extended data 8: measured load on networks #####
pdf(file=paste(figurefolder,"/Extended_data_8.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=1.3*(three_col/3),pointsize=pointsize_more_than_2row2col)
par(pars)
layout(matrix(c(1,2,4,6,3,5),nrow=2,byrow = T),heights=c(0.7,0.2))
root_path <- paste(disk_path,"/main_experiment",sep="")######linux laptop
plot_network(case="node_color_f_property",which_to_draw=c("PostTreatment_observed"),colours=c("task_group","measured_load","simulated_load"))
par(mar=c(0.9,0,0,0))
plot(1:3,rep(1,3),pch=NA,bty='n',xaxt="n",yaxt="n",xlab="",ylab="",xlim=c(0.5,3.5),ylim=c(0,3))
points(1:3,rep(1.5,3),pch=21,bg=statuses_colours[c("queen","nurse","forager")],cex=1.3,lwd=line_min)
text(1:3,rep(0.35,3),labels=c("Queen","Nurse","Forager"),cex=inter_cex,adj=0.5)
par(xpd=NA)
##LETTERS
x_text1 <- grconvertX(0+1/80, from='ndc'); x_text2 <- grconvertX(1/3+1/80, from='ndc'); x_text3 <- grconvertX(2/3++1/80, from='ndc')
y_text <- grconvertY((1-1/80), from='ndc')
text(x_text1,y_text,labels=panel_casse("a"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text2,y_text,labels=panel_casse("b"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
text(x_text3,y_text,labels=panel_casse("c"),font=panel_font, cex=panel_cex,adj=c(0,1),xpd=NA)
par(xpd=F)
dev.off()
######Extended data 9: qPCR vs network properties ############
pdf(file=paste(figurefolder,"/Extended_data_9.pdf",sep=""),family=text_font,font=text_font,bg="white",width= three_col,height=page_height*0.6,pointsize=pointsize_2row2col)
layout(matrix(c(3,1,4,2),byrow=T,nrow=2),heights=c(3,2))
partial_least_square_regression(experiments=c("age_experiment","main_experiment"))
x_text1 <- grconvertX(1/80, from='ndc');x_text2 <- grconvertX(0.5+1/80, from='ndc')
y_text1 <- grconvertY(1-2/80, from='ndc')
y_text2<- grconvertY(1-1/2-1/80, from='ndc')
y_text3<- grconvertY(1-3/5-1/80, from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text1,y_text3,labels=panel_casse("b"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
dev.off()
clean()
######Extenced Data 10: Distance to treated ############
pdf(file=paste(figurefolder,"/Extended_Data_10.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height*0.7,pointsize=pointsize_more_than_2row2col)
full_statuses_names_ori <- full_statuses_names
full_statuses_names[full_statuses_names%in%c("Foragers","Untreated\nforagers")] <- "Foragers\n"
statuses_colours_ori <- statuses_colours
statuses_colours[names(statuses_colours)%in%c("queen","outdoor_ant","not_outdoor_ant")] <- "black"
plot_type_ori <- plot_type
plot_type <- "means"
par(pars)
par_mar_ori <- par()$mar
par(mar=par_mar_ori+c(1,0,1,1))
heits <- c(1,10,1,10,1,10)
layout(matrix(c(7,1,7,3,7,5,7,2,7,4,7,6),nrow=6),heights=heits)
plot_qpcr_vs_distance_to_treated(experiments=c("age_experiment","main_experiment"))
####Add letters
par(xpd=NA)
x_text1 <- grconvertX(1/80, from='ndc');x_text2 <- grconvertX(0.5+1/80, from='ndc')
y_text1 <- grconvertY(1-1/80, from='ndc')
y_text2<- grconvertY(1-sum(heits[1:2])/sum(heits)-1/80, from='ndc')
y_text3 <- grconvertY(1-sum(heits[1:4])/sum(heits)-1/80, from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
# text(x_text2,y_text1,labels=panel_casse("b"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text1,y_text2,labels=panel_casse("b"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
# text(x_text2,y_text2,labels=panel_casse("d"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text1,y_text3,labels=panel_casse("c"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
# text(x_text2,y_text3,labels=panel_casse("f"),font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
x_text2 <- grconvertX(0.5, from='ndc')
text(x_text2,y_text1,labels="All workers",font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text2,y_text2,labels="Nurses",font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text2,y_text3,labels="Low contact with treated",font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
par(xpd=F)
plot_type <- plot_type_ori
full_statuses_names <- full_statuses_names_ori
statuses_colours <- statuses_colours_ori
par(mar=par_mar_ori)
dev.off()
clean()
######Extended data 11: survival experiment #####
pdf(file=paste(figurefolder,"/Extended_data_11.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height*0.54,pointsize=pointsize_more_than_2row2col)
par(pars)
layout(
matrix(
c(
1,5,2,
rep(5,3),
3,5,4
)
,nrow=3, byrow=T)
,heights=c(0.45,0.01,0.45),widths=c(0.45,0.03,0.45)
)
survival_analysis(experiment="survival_experiment",which_to_plot = "detailed")
par(xpd=NA)
##LETTERS
x_text1 <- grconvertX(0+1/80, from='ndc');
x_text2 <- grconvertX((0.45+0.05)/(0.45+0.05+0.45)+1/80, from='ndc');
y_text1 <- grconvertY((1-1/80), from='ndc')
y_text2 <- grconvertY((1-((0.45+0.01)/(0.45+0.01+0.45))-1/80), from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=panel_font, cex=panel_cex,xpd=NA)
text(x_text2,y_text1,labels=panel_casse("b"),font=panel_font, cex=panel_cex,xpd=NA)
text(x_text1,y_text2,labels=panel_casse("c"),font=panel_font, cex=panel_cex,xpd=NA)
text(x_text2,y_text2,labels=panel_casse("d"),font=panel_font, cex=panel_cex,xpd=NA)
par(xpd=F)
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Extended data 12: pathogen-induced network changes; individual node properties #####
pdf(file=paste(figurefolder,"/Extended_data_12.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height/5,pointsize=pointsize_more_than_2row2col)
par(pars)
ncoli <- 13
layout(matrix(c(rep(3,ncoli),
rep(3,ncoli/13),rep(1,6*ncoli/13),rep(2,6*ncoli/13)
), 2, ncoli, byrow = TRUE),heights=c(0.05,0.45))
queen <- F; treated <- T; nurses <- T; foragers <- T
root_path <- paste(disk_path,"/main_experiment",sep="")
variable_list <- c("degree","aggregated_distance_to_queen")
names(variable_list) <- c("degree","path length to queen")
transf_variable_list <- c("none","log")
predictor_list <- c("task_group","task_group")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/processed_data/network_properties/pre_vs_post_treatment/all_workers",sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="individual_data",boldy=T)
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Extended data 13: pathogen-induced simulation changes; colony-level plot#####
pdf(file=paste(figurefolder,"/Extended_data_13.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height/5,pointsize=pointsize_more_than_2row2col)
unit_ori <- unit; unit <- 24
time_window <- 24
par(pars)
ncoli <- 13
layout(matrix(c(rep(5,ncoli),
rep(5,ncoli/13),rep(1,3*ncoli/13),rep(2,3*ncoli/13),rep(3,3*ncoli/13),rep(4,3*ncoli/13)
), 2, ncoli, byrow = TRUE),heights=c(0.05,0.45))
root_path <- paste(disk_path,"/main_experiment",sep="")
variable_list <- c("probability_of_transmission")
names(variable_list) <- c("prob. transmission")
transf_variable_list <- c("power8")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/transmission_simulations/pre_vs_post_treatment/experimentally_exposed_seeds",sep=""),analysis=analysis,status="untreated",collective=F,pool_plot=F,pattern="individual_simulation_results",boldy=T,plot_untransformed = T)
variable_list <- c("simulated_load","probability_high_level","probability_low_level")
names(variable_list) <- c("simulated load","prob. high load","prob. low load")
transf_variable_list <- c("sqrt","none","none")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/transmission_simulations/pre_vs_post_treatment/experimentally_exposed_seeds",sep=""),analysis=analysis,status="untreated",collective=F,pool_plot=F,pattern="individual_simulation_results",boldy=T)
unit <- unit_ori
dev.off()
######## clean before next step###
clean();
Sys.sleep(2)
######Extended data 14: treatment-induced changes in worker behaviour #####
# pdf(file=paste(figurefolder,"/Extended_data_14.pdf",sep=""),family=text_font,font=text_font,bg="white",width=three_col,height=page_height*0.4,pointsize=pointsize_more_than_2row2col)
par(pars)
par(mar=par()$mar+c(0,0,0,0))
ncoli <- 10
heits <- c(0.08,0.45,0.08,0.45)
heits <- heits/sum(heits)
d <- 0.06
to_keep <- c(to_keep,"heits")
layout(matrix(c(
rep(7,ncoli),
rep(7,ncoli/10),rep(1,3*ncoli/10),rep(2,3*ncoli/10),rep(3,3*ncoli/10),
rep(7,ncoli),
rep(7,ncoli/10),rep(4,3*ncoli/10),rep(5,3*ncoli/10),rep(6,3*ncoli/10)
), 4, ncoli, byrow = TRUE),heights=heits,widths=c(d,rep((1-d)/9,9)))
experiment <- "main_experiment"
####1. individual behaviour ######
root_path <- paste(disk_path,experiment,sep="/")
queen <- F; treated <- T; nurses <- T; foragers <- T
variable_list <- c("proportion_time_active","average_bout_speed_pixpersec","total_distance_travelled_pix","within_nest_home_range","duration_of_contact_with_treated_min")
names(variable_list) <- c("Prop. time active","Speed while active (mm/sec)_changetomm","Total distance moved (mm)_changetomm","area visited within the nest_changetomm2","contact with treated (min)")
transf_variable_list <- c("none","log","sqrt","sqrt","log")
predictor_list <- rep("task_group",length(variable_list))
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/processed_data/individual_behaviour/pre_vs_post_treatment",sep=""),analysis=analysis,status="all",collective=F,pool_plot=F,pattern="individual_behavioural_data",boldy=T)
###2. Brood displacement #####
root_path <- paste(disk_path,experiment,sep="/")
variable_list <- c("distance_from_nest_entrance_pix")
names(variable_list) <- c("brood location (mm)_changetomm")
transf_variable_list <- c("none")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
violin_plot_param = list(c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15),c(1.5,0,-0.02,0.25,0.15)))
plot_before_vs_after(root_path=root_path, data_path=paste(root_path,"/processed_data/collective_behaviour/pre_vs_post_treatment",sep=""),analysis=analysis,status="collective",collective=T,pool_plot=T,pattern="brood_location.txt",boldy=T)
clean();
####3. Add letters ####
par(xpd=NA)
x_text1 <- grconvertX(1/80, from='ndc');x_text2 <- grconvertX(d+3*(1-d)/9+1/80, from='ndc');x_text2bis <- grconvertX(d+2*(1-d)/9, from='ndc');x_text3 <- grconvertX(d+6*(1-d)/9+1/80, from='ndc')
y_text1 <- grconvertY(1-1/80, from='ndc');y_text2 <- grconvertY(1-1/80-sum(heits[1:2]), from='ndc');
text(x_text1,y_text1,labels=panel_casse("a"),font=2, cex=max_cex,adj=c(0.5,1),xpd=NA)
text(x_text2,y_text1,labels=panel_casse("b"),font=2, cex=max_cex,adj=c(0.5,1),xpd=NA)
text(x_text3,y_text1,labels=panel_casse("c"),font=2, cex=max_cex,adj=c(0.5,1),xpd=NA)
text(x_text1,y_text2,labels=panel_casse("d"),font=2, cex=max_cex,adj=c(0.5,1),xpd=NA)
text(x_text2,y_text2,labels=panel_casse("e"),font=2, cex=max_cex,adj=c(0.5,1),xpd=NA)
text(x_text3,y_text2,labels=panel_casse("f"),font=2, cex=max_cex,adj=c(0.5,1),xpd=NA)
par(xpd=F)
####7. Close pdf ####
# dev.off()<file_sep>/data_prep_scripts/import_guppy_networks.R
#' Import guppy networks in R
#'
#' Imports from the clean association networks. Attaches some of the fish
#' attributes to the nodes. The format will be a list, with one segment thAT
#' goes to a list of high risk networks and low risk groups, where the matching
#' experiement groups are matched by index in the list.
import_guppy_networks <- function(){
filepath <- file.path("data", "guppies", "reformatted_guppy_networks.csv")
all_nets <- list()
guppy_edges <- readr::read_csv(filepath)
for(r in unique(guppy_edges$risk)){
all_nets[[r]] <- vector(mode = "list", length = 16)
for(g in unique(guppy_edges$group)){
all_nets[[r]][[g]] <- guppy_edges %>%
filter(risk == r, group == g, weight > 0) %>%
graph_from_data_frame()
}
}
return(all_nets)
}
<file_sep>/pre_made_scripts/infectionModel.r
### A simple model for disease spread with isolation probability after infection
# net: the square matrix indicating the amount of contact between two network members
# time50: the amount fo contact that results in a 50% contagion probability
# roundsBeforeRmoval: How long a network member is contagious before it is removed
# periods: how many rounds the simulation runs
# pIsolation: The probability for a network member to immediately isoalte after being infected
# is.directed: is the network directed or undirected
contagionModel <- function(net, time50=300, roundsBeforeRemoval=1, periods=20, pIsolation=0.3, is.directed=T){
if(is.directed){
# symmetrise the network
network <- net + t(net)
} else {
network <- net
}
# chose a random network member to be infected first
init <- rep(0, nrow(network))
init[floor(runif(1,1,(nrow(network) + 1)))] <- 1
# create a variable whether any network member is sick
# and make the initator one sick (state 1)
is.sick <- init
# decide whether the first infected network member isolates,
# if yes, move it to removed state (-1)
isolates <- floor(runif(1) + pIsolation)
if(isolates == 1){
is.sick[is.sick==1] <- -1
}
# create varaible that will be used remove network members
# after they were infectious for the specfied number of rounds
rounds.sick <- rep(0, nrow(network))
# generate help variable
all <- 1:nrow(network)
# create output variable as list
sick <- list()
# loop through all periods
for(i in 1:periods){
# write current state in output
sick[[i]] <- is.sick
# get the sick ones
who.is.sick <- all[all*(is.sick) > 0]
# loop through all sick ones
for(sick.one in who.is.sick){
# find the contacts they have that can be infected
at.risk <- all[network[,sick.one] > 0]
# loop though each one in the risk set and decide whether they will be infected
for(alter in at.risk){
# see if the alter is already infected or removed
if(is.sick[alter] == 0){
# determine whether the alter gets infected using the time50
is.sick[alter] <- floor(runif(1) + (((network[alter,sick.one])/ (time50)) /
(1 + (network[alter,sick.one])/ (time50))))
# if the new other is infected, decide whether it isolates
# in that case, move it to state removed (-1)
if(is.sick[alter] == 1){
isolates <- floor(runif(1) + pIsolation)
if(isolates == 1){
is.sick[alter] <- -1
}
}
}
}
# find out how long the infector mouse is sick and remove it if for longer than specified
if(rounds.sick[sick.one] >= roundsBeforeRemoval - 1){
is.sick[sick.one] <- -1
} else {
rounds.sick[sick.one] <- rounds.sick[sick.one] + 1
}
}
}
return(sick)
}
# example
# generate random network
randomNetwork <- matrix(floor(runif(225)*100), 15, 15)
# run simulation
results <- contagionModel(net = randomNetwork, time50 = 75, pIsolation = 0.2)
# results are interpreted as follows:
# each element of the results list refers to the status of all network members at the end of that round
# 1 means infected, -1 means removed (i.e. infected in the past but not contagious anymore), 0 means susceptible
<file_sep>/data/guppies/README.txt
For data accompanying: <NAME>, <NAME>. 2017. Fear of predation shapes social network structure and the acquisition of foraging information in guppy shoals. Proceedings of the Royal Society B: Biological Sciences.
Please note that individual identification in the “Individual Level Data” file differs from that used in the focal follows and association networks.
For example, individuals L17 and H123 in the “Individual Level Data” file are individual 7 in LowRisk group 1 and individual 3 in HighRisk group 12 respectively.
In contrast, in the data files for the focal follows and association networks, individuals within each group are simply labeled by a number ranging from 1 to 8.
One individual in groups LowRisk 2, LowRisk 16, HighRisk 8, and HighRisk 13 died during the familiarization period.
The focal follow data for each group is arranged in blocks of three, with each block made up of 24 observations for each focal individual taken at 10 second intervals.
For each observation, a number means that that individual was recorded as the focal individual’s nearest neighbor, while X’s mean that the focal individual was alone—i.e., no group members were within four body lengths.
Within the “Individual Level Data” file, each group and individual is given a unique identifier.
RiskTreatment indicates whether a group was exposed to high background predation risk (HighRisk) or low background predation risk (LowRisk) during the final four days of the familiarization period (see main text for details).
The experiment was conducted in four blocks, A–D, each of which represented a cohort of 8 groups.
Length_cm provides the standard length of each individual in centimeters.
Approached and Solved indicate respectively whether an individual approached to within 2 cm of the foraging task and whether it entered the foraging device.
ApproachLatency and SolveLatency indicate respectively when during the trial an individual first approached or solved the foraging task (maximum possible latency = 1200); for those individuals who failed to approach or solve the task, the respective entry is left blank.
TimesEntered provides the number of times an individual entered the foraging device during the trial.
Association networks were constructed from the total number of distinct contact phases shared between each pair of group members.
Individual identifiers are given in the first row and column of each network and each network is symmetrical.
In the “Assortativity Coefficients” file, the variables: “GroupID”, “RiskTreatment”, and “Block” are interpreted as described above for the “Individual Level Data” file.
r^w_BodyLength provides the assortativity coefficient with regards to body length for a group’s association network.
<file_sep>/visualizations/chimpanzee_work.py
import pandas
import numpy as np
import networkx
from matplotlib import pyplot
import os
np.random.seed(0)
PREFIX = '../data/Chimpanzees_HobaiterEtAl2014/'
PREFIX = os.path.abspath(PREFIX)
########
ef = pandas.ExcelFile(PREFIX + '/' + 'Data for online storage.xlsx')
df = ef.parse('Less Strict')
def get_datetime(row):
import datetime
import re
pattern = '[A-Z]{2,}\:\ ?([0-9]{1,})\:([0-9]{1,})'
hour,minute = re.match( pattern, row['Time action'] ).groups()
day,month,year = row['Date'].split('.')
dt = datetime.datetime(year=int(year)+2000, month=int(month), day=int(day), hour=int(hour), minute=int(minute))
return dt
#
df['datetime'] = [get_datetime(row) for row in df.iloc]
df = df.sort_values('datetime')
events_flat = []
non_unique_actors = []
for i,row in enumerate( df.iloc ):
m = row['MD']
os = []
non_unique_actors.append( m )
# extract all chimpanzees that observed the event.
for j in range(8,df.shape[1]):
if isinstance(row.iloc[j], str):
os.append( row.iloc[j][:2] )
events_flat.append( [m,row.iloc[j][:2], row['Day'], row['Novel technique']] )
else:
# missing string value means it's the end of the list of chimpanzees observing.
# We also want to record the chimpanzee exhibiting the event to "itself"
# for the purposes of tracking non-observed events.
events_flat.append( [m,m, row['Day'], row['Novel technique']] )
break
# add to the record of all chimpanzees.
non_unique_actors += os
#
df_events = pandas.DataFrame(data=events_flat, columns=['Mediator','Observer','Day','Novel technique'])
# remove duplicates of chimpanzee list.
actors = np.unique( non_unique_actors )
# try 1: create graph across all points in time.
# also construct dictionaries assigning chimpanzee names to integers.
A = np.zeros( (len(actors), len(actors)) )
adict = {a:i for i,a in enumerate(actors)}
invdict = {i:a for a,i in adict.items()}
for row in df_events.values:
A[adict[row[0]],adict[row[1]]] += 1
# build networkx directed graph object.
G = networkx.DiGraph(A)
G = networkx.relabel.relabel_nodes(G, invdict)
edge_weights = np.array( [G[u][v]['weight'] for u,v in G.edges()] )
# pick a layout... none here are 'perfect'.
#
#nodes_xy = networkx.kamada_kawai_layout(G)
#nodes_xy = networkx.circular_layout(G)
nodes_xy = networkx.shell_layout(G)
#nodes_xy = networkx.spectral_layout(G)
if __name__ == "__main__":
# visualize.
fig = pyplot.figure()
networkx.draw_networkx(G, with_labels=True, font_color='w' , width=edge_weights, node_size=200, pos=nodes_xy)
pyplot.ion()
pyplot.show(block=False)<file_sep>/data_prep_scripts/import_mice_networks.py
"""
import the mice networks into a dictionary that allows for easier manipulation.
Final Structure (dict):
{
'LPS':{
'before' : [net1, net2, ...]
'after' : [net1, net2, ...]
},
'Control':{
'before' : [net1, net2, ...]
'after' : [net1, net2, ...]
},
'no_injection: {
'before' : [net1, net2, ...]
'after' : [net1, net2, ...]
}
}
NOTE: The 'before injection' network is matched with it's corresponding 'after injection network by index.
"""
from os.path import join
import pandas as pd
import networkx as nx
from mice_cleaning import print_partitioned_list
def get_mice_networks():
"""Import the mice encounters as an edgelist, partitioned into the components.
"""
filename = "partitioned_dryad_encounters.csv"
parent_dir = join("data", "mice")
df = pd.read_csv(join(parent_dir, filename))
all_nets = {}
# For all tratement levels
for treatment in df['treatment'].unique():
all_nets[treatment] = {}
# For 'before' and 'after' injection
for timepoint in df['timepoint'].unique():
all_nets[treatment][timepoint] = []
condition_subset = df.loc[(df['treatment'] == treatment) & (df['timepoint'] == timepoint)]
# For all the components in that condition.
for c in condition_subset['component_num'].unique():
# Subset down to an edgelist for that component
component_subset = condition_subset.loc[
condition_subset['component_num'] == c].drop(
['treatment', 'timepoint', 'component_num'], axis = 1)
# Append network from pandas dataframe into master dictionary
all_nets[treatment][timepoint].append(nx.from_pandas_edgelist(component_subset,
source= "first_mouse", target="second_mouse", edge_attr=True))
print_partitioned_list(all_nets)
return all_nets
if __name__ == "__main__":
blarg = get_mice_networks()
<file_sep>/analysis_scripts/guppy_analysis.R
#' Iterate through the guppy datasets, and perform the ananlysis on all the
#' guppy networks and append into a large dataset.
source("data_prep_scripts/import_guppy_networks.R", echo = FALSE)
guppy_net_analysis <- function(){
#' Iterate through the list of lists in to form analysis on the mice networks.
g_df <- import_guppy_networks()
master_list <- list()
master_idx <- 1
for(r in names(g_df)){
for(n in 1:length(g_df[[r]])){
temp_net <- g_df[[r]][[n]]
# Metadata
temp_list <- c(
"network" = "guppy",
"animal" = "guppy",
"condition" = r,
"replicate_num" = n
)
# NOTE: Warnings are emitted because there is a weighted directed graphs
# for the eignevector centrality caluculation. Might need to adress to see
# if: acyclic, component size < 2
# warnings for all nets
temp_list <- get_graph_metrics(temp_net, temp_list)
master_list[[master_idx]] <- temp_list
master_idx <- master_idx + 1
}
}
# Append to dataframe.
final <- data.frame(do.call(rbind, master_list))
return(final)
}
guppy_ind_analysis <- function(){
#' Iterate through the list of lists in to form analysis on the mice networks.
g_df <- import_guppy_networks()
master_list <- list()
master_idx <- 1
for(r in names(g_df)){
for(n in 1:length(g_df[[r]])){
temp_net <- g_df[[r]][[n]]
# Metadata
temp_list <- c(
"network" = "guppy",
"animal" = "guppy",
"condition" = r,
"replicate_num" = n
)
# NOTE: Warnings are emitted because there is a weighted directed graphs
# for the eignevector centrality caluculation. Might need to adress to see
# if: acyclic, component size < 2
# warnings for all nets
temp_df <- get_graph_ind_metrics(temp_net)
for(name in names(temp_list)){
temp_df[[name]] <- temp_list[[name]]
}
master_list[[master_idx]] <- temp_df
master_idx <- master_idx + 1
}
}
# Append to dataframe.
final <- data.frame(do.call(rbind, master_list))
return(final)
}
guppy_pop_analysis <- function(){
#' Iterate through the list of lists in to form analysis on the mice networks.
g_df <- import_guppy_networks()
master_list <- list()
master_idx <- 1
for(r in names(g_df)){
for(n in 1:length(g_df[[r]])){
temp_net <- g_df[[r]][[n]]
# Metadata
temp_list <- c(
"network" = "guppy",
"animal" = "guppy",
"condition" = r,
"replicate_num" = n
)
# NOTE: Warnings are emitted because there is a weighted directed graphs
# for the eignevector centrality caluculation. Might need to adress to see
# if: acyclic, component size < 2
# warnings for all nets
temp_list <- get_graph_pop_metrics(temp_net, temp_list)
master_list[[master_idx]] <- temp_list
master_idx <- master_idx + 1
}
}
# Append to dataframe.
final <- data.frame(do.call(rbind, master_list))
return(final)
}
# guppy_results <- guppy_net_analysis()
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/heatmap_to_homerange_parameters.R
euc.dist <- function(A, B) {
return( sqrt(((A$x-B$x)^2)+((A$y-B$y)^2)))
}
###analysis parameters#######
grid_parameter <- 6 ####the lower the number, the finer the grid (e.g. if fine_grid_parameter=4 the program will regroup 16 pixels into 1; if fine_grid_parameter=2 the program will regroup 4 pixels into 1 , etc. ), the longer the processing time
###top left corner coordinates
tlc_x <- -1
tlc_y <- -1
###top right corner coordinates
trc_x <- 609
trc_y <- -1
###bottom right corner coordinates (remember: Y is positive towards the bottom)
brc_x <- 609
brc_y <- 912
###bottom left corner coordinates
blc_x <- -1
blc_y <- 912
#####read infos
########get information of where the nest is
ynestmin_px <- info[info$colony==colony_number,"Ynestmin"]
ynestmax_px <- info[info$colony==colony_number,"Ynestmax"]
if (ynestmin_px==0){
ynestmin <- 0
ynestmax <- ceiling(ynestmax_px/5)
yforagingmin <- ynestmax + 1
yforagingmax <- 911
nest_entrance <- data.frame(x=(1+608/2),y=ynestmax)
}else{
yforagingmin <- 0
yforagingmax <- floor(ynestmin_px/5) - 1
ynestmin <- floor(ynestmin_px/5)
ynestmax <- 911
nest_entrance <- data.frame(x=(1+608/2),y=ynestmin)
}
yallmin <- 0
yallmax <- 911
xallmin <- 0
xallmax <- 608
######### define boundaries to limit estimation of utilisation distributions at the nest walls- See Benhamou & Cornelis, 2010
######all
bound_all <- structure(list(X=c(tlc_x ,trc_x,brc_x ,blc_x ,tlc_x),Y=c(tlc_y ,trc_y,brc_y ,blc_y ,tlc_y)), .Names = c("X", "Y")) ## Prep for boundary of HR area
bound_all <- do.call("cbind",bound_all)
Slo1 <- Line(bound_all)
Sli1 <- Lines(list(Slo1), ID="frontier1")
bounder_all <- SpatialLines(list(Sli1))
######nest
bound_nest <- structure(list(X=c(tlc_x ,trc_x,brc_x ,blc_x ,tlc_x),Y=c(ynestmin-1 ,ynestmin-1,ynestmax+1 ,ynestmax +1,ynestmin-1)), .Names = c("X", "Y")) ## Prep for boundary of HR area
bound_nest <- do.call("cbind",bound_nest)
Slo1 <- Line(bound_nest)
Sli1 <- Lines(list(Slo1), ID="frontier1")
bounder_nest <- SpatialLines(list(Sli1))
######foraging
bound_foraging <- structure(list(X=c(tlc_x ,trc_x,brc_x ,blc_x ,tlc_x),Y=c(yforagingmin -1 ,yforagingmin-1 ,yforagingmax +1 ,yforagingmax +1 ,yforagingmin-1 )), .Names = c("X", "Y")) ## Prep for boundary of HR area
bound_foraging <- do.call("cbind",bound_foraging)
Slo1 <- Line(bound_foraging)
Sli1 <- Lines(list(Slo1), ID="frontier1")
bounder_foraging <- SpatialLines(list(Sli1))
span <- expand.grid(X=0:608,Y=0:911,obs=0)
overlap_methods <- c("BA")
DENSITY_95 <- F
fixed_bandwidth <- 15
<file_sep>/analysis/network metrics in R.Rmd
---
title: "network metrics in R"
author: "<NAME>"
date: "11/01/2021"
output: html_document
---
Some of the functions for the metrics we discussed.
We could finally make a loop to get the metrics for all networks
# load libraries
```{r setup, include=FALSE}
library(igraph)
library(einet)
library(EloRating)
```
# load data
```{r}
```
# loop to get network metrics
```{r}
# create matrix
# network graph
graph <- graph_from_adjacency_matrix(mx)
## individual-level
# betweenness centrality
between <- igraph::betweenness(graph, directed = TRUE,
weights = E(graph)$weight)
# eigenvector centrality
eigen <- eigen_centrality(graph, directed = TRUE, weights = E(graph)$weight)
ec <- eigen$vector
ec.value <- eigen$value
# pool individual
pool_id <- cbind.data.frame(between,
eigen, ec, ec.value)
## group-level
# density = number of observed dyads/total possible dyads
# average path length
apl <- igraph::mean_distance(graph) #average.path.length(graph.ref.crowd)
ie
# efficiency
library(einet)
ei <- effective_information(graph, effectiveness = FALSE)
eff <- ei/log2(n) # normalized value to control for network size
#Find proportion unknown relationships, a measure of sparseness
prunk <- EloRating::prunk(matrix)
prunk.pu <- as.numeric(prunk[1])
prunk.dyads <- as.numeric(prunk[2])
# pool group
pool_group <- cbind.data.frame(ec, ec.value,
apl,
ei, eff,
prunk.pu, prunk.dyads
)
```
<file_sep>/data_prep_scripts/guppy_cleaning.py
"""
Taking the association networks from the guppy data and saving to a friendlier format type, for easier use.
"""
import os
import csv
def reformat_raw_association_networks(directory):
"""Import the raw association matrices from the original file
on the repository. The current file is not very easy to import.
Args:
directory (string): Path file as returned by os.path.join() where
original file is stored.
"""
filename = os.path.join(directory, "Association Networks.csv")
# Store in a dictionary
all_networks = {}
# Open original file
with open(filename, "r") as datafile:
fin = csv.reader(datafile, delimiter = ",")
for row in fin:
# IF "Risk" is in the row, it's a header containing node labels
if "Risk" in row[0]:
# Group Number (1-16)
group_id = row[0].split("Risk")[-1]
# Get Node labels for this network
low_risk_header, high_risk_header = process_header(row)
# In the original file, like-group numbers are on the same row. Index
# forst by group number, then partition by risk.
all_networks[group_id] = {
'low_risk':[],
'high_risk': []
}
# IF the first element in the row is '', it's a spacer row.
elif row[0] != '':
# Data Row
temp_lr_edgelist, temp_hr_edgelist = process_non_header(low_risk_header, high_risk_header, row)
# Add to edge list of the network.
all_networks[group_id]['low_risk'].extend(temp_lr_edgelist)
all_networks[group_id]['high_risk'].extend(temp_hr_edgelist)
# Archive to file
archive_edgelist(all_networks)
def process_header(header_row):
"""Get the NODE IDs from header rows in the association networks.
Args:
header_row (list): List of strings, where the first element is the group (Risk + Number) and
the following elements are the node IDs.
Returns:
list, list: list of node labels (strings of numbers) for the low risk and high risk groups respectively.
"""
# Theres and empty cell between the high risk and low risk groups
break_idx = ["HighRisk" in x for x in header_row].index(True) - 1
# Low risk nodes
low_risk = [x for x in header_row[1:break_idx] if x != '']
# High Risk
high_risk = [x for x in header_row[break_idx + 2:] if x != '']
return low_risk, high_risk
def process_non_header(low_risk_header, high_risk_header, row):
"""Process row containing the edge weights in the association network.
Args:
low_risk_header (list): list of the node labels in the low risk group, each
item is a string of a number
high_risk_header (list): list of the node labels in the high risk group, each
item is a string of a number
row (list): List of association counts, the first element in the list is the node label.
Returns:
list[list]: A list of lists, where each element in the list is a list with the source, target and edge weight.
"""
low_risk_weights = row[1:(1+len(low_risk_header))]
high_risk_weights = row[11:11 + (len(high_risk_header))]
# The first item in the matrix is the node label of the individual
lr_ind = row[0]
hr_ind = row[10]
low_risk_edgelist = []
high_risk_edgelist = []
# Append the edge list for low risk groups
if lr_ind != '':
for idx, lr_h in enumerate(low_risk_header):
low_risk_edgelist.append([lr_ind, lr_h, low_risk_weights[idx]])
# For high risk groups
if hr_ind != '':
for idx, hr_h in enumerate(high_risk_header):
high_risk_edgelist.append([hr_ind, hr_h, high_risk_weights[idx]])
# NOTE: Had to do this seperately, because there might be didfferent populations sizes
# between high risk and low risk groups
return low_risk_edgelist, high_risk_edgelist
def archive_edgelist(networks):
"""Write the edgelist to file. Every network for every risk groups gets
it's own file. The format is group_(group number)_(risk level)_risk_group.csv
Args:
networks (dict): a dictionary of dictionaries, the keys map to another
dictionary, which then has a 'high_risk' and 'low_risk' key, which maps to a list
of lists, which represents the edgelist.
"""
filename = os.path.join("data", "guppies", "reformatted_guppy_networks.csv")
with open(filename, 'w', newline="\n") as fout:
net_tofile = csv.writer(fout, delimiter = ",")
net_tofile.writerow(['guppy1', "guppy2", 'weight', 'group', 'risk'])
# For each group.
for e in networks:
# For high and low risk
for risk_group in networks[e]:
# Header for file
# Edgelist to file.
for r in networks[e][risk_group]:
net_tofile.writerow([*r, e, risk_group])
# net_tofile.writerows(networks[e][risk_group])
if __name__ == "__main__":
reformat_raw_association_networks(os.path.join("data", "guppies"))
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/4_retagged_ant_modifications.R
####4_retagged_ant_modifications.R#####
### Calls C++ functions datcorr created when compiling Antorient (https://github.com/laurentkeller/anttrackingUNIL)
### Calls C++ functions change_tagid
### Modifies dat files for treated ants that lost their tags and were given a new tag during treatment (modify tag id)
### Modifies dat files for treated ants that lost their tags and were retagged with the same tag during treatment (modify rotation)
###Created by <NAME>
####Navigate to tag folder and list tagfiles
tag_path <- paste(data_path,"original_data/tag_files",sep="/")
setwd(tag_path)
tag_list <- paste(tag_path,list.files(pattern="\\.tags"),sep="/")
####Get information on retagged ants
setwd(paste(data_path,"original_data/retagged_ants",sep="/"))
retagged <- read.table("retagged_ants.txt",header = T,stringsAsFactors = F)
###1. Deal with ants that were given a new tag
newly_tagged <- retagged[which(retagged$comment%in%c("new_tag","old_tag")),]
###for each relevant replicate
for (colony_number in unique(newly_tagged$colony)){
###Get into the retagged ant folder, which contains the necessary input files to make the changes
setwd(paste(data_path,"original_data/retagged_ants",sep="/"))
colony <- paste("colony",paste(rep(0,3-nchar(colony_number)),collapse=""),colony_number,sep="")
###Get the tag file that contains information on the tag that still need to be rotated
tag_files <- paste(data_path,"original_data/retagged_ants",list.files()[grepl(colony,list.files())],sep="/")
sub_tag_file <- tag_files[which(grepl("fororient",tag_files))]
tag_file <- tag_files[which(!grepl("fororient",tag_files))]
###Get further information on old and new tag file
box <- info[info$colony==colony_number,"box"]
post_treatment_tag <- newly_tagged[newly_tagged$comment=="new_tag","tag"]
pre_treatment_tag <- newly_tagged[newly_tagged$comment=="old_tag","tag"]
###first, export taglist, which will be used as an argument for changeid
####if file exists delete it
if (file.exists("taglist.txt")){
file.remove("taglist.txt")
}
###NB: the tag that appears in the final tag file is the post-treatment tag, as it is the one which corresponds to the qPCR data
write.table(data.frame(from=pre_treatment_tag,to=post_treatment_tag),file="taglist.txt",append=F,row.names=F,col.names=F,sep=",")
###second, rewrite preTreatment dat file
setwd(paste(data_path,"/intermediary_analysis_steps/dat_files",sep="/"))
dat_list <- paste(data_path,"/intermediary_analysis_steps/dat_files",list.files(pattern="\\.dat"),sep="/")
dat_file <- dat_list[which(grepl(colony,dat_list)&grepl("PreTreatment",dat_list))]
name_root <- gsub("\\.dat","",unlist(strsplit(dat_file,split="\\/"))[grepl("\\.dat",unlist(strsplit(dat_file,split="\\/")))])
log_file <- paste(paste(data_path,"intermediary_analysis_steps/datfiles_uncorrected",sep="/"),"/",name_root,".log",sep="")
###apply rotation for the tag contained in sub_tag_file.
command_line <- paste(paste(executables_path,"/datcorr",sep=""),dat_file,sub_tag_file,gsub("\\.dat","_additional_rotation.dat",dat_file),log_file,sep=" ")
print(command_line)
system(command_line)
###change file names
system(paste("mv ",dat_file," ",gsub("\\.dat","_original.dat",dat_file)))
system(paste("mv ",gsub("\\.dat","_additional_rotation.dat",dat_file)," ",dat_file))
###and now modify tag id in the datfile
command_line <- paste(executables_path,"/change_tagid -d ",dat_file," -t ",tag_file," -o " ,gsub("\\.dat","_old_tagid_changed_to_new_tagid.dat",dat_file)," -b ",box," -l ",paste(data_path,"original_data/retagged_ants","taglist.txt",sep="/"),sep="")
print(command_line)
system(command_line)
system(paste("rm ",dat_file))
system(paste("mv ",gsub("\\.dat","_old_tagid_changed_to_new_tagid.dat",dat_file)," ",dat_file))
system(paste("rm ",gsub("\\.dat","_original.dat",dat_file)))
}
###2. Deal with ants that were given the same tag but with a different orientation
retagged <- retagged[which(retagged$comment%in%c("retagged")),]
###for each relevant replicate
for (colony_number in unique(retagged$colony)){
###Get into the retagged ant folder, which contains the necessary input files to make the changes
setwd(paste(data_path,"original_data/retagged_ants",sep="/"))
colony <- paste("colony",paste(rep(0,3-nchar(colony_number)),collapse=""),colony_number,sep="")
###Get the tag file that contains information on the tag that still need to be rotated
sub_tag_file <- paste(data_path,"original_data/retagged_ants",list.files()[grepl(colony,list.files())],sep="/")
box <- info[info$colony==colony_number,"box"]
###second, rewrite postTreatment dat file
setwd(paste(data_path,"/intermediary_analysis_steps/dat_files",sep="/"))
dat_list <- paste(data_path,"/intermediary_analysis_steps/dat_files",list.files(pattern="\\.dat"),sep="/")
dat_file <- dat_list[which(grepl(colony,dat_list)&grepl("PostTreatment",dat_list))]
name_root <- gsub("\\.dat","",unlist(strsplit(dat_file,split="\\/"))[grepl("\\.dat",unlist(strsplit(dat_file,split="\\/")))])
log_file <- paste(paste(data_path,"intermediary_analysis_steps/datfiles_uncorrected",sep="/"),"/",name_root,".log",sep="")
###apply rotation for the tag contained in sub_tag_file.
command_line <- paste(paste(executables_path,"/datcorr",sep=""),dat_file,sub_tag_file,gsub("\\.dat","_additional_rotation.dat",dat_file),log_file,sep=" ")
print(command_line)
system(command_line)
###change file names
system(paste("mv ",dat_file," ",gsub("\\.dat","_original.dat",dat_file)))
system(paste("mv ",gsub("\\.dat","_additional_rotation.dat",dat_file)," ",dat_file))
system(paste("rm ",gsub("\\.dat","_original.dat",dat_file)))
}
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/randomise_edges.cpp
//to compile with option -std=c++11
using namespace std;
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
#include <math.h>
#include <vector>
#include <random>
#include <chrono>
// [[Rcpp::export]]
DataFrame randomise_edges(DataFrame i_table){
/////////////////////////////////////////////////////////
//define columns
vector <int> Tag1 = i_table["Tag1"];
vector <int> Tag2 = i_table["Tag2"];
vector <int> Startframe = i_table["Startframe"];
vector <int> Stopframe = i_table["Stopframe"];
/////////////////////////////////////////////////////////
//get size of interaction table
int table_size;
table_size = Tag1.size();
//initialise resampled data
vector<int> resampled;
//initialise tag id variables
int i; int ii; int j; int jj;
int new_i; int new_ii; int new_j; int new_jj;
// initialise new index variable
int index;
double min_time; double max_time; double min_ttime; double max_ttime;
// build random number generator
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();//set a seed linked with the time at which the program is runs; ensures random number sequence will always be differemt
std::default_random_engine generator (seed); //set the random number generator using the desired seed
/////////////////////////////////////////////////////////
// Open input files
// initialise random number generators
std::uniform_int_distribution<int> uniform_integer_distribution(0,(table_size-1));
std::uniform_real_distribution<double> uniform_distribution(0.0,1.0);
/////////////////////////////////////////////////////////
// randomisation loop
/////////////////////////////////////////////////////////
for (int edge(0); edge < table_size;edge++){ //read all interaction lines
//check if edge has already been resampled
bool sampled (0);
if (resampled.size()>0){
for (int j(0); j < resampled.size(); j++){
if (resampled[j]==edge){
sampled = 1;
}
}
}
//only perform resampling if edge has not already been resampled
if (!sampled){
// get tags
i = Tag1[edge];
j = Tag2[edge];
// get min and max time of the interaction
min_time = Startframe[edge] ;
max_time = Stopframe[edge] ;
//initialise condition variable
bool condition (0);
while(!condition){// while condition not fulfilled
index = uniform_integer_distribution(generator);//index = index of the other edge with which we are going to draw
// get tag indices
ii = Tag1[index];
jj = Tag2[index];
// get min and max time of the interaction
min_ttime = Startframe[index];
max_ttime = Stopframe[index];
// now draw a random number between 0 and 1 to determine which switch you want to do
double rand (uniform_distribution(generator));
if (rand<0.5){
//cout << "case1" << endl;//with a probability of 1/2, replace (i,j) and (ii,jj) by (i,jj) and (ii,j)
new_i = i;new_ii = ii;
new_j = jj; new_jj = j;
}else{
//cout << "case2" << endl; //with a probability of 1/2, replace (i,j) and (ii,jj) by (i,ii) and (j,jj)
new_i = i;new_ii = j;
new_j = ii;new_jj = jj;
}
// check that one is not creating any multiple edge
// for this, check that there are no overlapping interaction with edge or index that already involves the same two parners
bool multiple_edge(0);
for (int k(0); k < table_size;k++){
//interactions overlapping with edge
if (((Startframe[k]>=min_time)&&(Startframe[k]<=max_time))||((Stopframe[k]>=min_time)&&(Stopframe[k]<=max_time))){
if (((Tag1[k]==new_i)&&(Tag2[k]==new_j))||((Tag1[k]==new_j)&&(Tag2[k]==new_i))){
multiple_edge=1;
}
}
//interactions overlapping with index
if (((Startframe[k]>=min_ttime)&&(Startframe[k]<=max_ttime))||((Stopframe[k]>=min_ttime)&&(Stopframe[k]<=max_ttime))){
if (((Tag1[k]==new_ii)&&(Tag2[k]==new_jj))||((Tag1[k]==new_jj)&&(Tag2[k]==new_ii))){
multiple_edge=1;
}
}
}
// now test whether rearrangement is valid
if (
(edge!=index)//condition 1: have drawn something different
&&
(new_i!=new_j)// condition 2: no self edge on edge
&&
(new_ii!=new_jj)// condition 3: no self edge on index
&&
(!multiple_edge)// condition 4: have not created a multiple edge
){
condition = 1;
}
}//while condition
//once condition is met, make the change into the table
////first updates new tag indices
Tag1[edge] = new_i;
Tag2[edge] = new_j;
Tag1[index] = new_ii;
Tag2[index] = new_jj;
////second update resampled
resampled.push_back(edge);
resampled.push_back(index);
}//if(!sampled)
}// for edge
return DataFrame::create(_["Tag1"]= Tag1, _["Tag2"]= Tag2);
}
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/7_trajectory.R
####7_trajectory.R#####
### Calls C++ functions trajectory (https://github.com/laurentkeller/anttrackingUNIL)
### Takes a datfile and a tagfile as inputs, and returns the trajectory of each ant in a separate file
#################################
####get dat list #####
input_dat <- paste(data_path,"intermediary_analysis_steps/dat_files_nest_zone",sep="/")
setwd(input_dat)
dat_list <- paste(input_dat,list.files(pattern="dat"),sep="/")
#### define outputfolders
outputfolder <- paste(data_path,"/intermediary_analysis_steps/trajectories",sep="")
if (!file.exists(outputfolder)){dir.create(outputfolder,recursive=T)}
for (datfile in dat_list){
root_name <- gsub("\\.dat","",unlist(strsplit(datfile,split="/"))[grepl("colony",unlist(strsplit(datfile,split="/")))])
outputfolder2 <- paste(outputfolder,root_name,sep="/");if (!file.exists(outputfolder2)){dir.create(outputfolder2,recursive=T)}
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
tagfile <- tag_list[grepl(colony,tag_list)]
command <- paste(executables_path,"/trajectory ",datfile," ",tagfile," ",outputfolder2,"/ant", ";",sep="")
print(command)
system(command)
}
<file_sep>/pre_made_scripts/ant_code/2_statistics_and_plotting/source/plotting_parameters.R
########Science-specific plotting parameters #####
####pdf width in inches
single_col <- conv_unit(55, "mm","inch")
double_col <- conv_unit(120, "mm","inch")
three_col <- conv_unit(183, "mm","inch")
page_height <- conv_unit(297, "mm","inch")
####Text size
####"In a layout with exactly two rows and columns the base value of “cex” is reduced by a factor of 0.83: if there are three or more of either rows or columns, the reduction factor is 0.66.”
ref_cex <- 11
pointsize_less_than_2row2col <- ref_cex
pointsize_2row2col <- ref_cex/0.83
pointsize_more_than_2row2col <- ref_cex/0.66
panel_cex <- ref_cex/ref_cex
max_cex <- (ref_cex-1)/ref_cex
inter_cex <- (ref_cex-2)/ref_cex
min_cex <- (ref_cex-3)/ref_cex
####Text font
text_font <- "Helvetica"
panel_font <- 2 ####panel letters must be bold upright
panel_casse <- function(x){
x <- tolower(x)
x <- capitalize(x)
return(x)
}
casse <- function(x){
###remove final point
if (substr(x,nchar(x),nchar(x))=="."){
x <- substr(x,1,(nchar(x)-1))
}
x <- tolower(x)
x <- capitalize(x)
return(x)
}
####Line sizes
line_max <- 1
line_min <- 0.5
line_inter <- line_min +0.5*(line_max-line_min)
if(!file.exists(figurefolder)){dir.create(figurefolder,recursive = T)}<file_sep>/analysis_scripts/fairywrens.R
fairywren<-read.csv("C:/Users/alexi/Google Drive (1)/Between Computers/CNWW2021/animal_response_nets/data/Fairywrens_LantzAndKarubian2017/fairwren_edgelist.csv")
head(fairywren)
#SP = pre or post fire, pre/post = 2013 data, PRE/POST = 2014 data
#location used to determine whether affected by fire or not
fairywren_pre<-subset(fairywren, SP=="Pre"|SP=="PRE")
fairywren_post<-subset(fairywren, SP=="Post"|SP=="POST")
fairywren_pre_2013_affected<-subset(fairywren_pre,Fire=="Y")
fairywren_post_2013_affected<-subset(fairywren_post,Fire=="Y")
fairywren_PRE_2014<-subset(fairywren_pre,SP=="PRE")
fairywren_POST_2014<-subset(fairywren_post,SP=="POST")
library(dplyr)
PRE_2014_edge<-fairywren_PRE_2014 %>% select(Bird1,Bird2)
network2014_pre <- igraph::graph_from_data_frame(PRE_2014_edge, directed=FALSE, vertices=NULL)
POST_2014_edge<-fairywren_POST_2014 %>% select(Bird1,Bird2)
network2014_post <- igraph::graph_from_data_frame(POST_2014_edge, directed=FALSE, vertices=NULL)
#Individual level
between_PRE_2014<-igraph::betweenness(network2014_pre, directed = FALSE,weights=NULL)
between_POST_2014<-igraph::betweenness(network2014_post, directed = FALSE,weights=NULL)
EC_PRE_2014<-igraph::eigen_centrality(network2014_pre, directed = FALSE,weights=NULL)$vector
EC_POST_2014<-igraph::eigen_centrality(network2014_post, directed = FALSE,weights=NULL)$vector
degree_PRE_2014<-igraph::degree(network2014_pre, mode="all")
degree_POST_2014<-igraph::degree(network2014_post, mode="all")
#########combine ##########
library(data.table)
between_PRE_2014_df<-as.data.frame(between_PRE_2014)
between_PRE_2014_df$Condition<-"Pre"
between_PRE_2014_df$Year<-"2014"
names(between_PRE_2014_df)[names(between_PRE_2014_df) == "between_PRE_2014"] <- "Betweenness"
between_PRE_2014_df<-setDT(between_PRE_2014_df, keep.rownames = "Network_ID")[]
between_PRE_2014_df$ID<-paste(between_PRE_2014_df$Network_ID,between_PRE_2014_df$Condition, sep="_")
between_POST_2014_df<-as.data.frame(between_POST_2014)
between_POST_2014_df$Condition<-"Post"
between_POST_2014_df$Year<-"2014"
names(between_POST_2014_df)[names(between_POST_2014_df) == "between_POST_2014"] <- "Betweenness"
between_POST_2014_df<-setDT(between_POST_2014_df, keep.rownames = "Network_ID")[]
between_POST_2014_df$ID<-paste(between_POST_2014_df$Network_ID,between_POST_2014_df$Condition, sep="_")
EC_PRE_2014_df<-as.data.frame(EC_PRE_2014)
EC_PRE_2014_df$Condition<-"Pre"
EC_PRE_2014_df$Year<-"2014"
names(EC_PRE_2014_df)[names(EC_PRE_2014_df) == "EC_PRE_2014"] <- "Eigenvector_Centrality"
EC_PRE_2014_df<-setDT(EC_PRE_2014_df, keep.rownames = "Network_ID")[]
EC_PRE_2014_df$ID<-paste(EC_PRE_2014_df$Network_ID,EC_PRE_2014_df$Condition, sep="_")
EC_POST_2014_df<-as.data.frame(EC_POST_2014)
EC_POST_2014_df$Condition<-"Post"
EC_POST_2014_df$Year<-"2014"
names(EC_POST_2014_df)[names(EC_POST_2014_df) == "EC_POST_2014"] <- "Eigenvector_Centrality"
EC_POST_2014_df<-setDT(EC_POST_2014_df, keep.rownames = "Network_ID")[]
EC_POST_2014_df$ID<-paste(EC_POST_2014_df$Network_ID,EC_POST_2014_df$Condition, sep="_")
degree_PRE_2014_df<-as.data.frame(degree_PRE_2014)
degree_PRE_2014_df$Condition<-"Pre"
degree_PRE_2014_df$Year<-"2014"
names(degree_PRE_2014_df)[names(degree_PRE_2014_df) == "degree_PRE_2014"] <- "Degree"
degree_PRE_2014_df<-setDT(degree_PRE_2014_df, keep.rownames = "Network_ID")[]
degree_PRE_2014_df$ID<-paste(degree_PRE_2014_df$Network_ID,degree_PRE_2014_df$Condition, sep="_")
degree_POST_2014_df<-as.data.frame(degree_POST_2014)
degree_POST_2014_df$Condition<-"Post"
degree_POST_2014_df$Year<-"2014"
names(degree_POST_2014_df)[names(degree_POST_2014_df) == "degree_POST_2014"] <- "Degree"
degree_POST_2014_df<-setDT(degree_POST_2014_df, keep.rownames = "Network_ID")[]
degree_POST_2014_df$ID<-paste(degree_POST_2014_df$Network_ID,degree_POST_2014_df$Condition, sep="_")
degree_2014_PrePost<-rbind(degree_PRE_2014_df,degree_POST_2014_df)
between_2014_PrePost<-rbind(between_PRE_2014_df,between_POST_2014_df)
EC_2014_PrePost<-rbind(EC_PRE_2014_df,EC_POST_2014_df)
deg_betwn_2014<-merge(degree_2014_PrePost,between_2014_PrePost, by="ID")
deg_betwn_EC_2014<-merge(EC_2014_PrePost,deg_betwn_2014, by="ID")
write.csv(deg_betwn_EC_2014, "C:/Users/alexi/Google Drive (1)/Between Computers/CNWW2021/animal_response_nets/data/Fairywrens_LantzAndKarubian2017/deg_betwn_EC_2014_pre_post_fairywren.csv")
#individuals<-rbind()
#Group level
n_nodes_PRE_2014<-length(igraph::V(network2014_pre))
n_nodes_POST_2014<-length(igraph::V(network2014_post))
density_PRE_2014<-igraph::edge_density(network2014_pre)
density_POST_2014<-igraph::edge_density(network2014_post)
effective_info_PRE_2014<-einet::effective_information(network2014_pre, effectiveness = F)
EI_normal_pre<-effective_info_PRE_2014/n_nodes_PRE_2014
effective_info_POST_2014<-einet::effective_information(network2014_post, effectiveness = F)
EI_normal_post<-effective_info_POST_2014/n_nodes_POST_2014
####### 2013 #############################
fairywren_pre<-subset(fairywren, SP=="Pre"|SP=="PRE")
fairywren_post<-subset(fairywren, SP=="Post"|SP=="POST")
fairywren_pre_2013_affected<-subset(fairywren_pre,Fire=="Y")
fairywren_post_2013_affected<-subset(fairywren_post,Fire=="Y")
fairywren_PRE_2013<-fairywren_pre_2013_affected
fairywren_POST_2013<-fairywren_post_2013_affected
library(dplyr)
PRE_2013_edge<-fairywren_PRE_2013 %>% select(Bird1,Bird2)
network2013_pre <- igraph::graph_from_data_frame(PRE_2013_edge, directed=FALSE, vertices=NULL)
POST_2013_edge<-fairywren_POST_2013 %>% select(Bird1,Bird2)
network2013_post <- igraph::graph_from_data_frame(POST_2013_edge, directed=FALSE, vertices=NULL)
#Individual level
between_PRE_2013<-igraph::betweenness(network2013_pre, directed = FALSE,weights=NULL)
between_POST_2013<-igraph::betweenness(network2013_post, directed = FALSE,weights=NULL)
EC_PRE_2013<-igraph::eigen_centrality(network2013_pre, directed = FALSE,weights=NULL)$vector
EC_POST_2013<-igraph::eigen_centrality(network2013_post, directed = FALSE,weights=NULL)$vector
degree_PRE_2013<-igraph::degree(network2013_pre, mode="all")
degree_POST_2013<-igraph::degree(network2013_post, mode="all")
#########combine ##########
library(data.table)
between_PRE_2013_df<-as.data.frame(between_PRE_2013)
between_PRE_2013_df$Condition<-"Pre"
between_PRE_2013_df$Year<-"2013"
names(between_PRE_2013_df)[names(between_PRE_2013_df) == "between_PRE_2013"] <- "Betweenness"
between_PRE_2013_df<-setDT(between_PRE_2013_df, keep.rownames = "Network_ID")[]
between_PRE_2013_df$ID<-paste(between_PRE_2013_df$Network_ID,between_PRE_2013_df$Condition, sep="_")
between_POST_2013_df<-as.data.frame(between_POST_2013)
between_POST_2013_df$Condition<-"Post"
between_POST_2013_df$Year<-"2013"
names(between_POST_2013_df)[names(between_POST_2013_df) == "between_POST_2013"] <- "Betweenness"
between_POST_2013_df<-setDT(between_POST_2013_df, keep.rownames = "Network_ID")[]
between_POST_2013_df$ID<-paste(between_POST_2013_df$Network_ID,between_POST_2013_df$Condition, sep="_")
EC_PRE_2013_df<-as.data.frame(EC_PRE_2013)
EC_PRE_2013_df$Condition<-"Pre"
EC_PRE_2013_df$Year<-"2013"
names(EC_PRE_2013_df)[names(EC_PRE_2013_df) == "EC_PRE_2013"] <- "Eigenvector_Centrality"
EC_PRE_2013_df<-setDT(EC_PRE_2013_df, keep.rownames = "Network_ID")[]
EC_PRE_2013_df$ID<-paste(EC_PRE_2013_df$Network_ID,EC_PRE_2013_df$Condition, sep="_")
EC_POST_2013_df<-as.data.frame(EC_POST_2013)
EC_POST_2013_df$Condition<-"Post"
EC_POST_2013_df$Year<-"2013"
names(EC_POST_2013_df)[names(EC_POST_2013_df) == "EC_POST_2013"] <- "Eigenvector_Centrality"
EC_POST_2013_df<-setDT(EC_POST_2013_df, keep.rownames = "Network_ID")[]
EC_POST_2013_df$ID<-paste(EC_POST_2013_df$Network_ID,EC_POST_2013_df$Condition, sep="_")
degree_PRE_2013_df<-as.data.frame(degree_PRE_2013)
degree_PRE_2013_df$Condition<-"Pre"
degree_PRE_2013_df$Year<-"2013"
names(degree_PRE_2013_df)[names(degree_PRE_2013_df) == "degree_PRE_2013"] <- "Degree"
degree_PRE_2013_df<-setDT(degree_PRE_2013_df, keep.rownames = "Network_ID")[]
degree_PRE_2013_df$ID<-paste(degree_PRE_2013_df$Network_ID,degree_PRE_2013_df$Condition, sep="_")
degree_POST_2013_df<-as.data.frame(degree_POST_2013)
degree_POST_2013_df$Condition<-"Post"
degree_POST_2013_df$Year<-"2013"
names(degree_POST_2013_df)[names(degree_POST_2013_df) == "degree_POST_2013"] <- "Degree"
degree_POST_2013_df<-setDT(degree_POST_2013_df, keep.rownames = "Network_ID")[]
degree_POST_2013_df$ID<-paste(degree_POST_2013_df$Network_ID,degree_POST_2013_df$Condition, sep="_")
degree_2013_PrePost<-rbind(degree_PRE_2013_df,degree_POST_2013_df)
between_2013_PrePost<-rbind(between_PRE_2013_df,between_POST_2013_df)
EC_2013_PrePost<-rbind(EC_PRE_2013_df,EC_POST_2013_df)
deg_betwn_2013<-merge(degree_2013_PrePost,between_2013_PrePost, by="ID")
deg_betwn_EC_2013<-merge(EC_2013_PrePost,deg_betwn_2013, by="ID")
write.csv(deg_betwn_EC_2013, "C:/Users/alexi/Google Drive (1)/Between Computers/CNWW2021/animal_response_nets/data/Fairywrens_LantzAndKarubian2017/deg_betwn_EC_2013_pre_post_fairywren.csv")
#individuals<-rbind()
#Group level
n_nodes_PRE_2013<-length(igraph::V(network2013_pre))
n_nodes_POST_2013<-length(igraph::V(network2013_post))
density_PRE_2013<-igraph::edge_density(network2013_pre)
density_POST_2013<-igraph::edge_density(network2013_post)
effective_info_PRE_2013<-einet::effective_information(network2013_pre, effectiveness = F)
EI_normal_pre<-effective_info_PRE_2013/n_nodes_PRE_2013
effective_info_POST_2013<-einet::effective_information(network2013_post, effectiveness = F)
EI_normal_post<-effective_info_POST_2013/n_nodes_POST_2013
<file_sep>/pre_made_scripts/ant_code/2_statistics_and_plotting/source/libraries.R
library(BSDA)
library(car)
library(coxme)
library(e1071)
library(extrafont)
loadfonts()
library(Hmisc)
library(gtools)
library(kSamples)
library(igraph)
library(lme4)
library(lmerTest)
library(measurements)
library(metap)
library(multcomp)
library(nlme)
library(plotrix)
library(pls)
library(RColorBrewer)
library(scales)
library(spatstat)
library(stringr)
library(survival)
library(survcomp)
library(vioplot)
library(viridisLite)
<file_sep>/data_prep_scripts/bat_cleaning.R
#' Data Converting hour-list of bat networks (67 hours)into ta dataframe
write_bat_edgelist_tofile <- function(hour_list){
# Save all df's to a file
all_dfs <- list()
# For every hour
for(h in 1:length(hour_list)){
# Write to edgelist
temp_edgelist <- igraph::as_data_frame(hour_list[[h]], what = "edges")
temp_edgelist$hour <- h
all_dfs[[h]] <- temp_edgelist
}
final <- do.call(rbind, all_dfs)
write.csv(final, file = "data/bats/bats_byhour_edgelist.R", row.names = F)
}
write_bat_edgelist_tofile(net.list)
# loop for generating multiple networks
# subset by hour, create an igraph for each hour, calculate metrics for each network hour
g <- read.table("bats_byhour_edgelist.csv", header = TRUE, sep = ",")
keys<-unique(g$hour)
new_df<-do.call(bind_rows, lapply(1:length(keys), function(i){
print(paste0(i," of ",length(keys)))
#subset out each hour
temp<- g %>%
filter(hour==keys[i])
#make igraph object
g2<-graph.data.frame(temp) #this is the igraph object
#compute metrics (e.g., density)
g3<- length(V(g2))
g4<-igraph::edge_density(g2)
g5<-mean(igraph::eigen_centrality(g2, directed = FALSE)$vector)
g6<-mean(igraph::betweenness(g2, directed = FALSE))
g7<-igraph::mean_distance(g2)
g8 <- effective_information(g2, effectiveness = FALSE)
g9 <- g8/log2(g3) # normalized value to control for network size
#write igraph object to file so that we can plot network later for each hour
save(g2, file=paste0("/Users/laurenstanton/Desktop/CNWW/Bats/igraph_objects_4_plotting/","hour_",keys[i],".RData"))
#create summary dataframe
dat<-data.frame(hour=keys[i], n_nodes =g3, density=g4, mean_eignvector_centrality=g5, mean_betweenness_centrality=g6, average.path.length = g7, effective_information=g8,ie_adjusted=g9)
return(dat)
}))
write.table(new_df,file="/Users/laurenstanton/Desktop/CNWW/Bats/bat_metrics.csv",sep=",", row.names=FALSE)
#to plot all 67 networks
for(i in 1:length(keys)){
load(paste0("/Users/laurenstanton/Desktop/CNWW/Bats/igraph_objects_4_plotting/","hour_",keys[i],".RData"))
plot(g2) #need to figure out what parameters to use for plotting networks - LAS
}
#to plot one at a time by changing value of i
i=15
load(paste0("/Users/laurenstanton/Desktop/CNWW/Bats/igraph_objects_4_plotting/","hour_",keys[i],".RData"))
plot(g2) # need to figure out what parameters to use for plotting networks - LAS
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/6_time_investment.R
####6_time_investment.R#####
### Calls C++ function time_investment (https://github.com/laurentkeller/anttrackingUNIL)
### Takes a datfile, a tagfile, a plumefile, and a time period as inputs, and returns the number of frames spent in each zone defined in the plume file
###Created by <NAME>
#################################3
####get dat list #####
input_dat <- paste(data_path,"intermediary_analysis_steps/dat_files",sep="/")
setwd(input_dat)
dat_list <- paste(input_dat,list.files(pattern="dat"),sep="/")
if (grepl("age",data_path)){
dat_list <- dat_list[grepl("PreTreatment",dat_list)]
}
#### define outputfolders
outputfolder <- paste(data_path,"/processed_data/time_investment",sep="")
if (!file.exists(outputfolder)){dir.create(outputfolder,recursive=T)}
outputfile <- paste(outputfolder,"/temp.txt",sep="")
outputspace_file <- paste(outputfolder,"/time_investment.txt",sep="")
space_dat <- NULL
behaviour_dat <- NULL
for (datfile in dat_list){
root_name <- gsub("\\.dat","",unlist(strsplit(datfile,split="/"))[grepl("colony",unlist(strsplit(datfile,split="/")))])
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
tagfile <- tag_list[grepl(colony,tag_list)]
if (length(tagfile)>1){
tagfile <- tagfile[grepl(unlist(strsplit(root_name,"_"))[grepl("Treatment",unlist(strsplit(root_name,"_")))],tagfile)]
}
split_file <- split_list[grepl(root_name,split_list)]
if (grepl("age",data_path)){
colony_ages <- ages[which(ages$colony==colony),]
}
split_info <- read.table(split_file,header=T,stringsAsFactors = F)
tag <- read.tag(tagfile)$tag
names(tag)[names(tag)=="#tag"] <- "tag"
tag <- tag[which(tag$tag!="#tag"),]
tag[which(tag$age==0),"age"] <- NA
plume_info <- info_plume[which(info_plume$dat_file==paste(root_name,".dat",sep="")),]
plume_file <- paste(data_path,"/original_data/plume_files/",plume_info["plume_file"],sep="")
box <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"box"]
treatment <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"treatment"]
colony_size <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"colony_size"]
final_frame <- info_datfile[which(info_datfile$dat_file==paste(root_name,".dat",sep="")),"end_frame"]
if (grepl("PreTreatment",root_name)){
period <- "before"
}else {
period <- "after"
}
for (i in 1:nrow(split_info)){
start_frame <- split_info [i,"frames"]
if (i<nrow(split_info)){
duration <- split_info [i+1,"frames"] - start_frame
}else{
duration <- final_frame-start_frame+1
}
###Run time investment
command <- paste(executables_path,"/time_investment -i ",datfile," -t ",tagfile," -p ",plume_file," -z nest -z water -z sugar -b ",box," -s ",start_frame," -d ",duration," -o ",outputfile,";",sep="")
print(command)
system(command)
Sys.sleep(1)
###Immediately re-read outputfile then delete it
temp <- read.table(outputfile,header=T,stringsAsFactors = F)
file.remove(outputfile)
###Modify temp
temp["outside"] <- temp$water+temp$sugar+temp$outzone
temp <- temp[c("tag","nest","outside","undetected")]; temp["detected"] <- temp$nest+temp$outside
temp["prop_time_outside"] <- temp$outside/temp$detected
### add information
temp <- data.frame(colony=colony,colony_size=colony_size,treatment=treatment,period=period,time_hours=split_info[i,"time_hours"],time_of_day=split_info[i,"time_of_day"],temp,stringsAsFactors = F)
### remove ants that did not survive until the end
temp <- merge(temp,tag[c("tag","final_status","group")]); names(temp)[names(temp)=="group"] <- "status"
temp <- temp[which(temp$final_status=="alive"),]
if (!grepl("age",data_path)){
temp$age <- NA
}else{
temp <- merge(temp,colony_ages,all.x=T,all.y=F)
}
###
temp <- temp[c("colony","colony_size","treatment","tag","age","status","period","time_hours","time_of_day","nest","outside","detected","undetected","prop_time_outside")]
space_dat <- rbind(space_dat,temp)
behaviour_dat <- rbind(behaviour_dat,temp[c("colony","colony_size","treatment","tag","age","status","period","time_hours","time_of_day","prop_time_outside")])
rm(list="temp")
}
}
###Write space dat
write.table(space_dat,file=outputspace_file,col.names=T,row.names=F,quote=F,append = F)
if (!grepl("age",data_path)){
output_behav <- paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment",sep="")
if (!file.exists(output_behav)){dir.create(output_behav,recursive=T)}
outputbehav_file <- paste(output_behav,"/individual_behavioural_data.txt",sep="")
behaviour_dat <- behaviour_dat[c("colony","colony_size","treatment","tag","age","status","period","time_hours","time_of_day","prop_time_outside")]
write.table(behaviour_dat,file=outputbehav_file,col.names=T,row.names=F,quote=F,append = F)
output_pre_treatment <- paste(data_path,"/processed_data/individual_behaviour/pre_treatment",sep="")
if (!file.exists(output_pre_treatment)){dir.create(output_pre_treatment,recursive=T)}
write.table(space_dat[which(space_dat$period=="before"),],file=paste(output_pre_treatment,"/network_position_vs_time_outside.dat",sep=""),col.names=T,row.names=F,quote=F,append = F)
}<file_sep>/visualizations/chimpanzee_byday_bytask.py
import numpy as np
import networkx
from matplotlib import pyplot
#,rcParams
#rcParams['axes.titlesize'] = 18
#rcParams['axes.labelsize'] = 18
import vis_params # local parameters file.
import chimpanzee_work as cw
c_involved = np.array([0.2,0.4,0.6,1.0])
c_not_involved = np.array([0.2,0.4,0.6,0.2])
c_learned_dict = {'moss':[0.2,0.6,0.4,1.0],
're-use1':[0.6,0.2,0.6,1.0]}
# arbitrary edge-case cast as moss.
# Only one event has this label.
cw.df_events.loc[cw.df_events['Novel technique']=='moss/re-use1' , 'Novel technique'] = 'moss'
techniques = np.unique( cw.df_events['Novel technique'].values )
days = np.unique( cw.df_events['Day'].values )
fig,ax = pyplot.subplots(len(techniques),len(days),
figsize=(3*len(days),3*len(techniques)),
constrained_layout=True,
sharex=True,
sharey=True)
for kk,c in enumerate( techniques ):
actives = cw.df_events.loc[cw.df_events['Novel technique']==c, ['Mediator','Observer']].values
actives = np.unique(actives)
learned = []
for ll,d in enumerate( days ):
eventmask = np.logical_and( cw.df_events['Novel technique'].values==c, cw.df_events['Day'].values==d )
eventmask = np.where(eventmask)[0]
edge_sub = cw.df_events.iloc[eventmask,:2].values
# print(c, d)
# print(edge_sub)
learned = np.unique( np.concatenate( [ learned, edge_sub[:,0] ] ) )
# assign color...
colors = []
for node in cw.G.nodes():
# has the chimpanzee exhibited the task?
if node in learned:
colors.append( c_learned_dict[c] )
else:
# will the chimpanzee ever observe/be observed?
if node in actives:
colors.append( c_involved )
else:
colors.append( c_not_involved )
#
pyplot.sca( ax[kk,ll] )
networkx.draw_networkx( cw.G, with_labels=True, font_color='w' ,
width=cw.edge_weights,
node_size=200,
pos = cw.nodes_xy,
edgelist = edge_sub,
font_size=8,
node_color=colors
)
if kk==0:
ax[kk,ll].set_title('Day %i'%(ll+1))
if ll==0:
ax[kk,ll].set_ylabel(c)
#
fig.savefig(vis_params.IMAGES_FOLDER + 'chimpanzee_bytechnique_byday.png')
fig.show()<file_sep>/data_prep_scripts/mice_cleaning.py
"""
The mice data is in a weird format, so this reformats the networks into a cleaner version
"""
from os.path import join
import datetime
import pandas as pd
import networkx as nx
def import_mouse_encounters(parent_dir = None):
dataset_directory = join("data", "mice") if parent_dir is None else parent_dir
encounters = pd.read_csv(join(dataset_directory, "dryad_encounters.csv"))
encounters['date_obs_dt'] = pd.to_datetime(encounters['date_obs'], format = "%d-%b")
return encounters
def networks_by_date():
encounters = import_mouse_encounters()
date_levels = get_date_levels(encounters, "date_obs_dt")
all_nets = {}
for date in date_levels:
encounters_subset = encounters.loc[encounters['date_obs'] == date]
all_nets[date] = nx.from_pandas_edgelist(encounters_subset,
source = "IDA[inside_first]",
target = "IDB[inside_after_IDA]", edge_attr=True,
create_using=nx.DiGraph)
return all_nets
def get_date_levels(df, date_col):
dates = df[date_col].unique()
dates.sort()
return list(pd.to_datetime(dates).strftime("%d-%b"))
def get_injection_data(parent_dir = None):
dataset_directory = join("data", "mice") if parent_dir is None else parent_dir
injections = pd.read_csv(join(dataset_directory, "dryad_injected_animal_info.csv"))
injections['date_injected_dt'] = pd.to_datetime(injections['date_injected'], format = "%d-%b")
return injections
def partition_network_components():
net_list = networks_by_date()
injections = get_injection_data()
injection_dates = get_date_levels(injections, "date_injected_dt")
encounters = import_mouse_encounters()
sample_dates = get_date_levels(encounters, "date_obs_dt")
partitioned_nets = {}
treatment_levels = list(injections['injection'].unique())
treatment_levels.append('no_injection')
for t in treatment_levels:
partitioned_nets[t] = {
'before': [],
'after' : []
}
subgraphs = get_network_subgraphs(net_list)
for date in injection_dates:
previous_date = sample_dates[sample_dates.index(date) - 1]
injection_subset = injections.loc[injections['date_injected'] == date]
for _, mouse in injection_subset.iterrows():
injected_mouse_net, subgraphs[date] = get_subgraph_w_mouse(mouse['ID'], subgraphs[date])
before_injection_mouse_net, subgraphs[previous_date] = get_subgraph_w_mouse(mouse['ID'], subgraphs[previous_date])
if injected_mouse_net is None or before_injection_mouse_net is None:
continue
if len(injected_mouse_net.nodes()) < 10 or len(before_injection_mouse_net.nodes()) < 10:
continue
# Append to the injection lists
partitioned_nets[mouse['injection']]['after'].append(injected_mouse_net)
partitioned_nets[mouse['injection']]['before'].append(before_injection_mouse_net)
# partition remaining mice for the rest of the networks.
for net in subgraphs[date]:
if len(net.nodes()) >= 10:
for prev_net in subgraphs[previous_date]:
if len(set(net.nodes()).intersection(set(prev_net.nodes()))) > 8:
partitioned_nets['no_injection']['after'].append(net.copy())
partitioned_nets['no_injection']['before'].append(prev_net.copy())
print_partitioned_list(partitioned_nets)
write_partitions_to_file(partitioned_nets)
def get_subgraph_w_mouse(mouse_id, subgraphs):
mouse_bool_array = [mouse_id in sub.nodes() for sub in subgraphs]
# mouse is not in network.
if sum(mouse_bool_array) == 0:
return None, subgraphs
mouse_net_index = mouse_bool_array.index(True)
mouse_net = subgraphs[mouse_net_index].copy()
return mouse_net, [s.copy() for idx, s in enumerate(subgraphs) if idx != mouse_net_index]
def print_partitioned_list(partition_list):
for treatment in partition_list:
for time in partition_list[treatment]:
print("Treatment {}:Time {}: N items: {}".format(treatment, time, len(partition_list[treatment][time])))
for idx, n in enumerate(partition_list[treatment][time]):
print("{}: | N Edges: {} | N Nodes: {}: | N Intersection of Nodes: {}".format(
idx, len(n.edges()), len(n.nodes()),
len(set(n.nodes()).intersection(set(partition_list[treatment]['before' if time == 'after' else 'after'][idx].nodes())))))
def get_network_subgraphs(parent_networks):
sub_graphs = {}
for net_date, net in parent_networks.items():
sub_graphs[net_date] = [net.subgraph(c).copy() for c in nx.strongly_connected_components(net)]
return sub_graphs
def write_partitions_to_file(partitioned_networks):
all_datasets = []
# Write the parititoned to file.
parent_dir = join("data", "mice")
for treatment in partitioned_networks:
for timepoint in partitioned_networks[treatment]:
for idx, n in enumerate(partitioned_networks[treatment][timepoint]):
# filename = "{}_{}_{}.csv".format(treatment, timepoint, idx)
df = nx.to_pandas_edgelist(n, source = 'first_mouse', target = "second_mouse")
df['treatment'] = treatment
df['timepoint'] = timepoint
df['component_num'] = idx
all_datasets.append(df)
# df.to_csv(join(parent_dir, filename))
final = pd.concat(all_datasets)
final.to_csv(join(parent_dir, "partitioned_dryad_encounters.csv"), index = False)
if __name__ == "__main__":
partition_network_components()
<file_sep>/data_prep_scripts/import_treelizard_networks.Rmd
---
title: "import_networks"
author: "<NAME>"
date: "11/01/2021"
output: html_document
---
```{r setup, include=FALSE}
library(readr)
library(dplyr)
library(igraph)
library(ggplot2)
library(einet)
library(EloRating)
library(geosphere)
```
```{r}
#make matrix function (from dataframe, 1st col with row names)
matrix.please<-function(x) {
m<-as.matrix(x[,-1])
rownames(m)<-x[,1]
m
}
```
# Import tree lizards networks
Lattanzio & Miles 2014
It's not a before and after a perturbation. Instead, spatial networks are compared between different sites differing in the frequency of a disturbance.
We could use the non-burned site as control (before treatment) and high burn site as after treatment.
'morph_networks'
Contains data for morphology, body condition (svl), parasite load, bite mark, perch use frequency, network construction (lat, long data) and analysis (degree, eigenvector centrality data), and morph frequency analyses.
'lat' and 'long' used to estimate spatial network at each site.
Connections (edges) in networks represent geographic distances (measured to nearest01 m) between all lizards captured at each site (nodes, n ≥ 28per site). Geographic distances were calculated from the latitude and longitude data using the program GEOGRAPHIC DISTANCE MATRIX
GENERATORversion 1.2.3 (Ersts 2013).
'mite_narea' = total number of distinct body regions with mites
'mite_load' = mite rank abundance scaled 0–6(rank in parenthesis): no
mites (0), 1–5 mites (1), 6–10 mites (2),11–15 mites (3), 16–20 mites (4), 21–25 mites (5) and >25 mites(6)
'contests'
Contains data for multivariate analysis of variance of male social contest behaviors.
'strength_data'
contains data for analysis of strength and mean strength of edges in each sites' spatial network.
'NBdiet' - 'HBdiet'
Each contain site-specific diet (trophic position) and microhabitat use (perch type) data for analyses comparing tree lizard colour morph differences in ecology.
'trt' = treatment (burn frequency)
'gps' = lizard territory location/id
'svl' = body size
'tcol' = color morph (blue, orange, yellow)
'perch' = microhabitat use either trees or snags
'tpos' = trophic position
NBdiet = non-burned site
LBdiet = low-frequency burn site
HBdiet = high-frequency burn site
# import data
```{r wood ants}
path_in <- "./data/LattanzioMiles_tree lizards/"
path_out <- "./analysis" # where do we want to save the networks?
library(readxl)
morph_networks <- read_excel("../data/LattanzioMiles_tree lizards/LattanzioMilesJAEdata.xlsx",
sheet = "morph_networks")
View(morph_networks)
contests <- read_excel("data/LattanzioMiles_tree lizards/LattanzioMilesJAEdata.xlsx",
sheet = "contests")
strength <- read_excel("data/LattanzioMiles_tree lizards/LattanzioMilesJAEdata.xlsx",
sheet = "strength_data")
NBdiet <- read_excel("data/LattanzioMiles_tree lizards/LattanzioMilesJAEdata.xlsx",
sheet = "NBdiet")
LBdiet <- read_excel("data/LattanzioMiles_tree lizards/LattanzioMilesJAEdata.xlsx",
sheet = "LBdiet")
HBdiet <- read_excel("data/LattanzioMiles_tree lizards/LattanzioMilesJAEdata.xlsx",
sheet = "HBdiet")
```
# number of networks: spatial networks
- condition/treatment: burn frequency sites (3)
- color morphs: blue, orange, yellow (3)
nodes: geographic locations of each lizards (lat, long)
lizard ids/territory names:
'gps' in morph_networks and diets files
'id' in contest file
Connections (edges) in networks represent geographic distances (measured to nearest 0.1 m) between all lizards captured at each site (nodes, n ≥ 28per site)
>50 m edge weight = 0
40-50 m = 1
30-40m = 2
20-30m = 3
10-20m = 4
0-10m = 5
undirected networks
# get data ready
```{r}
```
get distance between pairs of tree lizards
```{r}
networkdata<- morph_networks %>% select(trt, gps, tcol, lat, long)
# distance per colony --> could be done with a loop too
unique(networkdata$trt)
#### NB ####
NB<-filter(networkdata, trt=="NB") %>% select(gps, long, lat)
CP <- function(NB) {
Did = as.data.frame(t(combn(NB$gps, 2)))
Z <- merge(Did, NB, by.x = "V2", by.y = "gps")
Z <- merge(Z, NB, by.x = "V1", by.y = "gps")
return(Z)
}
coord_NB<- CP(NB) %>% rename(id1=V1, id2=V2, long1=long.y, lat1=lat.y,
long2=long.x, lat2=lat.x)
edge_distance_NB<- coord_NB%>%
rowwise() %>%
mutate(
distance = distHaversine(cbind(long1,lat1),cbind(long2,lat2)),
weight=if_else(distance>50, 0,
if_else(distance>40, 1,
if_else(distance>30, 2,
if_else(distance>20, 3,
if_else(distance>10, 4,
if_else(distance>0, 5, 5)))))),
trt="NB")
edge_distance_NB$weight[edge_distance_NB$distance>50]<-0
# filter out distance > 50 m
edge_distance_NB_filt <- edge_distance_NB %>% filter(weight!=0)
## convert to network format
graph_NB<-graph_from_data_frame(edge_distance_NB_filt, directed = FALSE)
graph_NB
edge.attributes(graph_NB)$weight <- edge_distance_NB_filt$weight
#plot
plot(graph_NB)
#### LB ####
LB<-filter(networkdata, trt=="LB") %>% select(gps, long, lat)
CP <- function(LB) {
Did = as.data.frame(t(combn(LB$gps, 2)))
Z <- merge(Did, LB, by.x = "V2", by.y = "gps")
Z <- merge(Z, LB, by.x = "V1", by.y = "gps")
return(Z)
}
coord_LB<- CP(LB) %>% rename(id1=V1, id2=V2, long1=long.y, lat1=lat.y,
long2=long.x, lat2=lat.x)
edge_distance_LB<- coord_LB%>%
rowwise() %>%
mutate(
distance = distHaversine(cbind(long1,lat1),cbind(long2,lat2)),
weight=if_else(distance>50, 0,
if_else(distance>40, 1,
if_else(distance>30, 2,
if_else(distance>20, 3,
if_else(distance>10, 4,
if_else(distance>0, 5, 5)))))),
trt="LB")
edge_distance_LB$weight[edge_distance_LB$distance>50]<-0
# filter out distance > 50 m
edge_distance_LB_filt <- edge_distance_LB %>% filter(weight!=0)
## convert to network format
graph_LB<-graph_from_data_frame(edge_distance_LB_filt, directed = FALSE)
graph_LB
edge.attributes(graph_LB)$weight <- edge_distance_LB_filt$weight
#### HB ####
HB<-filter(networkdata, trt=="HB") %>% select(gps, long, lat)
CP <- function(HB) {
Did = as.data.frame(t(combn(HB$gps, 2)))
Z <- merge(Did, HB, by.x = "V2", by.y = "gps")
Z <- merge(Z, HB, by.x = "V1", by.y = "gps")
return(Z)
}
coord_HB<- CP(HB) %>% rename(id1=V1, id2=V2, long1=long.y, lat1=lat.y,
long2=long.x, lat2=lat.x)
edge_distance_HB<- coord_HB%>%
rowwise() %>%
mutate(
distance = distHaversine(cbind(long1,lat1),cbind(long2,lat2)),
weight=if_else(distance>50, 0,
if_else(distance>40, 1,
if_else(distance>30, 2,
if_else(distance>20, 3,
if_else(distance>10, 4,
if_else(distance>0, 5, 5)))))),
trt="HB")
edge_distance_HB$weight[edge_distance_HB$distance>50]<-0
# filter out distance > 50 m
edge_distance_HB_filt <- edge_distance_HB %>% filter(weight!=0)
## convert to network format
graph_HB<-graph_from_data_frame(edge_distance_HB_filt, directed = FALSE)
graph_HB
edge.attributes(graph_HB)$weight <- edge_distance_HB_filt$weight
plot(graph_HB)
#### combine datasets
edge_distance <- bind_rows(edge_distance_NB, edge_distance_LB, edge_distance_HB) %>% select(trt, id1, id2, distance, weight)
glimpse(edge_distance)
# filter out edge weights of 0
edge_distance_filt <- bind_rows(edge_distance_NB_filt, edge_distance_LB_filt, edge_distance_HB_filt) %>% select(trt, id1, id2, distance, weight)
glimpse(edge_distance_filt)
```
# loop to get network and network metrics
```{r}
head(edge_distance)
head(edge_distance_filt) # filtered dataset 0 edge weights
trt<-unique(networkdata$trt)
# set data
#data<-edge_distance %>% select(id1, id2, trt, distance, weight)
data<-edge_distance_filt %>% select(id1, id2, trt, distance, weight)
all_nets = list() # empty list for networks
#make empty dataframe to fill
node_summary <- data.frame(focal=character(),
degree=numeric(),
eigenvector_centrality=numeric(),
betweenness_centrality=numeric())
network_summary <- data.frame(focal=character(),
n_nodes=numeric(),
density=numeric(),
normal_ei=numeric())
#apl=numeric(),
#ei=numeric())
#)
i=1
for (i in 1:length(trt)) {
# as a check and to know where in the loop we are
focal <- trt[i]
print(focal)
# subset the dataframe per combi
focal.data <- subset(data, trt==focal)
head(focal.data)
## convert to network format
graph<-graph_from_data_frame(focal.data, directed = F)
graph
#plot
plot(graph,
edge.width=E(graph)$weight,
vertex.color="grey",
vertex.label="",
edge.color=alpha("black", 1),
vertex.size=20,
#layout=layout_in_circle,
main=focal)
#### individual-level : Betweenness Centrality, Eigenvector Centrality, and Degree ###
# degree
degree <- igraph::degree(graph)
# betweenness centrality -> standardized
between <- igraph::betweenness(graph, directed = F,
weights = E(graph)$weight)
betweenness_centrality <- (between-min(between))/(max(between)-min(between))
# eigenvector centrality
eigenvector_centrality<-igraph::eigen_centrality(graph, directed = F)$vector
# pool individual
pool_id <- cbind.data.frame(focal,
degree,
betweenness_centrality,
eigenvector_centrality)
node_summary <- rbind(node_summary, pool_id)
#### network level (N Nodes, Density, Effective Information) ####
# number of nodes
n_nodes <- length(V(graph))
# density = number of observed dyads/total possible dyads
#density<-ecount(graph)/(vcount(graph)*(vcount(graph)-1)) #for a directed network
density<-igraph::edge_density(graph)
# average path length
apl <- igraph::mean_distance(graph) #average.path.length(graph.ref.crowd)
# efficiency
library(einet)
ei <- effective_information(graph, effectiveness = FALSE)
normal_ei <- ei/log2(n_nodes) # normalized value to control for network size
# betweenness_centrality <- mean(igraph::betweenness(graph, directed = F, weights = E(graph)$weight))
# eigenvector_centrality<-mean(igraph::eigen_centrality(graph, directed = F)$vector)
#Find proportion unknown relationships, a measure of sparseness
#prunk <- EloRating::prunk(matrix)
#prunk.pu <- as.numeric(prunk[1])
#prunk.dyads <- as.numeric(prunk[2])
## pool network data
pool_network<- cbind.data.frame(focal,
n_nodes,
density,
normal_ei)
network_summary <- rbind(network_summary, pool_network)
# pool networks
graph <- as.list(graph)
names(graph) <- focal
all_nets[[focal]] <- graph
}
all_treelizards_networks<-all_nets
```
```{r}
# community detection
ceb <- cluster_edge_betweenness(graph)
dendPlot(ceb, mode="hclust")
plot(ceb, graph)
clp <- cluster_label_prop(graph)
plot(clp, graph)
```
```{r}
# compile output and save
head(node_summary)
node_output<- node_summary %>%
tibble::rownames_to_column() %>% rename(nodeID=rowname) %>%
#separate(focal.m, c("replicate", "treatment")) %>%
rename(treatment=focal) %>%
mutate(study="LattanzioMiles", species="tree lizards", replicate="") %>%
select(study, species, treatment, replicate, everything())
node_output$treatment<- factor(node_output$treatment, levels=c("NB", "LB", "HB"), labels=c("no burn", "low burn", "high burn"))
head(node_output)
write.csv(node_output, file = "../analysis_results/node_output_treelizards_0weightexcl.csv")
# output network data
head(network_summary)
network_output <- network_summary %>%
#tibble::rownames_to_column() %>% rename(nodeID=rowname)
#separate(focal.m, c("replicate", "treatment")) %>%
rename(treatment=focal) %>%
mutate(study="LattanzioMiles", species="tree lizards", replicate="") %>%
select(study, species, treatment, replicate, everything())
network_output$treatment<- factor(network_output$treatment, levels=c("NB", "LB", "HB"), labels=c("no burn", "low burn", "high burn"))
head(network_output)
write.csv(network_output, file = "../analysis_results/network_output_treelizards_0weightexcl.csv")
# save network edgelist or matrix as csv
head(edge_distance)
glimpse(edge_distance)
write.csv(edge_distance, file = "../analysis_results/edgelist_treelizards.csv")
head(edge_distance_filt)
glimpse(edge_distance_filt)
write.csv(edge_distance_filt, file = "../analysis_results/edgelist_treelizards_0weightexcl.csv")
```
<file_sep>/metagear.Rmd
---
title: "metagear"
author: "<NAME>"
date: "18/04/2021"
output: html_document
---
metagear package allows to
- Initialize a dataframe containing bibliographic data (tile, abstract, journal) from multiple study references.
- Distribute these references randomly to two team members.
- Merge and summarize the screening efforts of this team.
http://lajeunesse.myweb.usf.edu/metagear/metagear_basic_vignette.html
https://cran.r-project.org/web/packages/metagear/metagear.pdf
```{r setup, include=FALSE}
# first load Bioconductor resources needed to install the EBImage package
# and accept/download all of its dependencies
#install.packages("BiocManager");
#BiocManager::install("EBImage")
#install.packages("metagear")
# then load metagear
library(metagear)
library(dplyr)
```
## distribute references
```{r load bib dataset}
# load a bibliographic dataset with the authors, titles, and abstracts of multiple study references
refs <- read.csv("savedrecsWOS_2021-04-18.csv")
# display the bibliographic variables in this dataset
names(refs)
# change naming now or later
refs_selectVar <- refs %>%
dplyr::select(Authors, Publication.Year, Article.Title, Volume, Start.Page, End.Page, DOI, Abstract)
example.names.metagear <- c("AUTHORS" "YEAR" "TITLE" "JOURNAL" "VOLUME" "LPAGES" "UPAGES" "DOI" "ABSTRACT")
# prime the study-reference dataset
theRefs <- effort_initialize(refs) # adds 3 columns: unique key per ref, empty reviewer column, and a screening effort column 'include'
# display the new columns added by effort_initialize
names(theRefs)
# randomly distribute screening effort to a team
theTeam <- c("Alex", "Alexis", "Annemarie","Catherine", "Connor", "Lauren", "Lisa", "Manuch", "Marya")
# randomly distribute screening effort to a team,
# but also saving these screening tasks to separate files for each team member
theRefs_unscreened <- effort_distribute(theRefs, reviewers = theTeam, save_split = TRUE) # add effort (e.g. = c(20, 80))) to delegate screening effort unevenly
theRefs_unscreened[c("STUDY_ID", "REVIEWERS")] # display screening tasks
list.files(pattern = "effort")
```
## Screening abstracts of references
Screening interface
no: to exclude study
maybe: more information is needed to determine inclusion
yes; include study
```{r screening abstracts}
# initialize screener GUI
abstract_screener("effort_Annemarie.csv",
aReviewer = "Annemarie",
titleColumnName = "Article.Title",
abstractColumnName = "Abstract")
```
## Merge screening efforts
```{r merge screening effort}
# WARNING: will merge all files named "effort_*" in directory
theRefs_screened <- effort_merge()
theRefs_screened[c("STUDY_ID", "REVIEWERS", "INCLUDE")]
theSummary <- effort_summary(theRefs_screened)
```
## Generating PRISMA plots
```{r Generating PRISMA plot}
phases <- c("START_PHASE: # of studies identified through database searching",
"START_PHASE: # of additional studies identified through other sources",
"# of studies after duplicates removed",
"# of studies with title and abstract screened",
"EXCLUDE_PHASE: # of studies excluded",
"# of full-text articles assessed for eligibility",
"EXCLUDE_PHASE: # of full-text articles excluded, not fitting eligibility criteria",
"# of studies included in qualitative synthesis",
"EXCLUDE_PHASE: # studies excluded, incomplete data reported",
"final # of studies included in quantitative synthesis (meta-analysis)")
thePlot <- plot_PRISMA(phases)
# PRISMA plot with custom layout
thePlot <- plot_PRISMA(phases, design = c(E = "lightcoral", flatArrow = TRUE))
```
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/8_process_trajectory_files.R
####8_process_trajectory_files.R#####
#### Defines activity bouts and calculates summary statistics for each trajectory
#### Outputs: modified trajectory file and modifed individual behaviour file
#################################
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
#### Parameters
to_keep_ori <- to_keep
max_time <- 1.5 # max time in sec, for which it is acceptable to calculate a distance moved (e.g. 1.5 sec: allows for up to 2 missing points between two successive detections and still calculates distance moved)
### Functions
insertRow <- function(existingDF, newrow, r) {
existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
existingDF[r,] <- newrow
existingDF
}
####get trajectory list #####
input_traj <- paste(data_path,"intermediary_analysis_steps/trajectories",sep="/")
setwd(input_traj)
traj_list <- paste(input_traj,dir(),sep="/")
#### reduce traj list to only PreTreatment folders
#### for each ant we will successively consider the Pre-treatment, then the Post-treatment trajectory
traj_list <- traj_list[grepl("Pre",traj_list)]
TAB_ALL <- NULL
##################################
for (traj_folder in traj_list){
root_name <- unlist(strsplit(traj_folder,split="/"))[grepl("colony",unlist(strsplit(traj_folder,split="/")))]
print(paste(unlist(strsplit(root_name,split="_"))[!grepl("Treatment",unlist(strsplit(root_name,split="_")))],collapse="_"))
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
tagfile <- tag_list[grepl(colony,tag_list)]
splitfiles <- split_list[grepl(colony,split_list)]
####read-in tag list to define list of live ants
tag <- read.tag(tagfile)$tag; names(tag)[names(tag)=="#tag"] <- "tag"; tag <- tag[which(tag$tag!="#tag"),]
alive <- paste("ant_",tag[which(tag$final_status=="alive"),"tag"],".txt",sep="")
splitinfo_Pre <- read.table(splitfiles[grepl("Pre",splitfiles)],header=T, stringsAsFactors = F)
splitinfo_Post <- read.table(splitfiles[grepl("Post",splitfiles)],header=T, stringsAsFactors = F)
###Navigate in folder
setwd(traj_folder)
traj_files <- list.files()
to_keep <- unique(c(to_keep,ls(),"traj_file","to_keep_ori"))
###Process each trajectory file
for (traj_file in traj_files){
print(gsub("_"," ",gsub("\\.txt","",traj_file)))
traj_file_Pre <- paste(traj_folder,traj_file,sep="/")
traj_file_Post <- gsub("Pre","Post",traj_file_Pre)
####delete files corresponding to dead ants
if (!traj_file %in% alive){
print("Deleting file (ant died before the end)")
file.remove(traj_file_Pre)
file.remove(traj_file_Post)
}else{# if (!traj_file %in% alive)
print("Modifying trajectory...")
###check if analysis has already been done
output <- system(paste( "head -1 ",traj_file_Post),intern=T)
if (!grepl("bout_id",output)){
bout_counter <- 0
####do the analysis for each of the Pre- and Post- files
for (suffix in c("_Pre","_Post")){
output <- system(paste( "head -1 ",get(paste("traj_file",suffix,sep=""))),intern=T)
if (!grepl("bout_id",output)){
traj <- read.table(get(paste("traj_file",suffix,sep="")),header=T,sep=",",comment.char="%")
names(traj)[names(traj)=="X.frame"] <- "frame"
#####Remove occasional duplicates
traj <- traj[!duplicated(traj$frame),]
##########################################################
######1. calculate distance moved ########################
##########################################################
####Prepare two tables offset by one line to facilitate calculation for calculations
traj_1 <- insertRow(traj,rep(NA,ncol(traj)),1)
traj_2 <- insertRow(traj,rep(NA,ncol(traj)),(nrow(traj)+1))[1:(nrow(traj)+1),]
names(traj_1) <- paste(names(traj_1),"_previousframe",sep="")
####merge them
full_trajectory <- data.frame(traj_1,traj_2)
####calculate time difference between two successive coordinates
full_trajectory["time_diff"] <- full_trajectory$time-full_trajectory$time_previousframe
####round time_diff to nearest 0.5
full_trajectory$time_diff <- round(full_trajectory$time_diff/0.5)*0.5;full_trajectory$time_diff[full_trajectory$time_diff==0]<-0.5
#### calculate distance moved between two successive frames
full_trajectory[,"total_dist"] <- (sqrt((full_trajectory[,"xcoor"]-full_trajectory[,"xcoor_previousframe"])^2+(full_trajectory[,"ycoor"]-full_trajectory[,"ycoor_previousframe"])^2))
#### calculate a distance per frame (i.e. speed) for intervals that are less than max_time
full_trajectory[which(full_trajectory$time_diff<=max_time),"dist_per_frame"] <- (sqrt((full_trajectory[which(full_trajectory$time_diff<=max_time),"xcoor"]-full_trajectory[which(full_trajectory$time_diff<=max_time),"xcoor_previousframe"])^2+(full_trajectory[which(full_trajectory$time_diff<=max_time),"ycoor"]-full_trajectory[which(full_trajectory$time_diff<=max_time),"ycoor_previousframe"])^2))/((full_trajectory[which(full_trajectory$time_diff<=max_time),"time_diff"]/0.5))
#### round
full_trajectory$dist_per_frame <- round(100*full_trajectory$dist_per_frame)/100
full_trajectory$total_dist <- round(100*full_trajectory$total_dist)/100
#### now use this new data to create a new traj file
traj <- full_trajectory[(1:(nrow(full_trajectory)-1)),c("frame","time","box","xcoor","ycoor","dist_per_frame","total_dist")]
#####calculate turn angles
trajectory <- as.ltraj(traj[c("xcoor","ycoor")],date=as.POSIXct(traj$time,origin="1970-01-01"),id=gsub("\\.txt","",gsub("ant_","",traj_file)),typeII=T,slsp="missing")
turn_angles <- abs(trajectory[[1]]$rel.angle)
#####modify it slightly, because I defined distance as distance moved between current frame and the previous; whereas turn angles are defined between current frame and the next
turn_angles <- c(NA,turn_angles[1:(length(turn_angles)-1)])
traj["turn_angle"] <- turn_angles
#####no movement = no turn. Therefore fill in NA turn angles when dist=0
traj[which(is.na(traj$turn_angle)&traj$dist_per_frame==0),"turn_angle"] <- 0
#####whenever the time separating 2 successive detections is greater than max_time, enter NA; because then the turn angle is not meaningful
times_1 <- c(NA,traj$time);times_2 <- c(traj$time,NA);time_diff <- times_2-times_1;time_diff <- time_diff[1:(length(time_diff)-1)]
time_diff <- round(time_diff/0.5)*0.5
traj[which(time_diff>max_time),"turn_angle"] <- NA
}else{
traj <- read.table(get(paste("traj_file",suffix,sep="")),header=T,comment.char="%")
traj <- traj[,which(!names(traj)%in%c("type","bout_id"))]
}
####################################################################
#######2. cut trajectory into bouts of activity vs. inactivity #####
####################################################################
#####define paremeters
min_segment_duration_sec <- 120; Lmin <- 2*min_segment_duration_sec #minimum duration of a bout, in frames
max_gap <- 15 ##anything larger than that needs to be subdivided into two different bouts
dist_threshold <- 15 #everything below that threshold (half a tag length) is considered inactive
power <- 0.125 ###power used before clustering
#####define an object that does not contain NAs in the dist_per_frame column
traj_noNA <- traj[which(!is.na(traj$dist_per_frame)),]
#####the analysis is only possible if there is enough data in traj_noNA
if (nrow(traj_noNA)>2*Lmin){
#####find segments based on distance moved
#####apply distance threshold
traj_noNA[traj_noNA$dist_per_frame<= dist_threshold,"dist_per_frame"] <- 0
#####use function cpt.meanvar to find breakpoints in the trajectory data
if (length(unique(traj_noNA$dist_per_frame))>2){
segments_dist <- cpt.meanvar(traj_noNA$dist_per_frame, method = "PELT",minseglen=Lmin)#####best by far
breakpoints <- segments_dist@cpts
rm(list="segments_dist")
}else{
breakpoints <- nrow(traj_noNA)
}
#####use breakpoints to define start and end times for bouts, and add the information into thr traj file
breakpoints <- match(traj_noNA[breakpoints,"time"],traj$time)
breakpoints[length(breakpoints)] <- max(nrow(traj),breakpoints[length(breakpoints)])
breakpoints <- c(1,breakpoints)
first_index <- breakpoints[1]
bout_start_indices <- c(first_index,(breakpoints+1)[2:(length(breakpoints)-1)])
bout_end_indices <- breakpoints[2:(length(breakpoints))]
bout_indices <- data.frame(start=bout_start_indices,end=bout_end_indices)
bout_count_index <- NULL
for (i in 1:nrow(bout_indices)){
bout_count_index <- c( bout_count_index , rep(i,(bout_indices[i,"end"]-bout_indices[i,"start"]+1)))
}
bout_count_index <- bout_counter + bout_count_index
traj["bout_index"] <- bout_count_index
bout_counter <- max(bout_count_index,na.rm=T)
}#if (nrow(traj_noNA)>20)
assign(paste("traj",suffix,sep=""),traj)
rm(list=c("traj"))
}##for (suffix in c("_Pre","_Post"))
###Now combine the two traj objects into a single one for the meta-analysis of active vs. inactive
if (ncol(traj_Pre)==ncol(traj_Post)){###do it only if bouts were defined for both periods
trajectory_table <- rbind(data.frame(period="before",traj_Pre),data.frame(period="after",traj_Post))
###Perform cluster analysis on the whole table to determine active/inactive using the mean and standard deviation of speed (dist_per_frame) and turn_angle as an input
for_multi <- aggregate(na.action="na.pass",cbind(turn_angle,(dist_per_frame)^power)~bout_index,function(x)cbind(mean(x,na.rm=T),sd(x,na.rm=T)),data=trajectory_table)
for_multi <- data.frame(for_multi$bout_index,for_multi$turn_angle,for_multi$V2);names(for_multi) <- c("bout_index","turn_angle","turn_angle_SD","Dist","Dist_SD")
cluster_BOTH <- kmeans( na.omit( for_multi [c("turn_angle","Dist","turn_angle_SD","Dist_SD")]), centers=2) ## clustering on ave & sd of relative turn angle & average distance
####Distinguish between active and inactive bout using the speed (active corresponds to higher speed)
types_BOTH <- c("inactive","active")[order(data.frame(cluster_BOTH["centers"])$centers.Dist)]
trajectory_table$type <- types_BOTH[cluster_BOTH$cluster[trajectory_table$bout_index]]
####Use the results from the cluster analysis to define bouts and interbouts
if (length(unique(trajectory_table$type))==1){
if (unique(trajectory_table$type)=="active"){to_fill <- "bout1"}else{to_fill <- "interbout1"}
trajectory_table[1:nrow(trajectory_table),"bout_id"] <- to_fill
}else{
##find indices of changes in activity type, in order to pool successive bouts of the same type together
changes <- data.frame(type=c(NA,trajectory_table$type),type.2=c(trajectory_table$type,NA))
changes$change <- changes$type==changes$type.2
breakpoints <- which(!changes$change[1:(length(changes$change)-1)])
start_indices <- c(1,breakpoints)
end_indices <- c(breakpoints-1,nrow(trajectory_table))
if(trajectory_table[1,"type"]!="active"){
interbout_indices <- 1+2*c(0:(ceiling(length(start_indices)/2)-1))
bout_indices <- 2*c(1:floor(length(start_indices)/2))
}else{
bout_indices <- 1+2*c(0:(ceiling(length(start_indices)/2)-1))
interbout_indices <- 2*c(1:floor(length(start_indices)/2))
}
bout_indices <- data.frame(start=start_indices[bout_indices],end=end_indices[bout_indices])
interbout_indices <- data.frame(start=start_indices[interbout_indices],end=end_indices[interbout_indices])
###copy the new bout information into the trajectory_table object
bout_index_list <- NULL
bout_count_index <- NULL
for (i in 1:nrow(bout_indices )){
bout_index_list <- c(bout_index_list, seq(bout_indices[i,"start"],bout_indices[i,"end"]))
bout_count_index <- c( bout_count_index , rep(i,(bout_indices[i,"end"]-bout_indices[i,"start"]+1)))
}
interbout_index_list <- NULL
interbout_count_index <- NULL
for (i in 1:nrow(interbout_indices )){
interbout_index_list <- c(interbout_index_list, seq(interbout_indices[i,"start"],interbout_indices[i,"end"]))
interbout_count_index <- c( interbout_count_index , rep(i,(interbout_indices[i,"end"]-interbout_indices[i,"start"]+1)))
}
trajectory_table[bout_index_list,"bout_id"] <- paste("bout",bout_count_index,sep="")
trajectory_table[interbout_index_list,"bout_id"] <- paste("interbout",interbout_count_index,sep="")
}
####Finally, find large gaps in trajectory and subdivide each bout that was defined across the gap
####separate bout_id into root and index
temp <- gregexpr("[0-9]+", trajectory_table$bout_id)
trajectory_table["idx"] <- as.numeric(unlist(regmatches(trajectory_table$bout_id,temp)))
trajectory_table[paste("bout",trajectory_table$idx,sep="")==trajectory_table$bout_id,"root"] <- "bout"
trajectory_table[paste("interbout",trajectory_table$idx,sep="")==trajectory_table$bout_id,"root"] <- "interbout"
###get times where more than 15 min gap
times_1 <- c(NA,trajectory_table$time);times_2 <- c(trajectory_table$time,NA);time_diff <- times_2-times_1;time_diff <- time_diff[1:(length(time_diff)-1)]
indices <- which(time_diff>(60*max_gap))
for (index in indices){
trajectory_table[(index:nrow(trajectory_table)),][trajectory_table[(index:nrow(trajectory_table)),"root"]==trajectory_table[index,"root"],"idx"] <- trajectory_table[(index:nrow(trajectory_table)),][trajectory_table[(index:nrow(trajectory_table)),"root"]==trajectory_table[index,"root"],"idx"] + 1
}
###copy new bout id into the table
trajectory_table <- within(trajectory_table, bout_id <- paste(root,idx,sep=""))
###Finally, divide the trajectory:table into pre- and post-treatment trajectories
traj_Pre <-trajectory_table[which(trajectory_table$period=="before"),]
traj_Post <-trajectory_table[which(trajectory_table$period=="after"),]
}else{
###In case one of the periods did not have enough data for bouts to be defined, fill the columns with NA
traj_Pre <- data.frame(period="before",traj_Pre); traj_Pre["bout_id"] <- NA; traj_Pre["type"] <- NA
traj_Post <- data.frame(period="after",traj_Post); traj_Post["bout_id"] <- NA; traj_Post["type"] <- NA
}
for (suffix in c("_Pre","_Post")){
###Add metadata and for each of the pre-treatment and pre-treatment trajectories
splitinfo <- get(paste("splitinfo",suffix,sep=""))
traj <- get(paste("traj",suffix,sep=""))
indices <- unlist(lapply(traj$time,function(x)max(which(x>=splitinfo$time))))
traj["time_hours"] <- splitinfo$time_hours[indices]
traj["time_of_day"] <- splitinfo$time_of_day[indices]
traj["colony"] <- colony
traj["treatment"] <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"treatment"]
traj <- traj[c("colony","treatment","box","period","time_hours","time_of_day","time","frame","xcoor","ycoor","dist_per_frame","total_dist","turn_angle","type","bout_id")]
##################################
####### Now analyse trajectory ###
##################################
####prepare output
tab <- expand.grid(colony=colony,
tag=gsub("\\.txt","",gsub("ant_","",traj_file)),
time_hours=splitinfo$time_hours,
proportion_time_active=NA,
average_bout_speed_pixpersec=NA,
total_distance_travelled_pix=NA)
###Analyse separately for each time point
for (time_point in unique(tab$time_hours)){
subtraj <- traj[which(traj$time_hours==time_point),]
if (!all(is.na(subtraj$type))){
bouts <- subtraj[which(subtraj$type=="active"),]
interbouts <- subtraj[which(subtraj$type=="inactive"),]
bout_number <- length(unique(bouts$bout_id))
interbout_number <- length(unique(interbouts$bout_id))
if (!(bout_number==0&interbout_number==0)){###if there is no bout data, leave everything as NA
if (bout_number==0){###if ant completely inactive
tab[which(tab$time_hours==time_point),c("proportion_time_active","total_distance_travelled_pix")] <- 0
}else {###if ant shows at least some activity
tab[which(tab$time_hours==time_point),"total_distance_travelled_pix"] <- sum(bouts$total_dist,na.rm=T)
bout_speed <- aggregate(na.rm=T,na.action="na.pass",dist_per_frame~bout_id,FUN=mean,data=bouts)
tab[which(tab$time_hours==time_point),"average_bout_speed_pixpersec"] <- mean(bout_speed$dist_per_frame,na.rm = T)*2 ####multiply by 2 because each frame lasts 0.5sec
if (interbout_number==0){###if ant completely active
tab[which(tab$time_hours==time_point),"proportion_time_active"] <- 1
}else{###if ant shows both activity and inactivity
###calculate cumulated bout duration
bout_starts <- aggregate(na.rm=T,na.action="na.pass",time~bout_id+time_hours,FUN=min,data=bouts); names(bout_starts)[names(bout_starts)=="time"] <- "Starttime"
bout_ends <- aggregate(na.rm=T,na.action="na.pass",time~bout_id+time_hours,FUN=max,data=bouts); names(bout_ends)[names(bout_ends)=="time"] <- "Stoptime"
bout_durations <- merge(bout_starts,bout_ends)
bout_duration <- sum(bout_durations$Stoptime-bout_durations$Starttime+0.5,na.rm=T)
###calculate cumulated interbout duration
interbout_starts <- aggregate(na.rm=T,na.action="na.pass",time~bout_id+time_hours,FUN=min,data=interbouts); names(interbout_starts)[names(interbout_starts)=="time"] <- "Starttime"
interbout_ends <- aggregate(na.rm=T,na.action="na.pass",time~bout_id+time_hours,FUN=max,data=interbouts); names(interbout_ends)[names(interbout_ends)=="time"] <- "Stoptime"
interbout_durations <- merge(interbout_starts,interbout_ends)
interbout_duration <- sum(interbout_durations$Stoptime-interbout_durations$Starttime+0.5,na.rm=T)
tab[which(tab$time_hours==time_point),"proportion_time_active"] <- bout_duration/(bout_duration+interbout_duration)
}
}
}
}
}
TAB_ALL <- rbind(TAB_ALL,tab)
###Finally, write results
###individual behaviour
behav <- read.table(paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""),header=T,stringsAsFactors = F)
if (!"proportion_time_active"%in%names(behav)){
behav[c("proportion_time_active","average_bout_speed_pixpersec","total_distance_travelled_pix")] <- NA
}
behav[match(as.character(interaction(tab$colony,tab$tag,tab$time_hours)),as.character(interaction(behav$colony,behav$tag,behav$time_hours))),c("proportion_time_active","average_bout_speed_pixpersec","total_distance_travelled_pix")] <- tab[c("proportion_time_active","average_bout_speed_pixpersec","total_distance_travelled_pix")]
options(digits=3)
write.table(behav,file=paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""), row.names=F, col.names=T,append=F,quote=F)
options(digits=16)
write.table(traj,file=get(paste("traj_file",suffix,sep="")), row.names=F, col.names=T,append=F,quote=F)
}
}else{#if (!grepl("bout_id",output))
print("Ant already processed.")
}
}#else (from if (!traj_file %in% alive))
clean()
}#for (traj_file in traj_files)
}# for (traj_folder in traj_list)
to_keep <- to_keep_ori<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/12_simulate_transmission.R
####12_simulate_transmission.R#####
#### Sources C++ function simulate_transmission from source folder
#### Takes an interaction list and simulates the transmission of that agent from a list of originally contaminated workers to the rest of the colony
###Created by <NAME>
####################################
to_keep_ori <- to_keep
Sys.setenv("PKG_CXXFLAGS"="-std=c++11")
sourceCpp(paste(code_path,"/simulate_transmission.cpp",sep=""))
#################################
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
#### get input file list
input_path <- paste(data_path,"/intermediary_analysis_steps/full_interaction_lists",sep="")
setwd(input_path)
input_files <- paste(input_path,"/",list.files(recursive=T,pattern="colony"),sep="")
#### arguments
N_SIM <- 500
if (!grepl("survival",data_path)){
seed_files <- c("treated_workers.txt","random_workers.txt","frequent_foragers.txt","occasional_foragers.txt","nurses.txt","low_degree.txt","high_degree.txt")
}else{
seed_files <- c("treated_workers.txt")
}
to_keep <- c(ls(),"to_keep","seed_file","outputfolder","interac_folders","reorder","interac_folder","interac_list","summary_collective","summary_individual","interac")
for (seed_file in seed_files ){
print(paste("Seeds =",gsub("\\.txt","",seed_file)))
if (seed_file=="treated_workers.txt"){
if (!grepl("survival",data_path)){
outputfolder <- paste(data_path,"/transmission_simulations/pre_vs_post_treatment/experimentally_exposed_seeds",sep="")
interac_folders <- "observed"
reorder <- T
}else{
outputfolder <- paste(data_path,"/transmission_simulations/post_treatment/experimentally_exposed_seeds",sep="")
interac_folders <- "observed"
reorder <- F
}
}else{
outputfolder <- paste(data_path,"/transmission_simulations/random_vs_observed/",gsub("\\.txt","",seed_file),sep="")
interac_folders <- c("observed",1:100)
reorder <- F
}
if (!file.exists(outputfolder)){dir.create(outputfolder,recursive = T)}
for (interac_folder in interac_folders){
if (interac_folder!="observed"){interac_folder <- paste("random_",paste(rep(0,3-nchar(interac_folder)),collapse=""),interac_folder,sep="")}
if (!file.exists(paste(outputfolder,"/individual_simulation_results_",interac_folder,".txt",sep=""))){
summary_collective <- NULL
summary_individual <- NULL
interac_list <- input_files[grepl(interac_folder,input_files)]
if (seed_file!="treated_workers.txt"){interac_list <- interac_list[grepl("PreTreatment",interac_list)]}
for (interac in interac_list){
print(interac)
####get colony info
root_name <- gsub("_interactions.txt","",unlist(strsplit(interac,split="/"))[grepl("colony",unlist(strsplit(interac,split="/")))])
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
colony_number <- as.numeric(gsub("colony","",colony))
####get period info
if (grepl("PreTreatment",root_name)){period="before"}else{period="after"}
####read interactions
interaction_table <- read.table(interac,header=T,stringsAsFactors=F)
interaction_table <- interaction_table[order(interaction_table$Starttime),]
####read tag list to define list of live ants
tagfile <- tag_list[grepl(colony,tag_list)]
tag <- read.tag(tagfile)$tag; names(tag)[names(tag)=="#tag"] <- "tag"; tag <- tag[which(tag$tag!="#tag"),]
if (!grepl("survival",data_path)){
alive <- tag[which(tag$final_status=="alive"),"tag"]
}else{
alive <- tag[which(as.numeric(tag$death)==0|as.numeric(tag$death)>=max(interaction_table$Stopframe,na.rm=T)),"tag"]
}
###read seeds
seeds <- read.table(paste(data_path,"/original_data/seeds/",seed_file,sep=""),header=T,stringsAsFactors = F)
seeds <- seeds[which(seeds$colony==colony_number),"tag"]
seeds <- seeds[which(seeds%in%alive)]
####read time aggregation info for both current file and PostTreatment file if relevant (i.e. if reorder=T), and get start time from that
if (!grepl("survival",data_path)){
splitfile <- split_list[grepl(root_name,split_list)]
splitinfo <- read.table(splitfile,header=T,stringsAsFactors = F)
if (reorder){
splitfile_Post <- split_list[grepl(gsub("Pre","Post",root_name),split_list)]
splitinfo_Post <- read.table(splitfile_Post,header=T,stringsAsFactors = F)
}
time_start <- min(splitinfo$time,na.rm=T)
}else{
time_start <- min(interaction_table$Starttime,na.rm=T)
}
####for simulations to be comparable between the Pre-Treatment and Post-treatment periods, they should start at the same time of day
####so in that case, Pre-Treatment interactions should be reordered
if (reorder & period=="before") {
####start time must be the same time of day as start time of after.
time_start <- min(splitinfo_Post$time,na.rm=T) - (24*3600)
####get the corresonding row number in the interaction table
start_index <- min(which(interaction_table$Starttime>=time_start))
####split the interaction table into two halves
interactions_unchanged <- interaction_table[start_index:nrow(interaction_table),]
interactions_to_change <- interaction_table[1:(start_index-1),]
####modify frame number and time of interactions_to_change
interactions_to_change[c("Starttime","Stoptime")] <- interactions_to_change[c("Starttime","Stoptime")] + 24 * 3600
frame_offset <- (interactions_unchanged[nrow(interactions_unchanged),"Startframe"]+floor((interactions_to_change[1,"Starttime"]-interactions_unchanged[nrow(interactions_unchanged),"Starttime"])*2))-interactions_to_change[1,"Startframe"]
interactions_to_change[c("Startframe","Stopframe")] <- interactions_to_change[c("Startframe","Stopframe")] + frame_offset
interaction_table <- rbind(interactions_unchanged,interactions_to_change)
}
####Create antlist object
antlist <- data.frame(tag=alive,status=0,load=0,stringsAsFactors = F)
antlist[which(antlist$tag%in%seeds),c("status","load")] <- 1
####Change formats to match formats expected by the C++ program
antlist$tag <- as.integer(antlist$tag )
antlist$status <- as.integer(antlist$status )
antlist$load <- as.numeric(antlist$load )
interaction_table$Tag1 <- as.integer(interaction_table$Tag1 )
interaction_table$Tag2 <- as.integer(interaction_table$Tag2 )
interaction_table$Startframe <- as.integer(interaction_table$Startframe )
interaction_table$Stopframe <- as.integer(interaction_table$Stopframe )
interaction_table$Starttime <- as.numeric(interaction_table$Starttime )
interaction_table$Stoptime <- as.numeric(interaction_table$Stoptime )
####Perform simulations
print("Performing simulations...")
simulations <- NULL
for (i in 1:N_SIM){
simulations <- rbind(simulations,data.frame(sim_number=i,simulate_transmission(interaction_table,antlist,time_start)))
}
####Summarise simulations
##Step 1: modify columns
simulations$relative_contamination_time <- simulations$relative_contamination_time/3600 ###express contamination time in hours instead of seconds
simulations <- simulations[,!names(simulations)%in%c("absolute_contamination_time","infectious")] ##remove unncessary columns
simulations["contaminated"] <- 1 ###add a column containing information on whether the ant was contaminated or not during the simulation
simulations["status"] <- "untreated"
simulations[which(simulations$tag%in%seeds),"status"] <- "treated"
##Step 2: add individuals that did not get contaminated during the simulations
all_individuals <- expand.grid(sim_number=c(1:N_SIM),tag=alive)
simulations <- merge(all_individuals,simulations,all.x=T,all.y=T)
if (nrow( simulations[which(is.na(simulations$relative_contamination_time)),])>0){
simulations[which(is.na(simulations$relative_contamination_time)),"status"] <- "untreated"
simulations[which(is.na(simulations$relative_contamination_time)),c("relative_contamination_time","contaminated_by","final_load","contaminated")] <- rep(c(24,-1,0,0) ,each=nrow(simulations[which(is.na(simulations$relative_contamination_time)),]))
}
simulations <- simulations[order(simulations$sim_number,simulations$relative_contamination_time),]
##Step3: add further individual-level information
############# Add infection rank
ranks <- aggregate(relative_contamination_time~sim_number,function(x)rank(x,ties.method="min"),data=simulations[which(simulations$status!="treated"),])
for (sim_number in unique(ranks$sim_number)){
simulations[which(simulations$sim_number==sim_number&simulations$status=="treated"),"rank"] <- 0
simulations[which(simulations$sim_number==sim_number&simulations$status!="treated"),"rank"] <- as.numeric(ranks[which(ranks$sim_number==sim_number),c(2:ncol(ranks))])
}
############# Add high load/low load
simulations["high_level"] <- as.numeric(simulations$final_load>high_threshold)
simulations["low_level"] <- as.numeric(simulations$final_load>0&simulations$final_load<=high_threshold)
##Step4: summarise simulations - colony-level data
#########Step 4.1: Prevalence, Mean load, Prop. high level, Prop. low level, Mean load
colony_level <- aggregate(na.rm=T,na.action="na.pass",cbind(contaminated,final_load,high_level,low_level)~sim_number,FUN=mean,data=simulations[which(simulations$status!="treated"),])
names(colony_level) <- c("sim_number","Prevalence","Mean_load","Prop_high_level","Prop_low_level")
#########Step 4.2: Load skewness
skewness <- aggregate(na.rm=T,na.action="na.pass",final_load~sim_number,FUN=skewness,data=simulations[which(simulations$status!="treated"),])
names(skewness) <- c("sim_number","Load_skewness")
colony_level <- merge(colony_level,skewness)
#########Step 4.3: Queen load
queen <- simulations[which(simulations$tag==queenid),c("sim_number","final_load")]
names(queen) <- c("sim_number","Queen_load")
colony_level <- merge(colony_level,queen)
#########Step 4.4: Transmission rate
colony_level["logistic_r"] <- NA
for (sim in unique(simulations$sim_number)){
#######define table that will be used in the non linear fit
subset <- simulations[which(simulations$sim_number==sim),]
#######remove from subset the ants that were not infected during the simulation and were added later
subset <- subset[which(subset$contaminated!=0),]
#######sort by time
subset <- subset[order(subset$relative_contamination_time,subset$status),]
#######get population size
pop_size <- sum(subset[1,c("nb_susceptible","nb_contaminated")])
#######get relevant data
spread <- subset[c("relative_contamination_time","rank")]
spread["nb_seeds"] <- nrow(subset[which(subset$status=="treated"),])
spread["nb_contaminated"] <- spread$rank+spread$nb_seeds
spread <- spread[which(!duplicated(spread[c("relative_contamination_time","nb_contaminated")])),]
spread["proportion_contaminated"] <- spread$nb_contaminated/pop_size
#######try logistic fit
y <- spread$proportion_contaminated
x <- spread$relative_contamination_time
P_zero <- spread[which(spread$rank==0),"proportion_contaminated"]
#K <- 1
if (exists("fit_logistic")){rm(list=c("fit_logistic"))}
try(fit_logistic <- nls(
y ~ (K*P_zero*exp(r*x))
/
(K+(P_zero*(-1+exp(r*x))))
,
start=list(r=1,K=1)
#start=list(r=1)
,
control=list(maxiter = 1000)
)
,silent=T)
if (exists("fit_logistic")){
r <- summary(fit_logistic)$coefficients["r","Estimate"]
K <- summary(fit_logistic)$coefficients["K","Estimate"]
colony_level[which(colony_level$sim_number==sim),"logistic_r"] <- r
}
rm(list=c("fit_logistic","r","K"))
}
#########Step 4.5: Take average over all simulations
colony_level <- colMeans(colony_level[names(colony_level)!="sim_number"],na.rm=T)
#########Step 4.6: Store
summary_collective <- rbind(summary_collective,cbind(data.frame(colony=colony,colony_size=info[which(info$colony==colony_number),"colony_size"],treatment=info[which(info$colony==colony_number),"treatment"],period=period,time_hours=interaction_table[1,"time_hours"],time_of_day=interaction_table[1,"time_of_day"],stringsAsFactors = F),t(colony_level)))
##Step5: summarise simulations - individual-level data
#########Step 5.1: Final_load, Prob. contamination, Prob. high level, Prob. low level
individual_level <- aggregate(na.rm=T,na.action="na.pass", cbind(final_load,contaminated,high_level,low_level) ~ tag,FUN=mean,data=simulations)
names(individual_level) <- c("tag","simulated_load","probability_of_transmission","probability_high_level","probability_low_level")
#########Step 5.2: Transmission latency and transmission rank
individual_level[c("transmission_latency","transmission_rank")] <- NA
for (ant in alive){
if (all(simulations[which(simulations$tag==ant),"contaminated"]==1)){
individual_level[which(individual_level$tag==ant),"transmission_latency"] <- mean(simulations[which(simulations$tag==ant),"relative_contamination_time"])
individual_level[which(individual_level$tag==ant),"transmission_rank"] <- mean(simulations[which(simulations$tag==ant),"rank"])
}else{
model <- coxph(Surv(relative_contamination_time,contaminated)~1,data=simulations[which(simulations$tag==ant),])
mean_data <- summary(survfit(model),rmean="common")$table
individual_level[which(individual_level$tag==ant),"transmission_latency"] <- mean_data["*rmean"]
model <- coxph(Surv(rank,contaminated)~1,data=simulations[which(simulations$tag==ant),])
mean_data <- summary(survfit(model),rmean="common")$table
individual_level[which(individual_level$tag==ant),"transmission_rank"] <- mean_data["*rmean"]
}
}
#########Step 5.3: Store
individual_level$antid <- as.character(interaction(colony,individual_level$tag))
individual_level$status <- "untreated";individual_level[which(individual_level$tag%in%seeds),"status"] <- "treated"
individual_level["colony"] <- colony
individual_level["colony_size"] <- info[which(info$colony==colony_number),"colony_size"]
individual_level["treatment"] <- info[which(info$colony==colony_number),"treatment"]
individual_level["period"] <- period
individual_level["time_hours"] <- interaction_table[1,"time_hours"]
individual_level["time_of_day"] <- interaction_table[1,"time_of_day"]
individual_level <- individual_level[c("colony","colony_size","treatment","tag","antid","status","period","time_hours","time_of_day","simulated_load","probability_of_transmission","probability_high_level","probability_low_level","transmission_latency","transmission_rank")]
summary_individual <- rbind(summary_individual,individual_level)
clean()
}
summary_collective <- summary_collective[order(summary_collective$colony,summary_collective$time_hours),]
summary_individual <- summary_individual[order(summary_individual$colony,summary_individual$tag,summary_individual$time_hours),]
if (grepl("random_vs_observed",outputfolder)){
summary_collective["randy"] <- interac_folder
summary_individual["randy"] <- interac_folder
}
write.table(summary_collective,paste(outputfolder,"/collective_simulation_results_",interac_folder,".txt",sep=""),col.names=T,row.names=F,quote=F,append=F)
write.table(summary_individual,paste(outputfolder,"/individual_simulation_results_",interac_folder,".txt",sep=""),col.names=T,row.names=F,quote=F,append=F)
}
}
if (grepl("random_vs_observed",outputfolder )){
setwd(outputfolder)
file_list <- list.files(pattern="individual")
all_indiv_results <- NULL
for (file in file_list){
temp <- read.table(file, header=T,stringsAsFactors = F)
if (grepl("random",unique(temp$randy))){
temp$randy <- "random"
}
all_indiv_results <- rbind(all_indiv_results,temp)
}
all_indiv_results <- aggregate(na.rm=T,na.action="na.pass",cbind(simulated_load,probability_of_transmission,probability_high_level,probability_low_level,transmission_latency,transmission_rank)~.,FUN=mean,data=all_indiv_results)
all_indiv_results$treatment <- all_indiv_results$randy
write.table(all_indiv_results,file=paste(outputfolder,"/summarised_individual_results.dat",sep=""),append=F,quote=F,row.names=F,col.names=T)
}
}
to_keep <- to_keep_ori
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/17_brood_location.R
####17_brood_location.R#####
####Calculates the distance between the center of gravity of the brood pile and the nest entrance based on the brood coordinates
###Created by <NAME>
###################################
### get input folder list
input_brood <- paste(data_path,"/original_data/brood_coordinates",sep="")
setwd(input_brood)
input_list <- paste(input_brood,dir(),sep="/")
###define outputfolder
outputfolder <- paste(data_path,"/processed_data/collective_behaviour/pre_vs_post_treatment",sep="")
if (!file.exists(outputfolder)){dir.create(outputfolder,recursive = T)}
brood_COG <- NULL
for (folder in input_list){
root_name <- unlist(strsplit(folder,split="/"))[grepl("colony",unlist(strsplit(folder,split="/")))]
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
colony_number <- as.numeric(gsub("colony","",colony))
treatment <- info[which(info$colony==colony_number),"treatment"]
colony_size <- info[which(info$colony==colony_number),"colony_size"]
source(paste(code_path,"/heatmap_to_homerange_parameters.R",sep=""))
if (grepl("PreTreatment",folder)){
period <- "before"
}else{
period <- "after"
}
setwd(folder)
brood_files <- list.files(pattern="brood")
for (brood_file in brood_files){
metadata <- unlist(strsplit(gsub("\\.txt","",brood_file),split="_"))
time_of_day <- as.numeric(gsub("TD","",metadata[which(grepl("TD",metadata))]))
time_hours <- as.numeric(gsub("TH","",metadata[which(grepl("TH",metadata))]))
###read coordinate file
t <- read.table(brood_file,header=T,stringsAsFactors = F)
t <- data.frame(X=t$X,Y=t$Y,obs=1)
#######modify t; indeed heatmaps and nest entrance position were calculated using cells of 5*5 pixels whereas t currently holds the real coordinates in pixels
t$X <- floor(t$X/5)
t$Y <- floor(t$Y/5)
observations <- aggregate(obs~X+Y,FUN=sum,data=t)
#######calculate centroid location
centroid <- data.frame(x=mean(observations$X),y=mean(observations$Y))
if ((centroid$y>=yforagingmin)&(centroid$y<=yforagingmax)){####if CoG is in foraging arena, then distance to nest entrance will be positive, whereas if it is inside the nest, it will be negative
fac <- 1
}else {
fac <- -1
}
distance_to_entrance <- fac*euc.dist(centroid,nest_entrance) #####this corresponds to a distance in 5*pixels
distance_to_entrance <- distance_to_entrance * 5 ##### this corresponds to a distance in real pixels
####record data
brood_COG <- rbind(brood_COG,data.frame(colony=colony,colony_size=colony_size,treatment=treatment,period=period,time_hours=time_hours,time_of_day=time_of_day,distance_from_nest_entrance_pix=distance_to_entrance,stringsAsFactors = F))
}
}
brood_COG <- brood_COG[order(brood_COG$colony,brood_COG$time_hours),]
write.table(brood_COG,file=paste(outputfolder,"/brood_location.txt",sep=""),col.names=T,row.names=F,append=F,quote=F)<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/10_process_interaction_files.R
####10_process_interaction_files.R#####
#### Removes interactions involving ants that died before the end of the experiment from the interaction file
#### Adds metadata to the interaction file
###Created by <NAME>
#################################
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
####get interaction list #####
input_interac <- paste(data_path,"intermediary_analysis_steps/filtered_interactions",sep="/")
setwd(input_interac)
interac_list <- paste(input_interac,dir(),sep="/")
####define outputfolder
if (!grepl("survival",data_path)){
outputfolder <- paste(data_path,"/intermediary_analysis_steps/binned_interaction_lists",sep="")
}
outputfolder2 <- paste(data_path,"/intermediary_analysis_steps/full_interaction_lists",sep="")
##################################
for (interac in interac_list){
root_name <- unlist(strsplit(interac,split="/"))[grepl("colony",unlist(strsplit(interac,split="/")))]
print(paste(unlist(strsplit(root_name,split="_")),collapse="_"))
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
tagfile <- tag_list[grepl(colony,tag_list)]
if (length(tagfile)>1){
tagfile <- tagfile[grepl(unlist(strsplit(gsub("\\.txt","",root_name),"_"))[grepl("Treatment",unlist(strsplit(gsub("\\.txt","",root_name),"_")))],tagfile)]
}
outputfolder4 <- paste(outputfolder2,"/",gsub("\\.txt","",unlist(strsplit(root_name,split="_"))[grepl("Treatment",unlist(strsplit(root_name,split="_")))]),"/observed",sep="")
if(!file.exists(outputfolder4)){dir.create(outputfolder4,recursive=T)}
### read in interaction file
tab <- read.table(interac,header=T,stringsAsFactors = F,sep=",",comment.char="%")
if (length(names(tab)[grepl("X\\.",names(tab))])>0){
names(tab)[grepl("X\\.",names(tab))] <- gsub("X\\.","",names(tab)[grepl("X\\.",names(tab))])
####read-in tag list to define list of live ants
tag <- read.tag(tagfile)$tag; names(tag)[names(tag)=="#tag"] <- "tag"; tag <- tag[which(tag$tag!="#tag"),]
if (!grepl("survival",data_path)){
alive <- tag[which(tag$final_status=="alive"),"tag"]
}else{
alive <- tag[which(as.numeric(tag$death)==0|as.numeric(tag$death)>=max(tab$Stopframe,na.rm=T)),"tag"]
}
###remove interactions involving ants that died before the end of the experiment
tab <- tab[which( (tab$Tag1%in%alive)&(tab$Tag2%in%alive)),]
###Add metadata and for each of the pre-treatment and pre-treatment tabectories
if(!grepl("survival",data_path)){
splitfile <- split_list[grepl(gsub("\\.txt","",root_name),split_list)]
if (length(splitfile)>0){
outputfolder3 <- paste(outputfolder,"/",gsub("\\.txt","",unlist(strsplit(root_name,split="_"))[grepl("Treatment",unlist(strsplit(root_name,split="_")))]),"/observed",sep="")
if(!file.exists(outputfolder3)){dir.create(outputfolder3,recursive=T)}
#### read in aggregation information
splitinfo <- read.table(splitfile,header=T, stringsAsFactors = F)
indices <- unlist(lapply(tab$Starttime,function(x)max(which(x>=splitinfo$time))))
tab["time_hours"] <- splitinfo$time_hours[indices]
tab["time_of_day"] <- splitinfo$time_of_day[indices]
}else{
tab["time_hours"] <- 0
tab["time_of_day"] <- 12
}
}else{
tab["time_hours"] <- 0
tab["time_of_day"] <- 12
}
tab["colony"] <- colony
tab["treatment"] <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"treatment"]
### Write the interaction list corresponding to each time point into a folder
if (length(unique(tab$time_hours))>1){
for (time_hours in unique(tab$time_hours)){
subtab <- tab[which(tab$time_hours==time_hours),]
time_of_day <- unique(subtab$time_of_day)
outfile <- paste(outputfolder3,"/",gsub("\\.txt","",root_name),"_TH",time_hours,"_TD",time_of_day,"_interactions.txt",sep="")
write.table(subtab,file=outfile,col.names=T,row.names=F,append=F,quote=F)
}
}
### Overwrite the full interaction list and copy it in another folder
write.table(tab,file=interac,col.names=T,row.names=F,append=F,quote=F)
outfile <- paste(outputfolder4,"/",gsub("\\.txt","",root_name),"_interactions.txt",sep="")
command <- paste("cp ", interac, " ",outfile,sep="")
system(command)
}
}<file_sep>/pre_made_scripts/ant_code/2_statistics_and_plotting/source/functions.R
add_stats <- function(dataset,plotx,means,ymin,ymax,predictor,p_colony,output,contrast.matrix,survival,p_queen=NA,lab_title){
model <- output[["modellist"]][["24"]][["1"]]
p_interaction <- output[["interaction_problist"]][["24"]][["1"]]
####reduce contrast.matrix
comparisons <- data.frame(name=rownames(contrast.matrix),stringsAsFactors = F) ####get all the comparisons
comparisons["term1"] <- unlist(lapply(comparisons$name,function(x)unlist(strsplit(x,split=" - "))[1]))
comparisons["term2"] <- unlist(lapply(comparisons$name,function(x)unlist(strsplit(x,split=" - "))[2]))
comparisons["treatment_index"] <- unlist(lapply(comparisons$term1,function(x)which(unlist(strsplit(x,split="_"))%in%treatments)))
treatment_index <- unique(comparisons$treatment_index)
comparisons["treatment1"] <- unlist(lapply(comparisons$term1,function(x)unlist(strsplit(x,split="_"))[treatment_index]))
comparisons["treatment2"] <- unlist(lapply(comparisons$term2,function(x)unlist(strsplit(x,split="_"))[treatment_index]))
comparisons["level1"] <- unlist(lapply(comparisons$term1,function(x)paste(unlist(strsplit(x,split="_"))[(treatment_index+1):length(unlist(strsplit(x,split="_")))],collapse="_")))
comparisons["level2"] <- unlist(lapply(comparisons$term2,function(x)paste(unlist(strsplit(x,split="_"))[(treatment_index+1):length(unlist(strsplit(x,split="_")))],collapse="_")))
comparisons["to_keep"] <- F
comparisons[which(comparisons$level1==comparisons$level2),"to_keep"] <- T
comparisons[which(comparisons$level1=="queen"),"to_keep"] <- F
contrast.matrix <- contrast.matrix[which(comparisons$to_keep),]
####if more than 2 levels, then add individual change comparisaon statistics
if (!is.na(p_interaction)&p_interaction <= 0.05){
post_hoc <- summary(glht(model,contrast.matrix),test=adjusted("BH"))
print("z value");print(post_hoc$test$tstat);print("Pr>|z|");print(post_hoc$test$pvalues);
p_values <- as.numeric(post_hoc$test$pvalues);names(p_values) <- names(post_hoc$test$coefficients)
if (!is.na(p_queen)){
names(p_queen) <- "queen"
p_values <- c(p_values,p_queen)
}
for (idx in 1:length(p_values)){
p_value <- p_values[idx]
if (names(p_value)=="queen"){level <- "queen"}else{level <- comparisons[which(comparisons$name==names(p_value)),"level1"]}
print(p_value)
if (p_value>0.05){p_cex <- par("cex") *inter_cex;adjust_line <- 0;fonty <- 1}else{p_cex <- par("cex") *max_cex*1.1;adjust_line <- -0.3; fonty <- 2}
mtext(from_p_to_ptext(p_value),side=3,line=stat_line+adjust_line,at=mean(plotx[which(means$predictor==level)]),xpd=T,cex=p_cex,font=fonty)
}
}else if (!is.na(p_interaction)&p_interaction > 0.05){
anov <- Anova(model)
if (!all(!grepl("moved",lab_title))){ ###for distance moved we are interested in the full interaction
p_value <- p_interaction
}else{
p_value <- anov["Pr(>Chisq)"]["time:treatment","Pr(>Chisq)"]
}
if (p_value>0.05){p_cex <- par("cex") *inter_cex;adjust_line <- 0;fonty <- 1}else{p_cex <- par("cex") *max_cex*1.1;adjust_line <- -0.3; fonty <- 2}
mtext(from_p_to_ptext(p_value),side=3,line=stat_line+adjust_line,xpd=T,cex=p_cex,font=fonty)
}
}
apply_alpha <- function(coli,alphi){
###Convert to rgb
coli <- as.vector(col2rgb(coli))
###Convert to CMYK
coli <- rgb2cmyk(R=coli[1],G=coli[2],B=coli[3])
###Multiply K by alphi
coli["K"] <- alphi*coli["K"]
###Convert back to rgb
coli <- cmyk2rgb(C=coli["C"],M=coli["M"],Y=coli["Y"],K=coli["K"])
###Convert from RGB to hex
rcol <- str_pad(as.hexmode(coli["R"]), width=2, side="left", pad="0")
gcol <- str_pad(as.hexmode(coli["G"]), width=2, side="left", pad="0")
bcol <- str_pad(as.hexmode(coli["B"]), width=2, side="left", pad="0")
Colourz <- paste("#",rcol,gcol,bcol,sep="" )
return(Colourz)
}
clean <- function(){
rm(list=ls(envir = .GlobalEnv)[!ls(envir = .GlobalEnv)%in%to_keep], envir = .GlobalEnv)
no_print <- gc(verbose=F)
}
closest_match <- function(x,y){
return(min(which(abs(x-y)==min(abs(x-y))),na.rm=T))
}
colo <- function(x){
return(paste("colony",paste(rep(0,3-nchar(x)),collapse=""),x,sep=""))
}
cmyk2rgb <- function(C,M,Y,K){
R <- round(255 * (1-C) * (1-K))
G <- round(255 * (1-M) * (1-K))
B <- round(255 * (1-Y) * (1-K))
outcol <- c(R,G,B)
names(outcol) <- c("R","G","B")
return(outcol)
}
partial_least_square_regression <- function(experiments){
variables <- c("modularity","density","diameter","degree_mean","clustering","task_assortativity","efficiency","colony_size")
names(variables) <- c("Modularity","Density","Diameter","Mean degree","Clustering","Task assortativity","Network efficiency","Colony size")
desired_treatments <- c("pathogen")
#####Read qPCR data
infection_data <- NULL
for (experiment in experiments){
temp <- read.table(paste(disk_path,experiment,"original_data/qPCR/qPCR_results.txt",sep="/"),header=T,stringsAsFactors=F)
temp["experiment"] <- experiment
if (!"age"%in%names(temp)){
temp["age"] <- NA
}
temp <- temp[,order(names(temp))]
infection_data <- rbind(infection_data,temp)
rm(list="temp")
}
infection_data <- infection_data[c("experiment","colony","treatment","tag","status","measured_load_ng_per_uL","above_detection_threshold")]
infection_data <-infection_data[which(infection_data$treatment%in%desired_treatments),]
infection_data <-infection_data[which(infection_data$status=="untreated"),]
infection_data <- infection_data[which(!grepl("brood",infection_data$tag)),]
names(infection_data)[ names(infection_data)=="above_detection_threshold"]<- "contaminated"
infection_data$contaminated <- as.numeric(infection_data$contaminated)
replac_val <- min(infection_data$measured_load_ng_per_uL[infection_data$measured_load_ng_per_uL!=0],na.rm=T)/sqrt(2)
#####Read network data
network <- NULL
for (experiment in experiments){
temp <- read.table(paste(disk_path,experiment,"processed_data/network_properties/post_treatment/network_properties_observed.txt",sep="/"),header=T,stringsAsFactors = F)
temp["experiment"] <- experiment
temp <- temp[,order(names(temp))]
network <- rbind(network,temp)
}
network <- network[which(network$time_hours>=0),]
network <- network[which(network$treatment%in%desired_treatments),]
prevalence <- aggregate(contaminated~experiment+colony,FUN=mean,data=infection_data)
names(prevalence) <- c("experiment","colony","prevalence")
intensity <- aggregate(log10(measured_load_ng_per_uL+replac_val)~experiment+colony,FUN=mean,data=infection_data)
names(intensity) <- c("experiment","colony","mean_received_load")
network <- aggregate(cbind(modularity, density,diameter,degree_mean,clustering,task_assortativity,efficiency)~experiment+colony+treatment+colony_size,FUN=mean,data=network)
network <- merge(network,prevalence)
network <- merge(network,intensity)
network$contaminated <- as.numeric(network$prevalence)
network$colony_size <- as.numeric(network$colony_size )
network$mean_received_load <- as.numeric(network$mean_received_load )
####is the lmer model acceptable?
model <- lm(mean_received_load ~ modularity+ density+diameter+degree_mean+clustering+task_assortativity+efficiency+colony_size,data=network)
print("Properties' VIF:")
print(vif(model))
for (variable in c("mean_received_load","prevalence")){
network["variable"] <- network[,variable]
###determine number of components (number of dimensions with lowest cross validation error)
pls.model <- plsr(variable ~ modularity+density+diameter+degree_mean+clustering+task_assortativity+efficiency+colony_size, ncomp = 8, data = network, validation = "CV",scale=T)
cv = RMSEP(pls.model)
best.dims = which.min(cv$val[estimate = "adjCV", , ][2:length(cv$val[estimate = "adjCV", , ])])
###refit pls with desired number of components
pls.model <- plsr(variable ~ modularity+density+diameter+degree_mean+clustering+task_assortativity+efficiency+colony_size, ncomp = as.numeric(best.dims), data = network,scale=T)
###extract model coefficients
coefficients = coef(pls.model)
###sort coefficients from lowest to highest
coefficients = sort(coefficients[, 1 , 1])
###define colours: negative coefficients in black, positive coefficients in white
colorz <- rep(NA,length(coefficients))
colorz[coefficients<0] <- "black"
colorz[coefficients>0] <- "white"
###Plot coefficients
par_mar_ori <- par("mar")
par_mgp_ori <- par("mgp")
par(mar=par("mar")+c(1.5,0,0,0))
par(mgp=par("mgp")+c(0.1,0,0))
par(cex.lab=inter_cex)
barplot(coefficients,ylab="Partial least square regression coefficients",cex.axis = min_cex,cex.names = min_cex,las=2,names.arg=names(variables[ match(names(coefficients),variables)]),col=colorz)
abline(h=0)
if (variable=="mean_received_load"){
mtext(expression(bold(paste("Mean measured load (ng/", mu, "L)"))),line=1,side=3,cex=par("cex")*max_cex,font=2)
ylab <- "Mean fitted load"
xlab <- "Mean measured load"
}else{
mtext("Measured prevalence (Prop. untreated workers)",line=1,side=3,cex=par("cex")*max_cex,font=2)
ylab <- "Fitted prevalence"
xlab <- "Measured prevalence"
}
par(mar=par_mar_ori)
par(mgp=par_mgp_ori)
###Plot fit
fitted <- predict(pls.model, ncomp = best.dims, newdata = network)
measured <- network$variable
ymin <- min(floor(fitted*2)/2)
ymax <- max(ceiling(fitted*2)/2)
xmin <- min(floor(measured*2)/2)
xmax <- max(ceiling(measured*2)/2)
plot(fitted~measured,bty="l",xlim=c(xmin,xmax),ylim=c(ymin,ymax),ylab=ylab,xlab=xlab,cex.axis=min_cex,cex.lab=inter_cex,yaxt="n",xaxt="n",pch=16)
where <- axisTicks(c(par("usr")[3],par("usr")[4]),log=F)
where <- where[which(where==round(where))]
axis(2,at=where,labels=format(10^(where),scientific=T),cex.lab=inter_cex,cex.axis=min_cex,lwd=0,lwd.ticks=1)
where <- axisTicks(c(par("usr")[1],par("usr")[2]),log=F)
where <- where[which(where==round(where))]
axis(1,at=where,labels=format(10^(where),scientific=T),cex.lab=inter_cex,cex.axis=min_cex,lwd=0,lwd.ticks=1)
model <- lm(fitted~measured)
abline(a=coef(model)["(Intercept)"],b=coef(model)["measured"],xpd=F,col="red")
pval <- Anova(model)["Pr(>F)"]["measured","Pr(>F)"]
title(from_p_to_ptext(pval))
}
}
create_diff <- function(dataset,predictor,type,form_stat=NULL,collective,plot_untransformed=F,diff_type="absolute_difference"){
if (is.null(dataset)){
return(NULL)
}else{
#################################################################################
####plot
#################################################################################
befores <- dataset[dataset$time=="Before",];afters <-dataset[dataset$time=="After",]
# print(plot_untransformed)
if (!plot_untransformed){
names(befores)[names(befores)=="variable"] <- "variable_before";names(afters)[names(afters)=="variable"] <- "variable_after"
}else{
names(befores)[names(befores)=="untransformed_variable"] <- "variable_before";names(afters)[names(afters)=="untransformed_variable"] <- "variable_after"
}
if ((!all(!grepl("time:treatment:predictor",as.character(form_stat))))|(!all(!grepl("time \\* treatment \\* predictor",as.character(form_stat))))){
befores <- aggregate(na.rm=T,na.action="na.pass",variable_before~colony_size+colony+predictor+treatment+antid+time_of_day+time_of_day_bis,FUN=mean,data=befores)
afters <- aggregate(na.rm=T,na.action="na.pass",variable_after~colony_size+colony+predictor+treatment+antid+time_of_day+time_of_day_bis,FUN=mean,data=afters)
}else{
if (!grepl("age",root_path)){
if (collective|type!="individual"){
befores <- aggregate(na.rm=T,na.action="na.pass",variable_before~colony_size+colony+predictor+time_of_day+time_of_day_bis,FUN=mean,data=befores)
afters <- aggregate(na.rm=T,na.action="na.pass",variable_after~colony_size+colony+predictor+time_of_day+time_of_day_bis,FUN=mean,data=afters)
}else{
befores <- aggregate(na.rm=T,na.action="na.pass",variable_before~colony_size+colony+predictor+antid+time_of_day+time_of_day_bis,FUN=mean,data=befores)
afters <- aggregate(na.rm=T,na.action="na.pass",variable_after~colony_size+colony+predictor+antid+time_of_day+time_of_day_bis,FUN=mean,data=afters)
}
}else{
if (collective){
befores <- aggregate(na.rm=T,na.action="na.pass",variable_before~colony_size+colony+treatment+time_of_day+time_of_day_bis,FUN=mean,data=befores)
afters <- aggregate(na.rm=T,na.action="na.pass",variable_after~colony_size+colony+treatment+time_of_day+time_of_day_bis,FUN=mean,data=afters)
}else{
if(type!="individual"){
befores <- aggregate(na.rm=T,na.action="na.pass",variable_before~colony_size+colony+predictor+treatment+time_of_day+time_of_day_bis,FUN=mean,data=befores)
afters <- aggregate(na.rm=T,na.action="na.pass",variable_after~colony_size+colony+predictor+treatment+time_of_day+time_of_day_bis,FUN=mean,data=afters)
}else{
befores <- aggregate(na.rm=T,na.action="na.pass",variable_before~colony_size+colony+predictor+treatment+antid+time_of_day+time_of_day_bis,FUN=mean,data=befores)
afters <- aggregate(na.rm=T,na.action="na.pass",variable_after~colony_size+colony+predictor+treatment+antid+time_of_day+time_of_day_bis,FUN=mean,data=afters)
}
}
}
}
befores["average_before"] <- mean(befores$variable_before,na.rm=T)
diff <- merge(befores,afters,all=T)
if (diff_type=="absolute_difference"){
diff["variable"] <- diff$variable_after-diff$variable_before;diff["time"] <- "diff"
}
if (diff_type=="normalised_by_average_before"){
diff["variable"] <- diff$variable_after-(diff$variable_before-diff$average_before);diff["time"] <- "diff"
}
if (diff_type=="relative_difference"){
diff["variable"] <- diff$variable_after-diff$variable_before; diff["time"] <- "diff"
if ("treatment"%in%names(diff)){
diff_control <- diff[which(as.character(diff$treatment)=="control"),]
diff <- diff[which(!as.character(diff$treatment)=="control"),]
diff_control <- aggregate(na.rm=T,na.action="na.pass",variable~predictor,FUN=get(relative_function),data=diff_control)
names(diff_control)[names(diff_control)=="variable"] <- "mean_diff_control"
diff <- merge(diff,diff_control,all.x=T)
diff$variable <- diff$variable-diff$mean_diff_control
diff <- diff[,which(names(diff)!="mean_diff_control")]
}else{
diff_control <- diff[which(as.character(diff$predictor)=="control"),]
diff <- diff[which(!as.character(diff$predictor)=="control"),]
diff_control <- aggregate(na.rm=T,na.action="na.pass",variable~1,FUN=get(relative_function),data=diff_control)
names(diff_control)[names(diff_control)=="variable"] <- "mean_diff_control"
diff <- merge(diff,diff_control,all.x=T)
diff$variable <- diff$variable-diff$mean_diff_control
diff <- diff[,which(names(diff)!="mean_diff_control")]
}
}
if (!grepl("age",root_path)){diff$predictor <- factor(diff$predictor)}else{diff$treatment <- factor(diff$treatment)}
return(diff)
}
}
from_p_to_ptext <- function(pvalue){
if (is.na(pvalue)){
pvaluetext <- "p = NA"
}else{
if
# (pvalue< 0.00001){
# pvaluetext <- "*****"
# }else if (pvalue< 0.0001){
# pvaluetext <- "****"
# }else if
(pvalue< 0.0001){
pvaluetext <- "***"
}else if (pvalue< 0.005){
pvaluetext <- "**"
}else if (pvalue< 0.05){
pvaluetext <- "*"
}else if (pvalue< 0.1){
pvaluetext <- paste("p=",sprintf("%.3f", pvalue),sep="")
}else if (pvalue< 1){
pvaluetext <- paste("p=",sprintf("%.2f", pvalue),sep="")
}else{
pvaluetext <- "p = 1"
}#if (pvalue< 10^-6)
}
return(pvaluetext)
}
GetColorHex <- function(color){
clr <- col2rgb(color)
hex_and_col <- sprintf("#%02X%02X%02X %3d %3d %3d", clr[1],clr[2],clr[3], clr[1], clr[2], clr[3])
hex <- unlist(strsplit(hex_and_col,split=" "))[1]
return(hex)
}
get_posthoc_groups <- function(model,matrix,levels,randy,dataset){
post_hoc <- summary(glht(model,matrix),test=adjusted("BH"))
print("z value");print(post_hoc$test$tstat);print("Pr>|z|");print(post_hoc$test$pvalues);
p_values <- as.numeric(post_hoc$test$pvalues);names(p_values) <- names(post_hoc$test$coefficients)
post_hoc_levels <- names(levels)
post_hoc_mat <- matrix(NA,nrow=length(post_hoc_levels)-1,ncol=length(post_hoc_levels)-1)
rownames(post_hoc_mat) <- post_hoc_levels[2:length(post_hoc_levels)]
colnames(post_hoc_mat) <- post_hoc_levels[1:(length(post_hoc_levels)-1)]
for (i in 1:nrow(post_hoc_mat)){
for (j in 1:i){
if (!is.null(randy)){
post_hoc_mat[i,j] <- as.logical(as.numeric(p_values[paste(randy," ",colnames(post_hoc_mat)[j]," minus ",randy," ",rownames(post_hoc_mat)[i],sep="")])>0.05)
}else{
post_hoc_mat[i,j] <- as.logical(as.numeric(p_values[paste(colnames(post_hoc_mat)[j]," - ",rownames(post_hoc_mat)[i],sep="")])>0.05)
}
}
}
g <- post_hoc_mat
g <- cbind(rbind(NA, g), NA)
g <- replace(g, is.na(g), FALSE)
g <- g + t(g)
diag(g) <- 1
n <- length(post_hoc_levels)
rownames(g) <- 1:n
colnames(g) <- 1:n
#g
same <- which(g==1)
topology <- data.frame(N1=((same-1) %% n) + 1, N2=((same-1) %/% n) + 1)
topology <- topology[order(topology[[1]]),] # Get rid of loops and ensure right naming of vertices
g3 <- simplify(graph.data.frame(topology,directed = FALSE))
#get.data.frame(g3)
#plot(g3)
res <- maximal.cliques(g3)
# Reorder given the smallest level
clique_value <- NULL
means <- aggregate(variable~treatment+predictor,FUN=mean,data=dataset)
means$predictor <- names(levels)
for (i in 1:length(res)){
clique_value <- c(clique_value,mean(means[as.numeric(unlist(res[[i]])),"variable"]))
}
res <- res[order(clique_value)]
# Get group letters
lab.txt <- vector(mode="list", n)
lab <- letters[seq(res)]
for(i in seq(res)){
for(j in res[[i]]){
lab.txt[[j]] <- paste0(lab.txt[[j]], lab[i])
}
}
post_hoc_groups <- unlist(lab.txt); names(post_hoc_groups) <- levels[post_hoc_levels]
return(post_hoc_groups)
}
is.even <- function(x) {
return(x %% 2 == 0)
}
log_transf <- function(x){
if (all(x>0)){
replac_val <- 0
}else if (all(x>=0)){
replac_val <- (min(x[x!=0],na.rm=T))/sqrt(2)
}else{
replac_val_1 <- -min(x,na.rm=T)
y <- x+replac_val_1
replac_val <- replac_val_1 + (min(y[y!=0],na.rm=T))/sqrt(2)
}
return(log10(x+replac_val))
}
meta_analysis <- function(p_values,effects,std.errors){
####Get effect signs
effect_signs <- sign(effects)
########## Create a vector of one-sided p-values for each possible effect direction each side
p_values_side1 <- p_values ###one-sided p testing whether observed is lower than random
p_values_side2 <- 1-p_values ###one-sided p testing whether observed is higher than random
############# Meanp method
####Check which of the two effect direction is the one to keep
best_idx <- which(c(meanp(p_values_side1)$p,meanp(p_values_side2)$p)== min(meanp(p_values_side1)$p,meanp(p_values_side2)$p))
####Get one-sided combined p-value and test statistics
p_value <-c(meanp(p_values_side1)$p,meanp(p_values_side2)$p)[best_idx]
z <- c(meanp(p_values_side1)$z,meanp(p_values_side2)$z)[best_idx]
####convert back to 2-sided pvalue
two_sided_p_value <- p_value*2
p_values_meta_analysis <- data.frame(meta_statistic = z,one_sided_p=p_value,two_sided_p=two_sided_p_value)
return(p_values_meta_analysis)
}
mycircle <- function(coords, v=NULL, params) {
vertex.color <- params("vertex", "color")
if (length(vertex.color) != 1 && !is.null(v)) {
vertex.color <- vertex.color[v]
}
vertex.size <- 1/200 * params("vertex", "size")
if (length(vertex.size) != 1 && !is.null(v)) {
vertex.size <- vertex.size[v]
}
vertex.frame.color <- params("vertex", "frame.color")
if (length(vertex.frame.color) != 1 && !is.null(v)) {
vertex.frame.color <- vertex.frame.color[v]
}
vertex.frame.width <- params("vertex", "frame.width")
if (length(vertex.frame.width) != 1 && !is.null(v)) {
vertex.frame.width <- vertex.frame.width[v]
}
mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,
vertex.size, vertex.frame.width,
FUN=function(x, y, bg, fg, size, lwd) {
symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,
circles=size, add=TRUE, inches=FALSE)
})
}
mysquare <- function(coords, v=NULL, params) {
vertex.color <- params("vertex", "color")
if (length(vertex.color) != 1 && !is.null(v)) {
vertex.color <- vertex.color[v]
}
vertex.size <- 1/200 * params("vertex", "size")
if (length(vertex.size) != 1 && !is.null(v)) {
vertex.size <- vertex.size[v]
}
vertex.frame.color <- params("vertex", "frame.color")
if (length(vertex.frame.color) != 1 && !is.null(v)) {
vertex.frame.color <- vertex.frame.color[v]
}
vertex.frame.width <- params("vertex", "frame.width")
if (length(vertex.frame.width) != 1 && !is.null(v)) {
vertex.frame.width <- vertex.frame.width[v]
}
mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,
vertex.size, vertex.frame.width,
FUN=function(x, y, bg, fg, size, lwd) {
symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,
squares=2*size, add=TRUE, inches=FALSE)
})
}
normalize_to_range <- function(Input, Min, Max){
Range <- max(Input) - min(Input)
Input <- (Input - min(Input)) / Range
Range2 <- Max - Min
Input <- (Input * Range2) + -1
return(Input)
}
perform_barplot_analysis <- function(root_path,collective=F,dataset,lab_title,type="individual",excluded=NULL,survival=F,pool=F,violin_params=NULL,pool_plot=F,adjust_title_line=0){
par_mar_ori <- par()$mar
for (tab in c("dataset","excluded")){
table <- get(tab)
if (!is.null(table)){
if (!grepl("age",root_path)){predictor <- "treatment";table["predictor"]<-table$treatment;inter <- "time*predictor";col_vector <- treatment_colours}else{predictor <- "status";table["predictor"]<-table$status;inter <- "time";col_vector <- statuses_colours}
assign(tab,table)
}
}
original_dataset <- dataset
#######simple barplot, comparison with full last 24h period, meaning there are some times that are compared with minus 48h
dataset <- original_dataset
if(!exists("prepare_stats")){
prepare_stats <- prepare_stats_1(collective,dataset,type,predictor,inter,survival); form_stat <- prepare_stats[["form_stat"]]; p_colony <- prepare_stats[["p_colony"]];contrast.matrix <- prepare_stats[["contrast.matrix"]]
}
temp <- transform_dataset(dataset,cut=F,predictor=predictor,form_stat,excluded); dataset <- temp[["dataset"]]; form_stat <- temp[["form_stat"]];excluded <- temp[["excluded"]]; rm(list=c("temp"))
output <- prepare_stats_2(dataset,form_stat,survival=survival)
diff <- create_diff(dataset,predictor,type,collective=collective,diff_type="relative_difference")
formula_plot <- update(form_stat,.~.-(1 | colony)-(1 | time_of_day_bis)-(1|time_of_day)-(1|antid)-colony_size)
diff["predictor_plot"] <- as.character(diff$predictor)
diff$predictor <- as.character(diff$predictor)
par(mar=par_mar_ori+c(-0.8,-2+0.1+0.5,0,0.5))
plot_diff(diff,lab_title,col_vector,predictor,form_stat,p_colony,contrast.matrix,output,dataset,collective=collective,violin_params = violin_params,adjust_title_line=adjust_title_line)
par(mar=par_mar_ori)
}
perform_barplot_analysis_refined <- function(root_path,collective=NULL,dataset,lab_title,type=NULL,survival=F,excluded=NULL,pool=F,violin_params=NULL,pool_plot=F,plot_untransformed=F,aligned=F,adjust_title_line=0){
par_mar_ori <- par()$mar
col_vector <- statuses_colours
###sort predictor levels
levels <- sort(unique(dataset$predictor))
levels <- levels[order(match(levels,status_order))]
dataset$predictor <- factor(dataset$predictor,levels = levels)
levels_treatment <- unique(as.character(dataset$treatment))
levels_treatment <- levels_treatment[order(match(levels_treatment,status_order))]
dataset$treatment <- factor(dataset$treatment,levels = levels_treatment)
queens <- dataset[which(dataset$predictor=="queen"),]
if(nrow(queens)>0){
print("Queens")
if (!grepl("age",root_path)){predictory <- "treatment";queens["predictor"]<-queens$treatment;inter <- "time*predictor";col_vector <- statuses_colours}else{predictory <- "status";queens["predictor"]<-queens$status;inter <- "time";col_vector <- statuses_colours}
prepare_stats <- prepare_stats_1(collective,queens,type="individual",predictor=predictory,inter="time*predictor",survival); form_stat <- prepare_stats[["form_stat"]]; p_colony <- prepare_stats[["p_colony"]];contrast.matrix <- prepare_stats[["contrast.matrix"]]
temp <- transform_dataset(queens,cut=F,predictor=predictory,form_stat,excluded); queens <- temp[["dataset"]]; form_stat <- temp[["form_stat"]];excluded <- temp[["excluded"]]; rm(list=c("temp"))
reduced_contrast_matrix <- rbind(contrast.matrix[1,])
row.names(reduced_contrast_matrix) <- row.names(contrast.matrix)[1]
output <- prepare_stats_2(queens,form_stat,survival,T,reduced_contrast_matrix)
p_queen <- as.numeric(output$interaction_problist[["24"]])
}else{
p_queen <- NA
}
prepare_stats <- prepare_stats_3(dataset,predictor,survival); form_stat <- prepare_stats[["form_stat"]]; p_colony <- prepare_stats[["p_colony"]];contrast.matrix <- prepare_stats[["contrast.matrix"]]
output <- prepare_stats_4(dataset,form_stat,survival)
dataset["time_of_day_bis"] <- dataset$time_of_day
diff <- create_diff(dataset,predictor,type="individual",form_stat=form_stat,collective=collective,plot_untransformed=plot_untransformed,diff_type="relative_difference")
diff["time"] <- "Delta"
ylab <- lab_title
par(mar=par_mar_ori+c(-0.3,-2+0.1+0.5,0,0.5))
if (pool_plot){
diff <- aggregate(na.rm=T,na.action="na.pass",variable~predictor+colony_size+colony+treatment+antid+time,FUN=mean,data=diff)
}
plot_refined(diff,lab_title,col_vector,predictor,output,contrast.matrix,survival,dataset,p_queen,violin_params=violin_params,aligned=aligned,adjust_title_line=adjust_title_line)
par(mar=par_mar_ori)
}
perform_barplot_analysis_simple <- function(root_path,collective=NULL,dataset,lab_title,type=NULL,survival=F,excluded=NULL,pool=F,violin_params=NULL,pool_plot=F,plot_untransformed=F,aligned=F,adjust_title_line=0){
par_mar_ori <- par()$mar
col_vector <- statuses_colours
###sort predictor levels
levels <- sort(unique(dataset$predictor))
levels <- levels[order(match(levels,status_order))]
dataset$predictor <- factor(dataset$predictor,levels = levels)
levels_treatment <- unique(as.character(dataset$treatment))
levels_treatment <- levels_treatment[order(match(levels_treatment,status_order))]
dataset$treatment <- factor(dataset$treatment,levels = levels_treatment)
print(par_mar_ori)
par(mar=par_mar_ori+c(-0.3,-0.1,0,0))
if (!is.null(violin_params)){
violin_params <- as.numeric(unlist(violin_params))
##read violin param
range <- violin_params[1]
ylim_fac1 <- violin_params[2]
ylim_fac2 <- violin_params[3]
wex <- violin_params[4]
h <- violin_params[5]
}
level_names <- expand.grid(levels(dataset$treatment),levels(dataset$predictor))
level_names <- within(level_names,Var3<-paste(Var1,Var2,sep="."))$Var3
names(level_names) <- level_names
if (length(level_names)==6){
contrast.matrix <- rbind(
"1 - 2"=c(0,-1,0,0,0,0,0),
"1 - 3"=c(0,0,-1,0,0,0,0),
"1 - 4"=c(0,-1,-1,0,0,-1,0),
"1 - 5"=c(0,0,0,-1,0,0,0),
"1 - 6"=c(0,-1,0,-1,0,0,-1),
"2 - 3"=c(0,1,-1,0,0,0,0),
"2 - 4"=c(0,0,-1,0,0,-1,0),
"2 - 5"=c(0,1,0,-1,0,0,0),
"2 - 6"=c(0,0,0,-1,0,0,-1),
"3 - 4"=c(0,-1,0,0,0,-1,0),
"3 - 5"=c(0,0,1,-1,0,0,0),
"3 - 6"=c(0,-1,1,-1,0,0,-1),
"4 - 5"=c(0,1,1,-1,0,1,0),
"4 - 6"=c(0,0,1,-1,0,1,-1),
"5 - 6"=c(0,-1,0,0,0,0,-1)
)
}else if (length(level_names)==4){
contrast.matrix <- rbind(
"1 - 2" = c(0,-1,0,0,0),
"1 - 3" = c(0,0,-1,0,0),
"1 - 4" = c(0,-1,-1,0,-1),
"2 - 3" = c(0,1,-1,0,0),
"2 - 4" = c(0,0,-1,0,-1),
"3 - 4" = c(0,-1,0,0,-1)
)
}
for (i in 1:length(level_names)){
rownames(contrast.matrix) <- gsub(i,level_names[i],rownames(contrast.matrix))
}
if ("antid"%in%names(dataset)){
form_stat <- as.formula(paste("variable~", paste(c("treatment*predictor","colony_size","(1|colony)","(1|antid)"), collapse= "+")))
}else{
form_stat <- as.formula(paste("variable~", paste(c("treatment*predictor","colony_size","(1|colony)"), collapse= "+")))
}
model <- do.call(lmer, list(formula=form_stat, data=dataset))
test_norm(residuals(model))
anov <- Anova(model)
print(anov)
posthoc_groups <- get_posthoc_groups(model=model,matrix=contrast.matrix,levels=level_names,randy=NULL,dataset=dataset)
for (randy in levels_treatment){
temp <- posthoc_groups[grepl(randy,names(posthoc_groups))]; names(temp) <- gsub(paste(randy,"\\.",sep=""),"",names(temp))
assign(paste("post_hoc_",randy,sep=""),temp)
}
means <- aggregate(na.rm=T,na.action="na.pass",variable~treatment+predictor,FUN="mean",data=dataset);ses <- aggregate(na.rm=T,na.action="na.pass",variable~treatment+predictor,FUN="std.error",data=dataset);
names(means)[names(means)=="variable"] <- "mean";names(ses)[names(ses)=="variable"] <- "se";means <- merge(means,ses)
means <- means[order(match(means$treatment,levels(dataset$treatment)),match(means$predictor,levels(dataset$predictor))),]
to_plot <- unique(means[c("treatment","predictor")])
means[is.na(means$se),"se"] <- 0
ymin <- min(c(means$mean-means$se),na.rm=T);ymax<- max(c(means$mean+means$se),na.rm=T)
if (ymin>0){ymin <- 0};if (ymax<0){ymax <- 0}
if (grepl("point",plot_type)|grepl("boxplot",plot_type)|grepl("violinplot",plot_type)){
rangy <- max(dataset$variable,na.rm=T)-min(dataset$variable,na.rm=T)
ymin <- min(ymin, min(dataset$variable,na.rm=T)-0.1*rangy)
ymax <- max(ymax, max(dataset$variable,na.rm=T)+0.1*rangy)
}else{
rangy <- ymax-ymin
ymax <- ymax+0.25*rangy
}
barwidth <- 0.5; barwidth_fac_within <- 0.5; barwidth_fac_between <- 2
barspace <- rep(c(barwidth_fac_between,rep(barwidth_fac_within,(length(unique(means$predictor))-1))),length(unique(means$treatment)))
col_vector <- statuses_colours
means["alpha"] <- as.numeric(alphas[as.character(means$treatment)])
means["full_col"] <- col_vector[as.character(means$predictor)]
means[which(as.character(means$predictor)=="outdoor_ant"),"alpha"] <- means[which(as.character(means$predictor)=="outdoor_ant"),"alpha"]*10
# for (colidx in 1:nrow(means)){
# means[colidx,"final_col"] <- apply_alpha(means[colidx,"full_col"],means[colidx,"alpha"])
# }
means["final_col"] <- means$full_col
plotx <- barplot(means$mean,plot=F,width=barwidth,space=barspace,lwd=line_max)
if (grepl("bars",plot_type)){
plotx <- barplot(means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)- 0.75*(barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ 0.75*(barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab=lab_title,bty="n",col=means$final_col,xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex,width=barwidth,space=barspace,xaxt="n",lwd=line_max)
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.025,colz=means$final_col)
}else if (grepl("boxplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)- (barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ (barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab=lab_title,bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
boxplot(dataset[which(dataset$treatment==means[lvly,"treatment"]&dataset$predictor==means[lvly,"predictor"]),"variable"],at=plotx[lvly],add=T,range=1.5,notch=T,names=F,col=means[lvly,"final_col"],xlab="",ylab="",xaxt="n",xaxs="i",yaxs="i",cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n",medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,pch=16)
}
}else if (grepl("violinplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)- (barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ (barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab=lab_title,bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
if (is.na(range)){
VioPlot(na.omit(dataset[which(dataset$treatment==means[lvly,"treatment"]&dataset$predictor==means[lvly,"predictor"]),"variable"]),col=alpha(means[lvly,"final_col"],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}else{
VioPlot(na.omit(dataset[which(dataset$treatment==means[lvly,"treatment"]&dataset$predictor==means[lvly,"predictor"]),"variable"]),range=range, h=h,col=alpha(means[lvly,"final_col"],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}
}
}else{
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)- (barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ (barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab=lab_title,bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n")
####arrows
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.025,colz=means$final_col)
####points
points(plotx,means$mean,col=means$final_col,cex=1.5*max_cex,pch=16,lwd=line_min)
}
par(xpd=T)
if (all(nchar(full_statuses_names[as.character(means$predictor)])==1)){
lassy <- 1
}else{
lassy <- 2
}
labels_even <- full_statuses_names[as.character(means$predictor)][2*(1:floor(length(full_statuses_names[as.character(means$predictor)])/2))]
labels_odd <- full_statuses_names[as.character(means$predictor)][(2*(1:ceiling(length(full_statuses_names[as.character(means$predictor)])/2)))-1]
axis(1,at=plotx[2*(1:floor(length(plotx)/2))],labels=labels_even,tick=F,cex.axis=min_cex,las=lassy)
axis(1,at=plotx[(2*(1:ceiling(length(plotx)/2)))-1],labels=labels_odd,tick=F,cex.axis=min_cex,las=lassy)
par(xpd=F)
par(xpd=F)
abline(h=0)
pvalue <- anov["treatment:predictor","Pr(>Chisq)"]
for (i in 1:(-1+length(unique(means$treatment)))){
abline(v= mean(plotx[c(max(which(means$treatment==unique(means$treatment)[i])), min(which(means$treatment==unique(means$treatment)[i+1])))]),lwd=line_max)
}
par(xpd=T)
for (predy in unique(means$treatment)){
textx <- mean(plotx[which(means$treatment==predy)])
mtext(full_statuses_names[predy],side=3,line=stat_line,adj=0.5,at=textx,cex=par("cex") *inter_cex,col="black",font=1)
for (idx in 1:length(get(paste("post_hoc_",predy,sep="")))){
group <- get(paste("post_hoc_",predy,sep=""))[idx]
mtext(group,side=3,line=stat_line-0.7,at=plotx[which(means$treatment==predy&means$predictor==names(get(paste("post_hoc_",predy,sep="")))[idx])],xpd=T,cex=par("cex") *inter_cex,font=2)
}
}
par(mar=par_mar_ori)
}
plot_age_dol <- function(experiments){
for (experiment in experiments){
####first plot time outside = f(age) ######
if (grepl("age",experiment)){
######read time investment data
data <- read.table(paste(disk_path,"/",experiment,"/processed_data/time_investment/time_investment.txt",sep=""),header=T,stringsAsFactors = F)
######modify time investment data to summarise behaviour over the entire 24-hour period
data <- aggregate(na.rm=T,na.action="na.pass",cbind(outside,detected)~colony+colony_size+treatment+tag+age+status+period,FUN=sum,data=data)
data$prop_time_outside <- data$outside/data$detected
data$antid <- as.character(interaction(data$colony,data$tag))
###remove queen
data <- data[which(data$tag!=queenid),]
####list desired variables and transformations
variable_list <- c("prop_time_outside")
names(variable_list) <- c("Prop. of time outside")
predictor_list <- c("age")
names(predictor_list) <- c("Worker age (weeks)")
transf_variable_list <- c("sqrt")
transf_predictor_list <- c("none")
analysis <- list(variable_list=variable_list,
predictor_list=predictor_list,
transf_variable_list=transf_variable_list,
transf_predictor_list=transf_predictor_list,
violin_plot_param = list(c(1,-0.02,-0.02,3,0.1)))
####plot
plot_regression(data=data,time_point="before",analysis=analysis,n_cat_horiz=15,n_cat_vertic=30,pool=c(F,F),collective=T,input_color=colour_palette_age)
}
#####second plot interaction frequencies, observed vs. random ##############
data <- read.table(paste(disk_path,"/",experiment,"/processed_data/collective_behaviour/random_vs_observed/interactions.dat",sep=""),header=T,stringsAsFactors = F)
if (grepl("age",experiment)){
variable_list <- c("slope_WW_contact_duration_f_age_diff","intra_caste_over_inter_caste_WW_contact_duration","slope_QW_contact_duration_f_W_age","QNurse_over_QForager_contact_duration")
names(variable_list) <- c("Slope [Log(contact) = f(delta age)]","Within/Between-task contact","Slope [Log(contact) = f(W age)]","Q-N/Q-F contacts")
}else{
variable_list <- c("intra_caste_over_inter_caste_WW_contact_duration","QNurse_over_QForager_contact_duration")
names(variable_list) <- c("Within/Between-task contact","Q-N/Q-F contacts")
}
plot_observed_vs_random(experiments=experiment,variables=variable_list,data_input=data)
#####third plot assortativity ############
if (grepl("age",experiment)){
variable_list <- c("age_assortativity","task_assortativity")
names(variable_list) <- c("Age assortativity","Task assortativity")
}else{
variable_list <- c("task_assortativity")
names(variable_list) <- c("Task assortativity")
}
plot_observed_vs_random(experiments=experiment,variables=variable_list,pattern="network_properties",data_path="/processed_data/network_properties/random_vs_observed")
#####fourth plot the community composition ##############
par_mar_ori <- par()$mar
par(mar=par_mar_ori+c(0,0,0,0.5))
overall_results <- read.table(paste(disk_path,"/",experiment,"/processed_data/network_properties/random_vs_observed/queen_community.dat",sep=""),header=T,stringsAsFactors = F)
overall_results$treatment <- overall_results$randy; overall_results$time_hours <- -30; overall_results$time_of_day <- -6;
if (grepl("age",experiment)){
variable_list <- c("age","proportion_of_foragers")
names(variable_list) <- c("Mean W age (weeks)","Prop. foragers")
}else{
variable_list <- c("proportion_of_foragers")
names(variable_list) <- c("Prop. foragers")
}
transf_variable_list <- c("none","none")
predictor_list <- c("in_queen_comm","in_queen_comm")
names(predictor_list) <- c("Community","Community")
analysis <- list(variable_list=variable_list,
transf_variable_list=transf_variable_list,
predictor_list=predictor_list,
violin_plot_param = list(c(1,0,-0.02,0.08,0.008),c(1,-0.02,-0.02,0.08,0.008)))
plot_regression(data=overall_results,time_point="comparison",analysis,n_cat_horiz=15,n_cat_vertic=30,pool=c(F,F),prepare=T,status="all",collective=F,pool_plot=F)
par(mar=par_mar_ori)
}
####plot dividing lines and titles#######
fac <- sum(heits)
par(xpd=NA)
x_line <- grconvertX(2/3, from='ndc')
y_line1 <- grconvertY(1, from='ndc')####lower left = 0-0;top_right=1-1
y_line2 <- grconvertY(0, from='ndc')
segments(x_line,y_line1,x_line,y_line2)
####write titles #######
##########MAIN TITLES #########
x_text1 <- grconvertX(2/6, from='ndc')
x_text2 <- grconvertX(2/3+1/6, from='ndc')
y_text <- grconvertY(1- (til/fac)/2, from='ndc')
text(x_text1,y_text,labels="Age experiment (n=11)",font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
text(x_text2,y_text,labels="Main experiment (n=22)",font=2, cex=max_cex,adj=c(0.5,0.5),xpd=NA)
##########LETTERS ###############
x_text1 <- grconvertX(1/80, from='ndc')
x_text2 <- grconvertX(1/3+1/80, from='ndc')
x_text3 <- grconvertX(1/3+1/6+1/80, from='ndc')
x_text4 <- grconvertX(2/3+1/80, from='ndc')
X_text1 <- grconvertX(1/80, from='ndc')
X_text2 <- grconvertX(1/3 +1/80, from='ndc')
X_text3 <- grconvertX(2/3+1/80, from='ndc')
X_text4 <- grconvertX(2/3+1/6+1/80, from='ndc')
y_text1 <- grconvertY(1- (heits[1])/fac- 4*(heits[2]/fac)/5+1/80, from='ndc')
y_text2 <- grconvertY(1- (sum(heits[c(1:3)]))/fac - 4*(heits[4]/fac)/5+1/80, from='ndc')
y_text3 <- grconvertY(1- (sum(heits[c(1:5)]))/fac - 4*(heits[6]/fac)/5+1/80, from='ndc')
text(x_text1,y_text1,labels=panel_casse("a"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(x_text2,y_text1,labels=panel_casse("b"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(x_text3,y_text1,labels=panel_casse("c"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(x_text4,y_text1,labels=panel_casse("d"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(X_text1,y_text2,labels=panel_casse("e"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(X_text2,y_text2,labels=panel_casse("f"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(X_text3,y_text2,labels=panel_casse("g"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(X_text4,y_text2,labels=panel_casse("h"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(X_text1,y_text3,labels=panel_casse("i"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
text(X_text3,y_text3,labels=panel_casse("j"),font=2, cex=max_cex,adj=c(0.5,0),xpd=NA)
########INDIVIDUAL TITLES #########
x_text1 <- grconvertX(1/6, from='ndc')
x_text2 <- grconvertX(1/3+1/12, from='ndc')
x_text3 <- grconvertX(1/3+1/6+1/12, from='ndc')
x_text4 <- grconvertX(2/3+1/6, from='ndc')
y_text1 <- grconvertY(1- (heits[1])/fac- 4*(heits[2]/fac)/5+1/160, from='ndc')
y_text2 <- grconvertY(1- (sum(heits[c(1:3)]))/fac - 4*(heits[4]/fac)/5+1/160, from='ndc')
y_text3 <- grconvertY(1- (sum(heits[c(1:5)]))/fac - 4*(heits[6]/fac)/5+1/160, from='ndc')
text(x_text1,y_text1,labels="Age-related DoL",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text2,y_text1,labels="Community age",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text3,y_text1,labels="Community task",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text4,y_text1,labels="Community task",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
x_text1 <- grconvertX(1/6, from='ndc')
x_text2 <- grconvertX(1/3+1/6, from='ndc')
x_text3 <- grconvertX(2/3+1/12, from='ndc')
x_text4 <- grconvertX(2/3+1/6+1/12, from='ndc')
text(x_text1,y_text2,labels="W-W contacts",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text2,y_text2,labels="Q-W contacts",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text3,y_text2,labels="W-W contacts",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text4,y_text2,labels="Q-W contacts",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
x_text1 <- grconvertX(1/6, from='ndc')
x_text2 <- grconvertX(1/3+1/6, from='ndc')
x_text3 <- grconvertX(2/3+1/6, from='ndc')
text(x_text1,y_text3,labels="Age assortativity",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text2,y_text3,labels="Task assortativity",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
text(x_text3,y_text3,labels="Task assortativity",font=4, cex=inter_cex,adj=c(0.5,1),xpd=NA)
par(xpd=F)
}
plot_arrows <- function(means,plotx,plot_type,LWD,LENGTH,colz=NULL,direction="normal"){
options(warn=-1)
if (grepl("points",plot_type)){
LENGTH <- LENGTH*2
}
if (grepl("bars",plot_type)){
if (direction=="normal"){
arrows_low <- means$mean-1*as.numeric(sign(means$mean)<=0)*means$se
arrows_high <- means$mean+1*as.numeric(sign(means$mean)>=0)*means$se
}else{
arrows_low <- means$mean-1*as.numeric(sign(means$mean)>=0)*means$se
arrows_high <- means$mean+1*as.numeric(sign(means$mean)<=0)*means$se
}
code1 <- which(arrows_high==means$mean&arrows_low<means$mean)
code2 <- which(arrows_low==means$mean&arrows_high>means$mean)
code3 <- which(arrows_low==means$mean&arrows_high==means$mean)
arrows (plotx[code1],arrows_low[code1],plotx[code1],arrows_high[code1],code=1,angle=90,col="black",lwd=LWD,length=LENGTH)
arrows (plotx[code2],arrows_low[code2],plotx[code2],arrows_high[code2],code=2,angle=90,col="black",lwd=LWD,length=LENGTH)
arrows (plotx[code3],arrows_low[code3],plotx[code3],arrows_high[code3],code=3,angle=90,col="black",lwd=LWD,length=LENGTH)
}else{
arrows_low <- means$mean-means$se
arrows_high <- means$mean+means$se
arrows (plotx,arrows_low,plotx,arrows_high,code=3,angle=90,col=colz,lwd=1.5*LWD,length=1.5*LENGTH)
}
options(warn=0)
}
plot_before_vs_after <- function(root_path,data_path,analysis,status,collective,pool_plot=F,pattern="",plot_untransformed=F,boldy=F,aligned=F){
setwd(data_path)
file_list <- list.files(pattern=pattern)
data <- NULL
for (file in file_list){
data <- rbind(data,read.table(file,header=T,stringsAsFactors = F))
}
if (status=="untreated"&"status"%in%names(data)){
data <- data[which(data$status=="untreated"),]
}
if (("task_group"%in%analysis[["predictor_list"]])&(!"task_group"%in%names(data))){
task_groups <- read.table(paste(root_path,"original_data",task_group_file,sep="/"),header=T,stringsAsFactors = F)
data <- merge(data,task_groups,all.x=T,all.y=F)
}
plot_regression(data=data,time_point="comparison",analysis,n_cat_horiz=15,n_cat_vertic=30,pool=F,prepare=T,status=status,collective=collective,pool_plot=pool_plot,plot_untransformed=plot_untransformed,boldy=boldy,aligned=aligned)
}
plot_diff <- function(plot_dat,ytitle,col_vector,predictor,form_stat,p_colony,contrast.matrix,output,dataset,collective,violin_params=NULL,adjust_title_line){
if (!is.null(violin_params)){
violin_params <- as.numeric(unlist(violin_params))
##read violin param
range <- violin_params[1]
ylim_fac1 <- violin_params[2]
ylim_fac2 <- violin_params[3]
wex <- violin_params[4]
h <- violin_params[5]
}
par_mgp_ori <- par()$mgp
par_mar_ori <- par()$mar
if (!((grepl("age",root_path))&collective)){
means <- aggregate(na.rm=T,na.action="na.pass",variable~time+predictor,FUN="mean",data=plot_dat);ses <- aggregate(na.rm=T,na.action="na.pass",variable~time+predictor,FUN="std.error",data=plot_dat);
names(means)[names(means)=="variable"] <- "mean";names(ses)[names(ses)=="variable"] <- "se";means <- merge(means,ses)
means <- means[order(match(means$predictor,status_order),match(means$time,status_order)),]
to_plot <- unique(means[c("time","predictor")])
}else{
means <- aggregate(na.rm=T,na.action="na.pass",variable~time,FUN="mean",data=plot_dat);ses <- aggregate(na.rm=T,na.action="na.pass",variable~time,FUN="std.error",data=plot_dat);
names(means)[names(means)=="variable"] <- "mean";names(ses)[names(ses)=="variable"] <- "se";means <- merge(means,ses)
means <- means[order(match(means$predictor,status_order)),]
to_plot <- unique(means[c("time")])
}
if (grepl("\n",full_statuses_names[as.character(means$predictor)][1])){
lassy <- 1
mgpy <- par_mgp_ori+c(0,par_mgp_ori[1]-par_mgp_ori[2],0)
fonty <- 3
cexy <- min_cex
}else{
lassy <- 2
mgpy <- c(0.8,0.05,0)
fonty <- 1
cexy <- inter_cex
}
means[is.na(means$se),"se"] <- 0
ymin <- min(c(means$mean-means$se),na.rm=T);ymax<- max(c(means$mean+means$se),na.rm=T)
ymin_ori <- ymin; ymax_ori <- ymax
if (ymin>0){ymin <- 0};if (ymax<0){ymax <- 0}
####Now center on 0 roughly
yminmax <- max(abs(ymin),abs(ymax))
ymin <- -yminmax
ymax <- yminmax
####Now get an idea of the spacing between ticks
prospected_vals <- axisTicks(c(ymin,ymax),log=F)
####And correct ymin and yrange accordingly
interval <- diff(prospected_vals)[1]
while(min(prospected_vals)>ymin){
prospected_vals <- c(min(prospected_vals)-interval,prospected_vals)
}
ymin <- min(prospected_vals)
while(max(prospected_vals)<ymax){
prospected_vals <- c(prospected_vals,max(prospected_vals)+interval)
}
ymax <- max(prospected_vals)
if (ymax<interval){ymax <- interval}
if (ymin>-interval){ymin <- -interval}
####and now center 0 roughly
yminmax <- max(abs(ymin),abs(ymax))
ymin <- -yminmax
ymax <- yminmax
if (grepl("point",plot_type)|grepl("boxplot",plot_type)|grepl("violinplot",plot_type)){
rangy <- max(plot_dat$variable,na.rm=T)-min(plot_dat$variable,na.rm=T)
ymin <- min(ymin, min(plot_dat$variable,na.rm=T)-0.1*rangy)
ymax <- max(ymax, max(plot_dat$variable,na.rm=T)+0.1*rangy)
yminmax <- max(abs(ymin),abs(ymax))
ymin <- -yminmax
ymax <- yminmax
}
# rangy <- (ymax-ymin)+(ymax-ymin)*abs(jitter(0,factor=5))
# ymin <- ymin-0.05*rangy
# ymax <- ymax+0.05*rangy
#plotx <- unique(c(1:nrow(means))+sort(rep(1:(nrow(means)/2),2)-1))
barwidth <- 0.5
barspace <- 0.5
arrowcodes <- c(1,2,3); names(arrowcodes) <- c("-1","1","0")
if (!(collective&(grepl("age",root_path)))){
plotx <- barplot(means$mean,plot=F,width=barwidth,space=barspace)
if (grepl("bars",plot_type)){
###The bars
plotx <- barplot(means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",col=col_vector[as.character(means$predictor)],xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex,width=barwidth,space=barspace,xaxt="n",yaxt="n",xpd=F)
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.05,colz=col_vector[as.character(means$predictor)])
###The points
if (grepl("point",plot_type)){
for (lvly in 1:nrow(means)){
stripchart(plot_dat[which(plot_dat$time==means[lvly,"time"]&plot_dat$predictor==means[lvly,"predictor"]),"variable"],at=plotx[lvly],add=T,vertical=T,pch=16,col=alpha("black",0.5),method = 'jitter',ylim=c(ymin,ymax),cex=min_cex)
}
ymin_ori <- ymin
ymax_ori <- ymax
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin_ori){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax_ori){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else if (grepl("boxplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
boxplot(plot_dat[which(plot_dat$time==means[lvly,"time"]&plot_dat$predictor==means[lvly,"predictor"]),"variable"],at=plotx[lvly],add=T,range=1.5,notch=T,names=F,col=col_vector[as.character(means[lvly,"predictor"])],xlab="",ylab="",xaxt="n",xaxs="i",yaxs="i",cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n",medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,pch=16)
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else if (grepl("violinplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
if (is.na(range)){
VioPlot(na.omit(plot_dat[which(plot_dat$time==means[lvly,"time"]&plot_dat$predictor==means[lvly,"predictor"]),"variable"]),col=alpha(col_vector[as.character(means[lvly,"predictor"])],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}else{
VioPlot(na.omit(plot_dat[which(plot_dat$time==means[lvly,"time"]&plot_dat$predictor==means[lvly,"predictor"]),"variable"]),range=range, h=h,col=alpha(col_vector[as.character(means[lvly,"predictor"])],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else{
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
####arrows
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.05,colz=col_vector[as.character(means$predictor)])
####points
points(plotx,means$mean,col=col_vector[as.character(means$predictor)],cex=1.5*max_cex,pch=16,lwd=line_min)
par(xpd=F)
abline(h=0,lwd=line_max,col="black")
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin_ori){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax_ori){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,lwd=0,lwd.ticks=line_inter,cex.axis=min_cex)
abline(v=min(plotx)-barwidth,lwd=line_max,col="black")
}
# plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-1,max(plotx)+1),xlab="",ylab=ytitle,xaxt="n",bty="n",col=col_vector[as.character(means$predictor)],pch=19,xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex)
# arrows (plotx,means$mean-means$se,plotx,means$mean+means$se,code=3,angle=90,col=col_vector[as.character(means$predictor)],lwd=line_max,length=0.15)
par(xpd=T)
axis(1,at=plotx,labels=full_statuses_names[as.character(means$predictor)],tick=F,cex.axis=cexy,las=lassy,mgp=mgpy,font=fonty)
par(xpd=F)
}else{
plotx <- barplot(means$mean,plot=F,width=barwidth,space=barspace)
if (grepl("bars",plot_type)){
plotx <- barplot(means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",bty="n",col=col_vector[as.character(means$predictor)],xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex,width=barwidth,space=barspace,xaxt="n",yaxt="n",xpd=F)
###The points
if (grepl("point",plot_type)){
for (lvly in 1:nrow(means)){
stripchart(plot_dat[which(plot_dat$time==means[lvly,"time"]),"variable"],at=plotx[lvly],add=T,vertical=T,pch=16,col=alpha("black",0.5),method = 'jitter',ylim=c(ymin,ymax),cex=min_cex)
}
ymin_ori <- ymin
ymax_ori <- ymax
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin_ori){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax_ori){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.05,colz=col_vector[as.character(means$predictor)])
}else if (grepl("boxplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
boxplot(plot_dat[which(plot_dat$time==means[lvly,"time"]),"variable"],at=plotx[lvly],add=T,range=1.5,notch=T,names=F,col=col_vector[as.character(means[lvly,"predictor"])],xlab="",ylab="",xaxt="n",xaxs="i",yaxs="i",cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n",medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,pch=16)
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else if (grepl("violinplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
if (is.na(range)){
VioPlot(na.omit(plot_dat[which(plot_dat$time==means[lvly,"time"]),"variable"]),col=alpha(col_vector[as.character(means[lvly,"predictor"])],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}else{
VioPlot(na.omit(plot_dat[which(plot_dat$time==means[lvly,"time"]),"variable"]),range=range, h=h,col=alpha(col_vector[as.character(means[lvly,"predictor"])],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else{
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",bty="n",xaxs="i",yaxs="i",type="n",cex.axis=min_cex,cex.lab=inter_cex,lwd=line_min,xaxt="n",yaxt="n")
####arrows
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.05,colz=col_vector[as.character(means$predictor)])
####points
points(plotx,means$mean,col=col_vector[as.character(means$predictor)],cex=1.5*max_cex,pch=16,lwd=line_min)
par(xpd=F)
abline(h=0,lwd=line_max,col="black")
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin_ori){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax_ori){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,lwd=0,lwd.ticks=line_inter,cex.axis=min_cex)
abline(v=min(plotx)-barwidth,lwd=line_max,col="black")
}
# plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-1,max(plotx)+1),xlab="",ylab=ytitle,bty="n",col=col_vector[as.character(means$time)],pch=19,xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex)
# arrows (plotx,means$mean-means$se,plotx,means$mean+means$se,code=3,angle=90,col=col_vector[as.character(means$time)],lwd=line_max,length=0.15)
}
###Now plot ylab
if (grepl("Modularity",ytitle)|grepl("transmission",ytitle)|grepl("with brood",ytitle)){
ytil <- list(quote("Pathogen-induced changes"),quote("relative to sham-induced changes"))
par(xpd=NA)
mtext(side=2,do.call(expression,ytil),line=pars$mgp[1]*(rev(1:length(ytil))-1)+pars$mgp[1],cex=par("cex") *inter_cex,xpd=NA)
par(xpd=F)
}
pvalue <- output[["interaction_problist"]][["24"]][["1"]]
# print(pvalue)
if (pvalue>0.05){p_cex <- inter_cex;adjust_line <- 0.2;fonty <- 1}else{p_cex <- max_cex*1.1;adjust_line <- -0.1; fonty <- 2}
title(main=from_p_to_ptext(pvalue),cex.main=p_cex,font.main=fonty,line=stat_line+adjust_line,xpd=T)
par(xpd=NA)
title(main=ytitle,cex.main=inter_cex,font.main=2,line=1+adjust_title_line,xpd=NA)
par(xpd=F)
}
plot_distribution <- function(experiments,desired_treatments){
par_mar_ori <- par()$mar
par(mar=par_mar_ori+c(0,0,0,0.5))
if (experiments=="all"){
experiments <- c("age_experiment","survival_experiment","main_experiment")
}
if (experiments =="both"){
experiments <- c("age_experiment","main_experiment")
}
transf <- function(x){
return(x^(1/2))
}
rev_transf <- function(x){
return(x^2)
}
xlabel <- substitute(sqrt ( xlabely),list(xlabely="Simulated load"))
####read data
infection_data <- NULL
for (experiment in experiments){
setwd(paste(disk_path,experiment,"transmission_simulations/pre_vs_post_treatment/experimentally_exposed_seeds",sep="/"))
si_outcome <- read.table("individual_simulation_results_observed.txt",header=T,stringsAsFactors = T)
si_outcome["ant_id"] <- as.character(interaction(experiment,si_outcome$colony,si_outcome$tag))
for (time_point in c("before","after")){
si_outcome_temp <- si_outcome[which(si_outcome$period==time_point),c("colony","treatment","tag","status","antid","simulated_load","transmission_rank")]
names(si_outcome_temp)[names(si_outcome_temp)%in%c("simulated_load","transmission_rank")] <- paste(names(si_outcome_temp)[names(si_outcome_temp)%in%c("simulated_load","transmission_rank")],time_point,sep="_")
assign(paste("si_outcome_",time_point,sep=""),si_outcome_temp)
}
si_outcome <- merge(si_outcome_before,si_outcome_after)
infection_data <- rbind(infection_data,data.frame(experiment=experiment,si_outcome,stringsAsFactors = F))
}
####fill in missing untreated and queen info
infection_data[which(infection_data$tag==queenid),"tag"] <- "queen"
###modify data
infection_data[,"colony"] <- as.character(interaction(infection_data$experiment,infection_data$colony))
####make new datasets for further analyses######
infection_data$status <- as.character(infection_data$status)
infection_data <- infection_data[infection_data$status!="treated",]###contains queens and untreated workers
infection_data <- infection_data[infection_data$tag!="queen",]###contains untreated workers
#####1. Make bins
xmin <- min(c(transf(infection_data$simulated_load_before),transf(infection_data$simulated_load_after)),na.rm=T)
xmin_bis <- min(
c(transf(infection_data$simulated_load_before),transf(infection_data$simulated_load_after))
[
c(transf(infection_data$simulated_load_before),transf(infection_data$simulated_load_after))
>0
]
,
na.rm=T
)
xmax <- max(c(transf(infection_data$simulated_load_before),transf(infection_data$simulated_load_after)),na.rm=T)
xmin <- min(c(floor((xmin)*100)/100))
xmax <- ceiling((xmax)*100)/100
breaks <- seq(from=xmin,to=xmax,length.out=23)
bw <- 0.09
xmax <- ceiling((xmax)*10)/10
###2. plot histograms plus densities
infection_data <- infection_data[which(infection_data$treatment%in%desired_treatments),]
afters_dens <- density(transf(infection_data$simulated_load_after),from=xmin,to=xmax,n=500,na.rm=T,bw=bw)
befores_dens <- density(transf(infection_data$simulated_load_before),from=xmin,to=xmax,n=500,na.rm=T,bw=bw)
percolony_density <- NULL
for (colony in sort(unique(infection_data$colony[!is.na(infection_data$colony)]))){
if (colony!="age_experiment.colony021"){
subsett <- infection_data[which(infection_data$colony==colony),]
afters <- density(transf(subsett$simulated_load_after),from=xmin,to=xmax,n=500,na.rm=T,bw=bw)
afters$y <- afters$y/sum(afters$y)
befores <- density(transf(subsett$simulated_load_before),from=xmin,to=xmax,n=500,na.rm=T,bw=bw)
befores$y <- befores$y/sum(befores$y)
percolony_density <- rbind(percolony_density,data.frame(colony=colony,xcoor=afters$x,density_after=afters$y,density_before=befores$y,density_diff=afters$y-befores$y))
}
}
####plot actual distributions
forplot <- data.frame(as.matrix(aggregate(cbind(density_after,density_before,density_diff)~xcoor,function(x)cbind(mean(x),std.error(x)),data=percolony_density)))
names(forplot) <- c("x","mean_after","std.error_after","mean_before","std.error_before","mean","std.error")
forplot["lower_y"] <- forplot$mean-forplot$std.error
forplot["top_y"] <- forplot$mean+forplot$std.error
forplot <- forplot[order(forplot$x),]
xshade <- c(forplot$x,rev(forplot$x))
yshade <- c(forplot$lower_y,rev(forplot$top_y))
##get ylims for plots ####
######first get an idea of how the density plots will be distributed
ymin_dens <- 2*min(forplot$lower_y)
ymax_dens <- max(c(forplot$mean_after,forplot$mean_before))+0.1*(max(c(forplot$mean_after,forplot$mean_before))-min(forplot$mean))
neg <- abs(ymin_dens)/abs(ymax_dens)
######second get an idea of how the histogram will be distributed
afters <- hist(transf(infection_data$simulated_load_after),breaks=breaks,plot=F)
befores <- hist(transf(infection_data$simulated_load_before),breaks=breaks,plot=F)
ymax <- max(c(afters$density,befores$density))+0.1*max(c(afters$density,befores$density))
#####...and deduce ymin
ymin <- -neg*ymax
###then plot histograms; in frequency
befores <- hist(transf(infection_data$simulated_load_before),breaks=breaks,plot=T,col=alpha("blue",0.4),prob=T,ylim=c(ymin,ymax),xlim=c(min(0,xmin),xmax),xaxt="n",yaxt="n",xaxs="i",yaxs="i",main="",bty="l",cex.axis=min_cex,cex.lab=inter_cex,xlab="",lwd=line_min/10,border="black")
afters <- hist(transf(infection_data$simulated_load_after),breaks=breaks,col=alpha("red",0.3),add=T,plot=T,prob=T,lwd=line_min/10,border="black")
prospected_ats <- axisTicks(c(min(0,xmin),xmax),log=F)
prospected_ats <- c(prospected_ats,prospected_ats[length(prospected_ats)]+prospected_ats[length(prospected_ats)]-prospected_ats[-1+length(prospected_ats)])
axis(1,at=prospected_ats,cex.axis=min_cex,cex.lab=inter_cex)
axis(2,cex.axis=min_cex,cex.lab=inter_cex)
title(xlab=xlabel,cex.axis=min_cex,cex.lab=inter_cex,mgp=par()$mgp+c(0.2,0,0))
###then add densities; with new axes
par(new=T)
#####get new ymin, ymax
plot(forplot$x,forplot$mean, type="n", axes=F, xlab=NA, ylab=NA, cex=1.2,col=statuses_colours[desired_treatments],ylim=c(ymin_dens,ymax_dens),xaxs="i",yaxs="i",main="",bty="l",cex.axis=min_cex,cex.lab=inter_cex,xlim=c(min(0,xmin),xmax))
polygon(xshade,yshade, border = alpha("yellow",0),col=alpha("yellow",0.6))
lines(forplot$x,forplot$mean,lwd=line_max,col="black")
####write legend
legend(x=par("usr")[2]+0.05*(par("usr")[2]-par("usr")[1]),y=par("usr")[4]-0.025*(par("usr")[4]-par("usr")[3]),xjust=1,yjust=1,legend=c("Pre-treatment","Post-treatment","Difference"),pt.bg=c(alpha("blue",0.4),alpha("red",0.3),alpha("yellow",0.6)),col=c("black","black",alpha("yellow",0)),bty='n',pch=22,lty=0,lwd=0,pt.lwd=1,pt.cex=1.5,text.col="white",cex=min_cex)
legend(x=par("usr")[2]+0.05*(par("usr")[2]-par("usr")[1]),y=par("usr")[4]-0.025*(par("usr")[4]-par("usr")[3]),xjust=1,yjust=1,legend=c("Pre-treatment","Post-treatment","Difference"),col=c(alpha("blue",0),alpha("red",0),"black"),bty='n',lty=c(0,0,1),lwd=c(0,0,1),cex=min_cex)
print("KS-test:")
ks_test <- ks.test(transf(infection_data$simulated_load_after),transf(infection_data$simulated_load_before))
print(ks_test)
p_value <- ks_test$p.value
where_to_print_stat <- median(c(transf(infection_data$simulated_load_after),transf(infection_data$simulated_load_before)))
par(xpd=T)
mtext(full_statuses_names[desired_treatments],side=3,line=stat_line,adj=0.5,cex=par("cex") *inter_cex,font=2)
mtext(from_p_to_ptext(p_value),side=3,line=stat_line-1,adj=0.5,cex=par("cex") *max_cex,font=2,at=where_to_print_stat)
# print("Thresholds at which after becomes lower than before")
forplot["positive"] <- forplot$mean>=0
change <- min(which(diff(forplot$positive)==-1))
threshold1 <- rev_transf(forplot[change,"x"])
threshold2 <- rev_transf(forplot[change+1,"x"])
if(!exists("threshold")){threshold <-round(((threshold1+threshold2)/2)*10000)/10000}
par(xpd=F)
lines(x=c(transf(threshold),transf(threshold)),y=c(0,ymin_dens),col="springgreen3",lty=1,lwd=2*line_max)
###Now write down "high level", "low_level"
arrows(x0=transf(threshold),y0=1.7*min(forplot$lower_y),x1=par("usr")[2],y1=1.7*min(forplot$lower_y),col="springgreen4",code=3,length=0.025)
text(x=mean(c(transf(threshold),par("usr")[2])),y=1.5*min(forplot$lower_y),labels="high load",adj=c(0.5,0),cex=min_cex,col="springgreen4",font=3)
xmin <-min(c(transf(infection_data$simulated_load_before),transf(infection_data$simulated_load_after)),na.rm=T)
arrows(x1=transf(threshold),y0=1.7*min(forplot$lower_y),x0=xmin_bis,y1=1.7*min(forplot$lower_y),col="springgreen2",code=3,length=0.025)
text(x=mean(c(transf(threshold),xmin)),y=1.5*min(forplot$lower_y),labels="low load",adj=c(0.5,0),cex=min_cex,col="springgreen2",font=3)
par(mar=par_mar_ori)
}
plot_observed_vs_random <- function(experiments,variables,data_input=NULL,data_path,pattern){
if (is.null(data_input)) {
###read-in data###
data <- NULL
for (experiment in experiments){
print(experiment)
### data files
setwd(paste(disk_path,experiment,data_path,sep="/"))
file_list <- list.files(pattern=pattern)
temp <- NULL
for (file in file_list){
dat <- read.table(file,header=T,stringsAsFactors=F)
dat <- dat[,which(names(dat)%in%c("randy","colony","treatment","period","time_hours","time_of_day",variables))]
temp <- rbind(temp,dat)
rm(list=c("dat"))
}
temp <- temp[,order(names(temp))]
temp <- data.frame(experiment=experiment,temp,stringsAsFactors = F)
if (!is.null(data)){
if (!all(names(data)%in%names(temp))){
temp[names(data)[which(!names(data)%in%names(temp))]] <- NA
temp <- temp[,names(data)]
}
}
data <- rbind(data,temp)
rm(list=c("temp"))
}
####modify period values to be simple and match what scatterplot function expects
data["colony"] <- as.character(interaction(data$experiment,data$colony))
}else{data <- data_input}
for (variable in variables){
data["variable"] <- data[,variable]
data[which(!is.finite(data$variable)),"variable"] <- NA
#####get random and observed mean
randys <- aggregate(variable~colony+treatment+randy,FUN=mean,data=data[which(data$randy!="observed"),]);
randys <- as.data.frame(as.matrix(randys));randys$variable <- as.numeric(as.character(randys$variable))
#####then get mean, median and standard error
randys <- aggregate(variable~colony+treatment,function(x)cbind(mean(x),median(x),std.error(x),length(x)),data=randys);
randys <- as.data.frame(as.matrix(randys))
names(randys)[names(randys)=="variable.1"] <- "random_mean";names(randys)[names(randys)=="variable.2"] <- "random_median";names(randys)[names(randys)=="variable.3"] <- "random_std.error";names(randys)[names(randys)=="variable.4"] <- "random_nb"
###do the same for observed
observeds <- aggregate(variable~colony+treatment+randy,FUN=mean,data=data[which(data$randy=="observed"),])
observeds <- as.data.frame(as.matrix(observeds));observeds$variable <- as.numeric(as.character(observeds$variable))
observeds <- aggregate(variable~colony+treatment,function(x)cbind(mean(x),median(x),length(x)),data=observeds);
observeds <- as.data.frame(as.matrix(observeds))
names(observeds)[names(observeds)=="variable.1"] <- "observed_mean";names(observeds)[names(observeds)=="variable.2"] <- "observed_median";names(observeds)[names(observeds)=="variable.3"] <- "observed_nb"
randys <- merge(randys,observeds);
randys$colony <- as.character(randys$colony)
randys$observed_mean <- as.numeric(as.character(randys$observed_mean))
randys$random_mean <- as.numeric(as.character( randys$random_mean))
randys$observed_median <- as.numeric(as.character(randys$observed_median))
randys$random_median <- as.numeric(as.character( randys$random_median))
randys$random_std.error <- as.numeric(as.character( randys$random_std.error))
randys["deviation"] <- randys$observed_median-randys$random_median
randys["relative_deviation"] <- (randys$observed_median-randys$random_median)/abs(randys$random_median)
randys["p_value"] <- NA
randys["variable"] <- variable
randys["n_observed"] <- NA
randys["n_random"] <- NA
for (coli in unique(randys$colony)){
random <- aggregate(variable~colony+treatment+randy,FUN=mean,data=data[which(data$colony==coli&data$randy!="observed"),])[,"variable"];
observed <- aggregate(variable~colony+treatment+randy,FUN=mean,data=data[which(data$colony==coli&data$randy=="observed"),])[,"variable"];
#####Get one-sided p: proportion of random values that are greater than observed values. Will be 0 if all values are lower and 1 if all values are greater
one_sided_p <- length(which(random>observed))/length(random)
randys[which(randys$colony==coli),"p_value"] <- one_sided_p
randys[which(randys$colony==coli),"one_sided_p_value_obs_lower_than_rand"] <- 1-one_sided_p
randys[which(randys$colony==coli),"one_sided_p_value_obs_greater_than_rand"] <- one_sided_p
randys[which(randys$colony==coli),"effect_sign"] <- sign( randys[which(randys$colony==coli),"deviation"])
randys[which(randys$colony==coli),"n_observed"] <- length(observed)
randys[which(randys$colony==coli),"n_random"] <- length(random)
}
randys_toprint <- data.frame(variable=variable,randys[c("colony","treatment","deviation","relative_deviation","effect_sign","one_sided_p_value_obs_lower_than_rand","one_sided_p_value_obs_greater_than_rand")],stringsAsFactors = F)
randys_toprint[which(randys_toprint$effect_sign==1),"effect_signs"] <- "+"
randys_toprint[which(randys_toprint$effect_sign==-1),"effect_signs"] <- "-"
randys_toprint[which(randys_toprint$effect_sign==0),"effect_signs"] <- "0"
#####now the stats: meta-analysis
p_values_meta_analysis <- meta_analysis(p_values = randys[,"p_value"],effects = randys[,"relative_deviation"],std.errors = randys[,"random_std.error"])
#####modify randys for plot
forplot <- data.frame(network="random",randys[c("colony","treatment","random_median")],stringsAsFactors=F); names(forplot)[grepl("median",names(forplot))] <- "median"
forplot2 <- data.frame(network="observed",randys[c("colony","treatment","observed_median")],stringsAsFactors=F); names(forplot2)[grepl("median",names(forplot2))] <- "median"
forplot <- aggregate(median~network+colony+treatment,FUN=mean,data=forplot)
forplot2 <- aggregate(median~network+colony+treatment,FUN=mean,data=forplot2)
forplot <- rbind(forplot,forplot2)
forplot$network <- factor(forplot$network,levels = c("random","observed"))
###get colony ordering from observed
col_medians <- aggregate(median~colony,FUN=median,data=forplot2)
col_medians <- col_medians [order(col_medians$median),]
col_list <- col_medians$colony
colour_pal <- colorRampPalette(brewer.pal(11, "Spectral"))(length(col_list))
par(bty="n",xaxt = "n")
for (coli in rev(col_list)){
if (coli==col_list[length(col_list)]){
addy <- F
}else{
addy <- T
}
titl <- names(variables[variables==variable])
if (grepl("delta",titl)){
titl1 <- unlist(strsplit(titl,"delta"))[1]
titl2 <- unlist(strsplit(titl,"delta"))[2]
titl <- substitute(paste(labo,Delta,laby),list(labo=titl1,laby=titl2))
}
stripchart(median ~ network, data = forplot[forplot$colony==coli,],vertical = TRUE,pch=16,col=alpha(colour_pal[which(coli==col_list)],1),method = 'jitter', jitter = 0.3,ylim=c(min(c(0,forplot$median)),max(c(forplot$median))), main = "",ylab=titl,add=addy,bty="l",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex)
}
###make boxplot
forplot3 <- data.frame(as.matrix(aggregate(median~network,function(x)cbind(mean(x),std.error(x)),data=forplot)),stringsAsFactors = F)
names(forplot3) <- c("network","mean","se")
boxplot(median ~ network, data = forplot,
outline = FALSE, notch=F, ## avoid double-plotting outliers, if any
main = "",yaxt="n",add=T,col=alpha("white",0),medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,bty="l")
par(xpd=T)
###add stat
pval <- p_values_meta_analysis$two_sided_p
one_sidedpval <- p_values_meta_analysis$one_sided_p
statistic <- p_values_meta_analysis$meta_statistic
print(paste(variable,": z=",statistic,"; one-sided p =",one_sidedpval,"; two-sided p =",pval))
if (pval>0.05){p_cex <- inter_cex;adjust_line <- 0.3;fonty <- 1}else{p_cex <- max_cex*1.1;adjust_line <- 0; fonty <- 2}
title(main=from_p_to_ptext(pval),cex.main=p_cex,font.main=fonty,line=stat_line+adjust_line,xpd=T)
par(xpd=F)
par(xaxt = "s")
axis(side=1,at=c(1,2),labels=c(full_statuses_names["random"],""),tick=F,lty=0,cex.axis=inter_cex)
axis(side=1,at=c(1,2),labels=c("",full_statuses_names["observed"]),tick=F,lty=0,cex.axis=inter_cex)
}
}
plot_network <- function(case,which_to_draw,colours="task_group"){
####Define two new vertex shapes (circle and square) which will allow to control the width of the vertex frame
add.vertex.shape("fcircle", clip=igraph.shape.noclip,
plot=mycircle, parameters=list(vertex.frame.color=1,
vertex.frame.width=1))
add.vertex.shape("fsquare", clip=igraph.shape.noclip,
plot=mysquare, parameters=list(vertex.frame.color=1,
vertex.frame.width=1))
##read qPCR data
qPCR <- read.table(paste(root_path,"original_data/qPCR/qPCR_results.txt",sep="/"),header=T,stringsAsFactors = F)
##read simulation data
si_outcome <- read.table(paste(root_path,"/transmission_simulations/pre_vs_post_treatment/experimentally_exposed_seeds/individual_simulation_results_observed.txt",sep=""),header=T,stringsAsFactors = F)
##read task_group data
task_groups <- read.table(paste(root_path,"original_data",task_group_file,sep="/"),header=T,stringsAsFactors = F)
##read experimentally treated list
treated <- read.table(paste(root_path,"original_data","treated_worker_list.txt",sep="/"),header=T,stringsAsFactors = F)
setwd(paste(root_path,"example_networks_for_figures",case,sep="/"))
networks <- list.files()
for (current in which_to_draw){
network_file <- networks[which( (grepl(unlist(strsplit(current,split="_"))[1],networks)) & (grepl(unlist(strsplit(current,split="_"))[2],networks)) )]
interactions <- read.table(network_file,header=T,stringsAsFactors = F)
if (current=="PreTreatment_random"){
network_title <- "Random network"
}else if (current=="PreTreatment_observed"&"PostTreatment_observed"%in%which_to_draw){
network_title <- "Pre-treatment network"
}else if (current=="PreTreatment_observed"&"PreTreatment_random"%in%which_to_draw){
network_title <- "Observed network"
}else if (current=="PostTreatment_observed"){
network_title <- "Post-treatment network"
}
###Make graph object
actors <- data.frame(name=as.character(unique(c(interactions$Tag1,interactions$Tag2))))
net <- graph.data.frame(interactions[c("Tag1","Tag2")],directed=F,vertices=actors)
E(net)$weight <- interactions[,"duration_frames"]
net <- simplify(net,remove.multiple=TRUE,remove.loop=TRUE,edge.attr.comb="sum")
###Drawing network
WEIGHTS <- E(net)$weight
########first change the weight values so it ranges from mini to 0, then define edge widths and colors
mini <- -100
normal <- (WEIGHTS-min(WEIGHTS)) / max(WEIGHTS-min(WEIGHTS)) ####ranging from 0 to 1
normal <- (normal-max(normal))*(mini/min(normal-max(normal)))
normal <- exp(normal/(-mini/(1/50)))
normal <- (normal-min(normal)) / max(normal-min(normal))
E(net)$ori_width <- 2*normal
E(net)$width <- 0.5*line_min+(3*line_max-0.5*line_min)*((E(net)$ori_width-min(E(net)$ori_width))/max(E(net)$ori_width-min(E(net)$ori_width)))
E(net)$color <- grey( 8/10*( 1-normal ))
########define node size, shapes, and labels
V(net)$size <- 10
V(net)$shape <- "fcircle"
V(net)$label=""
## Define layout
E(net)$Scaled_Contact_Weights <- sqrt(E(net)$weight) / max(sqrt(E(net)$weight))
net2 <- net ## get layout from edge=weight thresholded graph
Edge_Cutoff_P <- quantile(E(net2)$Scaled_Contact_Weights, probs=0.25)
net2 <- igraph::delete.edges(net2, E(net2) [E(net2)$Scaled_Contact_Weights < Edge_Cutoff_P ] ) ## delete edges below a threshold - leaves only the strongest edges indicative of high spatial correlatoin
# spring-embeded layout using contact weights
lay <- data.frame(tag=V(net)$name, layout_with_fr (net2, weights=E(net2)$Scaled_Contact_Weights, niter=50000)) ; colnames(lay )[2:3] <- c("x","y")
## contract outlier nodes
PLOT_CONTRACTIONS <- F
N_CONTRACTIONS <- 4
OUTLIER_QUANTILE <- 0.9
if (PLOT_CONTRACTIONS==TRUE) {par(mfrow=c(2,N_CONTRACTIONS/2))}
if (N_CONTRACTIONS>0)
{
for (IT in 1:N_CONTRACTIONS)
{
## centre so the CoG of all the nodes is at 0,0
lay$x <- lay$x - mean(lay$x)
lay$y <- lay$y - mean(lay$y)
## get nearest neighbour distance for each node & define those above a threshold as outliers
lay$nnd <- rowMeans(nndist(X=lay$x, Y=lay$y, k=1:2))
Outliers <- which(lay$nnd > quantile(lay$nnd,probs=OUTLIER_QUANTILE))
lay$Outliers <- 0 ; lay$Outliers [Outliers] <- 1
CoG <- colMeans(lay[lay$Outliers==0,c("x","y")])
lay$x_zero <- lay$x - CoG[1]
lay$y_zero <- lay$y - CoG[2]
lay$corrections <- 1
lay$corrections[lay$Outliers==1] <- lay$nnd[lay$Outliers==1]
lay$corrections[lay$Outliers==1] <- lay$corrections[lay$Outliers==1] / max(lay$nnd[lay$Outliers==1])
lay$corrections[lay$Outliers==1] <- 1 - lay$corrections[lay$Outliers==1]
lay$corrections[lay$Outliers==1] <- lay$corrections[lay$Outliers==1] + mean(sqrt(((lay$x-CoG["x"])^2+((lay$x-CoG["y"])^2))))
lay$corrections[lay$Outliers==1] <- lay$corrections[lay$Outliers==1] / max(lay$corrections[lay$Outliers==1])
lay$X <- NA; lay$Y <- NA
lay[c("X","Y")] <- lay$corrections * lay [,c("x","y")]
## plot each contraction
if (PLOT_CONTRACTIONS==TRUE)
{
plot(lay[,c("X","Y")], pch=lay[,"Outliers"]+1) ; abline(v=0, lty=2) ; abline(h=0, lty=2)
points(CoG[1], CoG[2], pch=21, bg=2, cex=2)
segments(x0 = lay$x[lay$Outliers==1], y0 = lay$y[lay$Outliers==1], x1 = lay$X[lay$Outliers==1], y1 = lay$Y[lay$Outliers==1], col=2)
}
## update the starting coords
lay[c("x","y")] <- lay[c("X","Y")]
}
}
## normalize the corrected x,y coords to -1, 1
colnames(lay ) [2:3]<- c("X","Y")
lay[,c("X","Y")] <- apply(lay[,c("X","Y")], 2, normalize_to_range, Min=-1, Max=1)
lay <- as.matrix(lay[match(V(net)$name,lay$tag),c("X","Y")])
rownames(lay) <- V(net)$name
##rotate network to facilitate comparisons, using two reference ants, 665 and 329
ref_vec <- c(1,-1)
obs_vec <- c(lay["329","X"]-lay["665","X"],lay["329","Y"]-lay["665","Y"])
theta <- atan2(obs_vec[2],obs_vec[1]) - atan2(ref_vec[2],ref_vec[1])
####then get rotation center
center <- c(X=mean(lay["665","X"]),Y=mean(lay["665","Y"]))
####Now do the rotation. First: make "center" the origin
lay[,"X"] <- lay[,"X"]-center["X"]
lay[,"Y"] <- lay[,"Y"]-center["Y"]
####Second make new lay vector and calculate new coordinates
lay_bis <- lay
lay_bis[,"X"] <- lay[,"X"]*cos(-theta)-lay[,"Y"]*sin(-theta)
lay_bis[,"Y"] <- lay[,"Y"]*cos(-theta)+lay[,"X"]*sin(-theta)
###Third retranslate
lay[,"X"] <- lay[,"X"]+center["X"]
lay[,"Y"] <- lay[,"Y"]+center["Y"]
lay_bis[,"X"] <- lay_bis[,"X"]+center["X"]
lay_bis[,"Y"] <- lay_bis[,"Y"]+center["Y"]
lay_bis[,c("X","Y")] <- apply(lay_bis[,c("X","Y")], 2, normalize_to_range, Min=-1, Max=1)
###define colours
colony <- unique(interactions$colony)
colony_number <- as.numeric(gsub("colony","",colony))
colony_treated <- treated[which(treated$colony==colony_number),"tag"]
for (colour in colours){
if (colour=="task_group"){
colony_task_groups <- task_groups[which(task_groups$colony==colony),]
colony_task_groups["color"] <- statuses_colours[colony_task_groups[,"task_group"]]
V(net)$color <- colony_task_groups[match(V(net)$name,colony_task_groups$tag),"color"]
if (length(colours)>1){
network_title <- "Task group"
}
}else if (colour=="measured_load"){
qPCR <- qPCR[which(qPCR$colony==colony),c("tag","status","measured_load_ng_per_uL")]
qPCR[qPCR$tag=="queen","tag"] <- queenid
qPCR <- qPCR[which(!is.na(as.numeric(qPCR$tag))),]
if (0%in%qPCR$measured_load_ng_per_uL){
replace_val <- min(qPCR$measured_load_ng_per_uL[qPCR$measured_load_ng_per_uL!=0])/sqrt(2)
}else{
replace_val <- 0
}
qPCR$log_measured <- log10(qPCR$measured_load_ng_per_uL+replace_val)
mini_val <- min(qPCR[,"log_measured"])
maxi_val <- max(qPCR[,"log_measured"])
qPCR$log_measured_normalised <- 0 + ((qPCR$log_measured-mini_val)/(maxi_val-mini_val))*(1-0)
palette <- rev(brewer.pal(9,"YlGnBu"))
colour_palette <- colorRampPalette(palette)(1001)
col_threshold <- "red"
colour_range <- c (mini_val,maxi_val)
qPCR[,"colour"] <- colour_palette[1+ceiling(qPCR[,"log_measured_normalised"]*1000)]
V(net)$color <- qPCR[match(V(net)$name,qPCR$tag),"colour"]
high_loadzes <- qPCR[which(qPCR[,"measured_load_ng_per_uL"]>translated_high_threshold),"tag"]
V(net)$shape <- "fcircle"
V(net)$shape[which(V(net)$name%in%high_loadzes)] <- "fsquare"
network_title <- "qPCR-measured pathogen load"
}else if (colour=="simulated_load"){
si_outcome <- si_outcome[which(si_outcome$colony==colony&si_outcome$period=="after"),c("tag","simulated_load")]
high_loadzes <- si_outcome[which(si_outcome$simulated_load>high_threshold),"tag"]
V(net)$shape <- "fcircle"
V(net)$shape[which(V(net)$name%in%high_loadzes)] <- "fsquare"
si_outcome$log_load <- log10(si_outcome$simulated_load)
mini_val <- min(si_outcome[,"log_load"])
maxi_val <- max(si_outcome[,"log_load"])
si_outcome$log_load_normalised <- 0 + ((si_outcome$log_load-mini_val)/(maxi_val-mini_val))*(1-0)
colour_palette <- inferno(1001, alpha = 1, begin = 0, end = 1, direction = 1)
colour_range <- c (mini_val,maxi_val)
si_outcome[,"colour"] <- colour_palette[1+ceiling(si_outcome[,"log_load_normalised"]*1000)]
V(net)$color <- si_outcome[match(V(net)$name,si_outcome$tag),"colour"]
network_title <- "Simulated pathogen load"
}
###Finally, plot net
plot_net <- net
###To improve visibility, delete thinnest edges before plotting
plot_net <- igraph::delete.edges(plot_net, E(plot_net) [(E(net)$ori_width/2)<0.02 ] )
par_mar_ori <- par()$mar
if("measured_load" %in% colours){
par(mar=c(1.2,0,0.2,0))
}else{
par(mar=c(0.2,0,1.2,0))
}
plot(plot_net, layout=lay_bis, edge.arrow.size=0.5, main="",rescale=F, vertex.frame.color="black",vertex.frame.width=line_min )#,"nodes")
points(lay_bis[which(V(plot_net)$name%in%colony_treated),"X"],lay_bis[which(V(plot_net)$name%in%colony_treated),"Y"],pch=16,col="black",cex=0.7)
if("measured_load" %in% colours){
title(sub=network_title,font.sub=2,cex.sub=inter_cex,line=0.2,xpd=NA)
}else{
title(main=network_title,font.main=2,cex.main=inter_cex,line=0.2,xpd=NA)
}
if (grepl("load",colour)){
par(mar=c(2,1,1,1))
par(mgp=c(1,0.1,0))
if (colour=="measured_load"){
image(y=1, x=1:length(colour_palette), matrix(1:length(colour_palette), ncol =1),cex.lab=min_cex, col= colour_palette, xlab="", ylab="", xaxt="n", yaxt="n", main="",font=2); box(lwd=line_inter)
title(main=expression(paste("(ng/", mu, "L)")),cex.main=inter_cex)
}else{
image(y=1, x=1:length(colour_palette), matrix(1:length(colour_palette), ncol =1),cex.lab=min_cex, col= colour_palette, xlab="", ylab="", xaxt="n", yaxt="n", main="",font=2); box(lwd=line_inter)
title(main="(Proportion of exposure dose)",cex.main=inter_cex,font.main=1)
}
colour_vals <- mini_val+c(0:1000)*(maxi_val-mini_val)/1000
ats <- ceiling(colour_range[1]):floor(colour_range[2])
labs <- format(10^(ats),scientific=T)
for (at in 1:length(ats)){
ats[at] <- closest_match(ats[at] ,colour_vals)
}
axis(side = 1, at=ats, labels = labs, las=1, cex.axis=min_cex,lend="square",tcl=-0.2,lwd=line_inter) ## ensure to back-transform the labels!!
if (colour=="simulated_load"){
thresh <- closest_match(log10(high_threshold) ,colour_vals)
par(xpd=F)
abline(v=thresh,col="white",lwd=1.5)
abline(v=thresh,col="springgreen2",lwd=1)
}else{
thresh <- closest_match(log10(translated_high_threshold) ,colour_vals)
par(xpd=F)
abline(v=thresh,col="white",lwd=1.5)
abline(v=thresh,col=col_threshold,lwd=1)
}
}
par(mar=par_mar_ori)
}
}
}
plot_qpcr <- function(experiments){
plot1 <- function(data,experiment,ylim=ylim){
par_mari <- par("mar")
par(mar=par_mari-c(0,0.35,0,par_mari[4]))
###Plot (load)=f(caste)
data["variable"] <- data$measured_load_ng_per_uL;data["predictor"] <- data$task_group
replac_val <- min(data$variable[data$variable!=0],na.rm=T)/sqrt(2)
####transform
data <- aggregate(na.action=na.pass,na.rm=T,log10(variable+replac_val)~predictor+colony,FUN=mean,data=data)
names(data)[grepl("variable",names(data))] <-"variable"
means <- aggregate(na.rm=T,na.action="na.pass",variable~predictor,FUN="mean",data=data);ses <- aggregate(na.rm=T,na.action="na.pass",variable~predictor,FUN="std.error",data=data);
names(means)[grepl("variable",names(means))] <- "mean";names(ses)[grepl("variable",names(ses))] <- "se";means <- merge(means,ses)
means <- means[order(match(means$predictor,status_order)),]
means[is.na(means$se),"se"] <- 0
if (is.null(ylim)){
ymin <- min(c(means$mean-means$se),na.rm=T);ymax<- max(c(means$mean+means$se),na.rm=T)
ymin <- floor(ymin)
ymax <- ceiling(ymax)
rangy <- ymax-ymin
ymax <- ymax+0.1*rangy
yrange <- c(ymin,ymax)
}else{
ymin <- ylim[1]
ymax <- ylim[2]
yrange <- ymax-ymin
yrange <- c(ymin-0.04*yrange,ymax+0.04*yrange)
}
barwidth <- 0.5; barwidth_fac_within <- 0.5; barwidth_fac_between <- 2
barspace <- c(barwidth_fac_between,barwidth_fac_within,barwidth_fac_within)
plotx <- barplot(means$mean,plot=F,width=barwidth,space=barspace)
####empty plot
plot(plotx,means$mean,ylim=yrange,xlim=c(min(plotx)- 0.6*(barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ 0.6*(barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab=expression(paste("Mean measured pathogen load (ng/", mu, "L)")),bty="n",xaxs="i",yaxs="i",type="n",cex.axis=min_cex,cex.lab=inter_cex,lwd=line_min,xaxt="n",yaxt="n")
####arrows
plot_arrows(means=means,plotx=plotx,plot_type="means",LWD=line_max,LENGTH=0.025,colz=statuses_colours[as.character(means$predictor)])
####points
points(plotx,means$mean,col=statuses_colours[as.character(means$predictor)],pch=16,cex=max_cex*0.8,lwd=line_min)
####Y-axis
axis(2,at=ymin:floor(ymax),labels=format(10^(ymin:floor(ymax)),scientific=T),cex.axis=min_cex,cex.lab=inter_cex,lwd=0,lwd.ticks=1)
par(xpd=T)
labses <- full_statuses_names[as.character(means$predictor)]
labses <- c(labses[1],rep("",length(labses)-1))
axis(1,at=plotx,labels=labses,tick=F,cex.axis=inter_cex,las=1,mgp=c(0.8,0.8,0))
for (labse in 2:length(labses)){
print(par("mgp")[2] + (labse-1)*1)
if (labse/2==round(labse/2)){
mtext(full_statuses_names[as.character(means$predictor)][labse],side=1,at=plotx[labse],line=0+par("mgp")[1] + 1,cex=par("cex")*inter_cex)
}else{
mtext(full_statuses_names[as.character(means$predictor)][labse],side=1,at=plotx[labse],line=0+par("mgp")[1] ,cex=par("cex")*inter_cex)
}
}
segments(x0=min(plotx)- 0.6*(barwidth_fac_between*barwidth/2+barwidth/2),y0=yrange[1],x1=max(plotx)+ 0.6*(barwidth_fac_between*barwidth/2+barwidth/2),lwd=line_max)
segments(x0=min(plotx)- 0.6*(barwidth_fac_between*barwidth/2+barwidth/2),y0=yrange[1],y1=yrange[2],lwd=line_max)
par(xpd=F)
data$predictor <- factor(data$predictor,levels=means$predictor)
model_lmer <- lmer(variable~predictor+(1|colony),data=data)
test_norm(residuals(model_lmer))
pvalue <- Anova(model_lmer)["predictor","Pr(>Chisq)"]
print(Anova(model_lmer))
# title(ylab=lab_title,cex.lab=1.5,mgp=c(5,1,0))
par(xpd=F)
abline(h=0)
if (pvalue>0.05){p_cex <- inter_cex}else{p_cex <- max_cex}
title(main=from_p_to_ptext(pvalue),cex.main=p_cex,font.main=2,line=stat_line,xpd=T)
post_hoc <- summary(glht(model_lmer,linfct = mcp(predictor="Tukey")),test=adjusted("BH"))
print(post_hoc)
post_hoc_groups <- cld(post_hoc)$mcletters$Letters
for (idx in 1:length(post_hoc_groups)){
group <- post_hoc_groups[as.character(means[idx,"predictor"])]
text(x=plotx[idx],y=ymax-0.1*(ymax-ymin),adj=c(0.5,0),labels=as.character(group),xpd=T,cex=inter_cex)
}
par(mar=par_mari)
}
all_qpcr_data <- NULL
data_for_plot <- NULL
for (experiment in experiments){
###read qpcr data
data <- read.table(paste(disk_path,"/",experiment,"/original_data/qPCR/qPCR_results.txt",sep=""),header=T,stringsAsFactors = F)
###keep only ants
data <- data[which(!is.na(as.numeric(data$tag))),]
###remove workers that died before the end
data <- data[which(data$alive_at_sampling_time),]
###read task group
task_groups <- read.table(paste(disk_path,"/",experiment,"/original_data/",task_group_file,sep=""),header=T,stringsAsFactors = F)
### add task groups info to data
data <- merge(data,task_groups,all.x=T,all.y=F)
###keep only pathogen treatments
data <- data[which(data$treatment%in%c("pathogen")),]
###add metadata
data <- data.frame(experiment=experiment,data,stringsAsFactors = F)
data$period <- "after"
####list desired variables and transformations
data$antid <- as.character(data$colony,data$tag)
all_qpcr_data <- rbind(all_qpcr_data,data)
data$colony <- as.character(interaction(data$experiment,data$colony))
###remove treated workers
data <- data[which(data$status!="treated"),]
data_for_plot <- rbind(data_for_plot,data)
}
all_sim_data <- NULL
for (experiment in experiments){
data <-read.table(paste(disk_path,experiment,"transmission_simulations/calibration","individual_simulation_results.dat",sep="/"),header=T,stringsAsFactors=F)
all_sim_data <- rbind(all_sim_data,data.frame(experiment=experiment,data[names(data)!="age"],stringsAsFactors = F))
}
###Now join qPCR and simulation data into single data frame
all_qpcr_data <- all_qpcr_data[which(!is.na(as.numeric(all_qpcr_data$tag))),]
all_qpcr_data <- all_qpcr_data[which(all_qpcr_data$alive_at_sampling_time),]
all_sim_qpcr_data <- merge(all_qpcr_data[c("experiment","colony","treatment","tag","status","task_group","age","measured_load_ng_per_uL")],all_sim_data[c("experiment","colony","tag","simulated_load")])
###remove treated individuals
all_sim_qpcr_data <- all_sim_qpcr_data[which(all_sim_qpcr_data$status!="treated"),]
all_sim_qpcr_data["antid"] <- as.character(interaction(all_sim_qpcr_data$experiment,all_sim_qpcr_data$colony,all_sim_qpcr_data$tag))
varb <- "simulated_load"
variable_list <- c("measured_load_ng_per_uL")
names(variable_list) <- c("Measured pathogen load")
predictor_list <- c( "simulated_load")
names(predictor_list) <- c("Simulated pathogen load")
transf_variable_list <- c("log")
transf_predictor_list <- c("log")
ymin <- floor(log10(min(all_sim_qpcr_data$measured_load_ng_per_uL[all_sim_qpcr_data$measured_load_ng_per_uL!=0])/sqrt(2)))
ymax <- ceiling(log10(max(all_sim_qpcr_data$measured_load_ng_per_uL)))
xmin <- floor(log10(min(all_sim_qpcr_data[all_sim_qpcr_data[,varb]!=0,varb])/sqrt(2)))
xmax <- ceiling(log10(max(all_sim_qpcr_data[,varb])))
analysis <- list(variable_list=variable_list,
predictor_list=predictor_list,
transf_variable_list=transf_variable_list,
transf_predictor_list=transf_predictor_list,
violin_plot_param = list(c(1,0,-0.025,0.2,0.2)))
predicted_value <- plot_regression(data=all_sim_qpcr_data,time_point="after",analysis=analysis,n_cat_horiz=20,n_cat_vertic=11,pool=c(F,F),collective=T,input_color=colour_palette_age,xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax,point_cex=1.5,predict=high_threshold)
par(xpd=NA)
if (varb =="simulated_load"){
title(sub=expression(italic("(Prop. exposure dose)")),cex.sub=min_cex,font.sub=1,mgp=c(1,0.1,0))
}else if (varb =="predicted_measured_load_ng_per_uL_SI"){
title(sub=expression(paste("(ng/", mu, "L)")),cex.sub=min_cex,font.sub=1,mgp=c(1,0.1,0))
}
par(xpd=F)
if (!exists("ymin")){
ylim <- NULL
}else{
ylim <- c(ymin,ymax)
}
plot1(data=data_for_plot,experiment="both",ylim=NULL)
if (exists("predicted_value")){return(predicted_value)}else{return(NULL)}
}
plot_qpcr_vs_distance_to_treated <- function(experiments){
all_qpcr_data <- NULL
for (experiment in experiments){
###read qpcr data
data <- read.table(paste(disk_path,"/",experiment,"/original_data/qPCR/qPCR_results.txt",sep=""),header=T,stringsAsFactors = F)
###keep only ants
data <- data[which(!is.na(as.numeric(data$tag))),]
###remove workers that died before the end
data <- data[which(data$alive_at_sampling_time),]
###read task group
task_groups <- read.table(paste(disk_path,"/",experiment,"/original_data/",task_group_file,sep=""),header=T,stringsAsFactors = F)
### add task groups info to data
data <- merge(data,task_groups,all.x=T,all.y=F)
###keep only pathogen treatments
data <- data[which(data$treatment%in%c("pathogen")),]
###add metadata
data <- data.frame(experiment=experiment,data,stringsAsFactors = F)
data$period <- "after"
####list desired variables and transformations
data$antid <- as.character(data$colony,data$tag)
all_qpcr_data <- rbind(all_qpcr_data,data)
}
all_network_data <- NULL
for (experiment in experiments){
###read data
data <-read.table(paste(disk_path,experiment,"processed_data/network_properties/post_treatment/node_properties_observed.txt",sep="/"),header=T,stringsAsFactors=F)
###read task group
task_group <- read.table(paste(disk_path,experiment,"original_data",task_group_file,sep="/"),header=T,stringsAsFactors = F)
data <- merge(data,task_group,all.x=T,all.y=F)
###keep only pathogen treatments
data <- data[which(data$treatment%in%c("pathogen")),]
all_network_data <- rbind(all_network_data,data.frame(experiment=experiment,data[names(data)!="age"],stringsAsFactors = F))
}
all_network_data <- aggregate((mean_aggregated_distance_to_treated)~experiment+colony+colony_size+treatment+tag+status+task_group,FUN=mean,data=all_network_data)
names(all_network_data)[grepl("aggregated",names(all_network_data))] <- "mean_aggregated_distance_to_treated"
all_sim_data <- NULL
for (experiment in experiments){
data <-read.table(paste(disk_path,experiment,"transmission_simulations/calibration","individual_simulation_results.dat",sep="/"),header=T,stringsAsFactors=F)
###keep only pathogen treatments
data <- data[which(data$treatment%in%c("pathogen")),]
all_sim_data <- rbind(all_sim_data,data.frame(experiment=experiment,data[names(data)!="age"],stringsAsFactors = F))
}
all_interaction_data <- NULL
for (experiment in experiments){
data <-read.table(paste(disk_path,experiment,"processed_data/individual_behaviour/post_treatment/interactions_with_treated.txt",sep="/"),header=T,stringsAsFactors=F)
###keep only pathogen treatments
data <- data[which(data$treatment%in%c("pathogen")),]
###keep only post-treatment values
data <- data[which(data$time_hours>=0),]
###sum interactions across entire post-treatment period
data$duration_of_contact_with_treated_min <- as.numeric(data$duration_of_contact_with_treated_min)
data <- aggregate(na.rm=T,na.action="na.pass",duration_of_contact_with_treated_min~colony+colony_size+treatment+tag+period,FUN=sum,data=data)
all_interaction_data <- rbind(all_interaction_data,data.frame(experiment=experiment,data[names(data)!="age"],stringsAsFactors = F))
}
###Join all data into single data frame
all_qpcr_data <- all_qpcr_data[which(!is.na(as.numeric(all_qpcr_data$tag))),]
all_qpcr_data <- all_qpcr_data[which(all_qpcr_data$alive_at_sampling_time),]
overall_data <- merge(all_network_data[c("experiment","colony","colony_size","tag","status","task_group","mean_aggregated_distance_to_treated")],all_qpcr_data[c("experiment","colony","tag","measured_load_ng_per_uL")],all.x=T)
overall_data <- merge(overall_data,all_sim_data[c("experiment","colony","tag","simulated_load")],all.x=T)
overall_data <- merge(overall_data,all_interaction_data[c("experiment","colony","tag","duration_of_contact_with_treated_min")],all.x=T)
###remove treated individuals
overall_data <- overall_data[which(overall_data$status!="treated"),]
overall_data["antid"] <- as.character(interaction(overall_data$experiment,overall_data$colony,overall_data$tag))
####define high, medium and low contact with treated
overall_data["contact_with_treated"] <- NA
overall_data[
which(overall_data$duration_of_contact_with_treated_min<quantile(overall_data$duration_of_contact_with_treated_min,probs=1/3,na.rm=T))
,
"contact_with_treated"] <- "low"
overall_data[
which(overall_data$duration_of_contact_with_treated_min>=quantile(overall_data$duration_of_contact_with_treated_min,probs=2/3,na.rm=T))
,
"contact_with_treated"] <- "high"
overall_data[
which(
overall_data$duration_of_contact_with_treated_min>=quantile(overall_data$duration_of_contact_with_treated_min,probs=1/3,na.rm=T)
&
overall_data$duration_of_contact_with_treated_min<quantile(overall_data$duration_of_contact_with_treated_min,probs=2/3,na.rm=T)
)
,
"contact_with_treated"] <- "medium"
overall_data$colony <- as.character(interaction(overall_data$experiment))
###Now perform analysis for all workers, nurses, and low contact with treated
for (who in c("all","nurses","low_contact_with_treated")){
if (who=="all"){subdata <- overall_data;NCAT <- 20}else if(who=="nurses"){subdata <- overall_data[which(overall_data$task_group=="nurse"),]; NCAT <- 6}else if(who=="low_contact_with_treated"){subdata <- overall_data[which(overall_data$contact_with_treated=="low"),]; NCAT <- 20}
variable_list <- c("measured_load_ng_per_uL","simulated_load")
names(variable_list) <- c("Measured pathogen load","Simulated pathogen load")
predictor_list <- c("mean_aggregated_distance_to_treated","mean_aggregated_distance_to_treated")
names(predictor_list) <- c("Mean network distance to treated","Mean network distance to treated")
transf_variable_list <- c("log","sqrt")
transf_predictor_list <- c("none","none")
analysis <- list(variable_list=variable_list,
predictor_list=predictor_list,
transf_variable_list=transf_variable_list,
transf_predictor_list=transf_predictor_list,
violin_plot_param = list(c(1,0,-0.025,4,0.2),c(1,0,-0.025,4,0.02)))
xmin_temp <- floor(round(10*(min(overall_data[overall_data$mean_aggregated_distance_to_treated!=0,"mean_aggregated_distance_to_treated"])/sqrt(2)))/10)
xmax_temp <- ceiling(round(10*(max(overall_data$mean_aggregated_distance_to_treated)))/10)
plot_regression(data=subdata,time_point="after",analysis=analysis,n_cat_horiz=NCAT,n_cat_vertic=11,pool=c(F,F),collective=T,input_color=colour_palette_age,point_cex=1.5,predict=NULL,xmin=xmin_temp,xmax=xmax_temp)
}
}
plot_refined <- function(diff,lab_title,col_vector,predictor,output,contrast.matrix,survival,dataset,p_queen=NA,violin_params=NULL,aligned=F,adjust_title_line){
if (!is.null(violin_params)){
violin_params <- as.numeric(unlist(violin_params))
##read violin param
range <- violin_params[1]
ylim_fac1 <- violin_params[2]
ylim_fac2 <- violin_params[3]
wex <- violin_params[4]
h <- violin_params[5]
}
par_mgp_ori <- par()$mgp
par_mar_ori <- par()$mar
means <- aggregate(na.rm=T,na.action="na.pass",variable~time+treatment+predictor,FUN="mean",data=diff);ses <- aggregate(na.rm=T,na.action="na.pass",variable~time+treatment+predictor,FUN="std.error",data=diff);
names(means)[names(means)=="variable"] <- "mean";names(ses)[names(ses)=="variable"] <- "se";means <- merge(means,ses)
means <- means[order(match(means$predictor,levels(diff$predictor)),match(means$treatment,levels(diff$treatment))),]
to_plot <- unique(means[c("time","treatment","predictor")])
#plotx <- c(1:nrow(means))+sort(rep(1:length(unique(means$predictor)),(nrow(means)/length(unique(means$predictor))))-1)
means[is.na(means$se),"se"] <- 0
ymin <- min(c(means$mean-means$se),na.rm=T);ymax<- max(c(means$mean+means$se),na.rm=T)
ymin_ori <- ymin; ymax_ori <- ymax
if (ymin>0){ymin <- 0};if (ymax<0){ymax <- 0}
# ####Now center on 0 roughly
if (Extended|aligned){
yminmax <- max(abs(ymin),abs(ymax))
ymin <- -yminmax
ymax <- yminmax
}
####Now get an idea of the spacing between ticks
prospected_vals <- axisTicks(c(ymin,ymax),log=F)
####And correct ymin and yrange accordingly
interval <- diff(prospected_vals)[1]
while(min(prospected_vals)>ymin){
prospected_vals <- c(min(prospected_vals)-interval,prospected_vals)
}
ymin <- min(prospected_vals)
while(max(prospected_vals)<ymax){
prospected_vals <- c(prospected_vals,max(prospected_vals)+interval)
}
ymax <- max(prospected_vals)
if (ymax<interval){ymax <- interval}
if (ymin>-interval){ymin <- -interval}
####and now center 0 roughly
if (Extended|aligned){
yminmax <- max(abs(ymin),abs(ymax))
ymin <- -yminmax
ymax <- yminmax
}
if (grepl("point",plot_type)|grepl("boxplot",plot_type)|grepl("violinplot",plot_type)){
rangy <- max(diff$variable,na.rm=T)-min(diff$variable,na.rm=T)
ymin <- min(ymin, min(diff$variable,na.rm=T)-0.1*rangy)
ymax <- max(ymax, max(diff$variable,na.rm=T)+0.1*rangy)
yminmax <- max(abs(ymin),abs(ymax))
ymin <- -yminmax
ymax <- yminmax
}
# rangy <- (ymax-ymin)
# ymax <- ymax+0.3*rangy
#
# plot(plotx,means$mean,ylim=c(ymin-0.3*(ymax-ymin),ymax+0.3*(ymax-ymin)),xlim=c(min(plotx)-1,max(plotx)+1),xlab="",ylab="",xaxt="n",bty="n",col=col_vector[as.character(means$treatment)],pch=19,xaxs="i",yaxs="i",cex.axis=1.1,yaxt="n")
# arrows (plotx,means$mean-means$se,plotx,means$mean+means$se,code=3,angle=90,col=col_vector[as.character(means$treatment)],lwd=2,length=0.15)
# axis(1,at=plotx,labels=treatment_names[as.character(means$treatment)],tick=F,cex.axis=1.54)
barwidth <- 0.5; barwidth_fac_within <- 0.5; barwidth_fac_between <- 2
barspace <- rep(c(barwidth_fac_between,barwidth_fac_within),length(means$mean)/2)
plotx <- barplot(means$mean,plot=F,width=barwidth,space=barspace)
###prepare colours
means["alpha"] <- as.numeric(alphas[as.character(means$treatment)])
means["full_col"] <- col_vector[as.character(means$predictor)]
means[which(as.character(means$predictor)=="outdoor_ant"),"alpha"] <- means[which(as.character(means$predictor)=="outdoor_ant"),"alpha"]*10
# for (colidx in 1:nrow(means)){
# means[colidx,"final_col"] <- apply_alpha(means[colidx,"full_col"],means[colidx,"alpha"])
# }
means["final_col"] <- means["full_col"]
if (grepl("bars",plot_type)){
offset <- 0
direction <- "normal"
plotx <- barplot(means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)- (barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ (barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab="",bty="n",col=means$final_col,xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex,width=barwidth,space=barspace,xaxt="n",yaxt="n",xpd=F,offset=offset)
if (grepl("point",plot_type)){
for (lvly in 1:nrow(means)){
stripchart(diff[which(diff$time==means[lvly,"time"]&diff$treatment==means[lvly,"treatment"]&diff$predictor==means[lvly,"predictor"]),"variable"],at=plotx[lvly],add=T,vertical=T,pch=16,col=alpha("black",0.5),method = 'jitter',ylim=c(ymin,ymax),cex=min_cex)
}
ymin_ori <- ymin
ymax_ori <- ymax
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin_ori){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax_ori){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
#print(labs)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
#print(labs)
axis(2,at=vals,labels=labs,cex.axis=min_cex)
means$mean <- means$mean + offset
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.025,colz=means$final_col,direction=direction)
par(xpd=F)
abline(h=0 ,col="black")
}else if (grepl("boxplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
boxplot(diff[which(diff$time==means[lvly,"time"]&diff$treatment==means[lvly,"treatment"]&diff$predictor==means[lvly,"predictor"]),"variable"],at=plotx[lvly],add=T,range=1.5,notch=T,names=F,col=means[lvly,"final_col"],xlab="",ylab="",xaxt="n",xaxs="i",yaxs="i",cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n",medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,pch=16)
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
#print(labs)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
#print(labs)
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else if (grepl("violinplot",plot_type)){
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab="",xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
par(bty="n")
for (lvly in 1:nrow(means)){
if (is.na(range)){
VioPlot(na.omit(diff[which(diff$time==means[lvly,"time"]&diff$treatment==means[lvly,"treatment"]&diff$predictor==means[lvly,"predictor"]),"variable"]),col=alpha(means[lvly,"final_col"],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}else{
VioPlot(na.omit(diff[which(diff$time==means[lvly,"time"]&diff$treatment==means[lvly,"treatment"]&diff$predictor==means[lvly,"predictor"]),"variable"]),range=range, h=h,col=alpha(means[lvly,"final_col"],0.7), horizontal=F, at=plotx[lvly], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Mean")
}
}
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
#print(labs)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
#print(labs)
axis(2,at=vals,labels=labs,cex.axis=min_cex)
par(xpd=F)
abline(h=0 ,col="black")
}else{
####empty plot
plot(plotx,means$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)- (barwidth_fac_between*barwidth/2+barwidth/2),max(plotx)+ (barwidth_fac_between*barwidth/2+barwidth/2)),xlab="",ylab="",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n")
####arrows
plot_arrows(means=means,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.025,colz=means$final_col)
####points
points(plotx,means$mean,col=means$final_col,cex=1.5*max_cex,pch=16,lwd=line_min)
par(xpd=F)
abline(h=0,lwd=line_max,col="black")
vals <- axisTicks(c(ymin,ymax),log=F,nint=6);interval <- mean(diff(vals))
while(min(vals)>ymin_ori){
vals <- c(min(vals)-interval,vals)
}
while(max(vals)<ymax_ori){
vals <- c(vals,max(vals)+interval)
}
labs <- formatC(vals)
if ("0" %in%labs ){
idx0 <- which(labs=="0")
if (is.even(idx0)){
labs[!is.even(1:length(labs))] <-""
}else{
labs[is.even(1:length(labs))] <-""
}
}
axis(2,at=vals,labels=labs,lwd=0,lwd.ticks=line_inter,cex.axis=min_cex)
abline(v=min(plotx)- (barwidth_fac_between*barwidth/2+barwidth/2),lwd=line_max,col="black")
}
if ((!(aligned&grepl(" low load",lab_title)))&((grepl(" load",lab_title)&!Extended)|!all(!grepl("time outside",lab_title))|!all(!grepl("with brood",lab_title))|!all(!grepl("Degree",lab_title))|!all(!grepl("time active",lab_title))|!all(!grepl("in the nest",lab_title)))){
ytil <- list(quote("Pathogen-induced changes"),quote("relative to sham-induced changes"))
par(xpd=NA)
mtext(side=2,do.call(expression,ytil),line=pars$mgp[1]*(rev(1:length(ytil))-1)+pars$mgp[1],cex=par("cex") *inter_cex,xpd=NA)
par(xpd=F)
}
if (grepl("\n",full_statuses_names[as.character(means$treatment)][1])){
lassy <- 1
mgpy <- par_mgp_ori+c(0,par_mgp_ori[1]-par_mgp_ori[2],0)
fonty <- 3
cexy <- min_cex
}else{
lassy <- 2
mgpy <- c(0.8,0.05,0)
fonty <- 1
cexy <- inter_cex
}
par(xpd=T)
axis(1,at=plotx,labels=full_statuses_names[as.character(means$treatment)],tick=F,cex.axis=cexy,las=lassy,mgp=mgpy,font=fonty)
par(xpd=F)
# title(ylab=lab_title,cex.lab=1.5,mgp=c(5,1,0))
pvalue <- output[["interaction_problist"]][["24"]][["1"]]
#title(main=from_p_to_ptext(pvalue),cex.main=max_cex,font.main=2,line=stat_line,xpd=T)
# for (i in 1:(-1+length(unique(means$predictor)))){
# abline(v= mean(plotx[c(max(which(means$predictor==unique(means$predictor)[i])), min(which(means$predictor==unique(means$predictor)[i+1])))]),lwd=line_max)
# }
par(xpd=T)
for (predy in unique(means$predictor)){
textx <- mean(plotx[which(means$predictor==predy)])
mtext(full_statuses_names[predy],side=1,line=0.5,adj=0.5,at=textx,cex=par("cex") *min_cex,col="black",font=1)
}
add_stats(dataset,plotx,means,ymin,ymax,predictor,p_colony,output,contrast.matrix,survival,p_queen,lab_title);
par(xpd=NA)
title(main=lab_title,cex.main=inter_cex,font.main=2,line=1+adjust_title_line,xpd=NA)
par(xpd=F)
}
plot_regression <- function(data,time_point,analysis,n_cat_horiz,n_cat_vertic,pool=F,prepare=F,status=NULL,collective=NULL,pool_plot=F,input_color=NULL,plot_untransformed=F,boldy=F,aligned=F,ymin=NULL,ymax=NULL,xmin=NULL,xmax=NULL,point_cex=NULL,adjust_title_line=0,predict=NULL){
adjust_title_line_ori <- adjust_title_line
data_ori <- data
#### plot regression for each desired combination of variable and predictor
for (i in 1:length(analysis[["variable_list"]])){
data <- data_ori
adjust_title_line <- adjust_title_line_ori
####get variable and predictor
variable <- analysis[["variable_list"]][i]
####if necessary: convert pixels to mm
if (grepl("changetomm",names(variable))){
if (grepl("changetomm2",names(variable))){
data[,variable] <- data[,variable]*pix_to_mm_ratio*pix_to_mm_ratio
names(variable) <- gsub("_changetomm2","",names(variable))
}else{
data[,variable] <- data[,variable]*pix_to_mm_ratio
names(variable) <- gsub("_changetomm","",names(variable))
}
}
print(variable)
predictor <- analysis[["predictor_list"]][i]
transf_variable <- analysis[["transf_variable_list"]][i]
transf_predictor <- analysis[["transf_predictor_list"]][i]
pooli <- pool[i]
####if necessary: include queen and treated into predictor function
if (!is.null(predictor)){
if ((!collective&refine!=""&predictor!="")&("tag"%in%names(data))){
####first change the content of predictor column
data["predictor"] <- data[,predictor]
###second add treated
data[which(data$status=="treated"),"predictor"] <- "treated"
####fourth copy back into predictor column
data[,predictor] <- data[,"predictor"]
####fifth if necessary remove queen
if (length(unique(data$predictor))>1){
if (!queen){
data <- data[which(data$tag!=queenid),]
}
if (!treated){
data <- data[which(data$predictor!="treated"),]
}
if (!nurses){
data <- data[which(data$predictor!="nurse"),]
}
if (!foragers){
data <- data[which(data$predictor!="forager"),]
}
}
}else if (predictor!=""){
data["predictor"] <- data[,predictor]
}
}
####if necessary: apply prepare dataset function
if (prepare){
data <- prepare_dataset(data,variable)
}else{
####process variable
data["variable"] <- data[,variable]
data[which(!is.finite(data$variable)),"variable"] <- NA
}
data["untransformed_variable"] <- data$variable
####transform variable
ylabel <- names(variable)
ylabel <- capitalize(ylabel)
if (transf_variable=="log"){
print("Logging variable...")
data[!is.na(data$variable),"variable"] <- log_transf(data[!is.na(data$variable),"variable"] )
if (!plot_untransformed){
if(boldy){
ylabel <- substitute(paste(bold(ylabel),bolditalic(" (log)")),list(ylabel=ylabel))
adjust_title_line <- 0.17
}else{
ylabel <- substitute(paste(ylabel,italic(" (log)")),list(ylabel=ylabel))
adjust_title_line <- 0.17
}
}
}else if (grepl("power",transf_variable)){
data[!is.na(data$variable),"variable"] <- (data[!is.na(data$variable),"variable"] )^as.numeric(gsub("power","",transf_variable))
if (!plot_untransformed){
if(boldy){
ylabel <- substitute(paste(bold(ylabel),bolditalic(" (") ^pow,bolditalic(")")),list(ylabel=ylabel,pow=as.numeric(gsub("power","",transf_variable))))
adjust_title_line <- 0
}else{
ylabel <- substitute(paste(ylabel,italic(" (") ^pow,italic(")")),list(ylabel=ylabel,pow=as.numeric(gsub("power","",transf_variable))))
adjust_title_line <- 0
}
}
}else if (transf_variable=="sqrt"){
data[!is.na(data$variable),"variable"] <- sqrt_transf(data[!is.na(data$variable),"variable"] )
if (!plot_untransformed){
if (boldy){
ylabel <- substitute(paste(bold(ylabel),bolditalic(" ("),sqrt(bolditalic(")"))),list(ylabel=ylabel))
adjust_title_line <- 0.24
}else{
ylabel <- substitute(paste(ylabel,italic(" ("),sqrt(italic(")"))),list(ylabel=ylabel))
adjust_title_line <- 0.24
}
}
}
####for comparison: use perform_analysis_combined_function
if (time_point=="comparison"){
if ("randy"%in%names(data)){
case <- "case3"
}else{
if (is.null(predictor)){
case <- "case1"
}else if (length(unique(data$predictor))==1){
case <- "case1"
}else if (!((!collective&refine!=""&predictor!=""))){
case <- "case1"
}else{
case <- "case2"
}
}
if (case=="case1"){
perform_barplot_analysis(root_path=root_path,collective=collective,dataset=data,lab_title=ylabel,excluded=NULL,pool=pool,violin_params=analysis[["violin_plot_param"]][i],pool_plot=pool_plot,adjust_title_line=adjust_title_line)
}else if (case=="case2"){
perform_barplot_analysis_refined(root_path=root_path,collective=collective,dataset=data,lab_title=ylabel,excluded=NULL,pool=pool,violin_params=analysis[["violin_plot_param"]][i],pool_plot=pool_plot,plot_untransformed=plot_untransformed,aligned=aligned,adjust_title_line=adjust_title_line)
}else{
perform_barplot_analysis_simple(root_path=root_path,collective=collective,dataset=data,lab_title=ylabel,excluded=NULL,pool=pool,violin_params=analysis[["violin_plot_param"]][i],pool_plot=pool_plot,plot_untransformed=plot_untransformed,aligned=aligned,adjust_title_line=adjust_title_line)
}
}else{
####process predictor
data["predictor"] <- data[,predictor]
if (is.numeric(data$predictor)){
data[which(!is.finite(data$predictor)),"predictor"] <- NA
if (transf_predictor=="log"){
if (!is.null(predict)){
transfi <- log_transf(c(data[!is.na(data$predictor),"predictor"] , predict))
predict <- transfi[length(transfi)]
data[!is.na(data$predictor),"predictor"] <- transfi[1:(length(transfi)-1)]
}else{
data[!is.na(data$predictor),"predictor"] <- log_transf(data[!is.na(data$predictor),"predictor"] )
}
xlabel<- paste("Log(", names(predictor),")",sep="")
}else if (transf_predictor=="power2"){
data[!is.na(data$predictor),"predictor"] <- (data[!is.na(data$predictor),"predictor"] )^2
if (!is.null(predict)){predict <- predict^2}
xlabel <- substitute( xlabely ^2,list(xlabely=names(predictor)))
}else if (transf_predictor=="sqrt"){
if (!is.null(predict)){
transfi <- sqrt_transf(c(data[!is.na(data$predictor),"predictor"] , predict))
predict <- transfi[length(transfi)]
data[!is.na(data$predictor),"predictor"] <- transfi[1:(length(transfi)-1)]
}else{
data[!is.na(data$predictor),"predictor"] <- sqrt_transf(data[!is.na(data$predictor),"predictor"] )
}
xlabel <- substitute(sqrt ( xlabely),list(xlabely=names(predictor)))
}else{
xlabel <- names(predictor)
}
}else{
xlabel <- ""
}
title <- ""
if(!"period"%in%names(data)){data["period"] <- data$time}
###process pool argument
if (pooli){
dat <- aggregate(na.rm=T,na.action="na.pass",variable~predictor+colony+antid+status+colony_size+period,FUN="mean",data=data)
}else{
dat <- data
}
###process horizontal bin argument
if (length(unique(dat[,"predictor"]))>n_cat_horiz){
dat[which(!is.na(dat[,"predictor"])),"predictor_plot"] <- as.numeric(gsub("\\(","",unlist(strsplit(as.character(cut(dat$predictor,n_cat_horiz,include_lowest=T)),split=","))[grepl("\\(",unlist(strsplit(as.character(cut(dat$predictor,n_cat_horiz,include_lowest=T)),split=",")))]))
}else{#if (length(unique(dat[,"predictor"]))>n_cat_horiz)
dat[,"predictor_plot"] <- dat[,"predictor"]
}##else
###define formula
formula_stat <- as.formula(paste("variable"," ~ ", paste(c("predictor","colony_size","(1|colony)","(1|antid)"), collapse= "+")))
if (length(unique(na.omit(aggregate(variable~antid,FUN=length,data=dat)$variable)))==1&unique(na.omit(aggregate(variable~antid,FUN=length,data=dat)$variable))[1]==1){
formula_stat <- update(formula_stat,~.-(1|antid))
}
formula_plot <- as.formula(paste("variable"," ~ ", paste(c("predictor_plot","period"), collapse= "+")))
###plot
predicted_value <- scatterplot_violin_forpaper(formula_stat=formula_stat,formula_plot=formula_plot,ylabel=ylabel,xlabel=xlabel,title=title,dat=dat,sorting="period",time_point=time_point,output=F,violin_params = analysis[["violin_plot_param"]][i],input_color=input_color,xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax,point_cex=point_cex,predict=predict)
if (!is.null(predicted_value)){
predicted_value <- data[,variable][closest_match(predicted_value,data$variable) ]
return(predicted_value)
}
}
}
}
plot_seeds <- function(experiments,seeds,variables,transf,color_pal){
collective_data <- NULL
for (seed in seeds){
for (experiment in experiments){
setwd(paste(disk_path,"/",experiment,"/transmission_simulations/random_vs_observed/",seed,sep=""))
temp <- data.frame(experiment=experiment,seed=seed,read.table("collective_simulation_results_observed.txt",header=T,stringsAsFactors = F),stringsAsFactors = F)
if (!is.null(collective_data)){
collective_data <-collective_data[,names(collective_data)%in%names(temp)]
temp <- temp[names(collective_data)]
}
collective_data <- rbind(collective_data,temp)
}
}
collective_data["colony"] <- as.character(interaction(collective_data$experiment,collective_data$colony))
for (variable in variables){
collective_data["variable"] <- collective_data[,variable]
dat <- collective_data[c("colony","seed","variable")]
transf_variable <- transf[which(variable==variables)]
ylabel <- names(variables[variables==variable])
if (transf_variable=="log"){
print("Logging variable...")
dat[!is.na(dat$variable),"variable"] <- log_transf(dat[!is.na(dat$variable),"variable"] )
ylabel <- substitute(paste(ylabel,italic(" (log)")),list(ylabel=ylabel))
}else if (grepl("power",transf_variable)){
dat[!is.na(dat$variable),"variable"] <- (dat[!is.na(dat$variable),"variable"] )^as.numeric(gsub("power","",transf_variable))
ylabel <- substitute(paste(ylabel,italic(" (") ^pow,italic(")")),list(ylabel=ylabel,pow=as.numeric(gsub("power","",transf_variable))))
}else if (transf_variable=="sqrt"){
dat[!is.na(dat$variable),"variable"] <- sqrt_transf(dat[!is.na(dat$variable),"variable"] )
ylabel <- substitute(paste(ylabel,italic(" ("),sqrt(italic(")"))),list(ylabel=ylabel))
}
dat$seed <- factor(dat$seed,levels=seeds)
mod <- lmer(variable~seed+(1|colony),data=dat)
pval <- Anova(mod)["seed","Pr(>Chisq)"]
###now plot
forplot <- data.frame(as.matrix(aggregate(variable~seed,function(x)cbind(mean(x),std.error(x)),data=dat)),stringsAsFactors = F)
names(forplot) <- c("seed","mean","se")
forplot$mean <- as.numeric(forplot$mean);forplot$se <- as.numeric(forplot$se)
ymin <- min(c(forplot$mean-forplot$se),na.rm=T);ymax<- max(c(forplot$mean+forplot$se),na.rm=T)
if (ymin>0){ymin <- 0};if (ymax<0){ymax <- 0}
if (grepl("point",plot_type)|grepl("boxplot",plot_type)|grepl("violinplot",plot_type)){
rangy <- max(dat$variable,na.rm=T)-min(dat$variable,na.rm=T)
ymin <- min(ymin, min(dat$variable,na.rm=T)-0.1*rangy)
ymax <- max(ymax, max(dat$variable,na.rm=T)+0.1*rangy)
}
rangy <- ymax-ymin
ymin <- ymin-0.005*rangy;ymax <- ymax+0.20*rangy
barwidth <- 0.5
barspace <- 0.5
arrowcodes <- c(1,2,3); names(arrowcodes) <- c("-1","1","0")
plotx <- barplot(forplot$mean,plot=F,width=barwidth,space=barspace)
if (grepl("bars",plot_type)){
plotx <- barplot(forplot$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab=ylabel,xaxt="n",bty="n",xaxs="i",yaxs="i",cex=0.5,cex.axis=min_cex,cex.lab=inter_cex,width=barwidth,space=barspace,col=color_pal[forplot$seed],xaxt="n")
plot_arrows(means=forplot,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.05,colz=color_pal[forplot$seed])
}else if (grepl("boxplot",plot_type)){
####empty plot
plot(plotx,forplot$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab=ylabel,xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n")
par(bty="n")
for (lvly in 1:nrow(forplot)){
boxplot(dat[which(dat$seed==forplot[lvly,"seed"]),"variable"],at=plotx[lvly],add=T,range=1.5,notch=T,names=F,col=color_pal[forplot[lvly,"seed"]],xlab="",ylab="",xaxt="n",xaxs="i",yaxs="i",cex.axis=min_cex,cex.lab=inter_cex,xaxt="n",yaxt="n",medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,pch=16)
}
}else{
####empty plot
plot(plotx,forplot$mean,ylim=c(ymin,ymax),xlim=c(min(plotx)-barwidth,max(plotx)+barwidth),xlab="",ylab=ylabel,xaxt="n",bty="n",xaxs="i",yaxs="i",type="n",lwd=line_min,cex.axis=min_cex,cex.lab=inter_cex,xaxt="n")
####arrows
plot_arrows(means=forplot,plotx=plotx,plot_type=plot_type,LWD=line_max,LENGTH=0.05,colz=color_pal[forplot$seed])
####points
points(plotx,forplot$mean,cex=1.5*max_cex,pch=16,lwd=line_min,col=color_pal[forplot$seed])
}
xlabel <- names(seeds)
###if necessary cut xlab and ylab in 2 lines
for (k in 1:length(xlabel)){
temp <- xlabel[k]
if (nchar(temp)>8){
###split label according to spaces
temp <- unlist(strsplit(temp,split=" "))
###count nb of characters in each word
temp_length <- unlist(lapply(temp,FUN=nchar))
###find roughly the middle
cutsy <- sum(temp_length/2)
cumul_length <- 0;cut_index <- NULL
for (idx in c(1:length(temp))){
cumul_length <- cumul_length + temp_length[idx]
if(cumul_length>=cutsy & is.null(cut_index)){
cut_index <- idx-1
}#if(cumul_length>=cutsy & is.null(cut_index))
}#for (idx in c(1:length(temp)))
temp <- paste(paste(temp[c(1:cut_index)],collapse=" "),paste(temp[c((cut_index+1):length(temp))],collapse=" "),sep=" \n ")
xlabel[k] <- temp
}
}#for (spec_lab in c("xlabel","ylabel"))
par_mgp <- par()$mgp
par(mgp=c(1.3,0.4,0))
axis(1,at=plotx,labels=xlabel,tick=F,cex.axis=min_cex)
title(xlab="Simulation seeds",cex.lab=inter_cex)
par(mgp=par_mgp)
par(xpd=F)
abline(h=0)
if (pval>0.05){p_cex <- inter_cex;adjust_line <- 0.4;fonty <- 1}else{p_cex <- max_cex*1.1;adjust_line <- 0.1; fonty <- 2}
title(main=from_p_to_ptext(pval),cex.main=p_cex,font.main=fonty,line=stat_line+adjust_line,xpd=T)
if (pval<0.05){
post_hoc <- summary(glht(mod,linfct = mcp(seed="Tukey")),test=adjusted("BH"))
post_hoc_groups <- cld(post_hoc)$mcletters$Letters
post_hoc_groups <- post_hoc_groups[forplot$seed]
for (i in 1:length(post_hoc_groups)){
mtext(post_hoc_groups[i],side=3,line=stat_line-0.7,at=plotx[i],xpd=T,cex=par("cex") *inter_cex,font=2)
}
}
}
}
points_plus_boxplot <- function(forplots,var,pred,levels,colour_pal,ylaby,pvalue,labels,option="boxplots",pool_plot){
par_mar_ori <- par()$mar
par(mar=par_mar_ori+c(0,0,0,0.5))
if (pool_plot){
jitter_param <- 0.15
}else{
jitter_param <- 0.3
}
forplot <- NULL; means <- NULL; ses <- NULL
for (lvl in 1:length(forplots)){
forplots[[lvl]]["var"] <- forplots[[lvl]][,var]
forplots[[lvl]]["pred"] <- forplots[[lvl]][,pred]
temp <- forplots[[lvl]]
if (option=="barplots"){
means <- rbind(means,aggregate(na.rm=T,na.action="na.pass",var~pred,FUN="mean",data=temp));ses <- rbind(ses,aggregate(na.rm=T,na.action="na.pass",var~pred,FUN="std.error",data=temp));
}
if (pool_plot){
temp <- aggregate(var~colony+time+pred,FUN=mean,data=temp)
}
forplot <- rbind(forplot,temp)
}
forplot$pred <- factor(forplot$pred,levels = levels)
###get colony ordering from observed
if (length(unique(forplot$colony))==length(unique(forplots[[length(forplots)]]$colony))){
col_means <- aggregate(var~colony,FUN=mean,data=forplots[[length(forplots)]])
}else{
col_means <- aggregate(var~colony,FUN=mean,data=forplot)
}
col_means <- col_means [order(col_means$var),]
coli_list <- col_means$colony
# colour_pal <- viridis(length(coli_list),alpha=0.5,begin=0.4,end=0.8,option="inferno")
colour_pal <- colour_pal(length(coli_list))
par(pars)
par(bty="n",xaxt = "n")
for (coli in rev(coli_list)){
if (coli==coli_list[length(coli_list)]){
addy <- F
}else{
addy <- T
}
stripchart(var ~ pred, data = forplot[forplot$colony==coli,],vertical = TRUE,pch=16,col=alpha(colour_pal[which(coli==coli_list)],1),method = 'jitter', jitter = jitter_param,ylim=c(min(c(forplot$var)),max(c(forplot$var))), main = "",ylab=ylaby,add=addy,bty="l",cex=0.6,cex.axis=min_cex,cex.lab=inter_cex)
}
if (option=="boxplots"){
###make boxplot
boxplot(var ~ pred, data = forplot,
outline = FALSE, ## avoid double-plotting outliers, if any
main = "",yaxt="n",add=T,col=alpha("white",0),medlwd=line_max,boxlwd=line_min+0.5*(line_max-line_min),whisklwd=line_min,whisklty=1,staplelwd=line_min,boxwex=0.7,bty="l")
}else if (option=="barplots"){
names(means)[names(means)=="var"] <- "mean";names(ses)[names(ses)=="var"] <- "se";means <- merge(means,ses)
means <- means[match(means$pred,levels),]
for (lvl in 1:length(levels)){
rect(lvl - 0.008, means[lvl,"mean"]-means[lvl,"se"], lvl + 0.008,
means[lvl,"mean"]+means[lvl,"se"], col = "black")
points(lvl, means[lvl,"mean"], pch = 21, col = "black",bg="white",cex=0.8)
}
}
if (!is.na(pvalue)){
par(xpd=T)
title(main=from_p_to_ptext(pvalue),cex.main=max_cex,font.main=2,line=-0.25,xpd=T)
par(xpd=F)
}
par(xaxt = "s")
axis(side=1,at=c(1,2),labels=labels,tick=F,lty=0,cex.axis=inter_cex)
par(mar=par_mar_ori)
}
prepare_dataset <- function(overall_results,variable,survival=F){
if(is.null(overall_results)){
dataset <- NULL
}else{
dataset <- overall_results
dataset["variable"] <- dataset[variable]
dataset <- dataset[(!is.na(dataset$variable))&(dataset$variable!=Inf),]
names(dataset)[names(dataset)=="period"] <- "time"
dataset$time <- as.character(dataset$time)
dataset$time <- capitalize(dataset$time)
dataset$time_of_day <- factor(dataset$time_of_day,levels=as.character(sort(unique(dataset$time_of_day))))
dataset$treatment <- factor(dataset$treatment,levels=as.character(sort(unique(dataset$treatment))))
if(survival){
dataset["censor_variable"] <- dataset[paste("cens_",variable,sep="")]
#####if survival, one must ensure that things are comparable between the 2 time windows
#####so for each time of day get the smallest period considered
min_time_considered <- aggregate(na.rm=T,na.action="na.pass",duration_considered_h~colony+time_of_day+tag,FUN=min,data=dataset)
#####and then if recorded period is larger, replace it by the smaller value and censor it
for (idx in 1:nrow(dataset)){
if (dataset[idx,"variable"]>min_time_considered[min_time_considered$colony==dataset[idx,"colony"]&min_time_considered$time_of_day==dataset[idx,"time_of_day"]&min_time_considered$tag==dataset[idx,"tag"],"duration_considered_h"]){
dataset[idx,"variable"] <- min_time_considered[min_time_considered$colony==dataset[idx,"colony"]&min_time_considered$time_of_day==dataset[idx,"time_of_day"]&min_time_considered$tag==dataset[idx,"tag"],"duration_considered_h"]
dataset[idx,"censor_variable"] <- 0
}
}
}
if (exists("refine")){
if ("tag"%in%names(dataset)){
if (refine=="caste_health_care.txt"){
dataset <- dataset[which(dataset$tag!=665),]
}
}
}
}
if (("tag"%in%names(dataset))&(!"antid"%in%names(dataset))){
dataset["antid"] <- as.character(interaction(dataset$colony,dataset$tag))
}
return(dataset)
}
prepare_stats_1 <- function(collective,dataset,type,predictor,inter,survival){
if (survival){statista <- "Pr(>|Chi|)"}else{statista <- "Pr(>Chisq)" }
if(survival){first_term <- "Surv(variable,censor_variable) ~ "}else{first_term <- "variable ~ "}
if(!collective){
if (type=="individual"){
form_stat <- as.formula(paste(first_term, paste(c("time*predictor","colony_size","(1|time_of_day)","(1|colony)","(1|antid)"), collapse= "+")))
if (nrow(unique(dataset[c("time_of_day","time")]))==nrow(unique(dataset[c("time")]))){
form_stat <- as.formula(paste(first_term, paste(c("time*predictor","colony_size","(1|colony)","(1|antid)"), collapse= "+")))
}
if (length(unique(dataset$antid))==1){
form_stat <- update(form_stat,.~.-(1|antid))
}
}else{#if (type=="individual")
form_stat <- as.formula(paste(first_term, paste(c("time*predictor","colony_size","(1|time_of_day)","(1|colony)"), collapse= "+")))
if (nrow(unique(dataset[c("time_of_day","time")]))==nrow(unique(dataset[c("time")]))){
form_stat <- as.formula(paste(first_term, paste(c("time*predictor","colony_size","(1|colony)"), collapse= "+")))
}
}#else#if (type=="individual")
}else{#!collective
form_stat <- as.formula(paste(first_term, paste(c(inter,"colony_size","(1|time_of_day)","(1|colony)"), collapse= "+")))
if (nrow(unique(dataset[c("time_of_day","time")]))==nrow(unique(dataset[c("time")]))){
form_stat <- as.formula(paste(first_term, paste(c(inter,"colony_size","(1|colony)"), collapse= "+")))
}
}#!collective
######statistics
if(exists("model")){rm(list=c("model"))}
if(exists("p_colony")){rm(list=c("p_colony"))}
if(!survival){
try(model <- do.call(lmer, list(formula=form_stat, data=dataset)),silent=T)
try(anov <- Anova(model),silent=T)
try(p_colony <- anov[statista]["colony_size",statista],silent=T)
}else{
try(model <- do.call(coxme, list(formula=form_stat, data=dataset)),silent=T)
try(p_colony <- printme_coxme(model)["colony_size"],silent=T)
}
####test effect of colony size ###
######1/case when the model was not identifiable: remove colony size
if((!exists("model"))|(!exists("p_colony"))){
form_stat <- update(form_stat,.~.-colony_size)
rm(list=c("model"))
p_colony <- NA
}else{####2/case where model was identifiable
if (is.na(p_colony)|((!is.na(p_colony))&(p_colony>0.05))){
form_stat <- update(form_stat,.~.-colony_size)
rm(list=c("model"))
}
}
if (length(unique(dataset$predictor))==3){
if ("colony_size"%in%all.vars(form_stat)){
if (grepl("age",root_path)){
contrast.matrix <- rbind( "change in untreated minus change in queen" = c(0, 0, 0, 0, 0, 0,-1),
"change in treated minus change in queen" = c(0, 0, 0, 0, 0,-1, 0),
"change in untreated minus change in treated" = c(0, 0, 0, 0, 0, 1,-1),
"queen after minus queen before" = c(0,-1, 0, 0, 0, 0, 0),
"treated after minus treated before" = c(0,-1, 0, 0, 0,-1, 0),
"untreated after minus untreated before" = c(0,-1, 0, 0, 0, 0,-1)
)
}else{
contrast.matrix <- rbind( "change in pathogen minus change in control" = c(0, 0, 0, 0, 0, 0,-1),
"change in killeds minus change in control" = c(0, 0, 0, 0, 0,-1, 0),
"change in pathogen minus change in killeds" = c(0, 0, 0, 0, 0, 1,-1),
"pathogen after minus pathogen before" = c(0,-1, 0, 0, 0, 0,-1),
"killeds after minus killeds before" = c(0,-1, 0, 0, 0,-1, 0),
"control after minus control before" = c(0,-1, 0, 0, 0, 0, 0)
)
}
}else{
if (grepl("age",root_path)){
contrast.matrix <- rbind( "change in untreated minus change in queen" = c(0, 0, 0, 0, 0,-1),
"change in treated minus change in queen" = c(0, 0, 0, 0,-1, 0),
"change in untreated minus change in treated" = c(0, 0, 0, 0, 1,-1),
"queen after minus queen before" = c(0,-1, 0, 0, 0, 0),
"treated after minus treated before" = c(0,-1, 0, 0,-1, 0),
"untreated after minus untreated before" = c(0,-1, 0, 0, 0,-1)
)
}else{
contrast.matrix <- rbind( "change in pathogen minus change in control" = c(0, 0, 0, 0, 0,-1),
"change in killeds minus change in control" = c(0, 0, 0, 0,-1, 0),
"change in pathogen minus change in killeds" = c(0, 0, 0, 0, 1,-1),
"pathogen after minus pathogen before" = c(0,-1, 0, 0, 0,-1),
"killeds after minus killeds before" = c(0,-1, 0, 0,-1, 0),
"control after minus control before" = c(0,-1, 0, 0, 0, 0)
)
}
}
}else{
if ("colony_size"%in%all.vars(form_stat)){
if (!grepl("age",root_path)){ contrast.matrix <- rbind( "change in pathogen minus change in control" = c(0, 0, 0, 0,-1),
"pathogen after minus pathogen before" = c(0,-1, 0, 0,-1),
"control after minus control before" = c(0,-1, 0, 0, 0)
)
}else{
contrast.matrix <- rbind( "change in treated minus change in untreated" = c(0, 0, 0, 0,1),
"treated after minus treated before" = c(0,-1, 0, 0,0),
"untreated after minus untreated before" = c(0,-1, 0, 0, -1)
)
}
}else{
if (!grepl("age",root_path)){
contrast.matrix <- rbind( "change in pathogen minus change in control" = c(0, 0, 0,-1),
"pathogen after minus pathogen before" = c(0,-1, 0,-1),
"control after minus control before" = c(0,-1, 0, 0)
)
}else{
contrast.matrix <- rbind( "change in treated minus change in untreated" = c(0, 0, 0, 1),
"treated after minus treated before" = c(0,-1, 0, 0),
"untreated after minus untreated before" = c(0,-1, 0, -1)
)
}
}
}
if(survival){contrast.matrix <- contrast.matrix[,2:ncol(contrast.matrix)]}
return(list(form_stat=form_stat,p_colony=p_colony,contrast.matrix=contrast.matrix))
}
prepare_stats_2 <- function(dataset,form_stat,survival,is_queens=F,contrast.matrix=NULL){
if (survival){statista <- "Pr(>|Chi|)"}else{statista <- "Pr(>Chisq)" }
interaction_problist <- vector("list", length(unique(c(24))))
names(interaction_problist) <- as.character(sort(unique(c(24))))
predictor_problist <- vector("list", length(unique(c(24))))
names(predictor_problist) <- as.character(sort(unique(c(24))))
time_problist <- vector("list", length(unique(c(24))))
names(time_problist) <- as.character(sort(unique(c(24))))
modellist <- vector("list", length(unique(c(24))))
names(modellist) <- as.character(sort(unique(c(24))))
for (time_window_ref in sort(unique(c(24)))){
if (time_window_ref==unit){
formi <- update(form_stat,.~.-(1|time_of_day_bis))
}else{
formi <- form_stat
}
nb_time_windows <- floor(24/time_window_ref)
interaction_probs <- NULL;time_probs <- NULL;predictor_probs <- NULL
models <- vector("list", nb_time_windows);names(models) <- as.character(1:nb_time_windows)
for (time_point in 1:nb_time_windows){
###subset dataset
subset <- dataset[(as.numeric(as.character(dataset$time_of_day_bis))>=(time_window_ref*(time_point-1)))&(as.numeric(as.character(dataset$time_of_day_bis))<(time_window_ref*time_point)),]
if (exists("model")){rm=list=c("model")}
gc()
if (!survival){
try(model <- do.call(lmer, list(formula=formi, data=subset)),silent=T)
try(anov <- Anova(model),silent=T)
}else{
try(model <- do.call(coxme, list(formula=formi, data=subset)),silent=T)
try(anov <- anova(model),silent=T)
}
if(exists("model")){
if (time_window_ref==24){test_norm(residuals(model));print(anov)}
models[[as.character(time_point)]] <- model
gc()
if(exists("pees")){rm(list=c("pees"))}
try(pees <- anov[statista]["time",statista],silent=T)
if (exists("pees")){
p_time <- anov[statista]["time",statista]
p_predictor <- anov[statista]["predictor",statista]
p_interaction <- anov[statista]["time:predictor",statista]
rm(list=c("pees"))
}else{
p_time <- NA
p_predictor <- NA
p_interaction <- NA
}
if (is_queens){
post_hoc <- summary(glht(model,contrast.matrix),test=adjusted("BH"))
print("z value");print(post_hoc$test$tstat);print("Pr>|z|");print(post_hoc$test$pvalues);
}
rm(list=c("model"))
}else{
models[[as.character(time_point)]] <- NULL
p_time <- NA
p_predictor <- NA
p_interaction <- NA
}
names(p_interaction) <- time_point;interaction_probs <- c(interaction_probs,p_interaction)
names(p_predictor) <- time_point;predictor_probs <- c(predictor_probs,p_predictor)
names(p_time) <- time_point;time_probs <- c(time_probs,p_time)
}
interaction_probs <- p.adjust(interaction_probs,method="hochberg"); time_probs <- p.adjust(time_probs,method="hochberg"); predictor_probs <- p.adjust(predictor_probs,method="hochberg");
interaction_problist[[as.character(time_window_ref)]] <- interaction_probs; time_problist[[as.character(time_window_ref)]] <- time_probs;predictor_problist[[as.character(time_window_ref)]] <- predictor_probs
modellist[[as.character(time_window_ref)]] <- models
}
return(list(interaction_problist=interaction_problist,time_problist=time_problist,predictor_problist=predictor_problist,modellist=modellist))
}
prepare_stats_3 <- function(dataset,predictor,survival){
if (survival){statista <- "Pr(>|Chi|)"}else{statista <- "Pr(>Chisq)" }
if(survival){first_term <- "Surv(variable,censor_variable) ~ "}else{first_term <- "variable ~ "}
form_stat <- as.formula(paste(first_term, paste(c("time*treatment*predictor","colony_size","(1|time_of_day)","(1|colony)","(1|antid)"), collapse= "+")))
######statistics
if(exists("model")){rm(list=c("model"))}
if(exists("p_colony")){rm(list=c("p_colony"))}
if(!survival){
try(model <- do.call(lmer, list(formula=form_stat, data=dataset)),silent=T)
try(anov <- Anova(model),silent=T)
try(p_colony <- anov[statista]["colony_size",statista],silent=T)
}else{
try(model <- do.call(coxme, list(formula=form_stat, data=dataset)),silent=T)
try(p_colony <- printme_coxme(model)["colony_size"],silent=T)
}
####test effect of colony size ###
######1/case when the model was not identifiable: remove colony size
if((!exists("model"))|(!exists("p_colony"))){
form_stat <- update(form_stat,.~.-colony_size)
rm(list=c("model"))
p_colony <- NA
}else{####2/case where model was identifiable
if (is.na(p_colony)|((!is.na(p_colony))&(p_colony>0.05))){
form_stat <- update(form_stat,.~.-colony_size)
rm(list=c("model"))
}
}
#####define contrast matrix
###first get the number and names of the levels
level_names <- levels(dataset$predictor)
treatment_names <- levels(dataset$treatment)
time_names <- unique(dataset$time)
###deduce the index of colony size in the parameter matrix
colony_index <- (1 + length(time_names)-1 + length(treatment_names)-1 + length(level_names)-1+ 1)
if (length(level_names)==2){
contrast.matrix <- rbind(
"Delta_treatment1_1 - Delta_treatment1_2" = c(0,0,0,0,0,0,1,0,0),
"Delta_treatment1_1 - Delta_treatment2_1" = c(0,0,0,0,0,1,0,0,0),
"Delta_treatment1_1 - Delta_treatment2_2" = c(0,0,0,0,0,1,1,0,1),
"Delta_treatment1_2 - Delta_treatment2_1" = c(0,0,0,0,0,1,-1,0,0),
"Delta_treatment1_2 - Delta_treatment2_2" = c(0,0,0,0,0,1,0,0,1),
"Delta_treatment2_1 - Delta_treatment2_2" = c(0,0,0,0,0,0,1,0,1)
)
}else if (length(level_names)==3){
contrast.matrix <- rbind(
"Delta_treatment1_1 - Delta_treatment1_2" = c(0,0,0,0,0,0,0,1,0,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment1_3" = c(0,0,0,0,0,0,0,0,1,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment2_1" = c(0,0,0,0,0,0,1,0,0,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment2_2" = c(0,0,0,0,0,0,1,1,0,0,0,1,0),
"Delta_treatment1_1 - Delta_treatment2_3" = c(0,0,0,0,0,0,1,0,1,0,0,0,1),
"Delta_treatment1_2 - Delta_treatment1_3" = c(0,0,0,0,0,0,0,-1,1,0,0,0,0),
"Delta_treatment1_2 - Delta_treatment2_1" = c(0,0,0,0,0,0,1,-1,0,0,0,0,0),
"Delta_treatment1_2 - Delta_treatment2_2" = c(0,0,0,0,0,0,1,0,0,0,0,1,0),
"Delta_treatment1_2 - Delta_treatment2_3" = c(0,0,0,0,0,0,1,-1,1,0,0,0,1),
"Delta_treatment1_3 - Delta_treatment2_1" = c(0,0,0,0,0,0,1,0,-1,0,0,0,0),
"Delta_treatment1_3 - Delta_treatment2_2" = c(0,0,0,0,0,0,1,1,-1,0,0,1,0),
"Delta_treatment1_3 - Delta_treatment2_3" = c(0,0,0,0,0,0,1,0,0,0,0,0,1),
"Delta_treatment2_1 - Delta_treatment2_2" = c(0,0,0,0,0,0,0,1,0,0,0,1,0),
"Delta_treatment2_1 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,0,1,0,0,0,1),
"Delta_treatment2_2 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,-1,1,0,0,-1,1)
)
}else if (length(level_names)==4){
contrast.matrix <- rbind(
"Delta_treatment1_1 - Delta_treatment1_2" = c(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment1_3" = c(0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment1_4" = c(0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment2_1" = c(0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0),
"Delta_treatment1_1 - Delta_treatment2_2" = c(0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0),
"Delta_treatment1_1 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0),
"Delta_treatment1_1 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),
"Delta_treatment1_2 - Delta_treatment1_3" = c(0,0,0,0,0,0,0,0,-1,1,0,0,0,0,0,0,0),
"Delta_treatment1_2 - Delta_treatment1_4" = c(0,0,0,0,0,0,0,0,-1,0,1,0,0,0,0,0,0),
"Delta_treatment1_2 - Delta_treatment2_1" = c(0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0),
"Delta_treatment1_2 - Delta_treatment2_2" = c(0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0),
"Delta_treatment1_2 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,1,-1,1,0,0,0,0,0,1,0),
"Delta_treatment1_2 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,1,-1,0,1,0,0,0,0,0,1),
"Delta_treatment1_3 - Delta_treatment1_4" = c(0,0,0,0,0,0,0,0,0,-1,1,0,0,0,0,0,0),
"Delta_treatment1_3 - Delta_treatment2_1" = c(0,0,0,0,0,0,0,1,0,-1,0,0,0,0,0,0,0),
"Delta_treatment1_3 - Delta_treatment2_2" = c(0,0,0,0,0,0,0,1,1,-1,0,0,0,0,1,0,0),
"Delta_treatment1_3 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0),
"Delta_treatment1_3 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,1,0,-1,1,0,0,0,0,0,1),
"Delta_treatment1_4 - Delta_treatment2_1" = c(0,0,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,0),
"Delta_treatment1_4 - Delta_treatment2_2" = c(0,0,0,0,0,0,0,1,1,0,-1,0,0,0,1,0,0),
"Delta_treatment1_4 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,1,0,1,-1,0,0,0,0,1,0),
"Delta_treatment1_4 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1),
"Delta_treatment2_1 - Delta_treatment2_2" = c(0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0),
"Delta_treatment2_1 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0),
"Delta_treatment2_1 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1),
"Delta_treatment2_2 - Delta_treatment2_3" = c(0,0,0,0,0,0,0,0,-1,1,0,0,0,0,-1,1,0),
"Delta_treatment2_2 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,0,-1,0,1,0,0,0,-1,0,1),
"Delta_treatment2_3 - Delta_treatment2_4" = c(0,0,0,0,0,0,0,0,0,-1,1,0,0,0,0,-1,1)
)
}
###then replace rownames matric with correct treatment
for (treaty in 1:length(levels(dataset$treatment))){
rownames(contrast.matrix) <- gsub(paste("treatment",treaty,sep=""),levels(dataset$treatment)[treaty],rownames(contrast.matrix))
}
###next remove colony size (the last column) if not in model
if (!"colony_size"%in%all.vars(form_stat)){
new_contrast.matrix <- rbind(contrast.matrix[,-colony_index])
rownames(new_contrast.matrix) <- rownames(contrast.matrix)
contrast.matrix <- new_contrast.matrix
}
###next replace names in contrast.matrix
for (i in 1:length(level_names)){
rownames(contrast.matrix) <- gsub(i,level_names[i],rownames(contrast.matrix))
}
###next, if survival=T, remove intercept from the matrix
if (survival){
new_contrast.matrix <- rbind(contrast.matrix[,-1])
rownames(new_contrast.matrix) <- rownames(contrast.matrix)
contrast.matrix <- new_contrast.matrix
}
return(list(form_stat=form_stat,p_colony=p_colony,contrast.matrix=contrast.matrix))
}
prepare_stats_4 <- function(dataset,form_stat,survival){
if (survival){statista <- "Pr(>|Chi|)"}else{statista <- "Pr(>Chisq)" }
interaction_problist <- vector("list", length(24))
names(interaction_problist) <- as.character(sort(24))
modellist <- vector("list", length(24))
names(modellist) <- as.character(sort(24))
for (time_window_ref in sort(24)){
if (time_window_ref==unit){
formi <- update(form_stat,.~.-(1|time_of_day))
}else{
formi <- form_stat
}
nb_time_windows <- floor(24/time_window_ref)
interaction_probs <- NULL;
models <- vector("list", nb_time_windows);names(models) <- as.character(1:nb_time_windows)
for (time_point in 1:nb_time_windows){
###subset dataset
subset <- dataset[(as.numeric(as.character(dataset$time_of_day))>=(time_window_ref*(time_point-1)))&(as.numeric(as.character(dataset$time_of_day))<(time_window_ref*time_point)),]
if (exists("model")){rm=list=c("model")}
gc()
if (!survival){
try(model <- do.call(lmer, list(formula=formi, data=subset)),silent=T)
try(anov <- Anova(model),silent=T)
}else{
try(model <- do.call(coxme, list(formula=formi, data=subset)),silent=T)
try(anov <- anova(model),silent=T)
}
if(exists("model")){
if (time_window_ref==24){test_norm(residuals(model));print(anov)}
models[[as.character(time_point)]] <- model
rm(list=c("model"))
gc()
if(exists("pees")){rm(list=c("pees"))}
try(pees <- anov[statista]["predictor",statista],silent=T)
if (exists("pees")){
p_interaction <- anov[statista]["time:treatment:predictor",statista]
rm(list=c("pees"))
}else{
p_interaction <- NA
}
}else{
models[[as.character(time_point)]] <- NULL
p_interaction <- NA
}
names(p_interaction) <- time_point;interaction_probs <- c(interaction_probs,p_interaction)
}
interaction_probs <- p.adjust(interaction_probs,method="hochberg");
interaction_problist[[as.character(time_window_ref)]] <- interaction_probs;
modellist[[as.character(time_window_ref)]] <- models
}
return(list(interaction_problist=interaction_problist,modellist=modellist))
}
printme_coxme <-function (x, rcoef = FALSE, digits = options()$digits, ...)
{
cat("Cox mixed-effects model fit by maximum likelihood\n")
if (!is.null(x$call$data))
#cat(" Data:", deparse(x$call$data))
if (!is.null(x$call$subset)) {
#cat("; Subset:", deparse(x$call$subset), "\n")
}
else cat("\n")
beta <- x$coefficients
nvar <- length(beta)
nfrail <- nrow(x$var) - nvar
omit <- x$na.action
cat(" events, n = ", x$n[1], ", ", x$n[2], sep = "")
if (length(omit))
cat(" (", naprint(omit), ")", sep = "")
loglik <- x$loglik + c(0, 0, x$penalty)
temp <- matrix(loglik, nrow = 1)
cat("\n Iterations=", x$iter, "\n")
dimnames(temp) <- list("Log-likelihood", c("NULL", "Integrated",
"Fitted"))
print(temp)
cat("\n")
chi1 <- 2 * diff(x$loglik[c(1, 2)])
chi1 <- 2 * diff(loglik[1:2])
chi2 <- 2 * diff(loglik[c(1, 3)])
temp <- rbind(c(round(chi1, 2), round(x$df[1], 2), signif(1 -
pchisq(chi1, x$df[1]), 5), round(chi1 - 2 * x$df[1],
2), round(chi1 - log(x$n[1]) * x$df[1], 2)), c(round(chi2,
2), round(x$df[2], 2), signif(1 - pchisq(chi2, x$df[2]),
5), round(chi2 - 2 * x$df[2], 2), round(chi2 - log(x$n[1]) *
x$df[2], 2)))
dimnames(temp) <- list(c("Integrated loglik", " Penalized loglik"),
c("Chisq", "df", "p", "AIC", "BIC"))
print(temp, quote = F, digits = digits)
cat("\nModel: ", deparse(x$call$formula), "\n")
if (nvar > 0) {
se <- sqrt(diag(x$var)[nfrail + 1:nvar])
tmp <- cbind(beta, exp(beta), se, round(beta/se, 2),
signif(1 - pchisq((beta/se)^2, 1), 2))
dimnames(tmp) <- list(names(beta), c("coef", "exp(coef)",
"se(coef)", "z", "p"))
to_return <- signif(1 - pchisq((beta/se)^2, 1), 2)
}
if (rcoef) {
coef <- unlist(lapply(ranef(x), function(y) {
if (is.matrix(y)) {
z <- c(y)
dd <- dimnames(y)
names(z) <- c(outer(dd[[1]], dd[[2]], paste,
sep = ":"))
z
}
else y
}))
se <- sqrt(diag(x$var)[1:nfrail])
rtmp <- cbind(coef, exp(coef), se)
dimnames(rtmp) <- list(names(coef), c("coef", "exp(coef)",
"Penalized se"))
}
if (nvar > 0 && rcoef) {
cat("Fixed and penalized coefficients\n")
print(rbind(tmp, cbind(rtmp, NA, NA)), na.print = "",
digits = digits)
}
else if (rcoef) {
cat("Penalized coefficients\n")
print(rtmp, digits = digits)
}
else if (nvar > 0) {
cat("Fixed coefficients\n")
print(tmp, digits = digits)
}
cat("\nRandom effects\n")
random <- VarCorr(x)
nrow <- sapply(random, function(x) if (is.matrix(x))
nrow(x)
else length(x))
maxcol <- max(sapply(random, function(x) if (is.matrix(x)) 1 +
ncol(x) else 2))
temp1 <- matrix(NA, nrow = sum(nrow), ncol = maxcol)
indx <- 0
for (term in random) {
if (is.matrix(term)) {
k <- nrow(term)
nc <- ncol(term)
for (j in 1:k) {
temp1[j + indx, 1] <- sqrt(term[j, j])
temp1[j + indx, 2] <- term[j, j]
if (nc > j) {
indx2 <- (j + 1):nc
temp1[j + indx, 1 + indx2] <- term[j, indx2]
}
}
}
else {
k <- length(term)
temp1[1:k + indx, 1] <- sqrt(term)
temp1[1:k + indx, 2] <- term
}
indx <- indx + k
}
indx <- cumsum(c(1, nrow))
temp3 <- rep("", nrow(temp1))
temp3[indx[-length(indx)]] <- names(random)
xname <- unlist(lapply(random, function(x) if (is.matrix(x))
dimnames(x)[[1]]
else names(x)))
temp <- cbind(temp3, xname, ifelse(is.na(temp1), "", format(temp1,
digits = digits)))
if (maxcol == 2)
temp4 <- c("Group", "Variable", "Std Dev", "Variance")
else temp4 <- c("Group", "Variable", "Std Dev", "Variance",
"Corr", rep("", maxcol - 3))
dimnames(temp) <- list(rep("", nrow(temp)), temp4)
print(temp, quote = F)
invisible(x)
return(to_return)
}
printcoef_coxme <-function (x, rcoef = FALSE, digits = options()$digits, ...)
{
cat("Cox mixed-effects model fit by maximum likelihood\n")
if (!is.null(x$call$data))
#cat(" Data:", deparse(x$call$data))
if (!is.null(x$call$subset)) {
#cat("; Subset:", deparse(x$call$subset), "\n")
}
else cat("\n")
beta <- x$coefficients
nvar <- length(beta)
nfrail <- nrow(x$var) - nvar
omit <- x$na.action
cat(" events, n = ", x$n[1], ", ", x$n[2], sep = "")
if (length(omit))
cat(" (", naprint(omit), ")", sep = "")
loglik <- x$loglik + c(0, 0, x$penalty)
temp <- matrix(loglik, nrow = 1)
cat("\n Iterations=", x$iter, "\n")
dimnames(temp) <- list("Log-likelihood", c("NULL", "Integrated",
"Fitted"))
print(temp)
cat("\n")
chi1 <- 2 * diff(x$loglik[c(1, 2)])
chi1 <- 2 * diff(loglik[1:2])
chi2 <- 2 * diff(loglik[c(1, 3)])
temp <- rbind(c(round(chi1, 2), round(x$df[1], 2), signif(1 -
pchisq(chi1, x$df[1]), 5), round(chi1 - 2 * x$df[1],
2), round(chi1 - log(x$n[1]) * x$df[1], 2)), c(round(chi2,
2), round(x$df[2], 2), signif(1 - pchisq(chi2, x$df[2]),
5), round(chi2 - 2 * x$df[2], 2), round(chi2 - log(x$n[1]) *
x$df[2], 2)))
dimnames(temp) <- list(c("Integrated loglik", " Penalized loglik"),
c("Chisq", "df", "p", "AIC", "BIC"))
print(temp, quote = F, digits = digits)
cat("\nModel: ", deparse(x$call$formula), "\n")
if (nvar > 0) {
se <- sqrt(diag(x$var)[nfrail + 1:nvar])
tmp <- cbind(beta, exp(beta), se, round(beta/se, 2),
signif(1 - pchisq((beta/se)^2, 1), 2))
dimnames(tmp) <- list(names(beta), c("coef", "exp(coef)",
"se(coef)", "z", "p"))
to_return <- tmp
}
if (rcoef) {
coef <- unlist(lapply(ranef(x), function(y) {
if (is.matrix(y)) {
z <- c(y)
dd <- dimnames(y)
names(z) <- c(outer(dd[[1]], dd[[2]], paste,
sep = ":"))
z
}
else y
}))
se <- sqrt(diag(x$var)[1:nfrail])
rtmp <- cbind(coef, exp(coef), se)
dimnames(rtmp) <- list(names(coef), c("coef", "exp(coef)",
"Penalized se"))
to_return <- rtmp
}
if (nvar > 0 && rcoef) {
cat("Fixed and penalized coefficients\n")
print(rbind(tmp, cbind(rtmp, NA, NA)), na.print = "",
digits = digits)
}
else if (rcoef) {
cat("Penalized coefficients\n")
print(rtmp, digits = digits)
}
else if (nvar > 0) {
cat("Fixed coefficients\n")
print(tmp, digits = digits)
}
cat("\nRandom effects\n")
random <- VarCorr(x)
nrow <- sapply(random, function(x) if (is.matrix(x))
nrow(x)
else length(x))
maxcol <- max(sapply(random, function(x) if (is.matrix(x)) 1 +
ncol(x) else 2))
temp1 <- matrix(NA, nrow = sum(nrow), ncol = maxcol)
indx <- 0
for (term in random) {
if (is.matrix(term)) {
k <- nrow(term)
nc <- ncol(term)
for (j in 1:k) {
temp1[j + indx, 1] <- sqrt(term[j, j])
temp1[j + indx, 2] <- term[j, j]
if (nc > j) {
indx2 <- (j + 1):nc
temp1[j + indx, 1 + indx2] <- term[j, indx2]
}
}
}
else {
k <- length(term)
temp1[1:k + indx, 1] <- sqrt(term)
temp1[1:k + indx, 2] <- term
}
indx <- indx + k
}
indx <- cumsum(c(1, nrow))
temp3 <- rep("", nrow(temp1))
temp3[indx[-length(indx)]] <- names(random)
xname <- unlist(lapply(random, function(x) if (is.matrix(x))
dimnames(x)[[1]]
else names(x)))
temp <- cbind(temp3, xname, ifelse(is.na(temp1), "", format(temp1,
digits = digits)))
if (maxcol == 2)
temp4 <- c("Group", "Variable", "Std Dev", "Variance")
else temp4 <- c("Group", "Variable", "Std Dev", "Variance",
"Corr", rep("", maxcol - 3))
dimnames(temp) <- list(rep("", nrow(temp)), temp4)
print(temp, quote = F)
invisible(x)
return(to_return)
}
pwe <- function(data, timevar, deathvar, bounds) {
# pwe: expands an S data frame for Piece-Wise Exponential survival
# <NAME>, Nov 29, 1992
#
# Check arguments: time and death must be variables in the data frame
# and boundaries must be non-negative and strictly increasing
if(!is.data.frame(data)) stop("First argument must be a data frame")
if(is.na(match(tn <- deparse(substitute(timevar)), names(data))))
stop(paste("\n\tSurvival time", tn,
"must be a variable in the data frame"))
if(is.na(match(dn <- deparse(substitute(deathvar)), names(data))))
stop(paste("\n\tDeath indicator", dn,
"must be a variable in the data frame"))
width <- diff(bounds)
if(any(bounds < 0) | any(width <= 0)) stop(paste(
"Invalid interval boundaries in", deparse(substitute(
bounds)))) #
# Expand the data frame creating one pseudo-observation for each
# interval visited, add interval number, events and exposure time
# (existing variables with these names will be overwriten)
n <- cut(data[, tn], bounds)
data <- data[rep(seq(along = n), n), ]
i <- NULL
for(k in 1:length(n))
i <- c(i, 1:n[k])
data$events <- ifelse(data[, tn] > bounds[i + 1], 0, data[, dn])
data$exposure <- ifelse(data[, tn] > bounds[i + 1], width[i], data[, tn
] - bounds[i])
data$interval <- i
attr(data$interval, "levels") <- attr(n, "levels")
data
}
quantil <- function(observed,random){
below <- length(which(random<observed))/length(random)
above <- length(which(random>observed))/length(random)
quantil <- below + (1-below-above)/2
return(quantil)
}
read.tag <- function(tagfile){
tag <- read.table(tagfile,sep=",",comment.char="%",as.is=TRUE,fill=TRUE,stringsAsFactors=F)
##find out in which line the names are contained
index_names <- match("#tag",tag[,1])
##remove the stuff above
if (index_names > 1){
tag <- data.frame(tag[index_names:nrow(tag),])
}
##in case there was a problem with the reading, fix it
if (ncol(tag)==1){
ncols <- min(which(!is.na(as.numeric(as.character(tag[,1]))))) -1
new_tag <- {}
for (line in 1:(nrow(tag)/ncols)){
new_tag <- rbind(new_tag,as.character(tag[(((line - 1) *ncols) +1 ):(((line - 1) *ncols) + ncols ),]))
}
tag <- data.frame(new_tag,stringsAsFactors=FALSE)
}
##update the line in which the names are contained
index_names <- match("#tag",tag[,1])
##get name list
original_name_list <- as.character(tag[index_names,])
names(tag) <- original_name_list
tag <-tag[tag["#tag"]!="#tag",]
names(tag)[names(tag)=="#tag"] <- "tag"
row.names(tag) <- 1:nrow(tag)
return(tag)
}
rgb2cmyk <- function(R,G,B){
R <- R/255
G <- G/255
B <- B/255
K <- 1-max(c(R, G, B))
C <- (1-R-K) / (1-K)
M <- (1-G-K) / (1-K)
Y <- (1-B-K) / (1-K)
outcol <- c(C,M,Y,K)
names(outcol) <- c("C","M","Y","K")
return(outcol)
}
scatterplot_violin_forpaper <- function(formula_stat,formula_plot,ylabel,xlabel,title,dat,ymin=NULL,ymax=NULL,xmin=NULL,xmax=NULL,sorting="status",time_point,IC=NULL,output=F,means=T,input_color=NULL,violin_params,point_cex=NULL,predict=NULL){
violin_params <- as.numeric(unlist(violin_params))
##read violin param
range <- violin_params[1]
ylim_fac1 <- violin_params[2]
ylim_fac2 <- violin_params[3]
wex <- violin_params[4]
h <- violin_params[5]
if (all(dat$predictor==dat$colony_size)){
formula_stat <- update(formula_stat,~.-colony_size)
}
dep_var <- row.names(attr(terms(formula_plot),"factors"))[1]
pf <- parent.frame()
dat["variable"] <- eval(parse(text=dep_var),dat,pf)
##########plotting########
if (is.numeric(dat$predictor)){
categories <- sort(unique(dat$predictor_plot))
}else{
categories <- unique(c(dat$predictor_plot))
categories <- categories[order(match(categories,status_order))]
}
if (is.null(input_color)){
if (sorting=="treatment"){
colour_pal <- NULL
for (category in categories){
colour_pal <- c(colour_pal,get(paste(category,"_colour",sep="")))
}
}else{
colour_pal <- rev(colorRampPalette(colour_palette_workers)(length(categories)))
}
}else{
colour_pal <- rev(colorRampPalette(input_color)(length(categories)))
}
names(colour_pal) <- categories
dat["colour"] <- colour_pal[match(dat$predictor_plot,names(colour_pal))]
forplot <- aggregate(na.rm=T,na.action="na.pass",colour~predictor_plot,FUN=unique,data=dat)
forplot_med <- aggregate(na.rm=T,na.action="na.pass",variable~predictor_plot,FUN=median,data=dat);names(forplot_med)[names(forplot_med)=="variable"] <- "median"
forplot_mean <- aggregate(na.rm=T,na.action="na.pass",variable~predictor_plot,FUN=mean,data=dat);names(forplot_mean)[names(forplot_mean)=="variable"] <- "mean"
forplot <- merge(merge(forplot,forplot_med),forplot_mean)
if (is.null(ymin)){
ymin <- min(dat$variable,na.rm=T) - ylim_fac1*(max(dat$variable,na.rm=T)-min(dat$variable,na.rm=T))
# ymin <- min(dat$variable,na.rm=T)
}
if (is.null(ymax)){
ymax <- max(dat$variable,na.rm=T) + ylim_fac2*(max(dat$variable,na.rm=T)-min(dat$variable,na.rm=T))
# ymax <- max(dat$variable,na.rm=T)
}
###prepare plot shell
par_mar_ori <- par()$mar
if(is.character(dat$predictor)){
forplot ["pred"] <- as.numeric(factor(forplot$predictor_plot,levels=categories))/2
dat["pred"] <- as.numeric(factor(dat$predictor_plot,levels=categories))/2
par(bty="n",xaxt = "n")
}else{
forplot ["pred"] <- forplot$predictor_plot
dat["pred"] <- dat$predictor_plot
par(bty='l')
}
par(mar=par_mar_ori+c(0,0,0,0.5))
values <- sort(unique(forplot$pred))
if (is.null(xmin)){
xlim <- c(min(forplot$pred),max(forplot$pred))+mean(diff(values,lag=1))*c(-0.5,0.5)
}else{
xlim <- c(xmin,xmax)
}
plot(dat$pred,dat$variable,xlab="",ylab="",xaxt="n",yaxt="n",cex.main=inter_cex,cex.lab=inter_cex,font.lab=1,cex.axis=min_cex,xlim=xlim,ylim=c(ymin,ymax),pch=21,type="n")
if (!all(!grepl("Log",xlabel))){
where <- axisTicks(c(par("usr")[1],par("usr")[2]),log=F)
where <- where[which(where==round(where))]
axis(1,at=where,labels=format(10^(where),scientific=T),cex.lab=inter_cex,cex.axis=min_cex)
xlab <- substr(gsub("Log\\(","",xlabel),1,-1+nchar(gsub("Log\\(","",xlabel)))
if (xlab=="Measured pathogen load"){
title(xlab=expression(paste("Measured pathogen load (ng/", mu, "L)")),cex.lab=inter_cex,mgp=par()$mgp+c(0.2,0,0))
}else{
title(xlab=xlab,cex.lab=inter_cex,mgp=par()$mgp+c(0.2,0,0))
}
}else{
axis(1,cex.lab=inter_cex,cex.axis=min_cex)
title(xlab=xlabel,cex.lab=inter_cex)
}
if(all(!grepl("log",ylabel))){
axis(2,cex.lab=inter_cex,cex.axis=min_cex)
title(ylab=ylabel,cex.lab=inter_cex)
}else{
where <- axisTicks(c(par("usr")[3],par("usr")[4]),log=F)
where <- where[which(where==round(where))]
axis(2,at=where,labels=format(10^(where),scientific=T),cex.lab=inter_cex,cex.axis=min_cex)
ylab <- as.character(ylabel[2])
if (ylab=="Measured pathogen load"){
title(ylab=expression(paste("Measured pathogen load (ng/", mu, "L)")),cex.lab=inter_cex,mgp=par()$mgp+c(0.1,0,0))
}else{
title(ylab=ylab,cex.lab=inter_cex,mgp=par()$mgp+c(0.1,0,0))
}
}
if(is.character(dat$predictor)){
par(xaxt = "s")
axis(side=1,at=sort(unique(forplot$pred)),labels=full_statuses_names[categories],tick=F,lty=0,cex.axis=inter_cex)
###plus add grid lines
par(xpd=F)
# for (idx in 1:nrow(forplot)){
# abline(h=forplot[idx,"median"],lwd=line_min,lty=3,col="black")
# }
abline(h=0,lwd=line_min,lty=3,col="black")
}
if(!is.null(title)){title(main=title,cex.main=inter_cex,line=2.5)}
###if input, add 95%IC
if(!is.null(IC)){
polygon(c(par("usr")[c(1,2)],par("usr")[c(2,1)]),c(IC[1],IC[1],IC[2],IC[2]),border=NA,col=alpha("orange",0.1))
}
par_cex_ori <- par()$cex
par(cex=0.3)
if (is.null(point_cex)){
cexMed <- min_cex
}else{
cexMed <- point_cex
}
###add violins
for (i in 1:nrow(forplot)){
subset <- dat[which(dat$pred==forplot[i,"pred"]),"variable"]
if (is.na(range)){
VioPlot(na.omit(subset),col=alpha(forplot[i,"colour"],0.7), horizontal=F, at=forplot[i,"pred"], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Median",cexMed=cexMed)
}else{
VioPlot(na.omit(subset),range=range, h=h,col=alpha(forplot[i,"colour"],0.7), horizontal=F, at=forplot[i,"pred"], add=TRUE,lty=1, rectCol="black",wex=wex,border=NA,lwd=line_min,mode="Median",cexMed=cexMed)
}
}
par(cex=par_cex_ori)
##########stats############
###initialise
to_plot <- data.frame(intercept=as.numeric(as.character()),slope=as.numeric(as.character()),colour=as.character(),stringsAsFactors=F)
to_mtext <- data.frame(effect=as.character(),pvalue=as.numeric(as.character()),stringsAsFactors=F)
pred<- attr(terms(formula_stat),"term.labels")
pred <- pred[!grepl("\\|",pred)]
###get final stats formula (step by step in case of a multiple terms model); i.e., reduce model
try(model_temp <- lmer(formula_stat,data=dat),silent=T)
if (exists("model_temp")){
coeff <- Anova(model_temp,type="III")
if ("Pr(>Chisq)"%in%colnames(coeff)){
###first test if colony size is significant; if not remove it
if ("colony_size" %in%pred){
if (coeff["colony_size","Pr(>Chisq)"]>0.05){
formula_stat <- update(formula_stat,~.-colony_size)
model_temp <- lmer(formula_stat,data=dat)
coeff <- Anova(model_temp,type="III")
}#if (coeff["colony_size","Pr(>Chisq)"]>0.05)
###and now that it is dealt with, remove it from pred
pred <- pred[pred!="colony_size"]
}#("colony_size" %in%pred)
if (time_point=="comparison"){
for (effect in pred){
to_mtext <- rbind(to_mtext,data.frame(effect=effect,pvalue=coeff[effect,"Pr(>Chisq)"],stringsAsFactors=F))
}
interaction_effect <- pred[grepl("\\:",pred)]
p_interaction <- coeff[interaction_effect,"Pr(>Chisq)"]
if (p_interaction>0.05){
if (sorting=="status"){
formula_stat <- update(formula_stat,~.-predictor:status)
}
if (sorting=="period"){
formula_stat <- update(formula_stat,~.-predictor:period)
}
pred<- attr(terms(formula_stat),"term.labels")
pred <- pred[!grepl("\\|",pred)&!grepl("colony_size",pred)]
try(model_bis <- lmer(formula_stat,data=dat),silent=T)
if (exists("model_bis")){
coeff <- Anova(model_bis,type="III")
pvalue <- coeff[pred[!grepl("predictor",pred)],"Pr(>Chisq)"]
to_mtext[to_mtext$effect==pred[!grepl("predictor",pred)],"pvalue"] <- pvalue
if (pvalue>0.05){
if (sorting=="status"){
formula_stat <- update(formula_stat,~.-status)
}
if (sorting=="period"){
formula_stat <- update(formula_stat,~.-period)
}
pred<- attr(terms(formula_stat),"term.labels")
pred <- pred[!grepl("\\|",pred)&!grepl("colony_size",pred)]
}
}
}#if (p_interaction>0.05)
}#if (time_point=="comparison")
}#if ("Pr(>Chisq)"%in%colnames(coeff))
rm(list=c("model_temp"))
}#(exists("model_temp"))
####get final pvalues based on final model
########get names of the predictors in the table for extracting coefficients
formula_simple <- update(formula_stat,~.-(1|colony)-(1|antid_1)-(1|antid_2)-(1|antid))
pred2 <- Names( formula_simple,dat);pred2 <- pred2[!grepl("Intercept",pred2)&!grepl("colony_size",pred2)];pred2 <- pred2[!grepl("\\|",pred2)]
try(model_final <- lmer(formula_stat,data=dat),silent=T)
#########testing normality of residuals
resids <- residuals(model_final)
test_norm(resids)
if (exists("model_final")){
coeff <- Anova(model_final,type="III")
print(coeff)
coeff2 <- summary(model_final)$coefficients
if ("Pr(>Chisq)"%in%colnames(coeff)){
if (length(pred)==1){
pvalue <- coeff[pred,"Pr(>Chisq)"]
to_output <- list(coeff2[pred2,"Estimate"])
names(to_output) <- time_point
if (nrow(to_mtext)==0){
to_mtext <- rbind(to_mtext,data.frame(effect=pred,pvalue=pvalue,stringsAsFactors=F))
}else{
to_mtext[to_mtext$effect==pred,"pvalue"] <- pvalue
}
if ( is.numeric(dat$predictor)){
if (pvalue < 0.05){
if ("colony_size"%in%Names(formula_simple,dat)){
to_plot <- rbind(to_plot,data.frame(
intercept = coeff2["(Intercept)","Estimate"]+coeff2["colony_size","Estimate"]*mean(dat$colony_size),
slope = coeff2[pred2,"Estimate"],
#colour = statuses_colours[time_point],stringsAsFactors=F))
colour = "black",stringsAsFactors=F))
}else{
to_plot <- rbind(to_plot,data.frame(intercept = coeff2["(Intercept)","Estimate"],slope = coeff2[pred2,"Estimate"],
#colour = statuses_colours[time_point],stringsAsFactors=F))
colour = "black",stringsAsFactors=F))
}
}#if (pvalue < 0.05)
}
}#if (length(pred)==1)
}#if ("Pr(>Chisq)"%in%colnames(coeff))
}#if (exists("model_final"))
###plot ablines
if (!is.null(predict)){
predicted_value <- to_plot[1,"intercept"] + to_plot[1,"slope"]*predict
segments(x0=predict,y0=ymin-0.1*(ymax-ymin),y1=predicted_value,col="springgreen2",xpd=F,lty=2)
segments(x0=xlim[1]-0.1*(xlim[2]-xlim[1]),y0=predicted_value,x1=predict,col="red",xpd=F,lty=2)
}
par(xpd=F)
if (nrow(to_plot)>=1){
for (i in 1:nrow(to_plot)){
abline(a=to_plot[i,"intercept"],b=to_plot[i,"slope"],col=to_plot[i,"colour"],lwd=line_inter)
}# i
}#(nrow(to_plot)>=1)
###plot mtext
if (nrow(to_mtext)>=1){
for (i in 1:nrow(to_mtext)){
pvalue <- to_mtext[i,"pvalue"];effect <- to_mtext[i,"effect"]
if(grepl("\\:",effect)){effect_ <- "Interaction: "}
if(!grepl(sorting,effect)){
effect_ <- paste(ylabel[1],": ",sep="")
if (nchar(effect_)>30){
effect_ <- "main: "
}
}
if (sorting=="status"){
if(!grepl("predictor",effect)){effect_ <- "treated vs. nestmates: "}
}
if (sorting=="period"){
if(!grepl("predictor",effect)){effect_ <- "before vs. after: "}
}
p_value <- from_p_to_ptext(pvalue)
if (pvalue>0.05){p_cex <- inter_cex}else{p_cex <- max_cex}
par(xpd=T)
if (nrow(to_mtext)==1){
title(main=p_value,cex.main=p_cex,font.main=2,line=stat_line-((i-1)*0.75),xpd=T)
}else{
title(main=paste(effect_,p_value,sep=""),cex.main=p_cex,font.main=2,line=stat_line-((i-1)*0.75),xpd=T)
}
par(xpd=T)
} # i
}#if (nrow(to_mtext)>=1)
if(output){return(to_output)}
par(mar=par_mar_ori)
if(!is.null(predict)){return(predicted_value)}else{return(predict)}
}#scatterplot_bubbles_qpcr
sqrt_transf <- function(x){
if(all(x>=0)){
replac_val <- 0
}else{
replac_val <- -min(x,na.rm=T)
}
return(sqrt(x+replac_val))
}
survival_analysis <- function(experiment,which_to_plot="all"){
####plotting function
plotty <- function(data_table,variable,survimin,legend_title){
data_table["variable"] <- data_table[,variable]
###########PART 1 - by variable ##########
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=data_table)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+variable+(1|colony),data=data_table)
survival_model_plot <- survfit(Surv(time=survival,event=censored_status)~variable,data=data_table)
status_names <- gsub("variable=","",unlist(strsplit(names(survival_model_plot$strata),split="\\."))[grepl("\\=",unlist(strsplit(names(survival_model_plot$strata),split="\\.")))])
if (which_to_plot=="all"){
xmin <- -0.1
}else{
xmin <- -0.5
}
surviplot <- plot(survival_model_plot, mark.time=F,col=alpha(statuses_colours[status_names],0),yaxt="n",xaxt="n",lty=styles[status_names],lwd=widths[status_names],ylab="Proportion surviving",xlab="Days after treatment",cex.axis=min_cex,cex.lab=inter_cex,xlim=c(xmin,1+1.1*max(data_table$survival)),bty="n",xaxs="i",yaxs="i",ylim=c(survimin,1+0.35*(1-survimin)))
axis(side=2,at=seq(from=survimin,to=1,by=0.05),tick=T,cex.axis=min_cex,xaxs="i",yaxs="i")
ats <- 1+c(2*c(0:(floor((max(data_table$survival)-1)/2))));
ats <- c(ats,max(ats)+2)
labs <- ats+1;
if (!xmin %in% ats){ats <- c(xmin,ats);labs <- c("",labs)}
axis(side=1,
at = ats
,
labels = labs
,
tick=T,cex.axis=min_cex
)
lines(survival_model_plot, mark.time=F,col=NA,yaxt="n",xaxt="n",lty=styles[status_names],lwd=widths[status_names],xlab="",cex.lab=inter_cex,cex.axis=min_cex,xlim=c(0,1.1*max(data_table$survival)),bty="n",xaxs="i",yaxs="i")
strata <- levels(summary(survival_model_plot)$strata)
final_surv <- c()
for (stratum in rev(strata)){
survival_values <- c(1,summary(survival_model_plot)$surv[summary(survival_model_plot)$strata==stratum])
time_values <- summary(survival_model_plot)$time[summary(survival_model_plot)$strata==stratum]
std_error_values <- c(0,summary(survival_model_plot)$std.err[summary(survival_model_plot)$strata==stratum])
last_y <- rev(summary(survival_model_plot)$surv[summary(survival_model_plot)$strata==stratum])[1]
y_lo <- survival_values-std_error_values
y_hi <- survival_values+std_error_values
xvalues <- c(0,rep(time_values,each=2),max(survival_model_plot$time)*(1+1/96))
yvalues <- rep(c(survival_values),each=2)
y_lovalues <- rep(y_lo,each=2)
y_hivalues <- rep(y_hi,each=2)
polygon(x=c(xvalues,rev(xvalues))
,
y=c(y_lovalues,rev(y_hivalues))
,
col=alpha(statuses_colours[gsub("variable=","",stratum)],0.2)
,
border=NA
)
lines(xvalues,yvalues, col=statuses_colours[gsub("variable=","",stratum)],lty=styles[gsub("variable=","",stratum)],lwd=widths[gsub("variable=","",stratum)])
names(last_y) <- stratum
final_surv <- c(final_surv,last_y)
}
if (grepl("load",status_names[1])){
legend("topright",xjust=1,yjust=1,legend=gsub(" predicted"," simulated",full_statuses_names[status_names]),pt.bg=alpha(statuses_colours[status_names],0.2),col=alpha(statuses_colours[status_names],0.2),bty='n',pch=15,lty=0,lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="white",cex=min_cex,title=legend_title,y.intersp=1.1)
legend("topright",xjust=1,yjust=1,legend=gsub(" predicted"," simulated",full_statuses_names[status_names]),pt.bg=alpha(statuses_colours[status_names],0.2),col=statuses_colours[status_names],bty='n',pch=NA,lty=styles[status_names],lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="black",cex=min_cex,title=legend_title,y.intersp=1.1)
}else{
legend("topright",xjust=1,yjust=1,legend=capitalize(gsub("Untreated","",gsub("\n","",full_statuses_names[status_names]))),pt.bg=alpha(statuses_colours[status_names],0.2),col=alpha(statuses_colours[status_names],0.2),bty='n',pch=15,lty=0,lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="white",cex=min_cex,title=legend_title,y.intersp=1.1)
legend("topright",xjust=1,yjust=1,legend=capitalize(gsub("Untreated","",gsub("\n","",full_statuses_names[status_names]))),pt.bg=alpha(statuses_colours[status_names],0.2),col=statuses_colours[status_names],bty='n',pch=NA,lty=styles[status_names],lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="black",cex=min_cex,title=legend_title,y.intersp=1.1)
}
arrow_x <- 0
arrow_y0 <- 1
arrow_y1 <- 1+0.05*(1-survimin)
arrows(arrow_x,arrow_y1,arrow_x,arrow_y0+(1-survimin)/100,length=0.025,lwd=line_max,col="springgreen3")
segments(x0=arrow_x,y0=survimin,y1=arrow_y0-0.00075,lty=3,lwd=line_inter,col="springgreen3")
par(lheight=.75)
mtext("time of load\nprediction",side=3,las=3,at=arrow_x,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col="springgreen3")
par(lheight=1)
top_surv_fit <- survfit(Surv(time=survival,event=censored_status)~1,data=data_table[which(data_table$variable==gsub("variable=","",names(final_surv[final_surv==max(final_surv)]))),])
arrow_x <- top_surv_fit$time[closest_match((break_point-1),top_surv_fit$time)]
arrow_y0 <- top_surv_fit$surv[closest_match((break_point-1),top_surv_fit$time)-1]
arrow_y1 <- 1+0.05*(1-survimin)
arrows(arrow_x,arrow_y1,arrow_x,arrow_y0+(1-survimin)/100,length=0.025,lwd=line_max,col="red")
segments(x0=arrow_x,y0=survimin,y1=arrow_y0-0.00075,lty=3,lwd=line_inter,col="red")
par(lheight=.75)
mtext("increase\nin mortality\n(untreated)",side=3,las=3,at=arrow_x,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col="red")
par(lheight=1)
####comparison of survival before break point
subsett <- data_table
subsett[which(subsett$survival>=(break_point-1)),"censored_status"] <- 0
subsett[which(subsett$survival>=(break_point-1)),"survival"] <- break_point-1
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=subsett)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+variable+(1|colony),data=subsett)
print("Between load prediction and inflexion")
print(anova(model1,survival_model))
p_before_break <- anova(model1,survival_model)["P(>|Chi|)"][2,"P(>|Chi|)"]
if (gsub("variable=","",names(final_surv[final_surv==max(final_surv)]))==status_names[length(status_names)]){
hazard_before_break <- sprintf("%.2f", exp(-printcoef_coxme(survival_model)[paste("variable",gsub("variable=","",names(final_surv[final_surv==max(final_surv)])),sep=""),"coef"]))
}else{
hazard_before_break <- sprintf("%.2f", exp(printcoef_coxme(survival_model)[paste("variable",gsub("variable=","",names(final_surv[final_surv==max(final_surv)])),sep=""),"coef"]))
}
# ####comparison of survival after break point
subsett <- data_table[which((!is.na(data_table$tag)&data_table$focal_status=="untreated")),]
subsett <- subsett[which(subsett$survival>(break_point-1)),]
subsett$survival <- subsett$survival-(break_point-1)
print("Between inflexion and end")
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=subsett)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+variable+(1|colony),data=subsett)
print( anova(model1,survival_model))
p_after_break <- anova(model1,survival_model)["P(>|Chi|)"][2,"P(>|Chi|)"]
if (gsub("variable=","",names(final_surv[final_surv==max(final_surv)]))==status_names[length(status_names)]){
hazard_after_break <- sprintf("%.2f", exp(-printcoef_coxme(survival_model)[paste("variable",gsub("variable=","",names(final_surv[final_surv==max(final_surv)])),sep=""),"coef"]))
}else{
hazard_after_break <- sprintf("%.2f", exp(printcoef_coxme(survival_model)[paste("variable",gsub("variable=","",names(final_surv[final_surv==max(final_surv)])),sep=""),"coef"]))
}
if (p_before_break<0.06){
text(x=0.5*(break_point-1),y=survimin+(0.25-1/20)*(1-survimin),labels=paste("HR=",hazard_before_break,sep=""),cex=min_cex,col="black")
if (p_before_break<0.05){
p_cex <- max_cex*1.1;adjust_line <- +0.00035; fonty <- 2
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
text(x=0.5*(break_point-1),y=survimin+0.25*(1-survimin)+adjust_line,labels=gsub(" ","",paste(from_p_to_ptext(p_before_break),sep="")),cex=p_cex,font=fonty)
if (p_after_break<0.06){
text(x= (break_point-1)+0.5*(max(data_table$survival)-(break_point-1)),y=survimin+(0.25-1/20)*(1-survimin),labels=paste("HR=",hazard_after_break,sep=""),cex=min_cex,col="black")
if (p_after_break<0.05){
p_cex <- max_cex*1.1;adjust_line <- +0.00035; fonty <- 2
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
text(x=(break_point-1)+0.5*(max(data_table$survival)-(break_point-1)),y=survimin+0.25*(1-survimin)+adjust_line,labels=gsub(" ","",paste(from_p_to_ptext(p_after_break),sep="")),cex=p_cex,font=fonty)
}
###parameters
root_path <- paste(disk_path,experiment,sep="/")
break_point <- 3.8
styles <- c(1,2,1,2,1,2); names(styles) <- c("treated","untreated","high_predicted_load","low_predicted_load","forager","nurse")
widths <- c(2*line_max,2*line_max,2*line_max,2*line_max,2*line_max,2*line_max); names(widths) <- c("treated","untreated","high_predicted_load","low_predicted_load","forager","nurse")
###read survival data
survival_data <- read.table(paste(root_path,"/original_data/survival.dat",sep=""),header=T,stringsAsFactors = F)
###get rid of accidental deaths / escapes
survival_data <- survival_data[which(survival_data$censored_status%in%c("alive","dead")),]
###update censored column
survival_data[survival_data$censored_status!="dead","censored_status"] <- 0
survival_data[survival_data$censored_status=="dead","censored_status"] <- 1
survival_data$censored_status <- as.numeric(survival_data$censored_status)
survival_data$colony <- as.character(survival_data$colony)
#######add predicted load
predicted_load <- read.table(paste(root_path,"/transmission_simulations/post_treatment/experimentally_exposed_seeds/individual_simulation_results_observed.txt",sep=""),header=T,stringsAsFactors = F)
survival_data <- merge(survival_data,predicted_load[which(predicted_load$period=="after"),c("colony","tag","simulated_load")],all.x=T,all.y=F,sort=F)
survival_data["final_load"] <- NA
survival_data[which(survival_data$simulated_load>high_threshold),"final_load"] <- "high_predicted_load"
survival_data[which(survival_data$simulated_load<=high_threshold),"final_load"] <- "low_predicted_load"
survival_data$final_load <- factor(survival_data$final_load)
#######add task group
task_group <- read.table(paste(disk_path,experiment,"original_data",task_group_file,sep="/"),header=T,stringsAsFactors = F)
survival_data <- merge(survival_data,task_group,all.x=T,all.y=F)
survival_data[which(survival_data$focal_status=="treated"),"task_group"] <- "treated"
survival_data[which(survival_data$tag==queenid),"task_group"] <- "queen"
#######add interaction with treated
int_with_treated <- read.table(paste(disk_path,experiment,"processed_data/individual_behaviour/post_treatment/interactions_with_treated.txt",sep="/"),header=T,stringsAsFactors = F)
survival_data <- merge(survival_data,int_with_treated[c("colony","tag","duration_of_contact_with_treated_min")],all.x=T,all.y=F)
survival_data$duration_of_contact_with_treated_min <- as.numeric(survival_data$duration_of_contact_with_treated_min)
Q1 <- quantile(survival_data[survival_data$focal_status!="treated","duration_of_contact_with_treated_min"],probs=1/3,na.rm=T)
Q2 <- quantile(survival_data[survival_data$focal_status!="treated","duration_of_contact_with_treated_min"],probs=2/3,na.rm=T)
survival_data["frequency_contact_with_treated"] <- NA
survival_data[which(survival_data$duration_of_contact_with_treated_min<Q1),"frequency_contact_with_treated"] <- "low"
survival_data[which(survival_data$duration_of_contact_with_treated_min>=Q1
&
survival_data$duration_of_contact_with_treated_min<Q2),"frequency_contact_with_treated"] <- "medium"
survival_data[which(survival_data$duration_of_contact_with_treated_min>=Q2),"frequency_contact_with_treated"] <- "high"
###start at -3 days
nb_days_before <- 3
survival_data <- survival_data[survival_data$survival >=(-nb_days_before*24),]
survival_data$survival <- survival_data$survival+(nb_days_before*24)
###modify survival time from hours to days
survival_data$survival <- as.numeric(survival_data$survival)/24
####fit a simple model to the data in order to predict expected death rate
####first get mortality rate before treatment for untreated
survival_data_untreated <- survival_data[which(survival_data$focal_status=="untreated"),]
modified_survival <- survival_data_untreated
modified_survival[which(modified_survival$survival>=nb_days_before),"censored_status"] <- 0
modified_survival[which(modified_survival$survival>=nb_days_before),"survival"] <- nb_days_before
wfit <- survreg(Surv(time=survival,event=censored_status)~1,data=modified_survival)
pp <- 0:1000/10000
wsurv <- predict(wfit, type='quantile', p=pp,
newdata=modified_survival[1:2,])
expected_survival_at_nb_days_before <- 1-pp[closest_match(nb_days_before,t(wsurv)[,1])]
observed_survival_at_nb_days_before <- nrow(modified_survival[which(modified_survival$censored_status==0),])/nrow(modified_survival)
expected_survival_at_break_point <- 1-pp[closest_match(nb_days_before+break_point,t(wsurv)[,1])]
observed_survival_at_break_point <- nrow(survival_data_untreated[which(survival_data_untreated$survival>=nb_days_before+break_point),])/nrow(survival_data_untreated)
end_of_experiment_in_days <- max(survival_data_untreated$survival,na.rm=T)
expected_survival_end_of_experiment <- 1-pp[closest_match(end_of_experiment_in_days,t(wsurv)[,1])]
actual_survival_at_end_of_experiment <- nrow(survival_data_untreated[which(survival_data_untreated$censored_status==0),])/nrow(survival_data_untreated)
###plot 1: survival = f(status)
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=survival_data)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+focal_status+(1|colony),data=survival_data)
survival_model_plot <- survfit(Surv(time=survival,event=censored_status)~focal_status,data=survival_data)
status_names <- gsub("focal_status=","",unlist(strsplit(names(survival_model_plot$strata),split="\\."))[grepl("\\=",unlist(strsplit(names(survival_model_plot$strata),split="\\.")))])
p_exposure <- anova(model1,survival_model)["P(>|Chi|)"][2,"P(>|Chi|)"]
print("Survival of treated vs. untreated workers")
print(anova(model1,survival_model))
hazard_exposure <- sprintf("%.2f", exp(-printcoef_coxme(survival_model)["focal_statusuntreated","coef"]))
survival_model_plot_untreated <- survfit(Surv(time=survival,event=censored_status)~1,data=survival_data[which(survival_data$focal_status=="untreated"),])
par_mar_ori <-par()$mar
par(mar=par()$mar+c(0,0,-0.75,0))
if (which_to_plot == "detailed"){
surviplot <- plot(survival_model_plot, mark.time=F,col=alpha(statuses_colours[status_names],0),yaxt="n",xaxt="n",lty=styles[status_names],lwd=widths[status_names],ylab="Proportion surviving",xlab="Days after treatment",cex.axis=min_cex,cex.lab=inter_cex,xlim=c(0,1.1*max(survival_data$survival)),bty="n",xaxs="i",yaxs="i",ylim=c(0,1.35))
axis(side=2,at=c(0,0.2,0.4,0.6,0.8,1),tick=T,cex.axis=min_cex,xaxs="i",yaxs="i")
ats <- c(nb_days_before - rev(2*c(1:floor(nb_days_before/2))),nb_days_before+2*c(0:ceiling((max(survival_data$survival)-nb_days_before)/2)))
labs <- ats-nb_days_before
if (!0 %in% ats){ats <- c(0,ats);labs <- c("",labs)}
axis(side=1,
at = ats
,
labels = labs
,
tick=T,cex.axis=min_cex
)
lines(survival_model_plot, mark.time=F,col=NA,yaxt="n",xaxt="n",lty=styles[status_names],lwd=widths[status_names],xlab="",cex.lab=inter_cex,cex.axis=min_cex,xlim=c(0,1.1*max(survival_data$survival)),bty="n",xaxs="i",yaxs="i")
strata <- levels(summary(survival_model_plot)$strata)
for (stratum in rev(strata)){
survival_values <- c(1,summary(survival_model_plot)$surv[summary(survival_model_plot)$strata==stratum])
time_values <- summary(survival_model_plot)$time[summary(survival_model_plot)$strata==stratum]
std_error_values <- c(0,summary(survival_model_plot)$std.err[summary(survival_model_plot)$strata==stratum])
last_y <- rev(summary(survival_model_plot)$surv[summary(survival_model_plot)$strata==stratum])[1]
y_lo <- survival_values-std_error_values
y_hi <- survival_values+std_error_values
xvalues <- c(0,rep(time_values,each=2),max(survival_model_plot$time)*(1+1/96))
yvalues <- rep(c(survival_values),each=2)
y_lovalues <- rep(y_lo,each=2)
y_hivalues <- rep(y_hi,each=2)
polygon(x=c(xvalues,rev(xvalues))
,
y=c(y_lovalues,rev(y_hivalues))
,
col=alpha(statuses_colours[gsub("focal_status=","",stratum)],0.2)
,
border=NA
)
lines(xvalues,yvalues, col=statuses_colours[gsub("focal_status=","",stratum)],lty=styles[gsub("focal_status=","",stratum)],lwd=widths[gsub("focal_status=","",stratum)])
}
legend("topright",xjust=1,yjust=1,legend=gsub("\\\nworkers"," ",gsub("\\\nforagers"," ",full_statuses_names[status_names])),pt.bg=alpha(statuses_colours[status_names],0.2),col=alpha(statuses_colours[status_names],0.2),bty='n',pch=15,lty=0,lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="white",cex=min_cex,title="Workers",y.intersp=1.2)
legend("topright",xjust=1,yjust=1,legend=gsub("\\\nworkers"," ",gsub("\\\nforagers"," ",full_statuses_names[status_names])),pt.bg=alpha(statuses_colours[status_names],0.2),col=statuses_colours[status_names],bty='n',pch=NA,lty=styles[status_names],lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="black",cex=min_cex,title="Workers",y.intersp=1.2)
treated_y <- surviplot$y[c(1)]
untreated_y <- surviplot$y[c(2)]
par(xpd=T)
if (p_exposure<0.06){
text(x= (break_point+3)+0.5*(max(survival_data$survival)-(break_point+3)),y=(0.55-1/20),labels=paste("HR=",hazard_exposure,sep=""),cex=min_cex,col="black")
if (p_exposure<0.05){
p_cex <- max_cex*1.1;adjust_line <- +0.00035; fonty <- 2
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
text(x=(break_point+3)+0.5*(max(survival_data$survival)-(break_point+3)),y=0.55+adjust_line,labels=gsub(" ","",paste(from_p_to_ptext(p_exposure),sep="")),cex=p_cex,font=fonty)
arrow_x <- nb_days_before
arrow_y0 <- 1
arrow_y1 <- 1.05
arrows(arrow_x,arrow_y1,arrow_x,arrow_y0+0.015,length=0.025,lwd=line_max,col=statuses_colours["pathogen"])
segments(x0=arrow_x,y0=0,y1=arrow_y0-0.005,lty=3,lwd=line_inter,col=statuses_colours["pathogen"])
par(lheight=.75)
mtext("pathogen\nexposure",side=3,las=3,at=nb_days_before,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col=statuses_colours["pathogen"])
par(lheight=1)
#####Now study that break point for untreated workers
####trying to appl y example from http://data.princeton.edu/wws509/stata/recidivismR.html
##We create an id variable
survival_data$id <- as.character(interaction(survival_data$colony,survival_data$tag))
##define breaks
breaks <- c(0,nb_days_before,nb_days_before+break_point,ceiling(max(survival_data$survival)/0.5)*0.5)
##now we use the pwefunction to create new dataset for piecewise
survival_datax <- pwe(survival_data,survival,censored_status,breaks)
survival_datax$interval = factor(survival_datax$interval,labels=levels(survival_datax$interval))
##We are now ready to fit a proportional hazards model with a piecewise exponential baseline where the hazard changes from year to year.
##We use the same model as Wooldridge(2002), involving ten predictors, all fixed covariates.
fit=glm(events~interval+offset(log(exposure)),data=survival_datax[which(survival_datax$focal_status=="untreated"),], family=poisson)
summary(fit)
coeffs <- summary(fit)$coefficients
b = coef(fit)
h = exp( b[1] + c(0,b[2:length(b)]) )
H = cumsum( diff(breaks)*h)
S = exp(-H)
arrow_x <- survival_model_plot_untreated$time[closest_match((nb_days_before+1),survival_model_plot_untreated$time)]
arrow_y0 <- survival_model_plot_untreated$surv[closest_match((nb_days_before+1),survival_model_plot_untreated$time)]
arrow_y1 <- 1.05
arrows(arrow_x,arrow_y1,arrow_x,arrow_y0+0.015,length=0.025,lwd=line_max,col="springgreen3")
segments(x0=arrow_x,y0=0,y1=arrow_y0-0.005,lty=3,lwd=line_inter,col="springgreen3")
par(lheight=.75)
mtext("time of load\nprediction",side=3,las=3,at=arrow_x,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col="springgreen3")
par(lheight=1)
arrow_x <- survival_model_plot_untreated$time[closest_match((nb_days_before+break_point),survival_model_plot_untreated$time)]
arrow_y0 <- survival_model_plot_untreated$surv[closest_match((nb_days_before+break_point),survival_model_plot_untreated$time)]
arrow_y1 <- 1.05
segments(x0=arrow_x,y0=0,y1=arrow_y0-0.005,lty=3,lwd=line_inter,col="red")
arrows(arrow_x,arrow_y1,arrow_x,arrow_y0+0.015,length=0.025,lwd=line_max,col="red")
par(lheight=.75)
mtext("increase\nin mortality\n(untreated)",side=3,las=3,at=arrow_x,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col="red")
par(lheight=1)
}
if (which_to_plot == "second_only"){
###plot 2: survival of untreated = f(predicted load)
#####start 1 day after treatment, once the predicted load is known
survival_data <- survival_data[survival_data$survival >=nb_days_before+1,]
survival_data$survival <- survival_data$survival-(nb_days_before+1)
survival_data <- survival_data[which(!is.na(survival_data$final_load)),]
#####and remove treated workers
survival_data <- survival_data[which(survival_data$focal_status=="untreated"),]
###prepare plot
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=survival_data)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+final_load+(1|colony),data=survival_data)
survival_model_plot <- survfit(Surv(time=survival,event=censored_status)~final_load,data=survival_data)
status_names <- gsub("final_load=","",unlist(strsplit(names(survival_model_plot$strata),split="\\."))[grepl("\\=",unlist(strsplit(names(survival_model_plot$strata),split="\\.")))])
p_load <- anova(model1,survival_model)["P(>|Chi|)"][2,"P(>|Chi|)"]
hazard_load <- sprintf("%.2f", exp(-printcoef_coxme(survival_model)["final_loadlow_predicted_load","coef"]))
if (which_to_plot=="all"){
xmin <- -0.1
}else{
xmin <- -0.5
}
surviplot <- plot(survival_model_plot, mark.time=F,col=alpha(statuses_colours[status_names],0),yaxt="n",xaxt="n",lty=styles[status_names],lwd=widths[status_names],ylab="Proportion surviving",xlab="Days after treatment",cex.axis=min_cex,cex.lab=inter_cex,xlim=c(xmin,1+1.1*max(survival_data$survival)),bty="n",xaxs="i",yaxs="i",ylim=c(0.85,1.0525))
axis(side=2,at=c(0.85,0.9,0.95,1),tick=T,cex.axis=min_cex,xaxs="i",yaxs="i")
ats <- 1+c(2*c(0:(floor((max(survival_data$survival)-1)/2))));
ats <- c(ats,max(ats)+2)
labs <- ats+1;
if (!xmin %in% ats){ats <- c(xmin,ats);labs <- c("",labs)}
axis(side=1,
at = ats
,
labels = labs
,
tick=T,cex.axis=min_cex
)
lines(survival_model_plot, mark.time=F,col=NA,yaxt="n",xaxt="n",lty=styles[status_names],lwd=widths[status_names],xlab="",cex.lab=inter_cex,cex.axis=min_cex,xlim=c(0,1.1*max(survival_data$survival)),bty="n",xaxs="i",yaxs="i")
strata <- levels(summary(survival_model_plot)$strata)
for (stratum in rev(strata)){
survival_values <- c(1,summary(survival_model_plot)$surv[summary(survival_model_plot)$strata==stratum])
time_values <- summary(survival_model_plot)$time[summary(survival_model_plot)$strata==stratum]
std_error_values <- c(0,summary(survival_model_plot)$std.err[summary(survival_model_plot)$strata==stratum])
last_y <- rev(summary(survival_model_plot)$surv[summary(survival_model_plot)$strata==stratum])[1]
y_lo <- survival_values-std_error_values
y_hi <- survival_values+std_error_values
xvalues <- c(0,rep(time_values,each=2),max(survival_model_plot$time)*(1+1/96))
yvalues <- rep(c(survival_values),each=2)
y_lovalues <- rep(y_lo,each=2)
y_hivalues <- rep(y_hi,each=2)
polygon(x=c(xvalues,rev(xvalues))
,
y=c(y_lovalues,rev(y_hivalues))
,
col=alpha(statuses_colours[gsub("final_load=","",stratum)],0.2)
,
border=NA
)
lines(xvalues,yvalues, col=statuses_colours[gsub("final_load=","",stratum)],lty=styles[gsub("final_load=","",stratum)],lwd=widths[gsub("final_load=","",stratum)])
}
legend("topright",xjust=1,yjust=1,legend=gsub(" predicted"," simulated",full_statuses_names[status_names]),pt.bg=alpha(statuses_colours[status_names],0.2),col=alpha(statuses_colours[status_names],0.2),bty='n',pch=15,lty=0,lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="white",cex=min_cex,title="Untreated workers",y.intersp=1.1)
legend("topright",xjust=1,yjust=1,legend=gsub(" predicted"," simulated",full_statuses_names[status_names]),pt.bg=alpha(statuses_colours[status_names],0.2),col=statuses_colours[status_names],bty='n',pch=NA,lty=styles[status_names],lwd=widths[status_names],pt.lwd=1,pt.cex=2,text.col="black",cex=min_cex,title="Untreated workers",y.intersp=1.1)
treated_y <- surviplot$y[c(1)]
untreated_y <- surviplot$y[c(2)]
arrow_x <- 0
arrow_y0 <- 1
arrow_y1 <- 1.0075
arrows(arrow_x,arrow_y0+0.03,arrow_x,arrow_y0+0.00225,length=0.05,lwd=line_max,col="springgreen3")
segments(x0=arrow_x,y0=0.85,y1=arrow_y0-0.00075,lty=3,lwd=line_inter,col="springgreen3")
if (which_to_plot=="all"){
mtext("time of load\nprediction",side=3,las=3,at=arrow_x,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col="springgreen3")
}
arrow_x <- survival_model_plot_untreated$time[closest_match((break_point-1),survival_model_plot_untreated$time)]
arrow_y0 <- survival_model_plot_untreated$surv[closest_match((break_point-1),survival_model_plot_untreated$time)]
arrow_y1 <- 1.0075
arrows(arrow_x,arrow_y0+0.03,arrow_x,arrow_y0+0.00225,length=0.05,lwd=line_max,col="red")
segments(x0=arrow_x,y0=0.85,y1=arrow_y0-0.00075,lty=3,lwd=line_inter,col="red")
if (which_to_plot=="all"){
mtext("increase\nin mortality\n(untreated)",side=3,las=3,at=arrow_x,line=-1.75,cex=par('cex')*inter_cex,adj=0.5,col="red")
}
####comparison of survival before break point
subsett <- survival_data[which(!is.na(survival_data$tag)&survival_data$focal_status=="untreated"),]
subsett[which(subsett$survival>=(break_point-1)),"censored_status"] <- 0
subsett[which(subsett$survival>=(break_point-1)),"survival"] <- break_point-1
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=subsett)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+final_load+(1|colony),data=subsett)
print("Between load prediction and inflexion")
print(anova(model1,survival_model))
p_before_break <- anova(model1,survival_model)["P(>|Chi|)"][2,"P(>|Chi|)"]
hazard_before_break <- sprintf("%.2f", exp(-printcoef_coxme(survival_model)["final_loadlow_predicted_load","coef"]))
####comparison of survival after break point
print("Between inflexion and end")
subsett <- survival_data[which(!is.na(survival_data$tag)&survival_data$focal_status=="untreated"),]
subsett <- subsett[which(subsett$survival>(break_point-1)),]
subsett$survival <- subsett$survival-(break_point-1)
model1 <- coxme(Surv(time=survival,event=censored_status)~1+(1|colony),data=subsett)
survival_model <- coxme(Surv(time=survival,event=censored_status)~1+final_load+(1|colony),data=subsett)
print( anova(model1,survival_model))
p_after_break <- anova(model1,survival_model)["P(>|Chi|)"][2,"P(>|Chi|)"]
hazard_after_break <- sprintf("%.2f", exp(-printcoef_coxme(survival_model)["final_loadlow_predicted_load","coef"]))
if (p_before_break<0.05){
text(x=0.5*(break_point-1),y=0.87,labels=paste("HR=",hazard_before_break,sep=""),cex=min_cex,col="black")
p_cex <- max_cex*1.1;adjust_line <- +0.00035; fonty <- 2
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
text(x=0.5*(break_point-1),y=0.88+adjust_line,labels=gsub(" ","",paste(from_p_to_ptext(p_before_break),sep="")),cex=p_cex,font=fonty)
if (p_after_break<0.05){
text(x= (break_point-1)+0.5*(max(survival_data$survival)-(break_point-1)),y=0.87,labels=paste("HR=",hazard_after_break,sep=""),cex=min_cex,col="black")
p_cex <- max_cex*1.1;adjust_line <- +0.00035; fonty <- 2
}else{
p_cex <- inter_cex;adjust_line <- 0;fonty <- 1
}
text(x=(break_point-1)+0.5*(max(survival_data$survival)-(break_point-1)),y=0.88+adjust_line,labels=gsub(" ","",paste(from_p_to_ptext(p_after_break),sep="")),cex=p_cex,font=fonty)
}
if (which_to_plot == "detailed"){
#####start 1 day after treatment, once the predicted load is known
survival_data <- survival_data[survival_data$survival >=nb_days_before+1,]
survival_data$survival <- survival_data$survival-(nb_days_before+1)
survival_data <- survival_data[which(!is.na(survival_data$final_load)),]
#####and remove treated workers
survival_data <- survival_data[which(survival_data$focal_status=="untreated"),]
#####and remove queen
survival_data <- survival_data[which(survival_data$tag!=queenid),]
#########create new tables that have limited data
survival_data_nurses <- survival_data[which(survival_data$task_group=="nurse"),]
survival_data_foragers <- survival_data[which(survival_data$task_group=="forager"),]
survival_data_low_contact_with_treated <- survival_data[which(survival_data$frequency_contact_with_treated=="low"),]
survival_data_medium_contact_with_treated <- survival_data[which(survival_data$frequency_contact_with_treated=="medium"),]
survival_data_high_contact_with_treated <- survival_data[which(survival_data$frequency_contact_with_treated=="high"),]
####Plot 1: survival = f(task_group)
plotty( data_table=survival_data[!is.na(survival_data$task_group),], variable="task_group",survimin=0.75,legend_title="Untreated workers")
####Plot 2: survival=f(load), nurses
plotty( data_table=survival_data_nurses, variable="final_load",survimin=0.75,legend_title="Nurses")
####Plot 3: survival=f(load), low contacts
plotty( data_table=survival_data_low_contact_with_treated, variable="final_load",survimin=0.75,legend_title="Low contact with treated")
}
par(mar=par_mar_ori)
}
test_norm <- function(resids){
print("Testing normality")
if (length(resids)<=300){
print("Fewer than 300 data points so performing Shapiro-Wilk's test")
print(shapiro.test(resids))
}else{
print("More than 300 data points so using the skewness and kurtosis approach")
print("Skewness should be between -3 and +3 (best around zero")
print(skewness(resids))
print("")
print("Excess kurtosis (i.e. absolute kurtosis -3) should be less than 4; ideally around zero")
print(kurtosis(resids))
}
}
transform_dataset <- function(dataset,cut=T,predictor,form_stat,excluded){
combis <- unique(dataset[c("colony","time_hours","time_of_day")],stringsAsFactors=F); combis$time_of_day <- as.numeric(as.character(combis$time_of_day));
if (0 %in%combis$time_hours){
combis <- combis[which(combis$time_hours==0),]
}else{
combis <- combis[which(combis$time_hours==-24),]
}
######1/ get most frequent starting time
time_ori <- aggregate (colony~time_of_day,FUN=length,data=combis);time_ori <- as.numeric(as.character(time_ori[which(time_ori$colony==max(time_ori$colony,na.rm=T)),"time_of_day"]))
######2/ for colonies that started before, cut beginning - if only one day kept
if(cut){
if (kept_days==1){
lows <- combis[combis$time_of_day<time_ori,"colony"]
if (length(lows)>0){
for (coli in lows){
to_cut <- (combis[combis$colony==coli,"time_of_day"]):(time_ori-1)
dataset[which((dataset$colony==coli)&(dataset$time=="After")&(dataset$time_of_day%in%to_cut)),"variable"] <- NA
}
}
######3/ for colonies that started after, cut
highs <- combis[combis$time_of_day>time_ori,"colony"]
if (length(highs)>0){
for (coli in highs){
to_cut <- ((time_ori):(combis[combis$colony==coli,"time_of_day"]-1))
dataset[which((dataset$colony==coli)&(dataset$time=="After")&(dataset$time_of_day%in%to_cut)),"variable"] <- NA
}
}
}#kept_days
}
dataset["time_of_day_bis"] <- as.numeric(as.character(dataset$time_of_day))-time_ori
dataset$time_of_day_bis[dataset$time_of_day_bis<0] <- dataset$time_of_day_bis[dataset$time_of_day_bis<0] + 24
form_stat <- update(form_stat,.~.-(1|time_of_day)+(1|time_of_day_bis))
if (!is.null(excluded)){
combis["offset"] <- combis$time_of_day-time_ori
excluded <- merge(excluded,combis[c("colony","offset")])
excluded$time_of_day <- as.numeric(as.character(excluded$time_of_day))
excluded$time_of_day <- excluded$time_of_day - excluded$offset
excluded["time_of_day_bis"] <- excluded$time_of_day - time_ori
}
return(list(dataset=dataset,form_stat=form_stat,excluded=excluded))
}
VioPlot <- function (x, ..., range = 1.5, h = NULL, ylim = NULL, names = NULL,
horizontal = FALSE, col = "magenta", border = "black", lty = 1,
lwd = 1, rectCol = "black", colMed = "black", pchMed = 21, bgMed = "white",
at, add = FALSE, wex = 1, drawRect = TRUE, mode="Median",cexMed=min_cex){
datas <- list(x, ...)
n <- length(datas)
if (missing(at)){
at <- 1:n
}
std_low <- vector(mode = "numeric", length = n)
std_high <- vector(mode = "numeric", length = n)
upper <- vector(mode = "numeric", length = n)
lower <- vector(mode = "numeric", length = n)
q1 <- vector(mode = "numeric", length = n)
q3 <- vector(mode = "numeric", length = n)
med <- vector(mode = "numeric", length = n)
meaN <- vector(mode = "numeric", length = n)
base <- vector(mode = "list", length = n)
height <- vector(mode = "list", length = n)
baserange <- c(Inf, -Inf)
args <- list(display = "none")
if (!(is.null(h))){
args <- c(args, h = h)
}
for (i in 1:n) {
data <- datas[[i]]
data.min <- min(data)
data.max <- max(data)
q1[i] <- quantile(data, 0.25)
q3[i] <- quantile(data, 0.75)
med[i] <- median(data)
meaN[i] <- mean(data)
std <- std.error(data)
std_low[i] <- meaN[i]-std
std_high[i] <- meaN[i]+std
iqd <- q3[i] - q1[i]
upper[i] <- min(q3[i] + range * iqd, data.max)
lower[i] <- max(q1[i] - range * iqd, data.min)
est.xlim <- c(min(lower[i], data.min), max(upper[i],
data.max))
smout <- do.call("sm.density", c(list(data, xlim = est.xlim),
args))
hscale <- 0.4/max(smout$estimate) * wex
base[[i]] <- smout$eval.points
height[[i]] <- smout$estimate * hscale
t <- range(base[[i]])
baserange[1] <- min(baserange[1], t[1])
baserange[2] <- max(baserange[2], t[2])
}
if (!add) {
xlim <- if (n == 1)
at + c(-0.5, 0.5)
else range(at) + min(diff(at))/2 * c(-1, 1)
if (is.null(ylim)) {
ylim <- baserange
}
}
if (is.null(names)) {
label <- 1:n
}
else {
label <- names
}
boxwidth <- 0.05 * wex
if (!add)
plot.new()
if (!horizontal) {
if (!add) {
plot.window(xlim = xlim, ylim = ylim)
axis(2)
axis(1, at = at, label = label)
}
box()
for (i in 1:n) {
polygon(c(at[i] - height[[i]], rev(at[i] + height[[i]])),
c(base[[i]], rev(base[[i]])), col = col, border = border,
lty = lty, lwd = lwd)
if (drawRect) {
if (mode=="Median"){
lines(at[c(i, i)], c(lower[i], upper[i]), lwd = lwd,
lty = lty)
rect(at[i] - boxwidth/2, q1[i], at[i] + boxwidth/2,
q3[i], col = rectCol)
points(at[i], med[i], pch = pchMed, col = colMed, bg=bgMed, cex=cexMed)
}else if (mode=="Mean"){
# rect(at[i] - boxwidth/2, std_low[i], at[i] + boxwidth/2,
# std_high[i], col = rectCol)
plot_arrows(means=data.frame(mean=meaN[i],se=std),plotx=at[i],plot_type="violinplot",LWD=line_max,LENGTH=0.05,colz="black")
points(at[i], meaN[i], pch = pchMed, col = colMed, bg=bgMed, cex=cexMed)
}
}
}
}
else {
if (!add) {
plot.window(xlim = ylim, ylim = xlim)
axis(1)
axis(2, at = at, label = label)
}
box()
for (i in 1:n) {
polygon(c(base[[i]], rev(base[[i]])), c(at[i] - height[[i]],
rev(at[i] + height[[i]])), col = col, border = border,
lty = lty, lwd = lwd)
if (drawRect) {
lines(c(lower[i], upper[i]), at[c(i, i)], lwd = lwd,
lty = lty)
rect(q1[i], at[i] - boxwidth/2, q3[i], at[i] +
boxwidth/2, col = rectCol)
points(med[i], at[i], pch = pchMed, col = colMed)
}
}
}
invisible(list(upper = upper, lower = lower, median = med,
q1 = q1, q3 = q3))
}<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/18_process_heatmaps.R
####18_process_heatmaps.R#####
#### Takes heatmaps as an input, and calculates the part of the ant's home range that is included within in nest,
#### the distance between the ant's center of gravity and the center of gravity of the untreated ants,
#### and the degree of spatial overlap between the ant's space use and the brood pile
###Created by <NAME>###
#################################
to_keep_ori <- to_keep
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
#######get heatmap list
input_heatmaps <- paste(data_path,"/intermediary_analysis_steps/heatmaps/individual",sep="")
setwd(input_heatmaps)
folder_list <- dir()
full_heatmap_list <- paste(input_heatmaps,list.files(recursive=T,pattern="ant"),sep="/")
#######get group heatmap list
input_group_heatmaps <- paste(data_path,"/intermediary_analysis_steps/heatmaps/group",sep="")
setwd(input_group_heatmaps)
full_group_heatmap_list <- paste(input_group_heatmaps,list.files(recursive=T,pattern="untreated"),sep="/")
#######get brood location list
input_brood <- paste(data_path,"/original_data/brood_coordinates",sep="")
setwd(input_brood)
full_brood_list <- paste(input_brood,list.files(recursive=T,pattern="brood"),sep="/")
#####Read behaviour file
behav <- read.table(paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""),header=T,stringsAsFactors = F)
#####Create new columns
if (!"within_nest_home_range"%in%names(behav)){
behav[c("within_nest_home_range","distance_antCoG_to_colonyCoG","BA_between_ant_and_brood")] <- NA
}
for (input_folder in folder_list){
print(input_folder)
heatmap_list <- data.frame(file=full_heatmap_list[grepl(input_folder,full_heatmap_list)],stringsAsFactors = F)
for (i in 1:nrow(heatmap_list)){
time_info <- paste(unlist(strsplit(heatmap_list[i,"file"],split="_"))[grepl("TD",unlist(strsplit(heatmap_list[i,"file"],split="_")))|grepl("TH",unlist(strsplit(heatmap_list[i,"file"],split="_")))],collapse="_")
heatmap_list[i,"time_info"] <- time_info
}
whens <- unique(heatmap_list$time_info)###get the list of time bins
for (when in whens){
print(when)
####CALCULATE UNTREATED COG POSITION for that time
reference_untreated <- full_group_heatmap_list[which((grepl(input_folder,full_group_heatmap_list))&(grepl(when,full_group_heatmap_list)))]
t_untreated <- read.table(reference_untreated, sep=",")
centroid_untreated <- data.frame(x=sum(t_untreated[,1]*t_untreated[,3])/sum(t_untreated[,3]),y=sum(t_untreated[,2]*t_untreated[,3])/sum(t_untreated[,3]))
####READ BROOD HEATMAP for that time
reference_brood <- full_brood_list[which((grepl(input_folder,full_brood_list))&(grepl(when,full_brood_list)))]
t_brood <- read.table(reference_brood,header=T,stringsAsFactors = F)
t_brood <- data.frame(X=t_brood$X,Y=t_brood$Y,obs=1)
#######modify t_brood; indeed heatmaps and nest entrance position were calculated using cells of 5*5 pixels whereas t_brood currently holds the real coordinates in pixels
t_brood$X <- floor(t_brood$X/5)
t_brood$Y <- floor(t_brood$Y/5)
observations_brood <- aggregate(obs~X+Y,FUN=sum,data=t_brood)
locations_brood <- NULL
if (nrow(observations_brood)>0){
for (value in unique(observations_brood[,3])){
subset <- observations_brood[observations_brood[,3]==value,1:2]
locations_brood <- rbind( locations_brood,data.frame(X=rep(subset[,1],value),Y=rep(subset[,2],value)))
}
}
heatmap_files <- heatmap_list[which(heatmap_list$time_info==when),"file"]
to_keep <- c(ls(),"to_keep","heatmap","customised_grid_all")
for (heatmap in heatmap_files){
####get metadata
colony_metadata <- unlist(strsplit(heatmap,split="/"))[grepl("colony", unlist(strsplit(heatmap,split="/")))]
colony <- unlist(strsplit(colony_metadata,split="_"))[grepl("colony",unlist(strsplit(colony_metadata,split="_")))]
colony_number <- as.numeric(gsub("colony","",colony))
treatment <- info[which(info$colony==colony_number),"treatment"]
colony_size <- info[which(info$colony==colony_number),"colony_size"]
source(paste(code_path,"/heatmap_to_homerange_parameters.R",sep=""))
time_point <- unlist(strsplit(colony_metadata,split="_"))[grepl("Treatment",unlist(strsplit(colony_metadata,split="_")))]
if (time_point=="PreTreatment"){period <- "before"}else{period <- "after"}
ant_metadata <- unlist(strsplit(heatmap,split="/"))[grepl("txt", unlist(strsplit(heatmap,split="/")))]
ant_metadata <- unlist(strsplit(ant_metadata,split="_"))
tag <- as.numeric(gsub("ant","",ant_metadata[grepl("ant",ant_metadata)&!grepl("txt",ant_metadata)]))
time_of_day <- as.numeric(gsub("TD","",ant_metadata[grepl("TD",ant_metadata)]))
time_hours <- as.numeric(gsub("TH","",ant_metadata[grepl("TH",ant_metadata)]))
#####Check if whether ant has already been processed, and do the rest only if it is the case
if (is.na(behav[which(behav$colony==colony&behav$tag==tag&behav$time_hours==time_hours),"distance_antCoG_to_colonyCoG"])){
print(paste("Analysing ",heatmap))
####read heatmap
t <- read.table(heatmap, sep=",")####read heatmap output file
###define grid (to do only the first time)
if (!exists("customised_grid_all")){
for_grid <- t[,1:2]###list of all x-y coordinates of the plot (each existing cell (even unvisited, empty cells) defined on 1 line by its x,y coordinates)
names(for_grid) <- c("x","y")
customised_grid_all <- (unique(round(for_grid/grid_parameter)))*grid_parameter
coordinates(customised_grid_all)=c("x","y")
gridded(customised_grid_all) <- TRUE
}
###use to t to make a location matrix
observations <- t[t[,3]!=0,]
locations <- NULL
if (nrow(observations)>0){
count <- 0
for (value in unique(observations[,3])){
count <- count + 1
subset <- observations[observations[,3]==value,1:2]
locations <- rbind(locations,data.frame(X=rep(subset[,1],value),Y=rep(subset[,2],value)))
}
}
####STEP 1 - calculate part of home range located within the nest
if (nrow(locations)>5){
locations_sp <- SpatialPoints(locations)
bandwidth <- kernelUD(locations_sp, h="href",grid=customised_grid_all,extent=0)@h$h###get bandwidth (without bounder - because there is a bug when using bounder and href)
if (exists("kud")){rm(list=c("kud"))}
try(kud <- kernelUD(locations_sp, h=bandwidth,boundary=bounder_all,grid=customised_grid_all,extent=0),silent=T)###calculate utilization distribution with border definition
if (exists("nest_home_range")){rm(list=c("nest_home_range"))}
if (exists("kud")){
if(exists("vud")){rm(list=c("vud"))}
try(vud <- getvolumeUD(kud,standardize=T),silent=T)
if(exists("vud")){
hr <- as.data.frame(vud)[,1]
hrtemp <- data.frame(as.numeric(hr <= 95))
coordinates(hrtemp) <- coordinates(vud)
hrnest <- hrtemp[( hrtemp@coords[,2]>=ynestmin)&( hrtemp@coords[,2]<=ynestmax),]
nest_home_range <- grid_parameter*grid_parameter*sum(hrnest@data)
rm(list=c("hrnest"))
}
}
if (exists("nest_home_range")){nest_home_range <- nest_home_range *5*5}else{nest_home_range <- NA} #####this corresponds to an are in (pixels)^2
}else{
nest_home_range <- 0
}
####STEP 2 - calculate CoG location and overlap with brood
###############Centroid location
centroid <- data.frame(x=mean(locations$X),y=mean(locations$Y))
distance_to_colony <- euc.dist(centroid,centroid_untreated) #####this corresponds to a distance in 5*pixels
distance_to_colony <- distance_to_colony * 5 ##### this corresponds to a distance in real pixels
###############Overlap with brood
####make a multi-animal spatial points
dataset <- rbind(data.frame(Name="focal_ant",locations,stringsAsFactors = F),data.frame(Name="brood",locations_brood,stringsAsFactors = F))
dataset$Name <- factor(dataset$Name)
SPDF <- SpatialPointsDataFrame(rbind(locations,locations_brood), dataset)
####calculate the utilization distributions with border definition
if(exists("uds")){rm(list=("uds"))}
try(uds <- kernelUD(SPDF[,1], h=fixed_bandwidth, grid=customised_grid_all, boundary=bounder_all, extent=0),silent=T)
if (exists("uds")){
####calculate overlap using Bhattacharyya's Affinity method
nrows <- uds[[1]]@grid@cells.dim[2]
ncols <- uds[[1]]@grid@cells.dim[1]
densit_m_list <- list()
for (r in 1:length(uds)){
####extract data
densit <- data.frame(X=uds[[r]]@coords[,1],Y=uds[[r]]@coords[,2],ud=uds[[r]]@data) ## pixels denote density
####reorder
densit <- densit[order(densit$X,densit$Y),]
densit_m <-t( matrix( (densit$ud/sum(densit$ud)) , ncol=ncols , nrow=nrows, byrow = F) )
densit_m_list[[r]] <- densit_m ## UPSIDE DOWN IMAGE
}
overlap_map <- matrix (ncol=nrows,nrow=ncols)
for (e in 1:ncols){ ## for each row of the distance map image matrix
for (f in 1:nrows){ ## for each column of the distance map image matrix
## for each pixel, find the min 'height' for the pair of ants.
overlap_map[e,f] <- sqrt(densit_m_list[[1]][e,f]) * sqrt(densit_m_list[[2]][e,f])
}#f
}#e
overlap <- sum(overlap_map)
}else{
overlap <- NA
}
####Now add data to behaviour file
behav[which(behav$colony==colony&behav$tag==tag&behav$time_hours==time_hours),c("within_nest_home_range","distance_antCoG_to_colonyCoG","BA_between_ant_and_brood")] <- c(nest_home_range,distance_to_colony,overlap)
}
clean()
}
options(digits=3)
write.table(behav,file=paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""), row.names=F, col.names=T,append=F,quote=F)
rm(list=c("reference_untreated","t_untreated","centroid_untreated","reference_brood","t_brood","observations_brood","locations_brood"))
}
rm(list=c("heatmap_list","when"))
}
to_keep <- to_keep_ori<file_sep>/data_prep_scripts/import_guppy_networks.py
"""
Import guppy association networks that are cleaned into a newtowkxobject, and the node attributes
associated with the other files.
By: <NAME> 09Jan21
There are 16 groups of high risk and low risk each.
Imported file filetype is a dictionary, one key for high risk, low risk, and a list for all the groups within each risk
group.
all_networks = {
low_risk: [net, net, net, ...],
high_risk: [net, net, net, ...]
}
"""
import os
import pandas as pd
import networkx as nx
def import_individual_data():
"""Import individual data from 'Individual Level Data.csv' from the
repository.
Returns:
Pandas DataFreame: Pandas Dataframe, in the same format as the original file.
"""
filepath = os.path.join("data", "guppies", "Individual Level Data.csv")
guppy_ind = pd.read_csv(filepath)
return guppy_ind
# NOTE: Deprecated, replaced the filetype.
# def import_assoc_networks():
# """Import clean association networks as networkx graph object. All graphs
# are in a dictionary.
# Returns:
# dict: Each key is 'high_risk' and 'low_risk' which maps to a list of networkx
# Graph objects. Each list should be 16 graphs long.
# """
# # Parent dir of the clean network edgelist files.
# parent_dir = os.path.join("data", "guppies", "reformatted_networks")
# all_nets = os.listdir(parent_dir)
# # Dictionary has two groups
# guppy_networks = {
# 'low_risk': [None] * 16,
# 'high_risk' : [None] * 16
# }
# # Iterate though all the edgelist files in the parent directory
# for n in all_nets:
# n_split = n.split("_")
# # Group Number (1-16), Index is Group Number - 1, (because of 0 indexing)
# group_n = int(n_split[1]) - 1
# group_risk = "{}_{}".format(n_split[2], n_split[3])
# # Read in file
# guppy_edgelist = pd.read_csv(os.path.join(parent_dir, n))
# # Convert to Networkx from directory.
# guppy_networks[group_risk][group_n] = nx.convert_matrix.from_pandas_edgelist(
# guppy_edgelist, source = "guppy1", target = 'guppy2', edge_attr=True)
# return guppy_networks
def import_assoc_networks():
"""Import clean association networks as networkx graph object. All graphs
are in a dictionary.
Returns:
dict: Each key is 'high_risk' and 'low_risk' which maps to a list of networkx
Graph objects. Each list should be 16 graphs long.
"""
# Parent dir of the clean network edgelist files.
file_path = os.path.join("data", "guppies", "reformatted_guppy_networks.csv")
# all_nets = os.listdir(parent_dir)
# Dictionary has two groups
guppy_networks = {
'low_risk': [None] * 16,
'high_risk' : [None] * 16
}
df = pd.read_csv(file_path)
# Iterate through group number and risk.
for r in df['risk'].unique():
for g in df['group'].unique():
df_subset = df.loc[(df['risk'] == r) & (df['group'] == g)]
guppy_networks[r][g - 1] = nx.convert_matrix.from_pandas_edgelist(
df_subset, source = "guppy1", target = "guppy2", edge_attr= True
)
return guppy_networks
def import_assoc_networks_w_attrs():
"""Import the associations from the clean files, and add on the node attributes.
Returns:
dict: Dictionary as returned by import_assoc_networks() but wth node attributes.
"""
nets_no_attr = import_assoc_networks()
nets_w_attr = append_guppy_ind_attr(nets_no_attr)
return nets_w_attr
def append_guppy_ind_attr(all_networks):
"""Add node attributes for the guppy association networks, from the
'Individual Level Data.csv' file.
NOTE: Only include IndividualID and body length, but easy to add more.
Args:
all_networks (dict): Dictionary containing list of networks as returned by import_assoc_networks()
Returns:
dict: Same format as passed parameter except nodes now have attributes.
"""
ind_data = import_individual_data()
for risk in all_networks:
risk_label = "H" if risk == "high_risk" else "L"
for n_idx, n in enumerate(all_networks[risk]):
n_attrs = {}
for node in n.nodes():
ind_id = "{}{}{}".format(risk_label, n_idx + 1, node)
ind_length = ind_data.loc[ind_data['IndividualID'] == ind_id, 'Length_cm'].values[0]
n_attrs[node] = {'ID' : ind_id, 'length': ind_length}
nx.set_node_attributes(n, n_attrs)
return all_networks
if __name__ == "__main__":
# import_individual_data()
# import_assoc_networks()
import_assoc_networks_w_attrs()<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/functions_and_parameters.R
clean <- function(){
rm(list=ls(envir = .GlobalEnv)[!ls(envir = .GlobalEnv)%in%to_keep], envir = .GlobalEnv)
no_print <- gc(verbose=F)
Sys.sleep(1)
}
closest_match <- function(x,y){
return(min(which(abs(x-y)==min(abs(x-y))),na.rm=T))
}
read.tag <- function(tagfile){
tag <- read.table(tagfile,sep=",",comment.char="%",as.is=TRUE,fill=TRUE,stringsAsFactors=F)
##find out in which line the names are contained
index_names <- match("#tag",tag[,1])
##remove the stuff above
if (index_names > 1){
header_part <- tag[1:(index_names-1),]
tag <- data.frame(tag[index_names:nrow(tag),])
}
##in case there was a problem with the reading, fix it
if (ncol(tag)==1){
ncols <- min(which(!is.na(as.numeric(as.character(tag[,1]))))) -1
new_tag <- {}
for (line in 1:(nrow(tag)/ncols)){
new_tag <- rbind(new_tag,as.character(tag[(((line - 1) *ncols) +1 ):(((line - 1) *ncols) + ncols ),]))
}
tag <- data.frame(new_tag,stringsAsFactors=FALSE)
}
##update the line in which the names are contained
index_names <- match("#tag",tag[,1])
##get name list
original_name_list <- as.character(tag[index_names,])
names(tag) <- original_name_list
return(list(tag=tag,header_part=header_part))
}
high_threshold <- 0.0411
info <- read.table(paste(data_path,"/original_data/info.txt",sep=""),header=T,stringsAsFactors = F)
treated <- read.table(paste(data_path,"/original_data/treated_worker_list.txt",sep=""),header=T,stringsAsFactors = F)
task_groups <- read.table(paste(data_path,"original_data/task_groups.txt",sep="/"),header=T,stringsAsFactors = F)
if (grepl("age",data_path)){
ages <- read.table(paste(data_path,"original_data","ant_ages.txt",sep="/"),header=T,stringsAsFactors = F)
}
if(file.exists(paste(data_path,"/original_data/info_dat.txt",sep=""))){
info_datfile <- read.table(paste(data_path,"/original_data/info_dat.txt",sep=""),header=T,stringsAsFactors = F)
info_plume <- read.table(paste(data_path,"/original_data/info_plume.txt",sep=""),header=T,stringsAsFactors = F)
}
#### get time_aggregation_list
if (!grepl("survival",data_path)){
input_aggregation_info <- paste(data_path,"original_data/time_aggregation_info",sep="/")
setwd(input_aggregation_info)
split_list <- paste(input_aggregation_info,list.files(pattern="txt"),sep="/")
}
####get tag list #####
input_tag <- paste(data_path,"original_data/tag_files",sep="/")
setwd(input_tag)
tag_list <- paste(input_tag,list.files(pattern="tags"),sep="/")
queenid <- 665
<file_sep>/clustering_class/exploratory.py
import vis_params
from matplotlib import pyplot
from sklearn import cluster, linear_model
import numpy as np
import pandas
from mpl_toolkits import mplot3d
def summarize(metadata,cluster_labels):
animal_list = np.unique(metadata['animal'].values)
animal_counts = {k:sum(metadata['animal']==k) for k in animal_list}
clusters = np.array(list(cluster_labels.keys()))
cluster_sizes = [len(cluster_labels[c]) for c in clusters]
presentation_order = np.argsort(cluster_sizes)[::-1]
clusters = clusters[ presentation_order ]
for k in clusters:
v = cluster_labels[k]
#
print('Cluster %s (n=%i)'%(str(k),len(v)))
print('================')
subs = metadata['animal'].iloc[v].values
subs_unique = np.unique(subs)
cluster_belong = np.zeros(len(subs_unique))
rel_belong = np.zeros(len(subs_unique))
# print(len(subs_unique))
for j,s in enumerate(subs_unique):
cluster_belong[j] = sum(subs==s)/len(v)
rel_belong[j] = sum(subs==s)/animal_counts[s]
#
ord = np.argsort(cluster_belong)
ord = ord[::-1] # decreasing order
for o in ord:
# print(subs_unique[o],type(subs_unique[o]))
# print(cluster_belong[o],type(cluster_belong[o]))
# print(rel_belong[o],type(rel_belong[o]))
print('\t%s: %.2f%% of cluster \t %.2f%% of animal.'%(str(subs_unique[o]).ljust(15),100*cluster_belong[o],100*rel_belong[o]))
#
print('')
#
#
df = pandas.read_csv( vis_params.ANALYSIS_FOLDER + 'all_individual_results.csv')
data = df[['eigenvector_centrality', 'betweeness', 'degree']].values
meta = df[['animal','condition']]
data[data[:,1]==0,1] = 0.1*np.min(data[data[:,1]!=0,1])
data[:,1] = np.log10(data[:,1])
data[:,2] = np.log10(data[:,2])
#data = np.log10(data)
#
dbs = cluster.DBSCAN(eps=0.15)
cluster_labels = dbs.fit_predict(data)
classes = {k:np.where(cluster_labels==k)[0] for k in np.unique(cluster_labels)}
#
fig = pyplot.figure(constrained_layout=True, figsize=(8,8))
ax = fig.add_subplot( projection='3d' )
clusters = np.array(list(classes.keys()))
cluster_sizes = [len(classes[c]) for c in clusters]
presentation_order = np.argsort(cluster_sizes)[::-1]
clusters = clusters[ presentation_order ]
#for i,(k,v) in enumerate( classes.items() ):
for i,k in enumerate(clusters):
v = classes[k]
if k==-1:
continue
ax.scatter(data[v,0],data[v,1],data[v,2], c=[pyplot.cm.tab10(i%20)], label='Cluster %s'%str(k))
if i==9:
break
#
v = classes[-1]
ax.scatter(data[v,0],data[v,1],data[v,2], c=[[0.8,0.8,0.8,0.5]], label='Noise cluster')
ax.set_xlabel('e-vec centrality')
ax.set_ylabel(r'$\log_{10}$(betweenness)')
ax.set_zlabel(r'$\log_{10}$(degree)')
ax.legend(loc='upper left')
fig.savefig('individual_clustering_dbscan.png')
fig.show()
pyplot.ion()
summarize(meta,classes)
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/simulate_transmission.cpp
//to compile with option -std=c++11
using namespace std;
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
#include <math.h>
#include <vector>
#include <random>
#include <chrono>
int get_tag_index( vector <int> taglist, int tag){
int taglist_size (taglist.size());
int tested_tag(-1);int tag_index (-1);int idx (-1);
while (tested_tag!=tag){
idx = idx+1;
tested_tag = taglist[idx];
}
return(idx);
};
struct event{
double absolute_contamination_time;
double relative_contamination_time;
int tag;
int contaminated_by;
int nb_susceptible;
int nb_contaminated;
double initial_load;
double final_load;
bool infectious;
};
// [[Rcpp::export]]
DataFrame simulate_transmission(DataFrame i_table, DataFrame ant_list, double t0){
// Fixed input parameters
double attenuation = 0.00066;
double load_threshold = 0.00024;
double p_transm = 0.39;
//define variables from input
vector <int> taglist = ant_list["tag"];
vector <int> status = ant_list["status"];
vector <double> load = ant_list["load"];
int tag_count (taglist.size());
vector <int> Tag1 = i_table["Tag1"];
vector <int> Tag2 = i_table["Tag2"];
vector <int> Startframe = i_table["Startframe"];
vector <int> Stopframe = i_table["Stopframe"];
vector <double> Starttime = i_table["Starttime"];
vector <double> Stoptime = i_table["Stoptime"];
int table_size (Tag1.size());
//declare variables that will be used in the loop
double time;int index_source; int index_recipient;double proba_transfer; int transfer_duration;double random;double x0; double xtot; double amount_transferred;int frame_number;double threshold;
int index1; int index2; double load1; double load2;
// build random number generator
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();//set a seed linked with the time at which the program is runs; ensures random number sequence will always be differemt
std::default_random_engine generator (seed); //set the random number generator using the desited seed
std::uniform_real_distribution<double> distribution(0.0,1.0); //define that you want a uniform diestribution between 0 and 1
// // print parameter values
// cout << "attenuation = " << attenuation << "; load_threshold = " << load_threshold << "; p_transm = " << p_transm << endl;
/////////////////////////////////////////////////////////
//perform checks
/////////////////////////////////////////////////////////
// //print first 2 lines of i_table
// cout << "first line of interaction table: " << endl;
// cout << Tag1[0] << "," << Tag2[0] << "," << Startframe[0] << "," << Stopframe[0] << "," << Starttime[0] << "," << Stoptime[0] << endl;
// cout << "last line of interaction table: " << endl;
// cout << Tag1[table_size-1] << "," << Tag2[table_size-1] << "," << Startframe[table_size-1] << "," << Stopframe[table_size-1] << "," << Starttime[table_size-1] << "," << Stoptime[table_size-1] << endl;
//
// //checking if the get tag function works
// cout << "checking get_tag_index function" << endl;
// index1 = get_tag_index(taglist,Tag1[0]); index2 = get_tag_index(taglist,Tag2[0]);
// cout << "first line: tag1 = " << taglist[index1] << ", infection status = "<< status[index1] <<", load = "<< load[index1]
// << "; tag2 = " << taglist[index2] << ", infection status = "<< status[index2] <<", load = "<< load[index2] << endl;
// index1 = get_tag_index(taglist,Tag1[table_size-1]); index2 = get_tag_index(taglist,Tag2[table_size-1]);
// cout << "last line: tag1 = " << taglist[index1] << ", infection status = "<< status[index1] <<", load = "<< load[index1]
// << "; tag2 = " << taglist[index2] << ", infection status = "<< status[index2] <<", load = "<< load[index2] << endl;
/////////////////////////////////////////////////////////
//initialise ant counts
/////////////////////////////////////////////////////////
int contaminated(0);
int susceptible(0);
for (int t1 (0); t1<tag_count; t1++){
if (status[t1]==0){//untreated workers
susceptible=susceptible+1;
}
if (status[t1]==1){//treated workers
contaminated =contaminated+1;
}
}
// cout << "At the beginning: " << contaminated << " infected ants; " << susceptible << " susceptible ants." << endl;
/////////////////////////////////////////////////////////
// initialise contamination events table
/////////////////////////////////////////////////////////
vector<event> events;
for (int t1 (0); t1<tag_count; t1++){
if (status[t1]==1){//treated workers
event infection;
infection.absolute_contamination_time = t0;
infection.relative_contamination_time = 0;
infection.tag = taglist[t1];
infection.contaminated_by = -1;
infection.nb_susceptible = susceptible;
infection.nb_contaminated = contaminated;
infection.initial_load = 1;
infection.final_load = -1;
infection.infectious = 1;
events.push_back(infection);
}
}
/////////////////////////////////////////////////////////
// Loop over interactions
/////////////////////////////////////////////////////////
for (int i(0); i < table_size;i++){ //read all interaction lines
amount_transferred = 0;
//get frame number
frame_number = Startframe[i];
// get the tag index of each ant involved in the interaction
index1 = get_tag_index(taglist,Tag1[i]); index2 = get_tag_index(taglist,Tag2[i]);
// get the current load of each ant involved in the interaction
load1 = load[index1]; load2 = load[index2];
// comparison: only performs interaction trial if at least one ant is infectious; i.e. above the load_threshold; and the 2 ants have different load
if (((load1>=load_threshold)|(load2>=load_threshold))&&(load1!=load2)){
time = Starttime[i]; //get time of beginning of interactions
//determine which is the source ant and which is the recipient ant
if (load1>load2){
index_source=index1;
index_recipient=index2;
}else{
index_source=index2;
index_recipient=index1;
}
//stochastic transmission event:depending on the concentration of the source ant (the larger the amount of infectious propagules, the higher the probability of transfer)
// Define transmission threshold
threshold=p_transm*load[index_source];
// Draw a random number between 0 and 1
random = distribution(generator);
// Check if a stochastic transmission event should occur (i.e., if random < threshold); if so, perform the rest
if (random <= threshold){
// Determine the duration of the interaction in frames
transfer_duration = Stopframe[i] - Startframe[i] +1;
// Determine the amount transferred depending on the transfer duration
x0 = load[index_recipient];
xtot = x0 + load[index_source];
double amount_transferred = ((pow((1-2*attenuation),transfer_duration))*(x0-(xtot/2))+(xtot/2)) - x0;
// If recipient ant was NOT contaminated yet, add a new event to table events
if (status[index_recipient]!=1){
// update status so that ant is now listed as contaminated
status[index_recipient] = 1;
//update number of ants in each category
contaminated = contaminated + 1;
susceptible = susceptible -1 ;
//create infection event
event infection;
infection.absolute_contamination_time = time;
infection.relative_contamination_time = time - t0;
infection.tag = taglist[index_recipient];
infection.contaminated_by = taglist [index_source];
infection.nb_susceptible = susceptible;
infection.nb_contaminated = contaminated;
infection.initial_load = amount_transferred;
infection.final_load = -1;
if (infection.initial_load>=load_threshold){
infection.infectious =1;
}else{
infection.infectious =0;
}
events.push_back(infection);
}else{
// if ant was already contaminated, and if her current load is above load threshold, then retrieve event and declare her infectious
if ((load[index_recipient] + amount_transferred)>=load_threshold){//check if new load higher than threshold
// find index of the right line
for (int j(0); j< events.size(); j++){//for each line of the table
int tag(events[j].tag);//get tag of interest
if (tag==taglist[index_recipient]){
events[j].infectious =1;
}
}
}
}
//4/ in any case, update load vector with new load values
load[index_source] = load[index_source] -amount_transferred ;
load[index_recipient] = load[index_recipient] +amount_transferred ;
}
}
}//end of transmission loop
//Prepare dataframe columns for output
vector <double> absolute_contamination_time (events.size());
vector <double> relative_contamination_time (events.size());
vector <int> tags (events.size());
vector <int> contaminated_by (events.size());
vector <int> nb_susceptible (events.size());
vector <int> nb_contaminated (events.size());
vector <double> initial_load (events.size());
vector <double> final_load (events.size());
vector <bool> infectious (events.size());
//fill in final load column in events table as well as output columns
for (int j(0); j< events.size(); j++){//for each line of the table
//update final load in events
int tag(events[j].tag);//get tag of interest
int index = get_tag_index(taglist,tag);
events[j].final_load = load[index];
// fill in column
absolute_contamination_time [j]=events[j].absolute_contamination_time;
relative_contamination_time [j]=events[j].relative_contamination_time;
tags [j]=events[j].tag;
contaminated_by [j]=events[j].contaminated_by;
nb_susceptible [j]=events[j].nb_susceptible;
nb_contaminated [j]=events[j].nb_contaminated;
initial_load [j]=events[j].initial_load;
final_load [j]=events[j].final_load;
infectious [j]=events[j].infectious;
}
return DataFrame::create(_["absolute_contamination_time"]= absolute_contamination_time,
_["relative_contamination_time"]= relative_contamination_time,
_["tag"] = tags,
_["contaminated_by"] = contaminated_by,
_["nb_susceptible"] = nb_susceptible,
_["nb_contaminated"] = nb_contaminated,
_["initial_load"] = initial_load,
_["final_load"] = final_load,
_["infectious"] = infectious
);
}<file_sep>/pre_made_scripts/LPS_belize_analysis14.R
# Analyze effects of LPS on Belize vampire bat social networks
# <NAME> and <NAME>
# # set directory
# setwd(dirname(file.choose()))
# setwd("~/Dropbox/Dropbox/_working/_ACTIVE/belize_LPS/2018_Belize_analysis")
# setwd("C:/Users/simon.ripperger/Dropbox/2018_Belize_analysis")
# .libPaths("C:/R libraries")
# clear workspace
rm(list=ls())
# load packages
library(tidyverse)
library(boot)
library(lubridate)
library(lme4)
library(lmerTest)
library(igraph)
library(cowplot)
library(patchwork)
library(scales)
# choose number of permutations
perms <- 100
perms <- 10000
# make random numbers consistent
set.seed(123)
# functions----
# get the mean and 95% CI of a vector by bootstrapping
boot_ci <- function(x, perms=5000) {
mean.w=function(x,w) sum(x*w)
numNA <- sum(is.na(x))
x <- as.vector(na.omit(x))
mean <- mean(x)
boot <- boot.ci(boot(data=x, statistic=mean.w, R=perms, stype="w", parallel = "multicore", ncpus = 4), type="bca")
low <- boot$bca[1,4]
high <- boot$bca[1,5]
c(low=low,mean=mean,high=high, N=round(length(x)))
}
# get the mean and 95% CI within groups of a dataframe by bootstrapping
boot_ci2 <- function(d=d, y=d$y, x=d$x, perms=5000){
df <- data.frame(effect=unique(x))
df$low <- NA
df$mean <- NA
df$high <- NA
df$n.obs <- NA
for (i in 1:nrow(df)) {
ys <- y[which(x==df$effect[i])]
if (length(ys)>1){
b <- boot_ci(y[which(x==df$effect[i])], perms=perms)
df$low[i] <- b[1]
df$mean[i] <- b[2]
df$high[i] <- b[3]
df$n.obs[i] <- b[4]
}else{
df$low[i] <- NA
df$mean[i] <- ys
df$high[i] <- NA
df$n.obs[i] <- 1
}
}
df
}
# convert a list of dyadic interactions to a sociomatrix
# (requires igraph)
a_b_edgelist_to_matrix <- function(el=el, symbol="_", directed= T, make.NA.zero=T){
a <- str_split(as.data.frame(el)[,1],symbol, simplify = TRUE)[,1]
r <- str_split(as.data.frame(el)[,1],symbol, simplify = TRUE)[,2]
y <- as.data.frame(el)[,2]
e <- data.frame(a,r,y, stringsAsFactors = F)
if (make.NA.zero){
g <- graph_from_data_frame(e, directed=directed)
m <- get.adjacency(g, attr='y', sparse=FALSE)
m
}else{
e$y <- e$y+1 # temporarily add one to distinguish between 0 and NA
g <- graph_from_data_frame(e, directed=directed)
m <- get.adjacency(g, attr='y', sparse=FALSE)
m[m==0] <- NA # relabel missing values as NA
m <- m-1 # subtract one to adjust values back
m
}
}
# convert interactions to rates (duration within time bin)
# this function adds zeros for possible associations/interactions within each time bin
# it assumes that every individual ("ids") is present in every time bin ("bin")
# it requires a df with dyad ("a_b"), bin, and duration
events_to_rates <- function(df= df, bin= df$bin, ids= ids, directed= T){
if(directed){print("Assuming interactions are directed")}
if(!directed){print("Assuming interactions are undirected")}
if (directed){
actual.rates <-
df %>%
mutate(bin= bin) %>%
group_by(bin, dyad) %>%
summarize(duration= sum(duration)) %>%
separate(dyad, into=c("actor", "receiver"), sep="_")
possible.rates <-
expand_grid(actor= ids, receiver= ids, bin= unique(bin)) %>%
filter(actor!=receiver) %>%
mutate(duration=0)
rates <-
rbind.data.frame(actual.rates, possible.rates) %>%
group_by(bin, actor, receiver) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
mutate(dyad= paste(actor, receiver, sep="_"))
rates
}else{
if (!directed){
actual.rates <-
df %>%
mutate(bin= bin) %>%
separate(dyad, into=c("id1", "id2"), sep="_") %>%
mutate(dyad= if_else(id1<id2, paste(id1,id2, sep="_"), paste(id2,id1, sep="_"))) %>%
group_by(bin, dyad) %>%
summarize(duration= sum(duration)) %>%
separate(dyad, into=c("id1", "id2"), sep="_")
possible.rates <-
expand_grid(id1= ids, id2= ids, bin= unique(bin)) %>%
filter(id1!=id2) %>%
filter(id1<id2) %>%
mutate(duration=0)
rates <-
rbind.data.frame(actual.rates, possible.rates) %>%
group_by(bin, id1, id2) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
mutate(dyad= paste(id1, id2, sep="_"))
rates
}
}
return(rates)
}
# plot permutation test results
hist_perm <- function(exp=exp, obs=obs, perms=perms){
ggplot()+
geom_histogram(aes(x=exp), color="black",fill="light blue")+
xlim(min= min(c(exp,obs)), max= max(c(exp,obs)))+
geom_vline(aes(xintercept=obs), color="red", size=1)+
xlab("expected values from null model")+
labs(subtitle= paste('obs = ',round(obs, digits=2),", one-sided p = ", mean(exp>=obs),", permutations=",perms, sep=""))
}
# get standard error of the mean
se <- function(x=x){sd(x, na.rm=T)/sqrt(sum(!is.na(x)))}
# define treatment time period-----
# all bats were injected by 2 pm (1400 h) on April 25
# LPS effect begins 3 hours later (1700 h)
# captive data shows LPS effects at 3 hours and 6 hours post-injection
# LPS effects could last longer
# start sampling behavior at 5 pm on April 25
treatment_start <- as.POSIXct("2018-04-25 17:00:00", tz = "CST6CDT")
# stop sampling before midnight (before bats are likely to forage)
LPS_duration_hours <- 6
treatment_stop <- treatment_start + LPS_duration_hours*60*60
# get first post-treatment time period (same time of day 24 hours later)
post24_start <- treatment_start + 60*60*24
post24_stop <- treatment_stop + 60*60*24
# get second post-treatment time period (same time of day 48 hours later)
post48_start <- treatment_start + 60*60*48
post48_stop <- treatment_stop + 60*60*48
# clean data----
# get raw meeting data (unfused)
Belize <-
read_delim("../data/Belize_pre-fusion.csv", delim = ";")
# exclude missing bats and dropped sensors ----
# bat ID 23 also seems to have left 1 day early
excluded_bats <- c(10,14,26,41)
BatIDs <- unique(c(unique(Belize$SenderID),unique(Belize$EncounteredID)))
BatIDs <- BatIDs[! BatIDs %in% excluded_bats]
# get bat attributes
bats <-
read.csv("../data/Belize_tracked_bats02.csv", stringsAsFactors = F) %>%
mutate(sex = "female") %>%
filter(sensor_node %in% BatIDs)
# define association using RSSI ----
thresholds <- quantile(Belize$RSSI, probs = c(0, 25, 50, 75, 80, 85, 90, 95, 97.5, 99)/100)
thresholds
RSSI_threshold = thresholds[6] #set RSSI threshold
RSSI_threshold
#threshold for 2019 Current Biology paper was -26dmb at 90%; here -27dbm at 85%
# plot and print RSSI threshold-----
rssi.plot <-
Belize %>%
ggplot(aes(x=RSSI))+
geom_histogram(binwidth=1, fill= "grey", color= 'black')+
geom_vline(xintercept= RSSI_threshold)+
ggtitle("proximity sensor signal strength threshold",
subtitle= paste(names(RSSI_threshold), "threshold at", RSSI_threshold, "dBm"))+
xlab("Received Signal Strength Indicator (RSSI)")+
theme_cowplot()
ggsave("RSSI_plot.pdf", width= 6, height= 3, units="in", dpi=1200)
# clean data
df <-
Belize %>%
filter(RSSI > RSSI_threshold) %>%
filter(SenderID %in% BatIDs ) %>%
filter(EncounteredID %in% BatIDs ) %>%
select(- PacketID, -ChunkID) %>%
mutate(dyad= if_else(SenderID<EncounteredID,
paste(SenderID,EncounteredID, sep="_"),
paste(EncounteredID,SenderID, sep="_"))) %>%
mutate(EndOfMeeting = StartOfMeeting + MeetingDuration) %>%
group_by(dyad) %>%
arrange(StartOfMeeting) %>%
mutate(indx = c(0, cumsum(as.numeric(lead(StartOfMeeting)) >
cummax(as.numeric(EndOfMeeting)))[-n()])) %>%
group_by(dyad, indx) %>%
summarise(StartOfMeeting = min(StartOfMeeting),
EndOfMeeting = max(EndOfMeeting),
duration = difftime(EndOfMeeting, StartOfMeeting,unit = "secs"),
RSSI = max(RSSI)) %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(duration = as.numeric(duration, unit = "secs"))
# insert hour breaks
# convert start and end times to interval
df$interval <- interval(df$StartOfMeeting, df$EndOfMeeting)
# label "events" sequentially
df$event <- c(1:nrow(df))
# create function to get hours within a time interval
get_hours <- function(event, StartOfMeeting, EndOfMeeting){
hours <- seq(StartOfMeeting-minute(StartOfMeeting)*60-second(StartOfMeeting),
EndOfMeeting-minute(EndOfMeeting)*60-second(EndOfMeeting),
"hour")
dateseq <- hours
dateseq[1] <- StartOfMeeting
r <- c(dateseq, EndOfMeeting)
dur <- as.numeric(difftime(r[-1], r[-length(r)], unit = 'secs'))
data.frame(event, hour = hours, duration = dur)
}
# create new events with event durations within each hour
df2 <-
df %>%
rowwise %>%
do(get_hours(.$event, .$StartOfMeeting, .$EndOfMeeting)) %>%
ungroup() %>%
group_by(event, hour) %>%
summarize(duration = sum(duration)) %>%
as.data.frame()
# match original start time back into new events
df2$StartOfMeeting <- df$StartOfMeeting[match(df2$event, df$event)]
# if start time is past the hour use that start time, otherwise use the hour slot as the start time
df2$StartOfMeeting <- if_else(df2$StartOfMeeting>df2$hour, df2$StartOfMeeting, df2$hour)
# match original end time back into new events
df2$EndOfMeeting <- df$EndOfMeeting[match(df2$event, df$event)]
# if end time is before the next hour (start hour+ 1 hour), use that end time, otherwise use the next hour
df2$EndOfMeeting <- if_else(df2$EndOfMeeting<(df2$hour+3600), df2$EndOfMeeting, df2$hour+3600)
# match other data back in
df2$dyad <- df$dyad[match(df2$event, df$event)]
df2$RSSI <- df$RSSI[match(df2$event, df$event)]
# set end of meeting
# set timezone to BelizeTime
# set start of study to 3pm on April 25th
df <-
df2 %>%
mutate(bat1 = sub( "_.*$", "", dyad ), bat2 = sub('.*_', '', dyad)) %>%
mutate(StartBelizeTime = force_tz(StartOfMeeting, tzone = "CST6CDT")) %>%
mutate(EndBelizeTime = force_tz(EndOfMeeting, tzone = "CST6CDT")) %>%
mutate(StartBelizeTime= StartBelizeTime - hours(8), EndBelizeTime=EndBelizeTime - hours(8)) %>%
filter(StartBelizeTime >= as.POSIXct("2018-04-25 15:00:00", tz = "CST6CDT")) %>%
select(StartBelizeTime,bat1,bat2,duration, RSSI)
# assign treatment for each bat into df
df$treatment_bat1 <- bats$treatment[match(df$bat1, bats$sensor_node)]
df$treatment_bat2 <- bats$treatment[match(df$bat2, bats$sensor_node)]
# remove other dataframe
rm(df2)
# label treatment and post-treatment periods
# label dyad types
d <-
df %>%
mutate(datetime= as.POSIXct(StartBelizeTime,tz = "CST6CDT")) %>%
mutate(treatment_period= datetime >= treatment_start & datetime < treatment_stop) %>%
mutate(post24_period= datetime >= post24_start & datetime < post24_stop) %>%
mutate(post48_period= datetime >= post48_start & datetime < post48_stop) %>%
mutate(dyad_type= case_when(
treatment_bat1== 'LPS' & treatment_bat2== 'LPS' ~ 'sick-sick',
treatment_bat1== 'PBS' & treatment_bat2== 'PBS' ~ 'control-control',
treatment_bat1!= treatment_bat2 ~ 'sick-control',
TRUE ~ 'NA')) %>%
mutate(hour= substring(datetime, 1,13))
# get treated bats
treated.bats <-
d %>%
mutate(treated= ifelse(treatment_bat1=="LPS", bat1,
ifelse(treatment_bat2=="LPS", bat2, NA))) %>%
filter(!is.na(treated)) %>%
pull(treated) %>%
unique()
# number of treated bats = 16
length(treated.bats)
# number of untreated bats = 15
d %>%
mutate(untreated= ifelse(treatment_bat1!="LPS", bat1,
ifelse(treatment_bat2!="LPS", bat2, NA))) %>%
filter(!is.na(untreated)) %>%
pull(untreated) %>%
unique() %>%
length()
# get hourly associations----
h <-
d %>%
mutate(dyad= paste(bat1, bat2, sep="_")) %>%
group_by(hour, dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
events_to_rates(df=., bin= .$hour, ids= BatIDs, directed=F) %>%
select(hour= bin, dyad, duration)
# make one-hour networks----------
# make multilayer network where every layer is an hour
# net.list is a list of networks (one per hour)
all.hours <- unique(h$hour)
net.list <- list()
for (i in 1:length(all.hours)){
layer <- sort(all.hours)[i]
net <-
h %>%
filter(hour==layer) %>%
select(dyad, duration) %>%
a_b_edgelist_to_matrix() %>% ###
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
net.list[[i]] <- net
}
# get mean centrality per treatment within each hour (as a list)
d.list <- list()
for (i in 1:length(all.hours)){
net <- net.list[[i]]
d.list[[i]] <-
tibble(hour= as.POSIXct(all.hours[i], format= "%Y-%m-%d %H", tz="CST6CDT"),
bat= names(degree(net)),
degree= degree(net),
strength= strength(net),
eigenvector= eigen_centrality(net)$vector) %>%
mutate(treated= bat %in% treated.bats)
}
# d2 is the mean centrality per treatment group and per hour ----
d2 <-
bind_rows(d.list) %>%
group_by(hour, treated) %>%
summarize(degree= mean(degree),
strength= mean(strength),
eigenvector= mean(eigenvector)) %>%
pivot_longer(cols= degree:eigenvector,
names_to = "centrality", values_to = "value") %>%
filter(hour <= as.POSIXct("2018-04-28 01:00:00", tz = "CST6CDT")) %>%
mutate(period= case_when(
hour >= treatment_start & hour < treatment_stop ~ 'treatment',
hour >= post24_start & hour < post24_stop ~ '24 hours later',
hour >= post48_start & hour < post48_stop ~ '48 hours later',
TRUE ~"none")) %>%
ungroup()
# get the corresponding standard errors
d2.se <-
bind_rows(d.list) %>%
group_by(hour, treated) %>%
summarize(degree= se(degree),
strength= se(strength),
eigenvector= se(eigenvector)) %>%
pivot_longer(cols= degree:eigenvector,
names_to = "centrality", values_to = "se") %>%
filter(hour <= as.POSIXct("2018-04-28 01:00:00", tz = "CST6CDT")) %>%
ungroup()
# add standard errors
d2 <- full_join(d2, d2.se)
rm(d2.se)
# d3 is the mean centrality per bat and per hour----
d3 <-
bind_rows(d.list) %>%
mutate(period= case_when(
hour >= treatment_start & hour < treatment_stop ~ 'treatment',
hour >= post24_start & hour < post24_stop ~ '24 hours later',
hour >= post48_start & hour < post48_stop ~ '48 hours later',
TRUE ~"none")) %>%
filter(period!="none") %>%
mutate(treatment= ifelse(treated, "sick", "control"))
# make six-hour network for each period----
network.treatment <-
d %>%
filter(treatment_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F)
network.post24 <-
d %>%
filter(post24_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
network.post48 <-
d %>%
filter(post48_period) %>%
mutate(dyad= paste(bat1,bat2, sep="_")) %>%
select(dyad, hour, duration) %>%
group_by(dyad, hour) %>%
summarize(duration= sum(duration)) %>%
group_by(dyad) %>%
summarize(duration= sum(duration)) %>%
ungroup() %>%
a_b_edgelist_to_matrix(directed=F) %>%
graph_from_adjacency_matrix("undirected", weighted=T, diag=F) ###
# function to plot networks
network_plot <- function(net, title=""){
set.seed(123)
V(net)$treated <- ifelse(V(net)$name %in% treated.bats, 'dark blue', "light blue")
layout <- layout_with_gem(net)
png(filename=paste(title,".png", sep=""), width = 1200, height = 1200)
plot(net,
edge.color="slate grey",
vertex.shape= 'sphere',
vertex.color=V(net)$treated,
vertex.label="",
vertex.size=8,
edge.width=log10(E(net)$weight),
layout=layout)
title(title,cex.main=5,col.main="black")
dev.off()
}
network_plot(network.treatment, 'social network during treatment period')
network_plot(network.post24, "social network after 24 hours")
network_plot(network.post48, 'social network after 48 hours')
# get network centrality by treatment period-----
centrality.treatment <-
tibble(bat= names(degree(network.treatment)),
degree= degree(network.treatment),
strength= strength(network.treatment),
eigenvector= eigen_centrality(network.treatment)$vector,
period= "treatment")
centrality.post24 <-
tibble(bat= names(degree(network.post24)),
degree= degree(network.post24),
strength= strength(network.post24),
eigenvector= eigen_centrality(network.post24)$vector,
period= "24 hours later")
centrality.post48 <-
tibble(bat= names(degree(network.post48)),
degree= degree(network.post48),
strength= strength(network.post48),
eigenvector= eigen_centrality(network.post48)$vector,
period= "48 hours later")
d.period <-
rbind(centrality.treatment, centrality.post24, centrality.post48) %>%
mutate(treated= bat %in% treated.bats) %>%
mutate(treatment= ifelse(treated, "sick", "control"))
# get mean centrality values
means.degree <-
d.period %>%
mutate(group= paste(treated, period, sep="_")) %>%
boot_ci2(y=.$degree, x=.$group) %>%
separate(effect, into=c('treated', 'period'), sep="_")
means.str<-
d.period %>%
mutate(group= paste(treated, period, sep="_")) %>%
boot_ci2(y=.$strength/3600, x=.$group) %>%
separate(effect, into=c('treated', 'period'), sep="_")
means.ec<-
d.period %>%
mutate(group= paste(treated, period, sep="_")) %>%
boot_ci2(y=.$eigenvector, x=.$group) %>%
separate(effect, into=c('treated', 'period'), sep="_")
# create function to plot effect sizes
plot_effect <- function (df){
df %>%
mutate(period2= factor(period, levels= c('treatment', '24 hours later', '48 hours later'))) %>%
mutate(treatment= ifelse(treated, 'sick', 'control')) %>%
ggplot(aes(x=treatment, y=mean, color=treatment, shape=treatment))+
facet_wrap(~period2)+
geom_point(size=3)+
geom_errorbar(aes(ymin=low, ymax=high, width=.1), size=1)+
theme_bw()+
theme(legend.position= 'none',
axis.title.y=element_blank(),
axis.title.x=element_blank())+
scale_color_manual(values=c("light blue", "dark blue"))+
scale_shape_manual(values=c("circle", 'triangle'))
}
# plot centrality by hour-----
ch.plot <-
d2 %>%
mutate(value= ifelse(centrality=='strength', value/3600, value)) %>%
mutate(se= ifelse(centrality=='strength', se/3600, se)) %>%
mutate(centrality= paste(centrality, "centrality")) %>%
mutate(centrality= factor(centrality,
levels= c("degree centrality", 'strength centrality', 'eigenvector centrality'))) %>%
mutate(injection= ifelse(treated, "sick", "control")) %>%
mutate(high= value+se, low= value-se) %>%
ggplot(aes(x=hour, y=value, color=injection, shape=injection))+
#facet_wrap(~centrality, scales = "free_y", nrow = 3, labeller = "label_value")+
facet_wrap(~centrality, scales = "free_y", nrow = 3,
strip.position = "left",
labeller = as_labeller(c(`degree centrality` = "degree centrality",
`strength centrality` = "strength centrality",
`eigenvector centrality` = "eigenvector centrality")))+
geom_point()+
geom_errorbar(aes(ymin=low, ymax= high), width=0.1)+
geom_line()+
geom_rect(aes(xmin=treatment_stop, xmax=post24_start, ymin=0, ymax=Inf), fill='white', color=NA, alpha=0.02)+
geom_rect(aes(xmin=post24_stop, xmax=post48_start, ymin=0, ymax=Inf), fill='white', color=NA, alpha=0.02)+
geom_rect(aes(xmin=post48_stop, xmax=max(d2$hour)+1500, ymin=0, ymax=Inf), fill='white', color=NA, alpha=0.02)+
geom_vline(xintercept = treatment_start, color= "black")+
geom_vline(xintercept=treatment_stop, color= "black")+
geom_vline(xintercept = post24_start, linetype= "solid")+
geom_vline(xintercept=post24_stop, linetype= "solid")+
geom_vline(xintercept = post48_start, linetype= "solid")+
geom_vline(xintercept=post48_stop, linetype= "solid")+
theme_bw()+
ylab(NULL) +
theme(strip.background = element_blank(),
strip.placement = "outside",
axis.title.x=element_blank(),
legend.position = c(0.18, 0.72),
legend.margin=margin(c(0.5,0.5,0.5,0.5)),
legend.justification = "left",
legend.title = element_blank(),
legend.direction = "horizontal",
legend.background = element_rect(fill='white',
size=0.5, linetype="solid"))+
scale_x_datetime(breaks=date_breaks("6 hour"), labels=date_format("%H:%M", tz = "CST6CDT")) +
scale_color_manual(values=c("light blue", "dark blue"))+
scale_shape_manual(values=c("circle", 'triangle'))
ch.plot
# add panels of effect sizes
p1 <- means.degree %>% plot_effect() + theme(axis.title.x=element_blank())
p2 <- means.str %>% plot_effect() + theme(axis.title.x=element_blank())
p3 <- means.ec %>% plot_effect() + theme(axis.title.x=element_blank())
p4 <- plot_grid(p1,p2,p3, ncol=1, align = 'hv', rel_heights = c(1,1,1))
# plot and print to PDF
plot_grid(ch.plot, p4, ncol = 2, axis= 't',align = "v", rel_widths = c(2,1))
ggsave("centrality_by_hour.pdf", width= 11, height= 5, units="in", dpi=1200)
# fit models----
# general linear mixed effect model of LPS effect on degree
# response = degree centrality (one network per time period)
# fixed effect = time period, treatment, and their interaction
# random effect = bat
# first fit parametric GLM model
# add day as variable
data <-
d.period %>%
mutate(day= case_when(
period=="treatment" ~ 1,
period=="24 hours later" ~ 2,
period=="48 hours later" ~ 3))
# get standardized effect sizes
# get degree effects
fit1 <- summary(lmer(scale(degree)~ day*treated+(1|bat), data= data))
fit2 <- summary(lm(scale(degree)~ treated, data= data[which(data$day==1),])) #effect during treatment
fit2b <- summary(lm(scale(degree)~ treated, data= data[which(data$day==2),]))
fit3 <- summary(lm(scale(degree)~ treated, data= data[which(data$day==3),])) #effect outside treatment
# get strength effects
fit4 <- summary(lmer(scale(strength)~ day*treated+(1|bat), data= data))
fit5 <- summary(lm(scale(strength)~ treated, data= data[which(data$day==1),]))
fit5b <- summary(lm(scale(strength)~ treated, data= data[which(data$day==2),]))
fit6 <- summary(lm(scale(strength)~ treated, data= data[which(data$day==3),]))
# get eigenvector effects
fit7 <- summary(lmer(scale(eigenvector)~ day*treated+(1|bat), data= data))
fit8 <- summary(lm(scale(eigenvector)~ treated, data= data[which(data$day==1),]))
fit8b <- summary(lm(scale(eigenvector)~ treated, data= data[which(data$day==2),]))
fit9 <- summary(lm(scale(eigenvector)~ treated, data= data[which(data$day==3),]))
# get biologically meaningful effect sizes
# get change in number of bats
summary(lm((degree)~ treated, data= data[which(data$day==1),]))
# 4 fewer bats
# get change in time spent per bat
summary(lm((strength/30)~ treated, data= data[which(data$day==1),]))
# 1510 fewer seconds/six hour
# get observed slopes
# degree
obs1 <- fit1$coefficients[4,1] # interaction effect treatedTrue:period
obs1.1 <- fit1$coefficients[3,1] # LPS effect controlling for period
obs2 <- fit2$coefficients[2,1] # LPS effect during treatment
obs2.1 <- fit2b$coefficients[2,1] # LPS effect on day 2
obs3 <- fit3$coefficients[2,1] # LPS effect post treatment
# strength
obs4 <- fit4$coefficients[4,1] # interaction effect treatedTrue:period
obs4.1 <- fit4$coefficients[3,1] # LPS effect controlling for period
obs5 <- fit5$coefficients[2,1] # LPS effect during treatment
obs5.1 <- fit5b$coefficients[2,1] # LPS effect on day 2
obs6 <- fit6$coefficients[2,1] # LPS effect post treatment
# eigenvector
obs7 <- fit7$coefficients[4,1] # interaction effect treatedTrue:period
obs7.1 <- fit7$coefficients[3,1] # LPS effect controlling for period
obs8 <- fit8$coefficients[2,1] # LPS effect during treatment
obs8.1 <- fit8b$coefficients[2,1] # LPS effect on day 2
obs9 <- fit9$coefficients[2,1] # LPS effect post treatment
# permutation test to obtain non-parametric p-values
if (TRUE){
# get observed coefficients
# get expected
exp1 <- rep(NA, perms)
exp1.1 <- rep(NA, perms)
exp2 <- rep(NA, perms)
exp2.1 <- rep(NA, perms)
exp3 <- rep(NA, perms)
exp4 <- rep(NA, perms)
exp4.1 <- rep(NA, perms)
exp5 <- rep(NA, perms)
exp5.1 <- rep(NA, perms)
exp6 <- rep(NA, perms)
exp7 <- rep(NA, perms)
exp7.1 <- rep(NA, perms)
exp8 <- rep(NA, perms)
exp8.1 <- rep(NA, perms)
exp9 <- rep(NA, perms)
start <- Sys.time()
for (i in 1:perms){
# swap which bats are treated
random.treated.bats <-
d.period %>%
group_by(bat) %>%
summarize(treated=sum(treated)==3) %>%
mutate(random.treated= sample(treated)) %>%
filter(random.treated) %>%
pull(bat)
# refit models with random treated bats
rdata <-
d.period %>%
mutate(day= case_when(
period=="treatment" ~ 1,
period=="24 hours later" ~ 2,
period=="48 hours later" ~ 3)) %>%
# relabel treated bats
mutate(treated= bat %in% random.treated.bats)
# get degree effects
rfit1 <- summary(lmer(scale(degree)~ day*treated+(1|bat), data= rdata))
rfit2 <- summary(lm(scale(degree)~ treated, data= rdata[which(rdata$day==1),])) #effect during treatment
rfit2b <- summary(lm(scale(degree)~ treated, data= rdata[which(rdata$day==2),])) # effect on day 2
rfit3 <- summary(lm(scale(degree)~ treated, data= rdata[which(rdata$day==3),])) #effect outside treatment
# get strength effects
rfit4 <- summary(lmer(scale(strength)~ day*treated+(1|bat), data= rdata))
rfit5 <- summary(lm(scale(strength)~ treated, data= rdata[which(rdata$day==1),]))
rfit5b <- summary(lm(scale(strength)~ treated, data= rdata[which(rdata$day==2),])) # effect on day 2
rfit6 <- summary(lm(scale(strength)~ treated, data= rdata[which(rdata$day==3),]))
# get eigenvector effects
rfit7 <- summary(lmer(scale(eigenvector)~ day*treated+(1|bat), data= rdata))
rfit8 <- summary(lm(scale(eigenvector)~ treated, data= rdata[which(rdata$day==1),]))
rfit8b <- summary(lm(scale(eigenvector)~ treated, data= rdata[which(rdata$day==2),])) # effect on day 2
rfit9 <- summary(lm(scale(eigenvector)~ treated, data= rdata[which(rdata$day==3),]))
# save coefficients
exp1[i]<- rfit1$coefficients[4,1]
exp1.1[i]<- rfit1$coefficients[3,1]
exp2[i] <- rfit2$coefficients[2,1]
exp2.1[i] <- rfit2b$coefficients[2,1]
exp3[i] <- rfit3$coefficients[2,1]
exp4[i]<- rfit4$coefficients[4,1]
exp4.1[i]<- rfit4$coefficients[3,1]
exp5[i] <- rfit5$coefficients[2,1]
exp5.1[i] <- rfit5b$coefficients[2,1]
exp6[i] <- rfit6$coefficients[2,1]
exp7[i]<- rfit7$coefficients[4,1]
exp7.1[i]<- rfit7$coefficients[3,1]
exp8[i] <- rfit8$coefficients[2,1]
exp8.1[i] <- rfit8b$coefficients[2,1]
exp9[i] <- rfit9$coefficients[2,1]
if(i%%10==0) print(paste(i, "of", perms))
}
save(list= c('exp1', 'exp1.1','exp2','exp2.1', 'exp3','exp4', 'exp4.1','exp5','exp5.1', 'exp6','exp7', 'exp7.1','exp8', 'exp8.1', 'exp9'),
file= "perm_results.Rdata") ###
}else{ load('perm_results.Rdata') }
# end permutation test
speed <- Sys.time()- start
speed
# get perm test results----
# model coefficients (slopes) and p-values
# degree
# interaction effect (does LPS effect differ by treatment period?)
t1 <- hist_perm(exp1, obs1, perms)+labs(title='does LPS effect on degree differ by treatment period?')
# does LPS have an effect (controlling for period)?
t2 <- hist_perm(exp1.1, obs1.1, perms)+labs(title='does LPS affect degree?')
# does LPS have effect during treatment period?
t3 <- hist_perm(exp2, obs2, perms)+labs(title='does LPS affect degree in treatment period?')
t3.1 <- hist_perm(exp2.1, obs2.1, perms)+labs(title='does LPS affect degree on day 2?')
# does LPS have effect outside the treatment period?
t4 <- hist_perm(exp3, obs3, perms)+labs(title='does LPS affect degree in post-treatment period?')
# strength
# interaction effect (does LPS effect differ by treatment period?)
t5 <- hist_perm(exp4, obs4, perms)+labs(title='does LPS effect on strength differ by treatment period?')
# does LPS have an effect (controlling for period)?
t6 <- hist_perm(exp4.1, obs4.1, perms)+labs(title='does LPS affect strength?')
# does LPS have effect during treatment period?
t7 <- hist_perm(exp5, obs5, perms)+labs(title='does LPS affect strength in treatment period?')
t7.1 <- hist_perm(exp5.1, obs5.1, perms)+labs(title='does LPS affect strength on day 2?')
# does LPS have effect outside the treatment period?
t8 <- hist_perm(exp6, obs6, perms)+labs(title='does LPS affect strength in post-treatment period?')
# eigenvector
# interaction effect (does LPS effect differ by treatment period?)
t9 <- hist_perm(exp7, obs7, perms)+labs(title='does LPS effect on eigenvector centrality differ by treatment period?')
# does LPS have an effect (controlling for period)?
t10 <- hist_perm(exp7.1, obs7.1, perms)+labs(title='does LPS affect eigenvector centrality?')
# does LPS have effect during treatment period?
t11 <- hist_perm(exp8, obs8, perms)+labs(title='does LPS affect eigenvector centrality in treatment period?')
t11.1 <- hist_perm(exp8.1, obs8.1, perms)+labs(title='does LPS affect eigenvector centrality in treatment period?')
# does LPS have effect outside the treatment period?
t12 <- hist_perm(exp9, obs9, perms)+labs(title='does LPS affect eigenvector centrality in post-treatment period?')
# combine plots
(perm.test <- t1+t2+t3+t3.1+t4+t5+t6+t7+t7.1+t8+t9+t10+t11+t11.1+t12+plot_layout(ncol=3))
ggsave("perm_tests.pdf", width=18, height= 15, units="in", dpi=1200)
# make results table-----
results <-
data.frame(response= rep(c('degree', 'strength', 'eigenvector'), times=1, each=5),
fixed_effect= rep(c('interaction', 'treatment', 'treatment.within.period','treatment.day2', 'treatment.within.post'), times=3),
coefficient= c(obs1, obs1.1, obs2, obs2.1, obs3, obs4, obs4.1, obs5, obs5.1, obs6, obs7, obs7.1, obs8, obs8.1, obs9),
pvalue= c(mean(exp1>=obs1),
mean(exp1.1>=obs1.1),
mean(exp2>=obs2),
mean(exp2.1>=obs2.1),
mean(exp3>=obs3),
mean(exp4>=obs4),
mean(exp4.1>=obs4.1),
mean(exp5>=obs5),
mean(exp5.1>=obs5.1),
mean(exp6>=obs6),
mean(exp7>=obs7),
mean(exp7.1>=obs7.1),
mean(exp8>=obs8),
mean(exp8.1>=obs8.1),
mean(exp9>=obs9))) %>%
mutate(pvalue= if_else(coefficient<0, (1-pvalue),pvalue)) %>%
mutate(pvalue2= c(mean(abs(exp1) >= abs(obs1)),
mean(abs(exp1.1) >= abs(obs1.1)),
mean(abs(exp2) >= abs(obs2)),
mean(abs(exp2.1) >= abs(obs2.1)),
mean(abs(exp3) >= abs(obs3)),
mean(abs(exp4) >= abs(obs4)),
mean(abs(exp4.1) >= abs(obs4.1)),
mean(abs(exp5) >= abs(obs5)),
mean(abs(exp5.1) >= abs(obs5.1)),
mean(abs(exp6) >= abs(obs6)),
mean(abs(exp7) >= abs(obs7)),
mean(abs(exp7.1) >= abs(obs7.1)),
mean(abs(exp8) >= abs(obs8)),
mean(abs(exp8.1) >= abs(obs8.1)),
mean(abs(exp9) >= abs(obs9))))
results
# Alternate analysis----
# this is an alternate analysis requested by reviewers
if(TRUE){
# fit models on HOURLY DATA----
# general linear mixed effect model of LPS effect on degree
# response = degree centrality (one network per hour)
# fixed effect = time period, treatment, and their interaction
# random effect = bat, hour
time1=Sys.time()
perms2=1000
# first fit parametric GLM model
# add day as variable
data <-
d3 %>%
mutate(day= case_when(
period=="treatment" ~ 1,
period=="24 hours later" ~ 2,
period=="48 hours later" ~ 3)) %>%
# convert datetime to hours (1-6)
mutate(hour= as.numeric(substring(hour, 12,13)) -16 ) %>%
# convert to string
mutate(hour=as.character(hour))
# get degree effects
fit1 <- summary(lmer(scale(degree)~ day*treated+(1|hour) +(1|bat), data= data))
fit2 <- summary(lmer(scale(degree)~ treated+(1|hour), data= data[which(data$day==1),])) #effect during treatment
fit2b <- summary(lmer(scale(degree)~ treated+(1|hour), data= data[which(data$day==2),]))
fit3 <- summary(lmer(scale(degree)~ treated+(1|hour), data= data[which(data$day==3),])) #effect outside treatment
# get strength effects
fit4 <- summary(lmer(scale(strength)~ day*treated+(1|hour)+(1|bat), data= data))
fit5 <- summary(lmer(scale(strength)~ treated+(1|hour), data= data[which(data$day==1),]))
fit5b <- summary(lmer(scale(strength)~ treated+(1|hour), data= data[which(data$day==2),]))
fit6 <- summary(lmer(scale(strength)~ treated+(1|hour), data= data[which(data$day==3),]))
# get eigenvector effects
fit7 <- summary(lmer(scale(eigenvector)~ day*treated+(1|hour)+(1|bat), data= data))
fit8 <- summary(lmer(scale(eigenvector)~ treated+(1|hour), data= data[which(data$day==1),]))
fit8b <- summary(lmer(scale(eigenvector)~ treated+(1|hour), data= data[which(data$day==2),]))
fit9 <- summary(lmer(scale(eigenvector)~ treated+(1|hour), data= data[which(data$day==3),]))
# get observed slopes
# degree
obs1 <- fit1$coefficients[4,1] # interaction effect treatedTrue:period
obs1.1 <- fit1$coefficients[3,1] # LPS effect controlling for period
obs2 <- fit2$coefficients[2,1] # LPS effect during treatment
obs2.1 <- fit2b$coefficients[2,1] # LPS effect on day 2
obs3 <- fit3$coefficients[2,1] # LPS effect post treatment
# strength
obs4 <- fit4$coefficients[4,1] # interaction effect treatedTrue:period
obs4.1 <- fit4$coefficients[3,1] # LPS effect controlling for period
obs5 <- fit5$coefficients[2,1] # LPS effect during treatment
obs5.1 <- fit5b$coefficients[2,1] # LPS effect on day 2
obs6 <- fit6$coefficients[2,1] # LPS effect post treatment
# eigenvector
obs7 <- fit7$coefficients[4,1] # interaction effect treatedTrue:period
obs7.1 <- fit7$coefficients[3,1] # LPS effect controlling for period
obs8 <- fit8$coefficients[2,1] # LPS effect during treatment
obs8.1 <- fit8b$coefficients[2,1] # LPS effect on day 2
obs9 <- fit9$coefficients[2,1] # LPS effect post treatment
# permutation test to obtain non-parametric p-values
if (TRUE){
# get observed coefficients
# get expected
exp1 <- rep(NA, perms2)
exp1.1 <- rep(NA, perms2)
exp2 <- rep(NA, perms2)
exp2.1 <- rep(NA, perms2)
exp3 <- rep(NA, perms2)
exp4 <- rep(NA, perms2)
exp4.1 <- rep(NA, perms2)
exp5 <- rep(NA, perms2)
exp5.1 <- rep(NA, perms2)
exp6 <- rep(NA, perms2)
exp7 <- rep(NA, perms2)
exp7.1 <- rep(NA, perms2)
exp8 <- rep(NA, perms2)
exp8.1 <- rep(NA, perms2)
exp9 <- rep(NA, perms2)
start <- Sys.time()
for (i in 1:perms2){
# swap which bats are treated
random.treated.bats <-
d.period %>%
group_by(bat) %>%
summarize(treated=sum(treated)==3) %>%
mutate(random.treated= sample(treated)) %>%
filter(random.treated) %>%
pull(bat)
# refit models with random treated bats
rdata <-
d3 %>%
mutate(day= case_when(
period=="treatment" ~ 1,
period=="24 hours later" ~ 2,
period=="48 hours later" ~ 3)) %>%
# convert datetime to hours (1-6)
mutate(hour= as.numeric(substring(hour, 12,13)) -16 ) %>%
# convert to string
mutate(hour=as.character(hour)) %>%
# relabel treated bats
mutate(treated= bat %in% random.treated.bats)
# get degree effects
rfit1 <- summary(lmer(scale(degree)~ day*treated+(1|hour), data= rdata))
rfit2 <- summary(lmer(scale(degree)~ treated+(1|hour), data= rdata[which(rdata$day==1),])) #effect during treatment
rfit2b <- summary(lmer(scale(degree)~ treated+(1|hour), data= rdata[which(rdata$day==2),])) # effect on day 2
rfit3 <- summary(lmer(scale(degree)~ treated+(1|hour), data= rdata[which(rdata$day==3),])) #effect outside treatment
# get strength effects
rfit4 <- summary(lmer(scale(strength)~ day*treated+(1|hour), data= rdata))
rfit5 <- summary(lmer(scale(strength)~ treated +(1|hour), data= rdata[which(rdata$day==1),]))
rfit5b <- summary(lmer(scale(strength)~ treated +(1|hour), data= rdata[which(rdata$day==2),])) # effect on day 2
rfit6 <- summary(lmer(scale(strength)~ treated+(1|hour), data= rdata[which(rdata$day==3),]))
# get eigenvector effects
rfit7 <- summary(lmer(scale(eigenvector)~ day*treated+(1|hour), data= rdata))
rfit8 <- summary(lmer(scale(eigenvector)~ treated+(1|hour), data= rdata[which(rdata$day==1),]))
rfit8b <- summary(lmer(scale(eigenvector)~ treated+(1|hour), data= rdata[which(rdata$day==2),])) # effect on day 2
rfit9 <- summary(lmer(scale(eigenvector)~ treated+(1|hour), data= rdata[which(rdata$day==3),]))
# save coefficients
exp1[i]<- rfit1$coefficients[4,1]
exp1.1[i]<- rfit1$coefficients[3,1]
exp2[i] <- rfit2$coefficients[2,1]
exp2.1[i] <- rfit2b$coefficients[2,1]
exp3[i] <- rfit3$coefficients[2,1]
exp4[i]<- rfit4$coefficients[4,1]
exp4.1[i]<- rfit4$coefficients[3,1]
exp5[i] <- rfit5$coefficients[2,1]
exp5.1[i] <- rfit5b$coefficients[2,1]
exp6[i] <- rfit6$coefficients[2,1]
exp7[i]<- rfit7$coefficients[4,1]
exp7.1[i]<- rfit7$coefficients[3,1]
exp8[i] <- rfit8$coefficients[2,1]
exp8.1[i] <- rfit8b$coefficients[2,1]
exp9[i] <- rfit9$coefficients[2,1]
if(i%%10==0) print(paste(i, "of", perms2))
}
save(list= c('exp1', 'exp1.1','exp2','exp2.1', 'exp3','exp4', 'exp4.1','exp5','exp5.1', 'exp6','exp7', 'exp7.1','exp8', 'exp8.1', 'exp9'),
file= "perm_results02.Rdata") ###
}else{ load('perm_results02.Rdata') }
# end permutation test
# get perm test results
# model coefficients (slopes) and p-values
# degree
# interaction effect (does LPS effect differ by treatment period?)
t1 <- hist_perm(exp1, obs1, perms2)+labs(title='does LPS effect on degree differ by treatment period?')
# does LPS have an effect (controlling for period)?
t2 <- hist_perm(exp1.1, obs1.1, perms2)+labs(title='does LPS affect degree?')
# does LPS have effect during treatment period?
t3 <- hist_perm(exp2, obs2, perms2)+labs(title='does LPS affect degree in treatment period?')
t3.1 <- hist_perm(exp2.1, obs2.1, perms2)+labs(title='does LPS affect degree on day 2?')
# does LPS have effect outside the treatment period?
t4 <- hist_perm(exp3, obs3, perms2)+labs(title='does LPS affect degree in post-treatment period?')
# strength
# interaction effect (does LPS effect differ by treatment period?)
t5 <- hist_perm(exp4, obs4, perms2)+labs(title='does LPS effect on strength differ by treatment period?')
# does LPS have an effect (controlling for period)?
t6 <- hist_perm(exp4.1, obs4.1, perms2)+labs(title='does LPS affect strength?')
# does LPS have effect during treatment period?
t7 <- hist_perm(exp5, obs5, perms2)+labs(title='does LPS affect strength in treatment period?')
t7.1 <- hist_perm(exp5.1, obs5.1, perms2)+labs(title='does LPS affect strength on day 2?')
# does LPS have effect outside the treatment period?
t8 <- hist_perm(exp6, obs6, perms2)+labs(title='does LPS affect strength in post-treatment period?')
# eigenvector
# interaction effect (does LPS effect differ by treatment period?)
t9 <- hist_perm(exp7, obs7, perms2)+labs(title='does LPS effect on eigenvector centrality differ by treatment period?')
# does LPS have an effect (controlling for period)?
t10 <- hist_perm(exp7.1, obs7.1, perms2)+labs(title='does LPS affect eigenvector centrality?')
# does LPS have effect during treatment period?
t11 <- hist_perm(exp8, obs8, perms2)+labs(title='does LPS affect eigenvector centrality in treatment period?')
t11.1 <- hist_perm(exp8.1, obs8.1, perms2)+labs(title='does LPS affect eigenvector centrality in treatment period?')
# does LPS have effect outside the treatment period?
t12 <- hist_perm(exp9, obs9, perms2)+labs(title='does LPS affect eigenvector centrality in post-treatment period?')
# combine plots
(perm.test2 <- t1+t2+t3+t3.1+t4+t5+t6+t7+t7.1+t8+t9+t10+t11+t11.1+t12+plot_layout(ncol=3))
ggsave("perm_tests2.pdf", width=18, height= 15, units="in", dpi=1200)
# make results table
results2 <-
data.frame(response= rep(c('degree', 'strength', 'eigenvector'), times=1, each=5),
fixed_effect= rep(c('interaction', 'treatment', 'treatment.within.period','treatment.day2', 'treatment.within.post'), times=3),
coefficient= c(obs1, obs1.1, obs2, obs2.1, obs3, obs4, obs4.1, obs5, obs5.1, obs6, obs7, obs7.1, obs8, obs8.1, obs9),
pvalue= c(mean(exp1>=obs1),
mean(exp1.1>=obs1.1),
mean(exp2>=obs2),
mean(exp2.1>=obs2.1),
mean(exp3>=obs3),
mean(exp4>=obs4),
mean(exp4.1>=obs4.1),
mean(exp5>=obs5),
mean(exp5.1>=obs5.1),
mean(exp6>=obs6),
mean(exp7>=obs7),
mean(exp7.1>=obs7.1),
mean(exp8>=obs8),
mean(exp8.1>=obs8.1),
mean(exp9>=obs9))) %>%
mutate(pvalue= if_else(coefficient<0, (1-pvalue), pvalue)) %>%
mutate(pvalue2= c(mean(exp1>=obs1),
mean(exp1.1>=obs1.1),
mean(exp2>=obs2),
mean(exp2.1>=obs2.1),
mean(exp3>=obs3),
mean(exp4>=obs4),
mean(exp4.1>=obs4.1),
mean(exp5>=obs5),
mean(exp5.1>=obs5.1),
mean(exp6>=obs6),
mean(exp7>=obs7),
mean(exp7.1>=obs7.1),
mean(exp8>=obs8),
mean(exp8.1>=obs8.1),
mean(exp9>=obs9)),
pvalue2= c(mean(abs(exp1) >= abs(obs1)),
mean(abs(exp1.1) >= abs(obs1.1)),
mean(abs(exp2) >= abs(obs2)),
mean(abs(exp2.1) >= abs(obs2.1)),
mean(abs(exp3) >= abs(obs3)),
mean(abs(exp4) >= abs(obs4)),
mean(abs(exp4.1) >= abs(obs4.1)),
mean(abs(exp5) >= abs(obs5)),
mean(abs(exp5.1) >= abs(obs5.1)),
mean(abs(exp6) >= abs(obs6)),
mean(abs(exp7) >= abs(obs7)),
mean(abs(exp7.1) >= abs(obs7.1)),
mean(abs(exp8) >= abs(obs8)),
mean(abs(exp8.1) >= abs(obs8.1)),
mean(abs(exp9) >= abs(obs9))))
results2
time2= Sys.time() - time1
time2
}
# get associations by dyad type----
# label edge types in hourly data
dt <-
d %>%
mutate(dyad= paste(bat1, bat2, sep='_')) %>%
group_by(dyad, dyad_type) %>%
summarize(n=n())
h$dyad_type <- dt$dyad_type[match(h$dyad, dt$dyad)]
# get mean association time and prob per edge type per hour
e <-
h %>%
mutate(hour= as.POSIXct(hour, format= "%Y-%m-%d %H", tz="CST6CDT")) %>%
group_by(hour, dyad_type) %>%
summarize(`mean association duration`= mean(duration),
`mean association probability`= mean(duration>0)) %>%
ungroup() %>%
filter(hour <= as.POSIXct("2018-04-28 01:00:00", tz = "CST6CDT")) %>%
pivot_longer(cols= 'mean association duration' : 'mean association probability',
values_to = 'value', names_to = 'measure') %>%
mutate(period= case_when(
hour >= treatment_start & hour < treatment_stop ~ 'treatment',
hour >= post24_start & hour < post24_stop ~ '24 hours later',
hour >= post48_start & hour < post48_stop ~ '48 hours later',
TRUE ~"none"))
# plot dyad-type associations per hour-----
(eh.plot <-
e %>%
ggplot(aes(x=hour, y=value, color= dyad_type, shape=dyad_type, linetype= dyad_type))+
facet_wrap(~measure, ncol=1, scales="free_y")+
geom_point()+
geom_line()+
geom_rect(aes(xmin=treatment_stop, xmax=post24_start, ymin=0, ymax=Inf), fill='white', color=NA, alpha=0.01)+
geom_rect(aes(xmin=post24_stop, xmax=post48_start, ymin=0, ymax=Inf), fill='white', color=NA, alpha=0.01)+
geom_rect(aes(xmin=post48_stop, xmax=max(d2$hour)+1500, ymin=0, ymax=Inf), fill='white', color=NA, alpha=0.01)+
geom_vline(xintercept = treatment_start, color= "black")+
geom_vline(xintercept=treatment_stop, color= "black")+
geom_vline(xintercept = post24_start, linetype= "solid")+
geom_vline(xintercept=post24_stop, linetype= "solid")+
geom_vline(xintercept = post48_start, linetype= "solid")+
geom_vline(xintercept=post48_stop, linetype= "solid")+
theme_bw()+
ylab("")+
theme(legend.position = c(0.18, 0.58),
legend.margin=margin(c(0.5,0.5,0.5,0.5)),
legend.justification = "left",
legend.title = element_blank(),
legend.direction = "horizontal",
legend.background = element_rect(fill='white',
size=0.5, linetype="solid"))+
scale_x_datetime(breaks=date_breaks("6 hour"), labels=date_format("%H:%M", tz = "CST6CDT")) +
scale_color_manual(values=c("black", "red", "springgreen"))+
scale_linetype_manual(values= c('solid', 'dashed', 'dotted'))+
scale_shape_manual(values=c("circle", "triangle", "square")))
# get association times and probs by dyad type during treatment and post-treatment periods----
d4 <-
h %>%
mutate(hour= as.POSIXct(hour, format= "%Y-%m-%d %H", tz="CST6CDT")) %>%
filter(hour <= as.POSIXct("2018-04-28 01:00:00", tz = "CST6CDT")) %>%
mutate(period= case_when(
hour >= treatment_start & hour < treatment_stop ~ 'treatment',
hour >= post24_start & hour < post24_stop ~ '24 hours later',
hour >= post48_start & hour < post48_stop ~ '48 hours later',
TRUE ~"none")) %>%
filter(period!='none') %>%
group_by(hour, dyad, dyad_type, period) %>%
summarize(time= mean(duration),
prob= mean(duration>0)) %>%
group_by(dyad, dyad_type, period) %>%
summarize(time= mean(time),
prob= mean(prob),
n= n()) %>%
ungroup()
# get means and 95% CI
assoc.untreated <-
d4 %>%
filter(dyad_type=='control-control') %>%
select(period, time, prob) %>%
boot_ci2(y=.$time, x=.$period) %>%
mutate(type= 'control-control')
assoc.mixed <-
d4 %>%
filter(dyad_type=='sick-control') %>%
select(period, time, prob) %>%
boot_ci2(y=.$time, x=.$period) %>%
mutate(type= 'sick-control')
prob.untreated <-
d4 %>%
filter(dyad_type=='control-control') %>%
select(period, time, prob) %>%
boot_ci2(y=.$prob, x=.$period) %>%
mutate(type= 'control-control')
prob.mixed <-
d4 %>%
filter(period!='none') %>%
filter(dyad_type=='sick-control') %>%
select(period, time, prob) %>%
boot_ci2(y=.$prob, x=.$period) %>%
mutate(type= 'sick-control')
# plot association time
p1 <-
rbind(assoc.untreated, assoc.mixed) %>%
mutate(period= factor(effect, levels= c('treatment', '24 hours later', '48 hours later'))) %>%
ggplot(aes(x=type, y=mean, color=type, shape=type))+
facet_wrap(~period)+
geom_point(size=3)+
geom_errorbar(aes(ymin=low, ymax=high, width=.1), size=1)+
scale_color_manual(values=c("black", 'red'))+
scale_shape_manual(values=c('circle', 'triangle'))+
theme_bw()+
theme(legend.position= 'none',
axis.title.y=element_blank(),
axis.title.x=element_blank(),
axis.text.x=element_blank())
# plot association prob
p2 <-
rbind(prob.untreated, prob.mixed) %>%
mutate(period= factor(effect, levels= c('treatment', '24 hours later', '48 hours later'))) %>%
mutate(type= ifelse(type=="control-control", "c-c", 's-c')) %>%
ggplot(aes(x=type, y=mean, color=type, shape=type))+
facet_wrap(~period)+
geom_point(size=3)+
geom_errorbar(aes(ymin=low, ymax=high, width=.1), size=1)+
scale_color_manual(values=c("black", 'red'))+
scale_shape_manual(values=c('circle', 'triangle'))+
theme_bw()+
theme(legend.position= 'none',
axis.title.y=element_blank())+
xlab("dyad type")
# plot and make PDF
(eh.plot2 <- (eh.plot|(p1+p2+plot_layout(ncol=1)))+plot_layout(widths= c(2,1)))
ggsave("dyad_types_by_hour.pdf", width=11, height= 5, units="in", dpi=1200)
# save output with timestamp-----
timestamp <- substr(gsub(x=gsub(":","_",Sys.time()),
pattern=" ", replace="_"), start=1, stop=16)
workspace <- paste("results_", timestamp, ".Rdata", sep="")
save.image(file= workspace)
# print results table
results
results2
# print current results file (paste and copy below)
workspace
# code to load old data
if(FALSE){
load("results_2020-09-16_17_12.Rdata")
}
<file_sep>/visualizations/treelizard.py
import pandas
import networkx
import numpy as np
from matplotlib import pyplot
import os
#from vis_params import rcParams
import vis_params
#PREFIX = '../analysis_results/'
df = pandas.read_csv(vis_params.ANALYSIS_FOLDER + 'edgelist_treelizards_0weightexcl.csv')
#df = df[['trt', 'id1', 'id2', 'distance', 'weight']]
elist = df[['id1','id2']].values
#eweights = df['distance'].values
eweights = df['weight'].values
elist2 = [ (e[0],e[1],w) for e,w in zip(elist,eweights) ]
G = networkx.DiGraph()
G.add_weighted_edges_from(elist2)
#G = networkx.from_edgelist(elist2)
fig,ax = pyplot.subplots(1,1, constrained_layout=True)
pos_xy = networkx.spring_layout(G)
networkx.draw_networkx(G,
# arrowsize=eweights,
pos = pos_xy,
font_color=[1,1,1],
font_size=8,
edge_color=[0,0,0,0.4],
node_shape='s',
node_size=400
)
fig.savefig(vis_params.IMAGES_FOLDER + 'treelizard.png')
fig.show()<file_sep>/data_prep_scripts/SticklebackAnalyses.R
# <NAME> 1/12/21 CNWW Team Before and After - I'm sorry this is SO inefficient!
# # FYI "In all but one of the association networks obtained for
# our groups, all fish were seen to associate with all others
# in their group at least once (fig. 1D). For this reason, many
# of the standard network metrics, such as path length, betweenness,
# and clustering coefficient, which are commonly
# used to describe networks with incomplete connectedness,
# were unnecessary or inapplicable here (see Croft et al.
# 2008). Instead, we focused on just three metrics: mean
# subgroup size, network density, and network differentiation."
#Outside of R I put the first 5 pre association matrices and the 5 post association matrices
#into separate CSV files
#load libraries
install.packages("igraph")
library(igraph)
install.packages("einet")
library(einet)
## PRE - UNSTRUCTURED , just the first 5 since post has five
#group 1_unstructured_pre-foraging task imported, no heading SHOULD HAVE IMPORTED W/ HEADING so now I have to delete first column and first row
Group1_Unstructured_Pre
Group1_Unstructured_Pre2<- Group1_Unstructured_Pre[-c(1),-c(1)]
#make matrix and graph
m1<-as.matrix(Group1_Unstructured_Pre2)
g1<-graph.adjacency(m,mode="undirected",weighted=TRUE,diag=FALSE)
plot.igraph(g1)
#do for the rest of the pre- groups
Group2_Unstructured_Pre
Group2_Unstructured_Pre2<- Group2_Unstructured_Pre[-c(1),-c(1)]
m2<- as.matrix(Group2_Unstructured_Pre2)
g2<-graph.adjacency(m2,mode="undirected",weighted=TRUE,diag=FALSE)
Group3_Unstructured_Pre
Group3_Unstructured_Pre2<- Group3_Unstructured_Pre[-c(1),-c(1)]
m3<-as.matrix(Group3_Unstructured_Pre2)
g3<-graph.adjacency(m3,mode="undirected",weighted=TRUE,diag=FALSE)
Group4_Unstructured_Pre
Group4_Unstructured_Pre2<-Group4_Unstructured_Pre[-c(1),-c(1)]
m4<-as.matrix(Group4_Unstructured_Pre2)
g4<-graph.adjacency(m4,mode="undirected",weighted=TRUE,diag=FALSE)
Group5_Unstructured_Pre
Group5_Unstructured_Pre2<-Group5_Unstructured_Pre[-c(1),-c(1)]
m5<-as.matrix(Group5_Unstructured_Pre2)
g5<-graph.adjacency(m5,mode="undirected",weighted=TRUE,diag=FALSE)
#calculate measures for pre- groups
#first make a list of their matrices and a list of their graphs
matrixListPre <- list(m1,m2,m3,m4,m5)
graphListPre<-list(g1,g2,g3,g4,g5)
sample_function <- function(g){
all_betweenness <- igraph::betweenness(g,directed=FALSE)
return(mean(all_betweenness))
}
pre_between<-lapply(graphListPre, sample_function)
between_function <- function(g){
all_eigenvector <- igraph::eigen_centrality(g, directed=FALSE)$vector
return(mean(all_eigenvector))
}
pre_eigen<-lapply(graphListPre, between_function)
pre_density<-lapply(graphListPre, igraph::edge_density)
length_function<-function(g){
all_length<-length(V(g))
return(all_length)
}
pre_length<-lapply(graphListPre,length_function)
ei_function<-function(g){
all_ei<-einet::effective_information(g,effectiveness=FALSE)
return(all_ei/log2(8)) #all my networks have 8 nodes
}
pre_ei<-lapply(graphListPre,ei_function)
## POST - UNSTRUCTURED
Group1_Unstructured_Post
Group1_Unstructured_Post2<- Group1_Unstructured_Post[-c(1),-c(1)]
m1_post<-as.matrix(Group1_Unstructured_Post2)
g1_post<-graph.adjacency(m1_post,mode="undirected",weighted=TRUE,diag=FALSE)
Group2_Unstructured_Post
Group2_Unstructured_Post2<- Group2_Unstructured_Post[-c(1),-c(1)]
m2_post<-as.matrix(Group2_Unstructured_Post2)
g2_post<-graph.adjacency(m2_post,mode="undirected",weighted=TRUE,diag=FALSE)
Group3_Unstructured_Post
Group3_Unstructured_Post2<- Group3_Unstructured_Post[-c(1),-c(1)]
m3_post<-as.matrix(Group3_Unstructured_Post2)
g3_post<-graph.adjacency(m3_post,mode="undirected",weighted=TRUE,diag=FALSE)
Group4_Unstructured_Post
Group4_Unstructured_Post2<- Group4_Unstructured_Post[-c(1),-c(1)]
m4_post<-as.matrix(Group4_Unstructured_Post2)
g4_post<-graph.adjacency(m4_post,mode="undirected",weighted=TRUE,diag=FALSE)
Group5_Unstructured_Post
Group5_Unstructured_Post2<- Group5_Unstructured_Post[-c(1),-c(1)]
m5_post<-as.matrix(Group5_Unstructured_Post2)
g5_post<-graph.adjacency(m5_post,mode="undirected",weighted=TRUE,diag=FALSE)
matrixListPost <- list(m1_post,m2_post,m3_post,m4_post,m5_post)
graphListPost<-list(g1_post,g2_post,g3_post,g4_post,g5_post)
#calculate measures for post- groups
sample_function <- function(g){
all_betweenness <- igraph::betweenness(g,directed=FALSE)
return(mean(all_betweenness))
}
post_between<-lapply(graphListPost, sample_function)
between_function <- function(g){
all_eigenvector <- igraph::eigen_centrality(g, directed=FALSE)$vector
return(mean(all_eigenvector))
}
post_eigen<-lapply(graphListPost, between_function)
post_density<-lapply(graphListPost, igraph::edge_density)
length_function<-function(g){
all_length<-length(V(g))
return(all_length)
}
post_length<-lapply(graphListPost,length_function)
ei_function<-function(g){
all_ei<-einet::effective_information(g,effectiveness=FALSE)
return(all_ei/log2(8)) #all my networks have 8 nodes
}
post_ei<-lapply(graphListPost,ei_function)
##combine pre and post measures into data frame
stickleback_data<- data.frame(matrix(NA, nrow=10, ncol=9))
stickleback_data$Study<-rep("Stickleback", 10)
stickleback_data$Animal<-rep("Stickleback",10)
stickleback_data$Treatment<-c(rep("Pre",5), rep("Post",5))
stickleback_data$GroupID<-c(1:5,1:5)
stickleback_data$N_Nodes<-c(pre_length,post_length)
stickleback_data$Density<-c(pre_density,post_density)
stickleback_data$Mean_Eigenvector_Centrality<-c(pre_eigen,post_eigen)
stickleback_data$Mean_Betweenness_Centrality<-c(pre_between,post_between)
stickleback_data$Effective_Information<-c(pre_ei, post_ei)
stickleback_data<-stickleback_data[,-c(1:9)]
as.data.frame(stickleback_data)
str(stickleback_data)
getwd()
df <- apply(stickleback_data,2,as.character)
write.csv(df, "stickleback_data_output.csv")
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/16_heatmaps_groups.R
####16_heatmaps_groups.R#####
### Calls C++ function heatmap3_tofile (https://github.com/laurentkeller/anttrackingUNIL)
### Takes a datfile, a tagfile, a group of ants, and a time period as inputs, and returns a file containing the number of visits to each coordinate, summed across all ants in the specified group
###Created by <NAME>
#################################3
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
####get dat list #####
input_dat <- paste(data_path,"intermediary_analysis_steps/dat_files",sep="/")
setwd(input_dat)
dat_list <- paste(input_dat,list.files(pattern="dat"),sep="/")
#### define outputfolders
outputfolder <- paste(data_path,"/intermediary_analysis_steps/heatmaps/group",sep="")
if (!file.exists(outputfolder)){dir.create(outputfolder,recursive=T)}
for (datfile in dat_list){
root_name <- gsub("\\.dat","",unlist(strsplit(datfile,split="/"))[grepl("colony",unlist(strsplit(datfile,split="/")))])
outputfolder2 <- paste(outputfolder,root_name,sep="/");if (!file.exists(outputfolder2)){dir.create(outputfolder2,recursive=T)}
colony <- unlist(strsplit(root_name,split="_"))[grepl("colony",unlist(strsplit(root_name,split="_")))]
tagfile <- tag_list[grepl(colony,tag_list)]
split_file <- split_list[grepl(root_name,split_list)]
split_info <- read.table(split_file,header=T,stringsAsFactors = F)
tag <- read.tag(tagfile)$tag
names(tag)[names(tag)=="#tag"] <- "tag"
tag <- tag[which(tag$tag!="#tag"),]
tag[which(tag$age==0),"age"] <- NA
antlist <- tag[which(tag$final_status=="alive"),"tag"]
box <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"box"]
treatment <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"treatment"]
colony_size <- info[which(info$colony==as.numeric(gsub("colony","",colony))),"colony_size"]
final_time <- info_datfile[which(info_datfile$dat_file==paste(root_name,".dat",sep="")),"end_time"]
if (grepl("PreTreatment",root_name)){
period <- "before"
}else {
period <- "after"
}
for (i in 1:nrow(split_info)){
print(paste(datfile,"; Time window =",i))
start_time <- split_info [i,"time"]
if (i<nrow(split_info)){
duration <- split_info [i+1,"time"] - start_time -0.25
}else{
duration <- final_time-start_time-0.25
}
###Run Heatmap
for (group in c("untreated")){
outputfile <- paste(outputfolder2,"/",group,"_TD",split_info[i,"time_of_day"],"_TH",split_info[i,"time_hours"],sep="")
command <- paste(executables_path,"/heatmap3_tofile -i ",datfile," -t ",tagfile," -b ",box," -s ",start_time, " -d ", duration," -n 1 -h group -g ",group," -m ",outputfile,";",sep="")
system(command)
}
}
}
<file_sep>/analysis_scripts/mice_analysis.R
#' Analysis Scripts for comparing the change in network metric for analysing the
#' mouse nets to compare across different species.
#'
#' The metrics that are analysed will be used:
#'
# Import the mice networks.
source("data_prep_scripts/import_mice_networks.R", echo = FALSE)
mice_net_analysis <- function(){
#' Iterate through the list of lists in to form analysis on the mice networks.
m_df <- import_mice_networks()
master_list <- list()
master_idx <- 1
for(tr in names(m_df)){
for(tp in names(m_df[[tr]])){
for(n in 1:length(m_df[[tr]][[tp]])){
temp_net <- m_df[[tr]][[tp]][[n]]
# Metadata
temp_list <- c(
"network" = paste0("mouse_", tr),
"animal" = "mouse",
"condition" = tp,
"replicate_num" = n
)
temp_list <- get_graph_metrics(temp_net, temp_list)
master_list[[master_idx]] <- temp_list
master_idx <- master_idx + 1
}
}
}
# Append to dataframe.
final <- data.frame(do.call(rbind, master_list))
return(final)
}
mice_ind_analysis <- function(){
#' Iterate through the list of lists in to form analysis on the mice networks.
m_df <- import_mice_networks()
master_list <- list()
master_idx <- 1
for(tr in names(m_df)){
if(tr != "LPS"){
next()
}
for(tp in names(m_df[[tr]])){
for(n in 1:length(m_df[[tr]][[tp]])){
temp_net <- m_df[[tr]][[tp]][[n]]
# Metadata
temp_list <- c(
"network" = paste0("mouse_", tr),
"animal" = "mouse",
"condition" = tp,
"replicate_num" = n
)
temp_df <- get_graph_ind_metrics(temp_net)
for(name in names(temp_list)){
temp_df[[name]] <- temp_list[[name]]
}
temp_list <- temp_df
master_list[[master_idx]] <- temp_list
master_idx <- master_idx + 1
}
}
}
# Append to dataframe.
final <- data.frame(do.call(rbind, master_list))
return(final)
}
mice_pop_analysis <- function(){
#' Iterate through the list of lists in to form analysis on the mice networks.
m_df <- import_mice_networks()
master_list <- list()
master_idx <- 1
for(tr in names(m_df)){
for(tp in names(m_df[[tr]])){
for(n in 1:length(m_df[[tr]][[tp]])){
temp_net <- m_df[[tr]][[tp]][[n]]
# Metadata
temp_list <- c(
"network" = paste0("mouse_", tr),
"animal" = "mouse",
"condition" = tp,
"replicate_num" = n
)
temp_list <- get_graph_pop_metrics(temp_net, temp_list)
master_list[[master_idx]] <- temp_list
master_idx <- master_idx + 1
}
}
}
# Append to dataframe.
final <- data.frame(do.call(rbind, master_list))
return(final)
}
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/1_trackconverter.R
####1_trackconverter.R#####
### Calls C++ functions trackconverter and controldat (https://github.com/laurentkeller/anttrackingUNIL)
### Takes tracking csv files as an input and creates a binary data file of class 'datfile', a log file, a tags file containing the list of dead, and a double file containing information on double detections
### Checks the integrity of the file created
### Note that the tag files produced by trackconverter need to be modified to take into account the orientation of the ant compared to the tag using Antorient (https://github.com/laurentkeller/anttrackingUNIL),
### to remove false detections,
### and to record the frame of death / tag loss if relevant (see 2_define_deaths.R)
### The final processed tag files are provided in the subfolder original_data/tag_files and will be used in all later steps of the analysis
###Created by <NAME>
###################################
### define directories
input_path <- paste(data_path,"original_data",sep="/")
output_path <- paste(data_path,"intermediary_analysis_steps/datfiles_uncorrected",sep="/")
####If necessary, create output folder
if(!exists(output_path)){
dir.create(output_path,recursive = T,showWarnings = F)
}
#####Navigate to tracking data folder and list data files
setwd(paste(input_path,"tracking",sep="/"))
tracking_files <- paste(input_path,"/tracking/",list.files(pattern="csv"),sep="")
tracking_files <- tracking_files[!grepl("corr",tracking_files)]
#####Navigate to output folder
setwd(output_path)
#####for each file
for (tracking_file in tracking_files){
file_root_name <- gsub(paste(input_path,"/tracking/",sep=""),"",tracking_file)
colony <- as.numeric(gsub("colony","",unlist(strsplit(file_root_name,split="_"))[1]))
command_line <- paste(executables_path,"/trackconverter ",gsub("csv","dat",file_root_name), " ",info[info$colony==colony,"box"]," ",gsub("csv","log",file_root_name)," ", tracking_file,sep="")
print(command_line)
system(command_line)
command_line <- paste(executables_path,"/controldat ",gsub("csv","dat",file_root_name),sep="")
print(command_line)
system(command_line)
}
#####Navigate to tracking data folder and remove temporary corrected files
setwd(paste(input_path,"tracking",sep="/"))
system("rm *corr*")
<file_sep>/data_prep_scripts/Great_tits_Firth et al 2017.R
rm(list=ls())
# Great tits #############
#setwd("C:/Users/alexis/Google Drive (1)/Between Computers/CNWW2021/Great_tits_Firth et al 2017")
load("C:/Users/alexis/Google Drive (1)/Between Computers/CNWW2021/Great_tits_Firth et al 2017/Raw Data For Firth et al.RData")
library(asnipe)
library(dplyr)
library(igraph)
library(einet)
# time must be numeric for asnipe package
records$TimeStamp<-as.numeric(as.POSIXct(records$time))
for(i in unique(records$week)){
print(i)
df1<-subset(records,week==i)
df_assoc_pts<-(df1 %>%
select(ring, TimeStamp,location))
try(Location2 <- df_assoc_pts %>% count(location) %>% filter(n > 2))
try(df_assoc_pts_filtered<- df_assoc_pts %>% filter(location %in% Location2$location)) #all had more than 2 points anyway so wasn't really necessary
try(df_assoc_pts_filtered$ring<-as.factor(df_assoc_pts_filtered$ring))
try(global_ids<-levels(df_assoc_pts_filtered$ring))
try(gmm_data<- asnipe::gmmevents(time = df_assoc_pts_filtered$TimeStamp,
identity = df_assoc_pts_filtered$ring,
location = df_assoc_pts_filtered$location,
global_ids=global_ids))
try(gbi<-(gmm_data$gbi))
try(events<- gmm_data$metadata %>% mutate(time_window = (End - Start)))
try(observations_per_event <- gmm_data$B)
try(adjm_gmm <- asnipe::get_network(gbi, data_format = "GBI", association_index = "SRI"))
try(net_gmm <- igraph::graph.adjacency(adjm_gmm, mode = "undirected", diag = F, weighted = T))
try(save(adjm_gmm, file = paste("adjm_gmm_",i,".RData")))
try( write.csv(adjm_gmm, paste("adjm_gmm_",i,".csv")))
try(write.csv(gbi, paste("gbi_gmm_",i,".csv")))
try( png(paste("plot", i, ".png", sep = ""), width = 1000, height = 1000))
try(plot(net_gmm))
dev.off()
try(between<-igraph::betweenness(net_gmm, directed = TRUE,weights=E(net_gmm)$weight))
eigen <- eigen_centrality(net_gmm, directed = TRUE, weights = E(net_gmm)$weight)
ec <- eigen$vector
ec.value <- eigen$value
# pool individual
pool_id <- cbind.data.frame(between,
eigen, ec, ec.value)
### group-level ##
density<-graph.density(net_gmm) #should be same as: density=mean(igraph::degree(net_gmm))/(vcount(net_gmm)-1)
apl <- igraph::mean_distance(net_gmm) #average.path.length(graph.ref.crowd)
ei <- effective_information(net_gmm, effectiveness = FALSE)
n<-length(unique(df1$ring))
eff <- ei/log2(n) # normalized value to control for network size
#Find proportion unknown relationships, a measure of sparseness
prunk <- EloRating::prunk(adjm_gmm)
prunk.pu <- as.numeric(prunk[1])
prunk.dyads <- as.numeric(prunk[2])
# pool group
pool_group <- cbind.data.frame(ec, ec.value,
apl,
ei, eff,
prunk.pu, prunk.dyads, density
)
#try(pool_id$ring <- rownames(pool_id))
try(pool_id <-cbind(rownames(pool_id), data.frame(pool_id, row.names=NULL)))
names(pool_id)[names(pool_id) == "rownames(pool_id)"] <- "ring"
try(pool_id$week<-i)
#try(pool_group$ring <- rownames(pool_group))
try(pool_group <-cbind(rownames(pool_group), data.frame(pool_group, row.names=NULL)))
names(pool_group)[names(pool_group) == "rownames(pool_group)"] <- "ring"
try(pool_group$week<-i)
print(i)
try(EdgeList<-as_edgelist(net_gmm, names = TRUE))
try(EdgeList<-as.data.frame(EdgeList))
try(EdgeList$week<-i)
assign( paste("pool_id", i, sep = "_") , pool_id, envir = globalenv() )
assign( paste("pool_group", i, sep = "_") , pool_group, envir = globalenv() )
assign( paste("EdgeList", i, sep = "_") , EdgeList, envir = globalenv() )
}
ID_sheets<-grep("pool_id",names(.GlobalEnv),value=TRUE)
ID_sheets_list<-do.call("list",mget(ID_sheets))
poolID_allWeeks<-do.call(rbind, ID_sheets_list)
#write.csv(poolID_allWeeks,"great_tits_Firth.et.al.2017_pool_id.csv")
group_sheets<-grep("pool_group",names(.GlobalEnv),value=TRUE)
group_sheets_list<-do.call("list",mget(group_sheets))
pool_group_allWeeks<-do.call(rbind, group_sheets_list)
#write.csv(pool_group_allWeeks,"great_tits_Firth.et.al.2017_pool_group.csv")
Edge_sheets<-grep("EdgeList",names(.GlobalEnv),value=TRUE)
Edge_sheets_list<-do.call("list",mget(Edge_sheets))
Edge_sheets_allWeeks<-do.call(rbind, Edge_sheets_list)
write.csv(Edge_sheets_allWeeks,"EdgeLists_perWeek_Great_tits_Firth et al 2017.csv")
<file_sep>/visualizations/bats.py
import pandas
import matplotlib
from matplotlib import pyplot
import numpy as np
import networkx
import vis_params # local parameters file.
import reorder # node reordering, for e.g. circular layout.
#
treatment_palette = {
'sick': [0,0.5,0],
'control': [0.5,0,0.5]
}
#
df = pandas.read_csv(vis_params.ANALYSIS_FOLDER + 'bats_pre_post_edgelist.csv')
all_bats = np.unique( df[['bat1','bat2']].values )
n = len(all_bats)
cond_dict = dict( list( df.groupby('condition') ) )
ncond = len(cond_dict)
# assign a node color for every bat by treatment.
treatment_col_dict = {b: treatment_palette['control'] for b in all_bats}
for row in df.iloc:
treatment_col_dict[ row['bat1'] ] = treatment_palette[ row['treatment_bat1'] ]
#
####
# make the figure.
fig,ax = pyplot.subplots( 1,ncond, figsize=(10,5), constrained_layout=True )
for i,c in enumerate(['pre', 'post']):
df_s = cond_dict[c]
elist = df_s[['bat1','bat2','weight']].values
G = networkx.Graph()
G.add_weighted_edges_from(elist)
# reorder for some sort of clustering
G = reorder.reorder_nx_Graph(G)
edge_widths = [G[u][v]['weight']/1000 for u,v in G.edges()]
if c=='pre':
pos_xy = networkx.spectral_layout(G)
pos_xy = networkx.spring_layout(G, pos=pos_xy, iterations=1, k=0.4)
else:
# try manual adjustment
# many iterations will get to a steady state - but
# no real "message" about how network adjusts after treatment.
# pos_xy = networkx.spectral_layout(G)
pos_xy = networkx.spring_layout(G, pos=pos_xy, iterations=1, k=0.4)
#
node_colors = [treatment_col_dict[b] for b in G.nodes()]
pyplot.sca( ax[i] )
networkx.draw_networkx( G,
node_color = node_colors,
pos = pos_xy,
arrowsize=edge_widths,
font_color='w',
font_size=12,
edge_color=[0,0,0,0.2],
node_shape='s')
ax[i].set_title(c)
#
# make a legend to indicate color meaning
for k,v in treatment_palette.items():
ax[0].scatter([],[], c=[v], label=k, s=200)
ax[0].legend(loc='best')
if __name__=="__main__":
fig.show()
fig.savefig(vis_params.IMAGES_FOLDER + 'bats.png')<file_sep>/figures/visualisations.R
#' Visualistions
library(dplyr)
library(ggplot2)
source("analysis_scripts/general_analysis.R", echo = F)
import_individuals_all <- function(){
return(readr::read_csv(file.path("analysis_results", "all_individual_results.csv"),
col_types = c("cdddcccc")))
}
all_ind_data <- import_individuals_all()
import_population_all <- function(){
return(readr::read_csv(file.path("analysis_results", "all_population_results.csv"),
col_types = c("ccccdid")))
}
all_pop_data <- import_population_all()
fix_timepoints <- function(d_f){
cond_1 <- c("low_risk", "before", "Pre")
cond_2 <- c("high_risk", "after", "Post")
d_f$numerical_condition <- NA
d_f$numerical_condition[d_f$condition %in% cond_1] <- 1
d_f$numerical_condition[d_f$condition %in% cond_2] <- 2
return(d_f)
}
get_difference <- function(d_f){
#' Get the difference of values the
return(d_f %>%
fix_timepoints() %>%
select(-network, -condition) %>%
# group_by(animal, replicate_num) %>%
arrange(animal, replicate_num, numerical_condition) %>%
mutate_at(vars(-animal, -replicate_num, -numerical_condition), difference_calc) %>%
filter(numerical_condition == 1))
}
difference_calc <- function(x){
return(as.numeric(x) - as.numeric(lag(x)))
}
# For testing.
# arrange(animal, replicate_num, numerical_condition) %>% View()
plot_comparison_plots <- function(d_f){
final_plot <- d_f %>%
fix_timepoints() %>%
tidyr::pivot_longer(c("density", "eigenvector_centrality",
"betweenness_centrality","n_nodes",
"effective_information"), names_to = "metric",
values_to = "value") %>%
ggplot(aes(x = as.factor(numerical_condition), y = as.numeric(value), fill = animal))+
geom_boxplot()+
facet_grid(metric~animal, scale = "free")+
labs(x = "Pre (1) or Post (2) Stimulus", y = "Value",
title = "Pre and Post Stimuls in animal social networks.")
ggsave(final_plot, path = "figures", height = 8, width = 6,
filename = "comparing_pre_post_boxplot.png", device = "png")
}
plot_comparison_plots(final_df)
plot_individual_distributions <- function(d_f){
p1 <- d_f %>%
fix_timepoints() %>%
ggplot(aes(x = degree, fill = condition)) +
geom_histogram(binwidth = 1)+
facet_wrap(.~animal, scale = "free") +
labs(title = "Degree Distribution for Individuals in the population")
ggsave(p1, path = "figures", filename = "degree_distribution.png", device = "png")
p2 <- d_f %>%
fix_timepoints() %>%
ggplot(aes(x = eigenvector_centrality, fill = condition)) +
geom_histogram()+
facet_wrap(.~animal, scale = "free") +
labs(title = "Eigenvector Centrality for Individuals in the population")
ggsave(p2, path = "figures", filename = "eigenvector_distribution.png", device = "png")
p3 <- d_f %>%
fix_timepoints() %>%
ggplot(aes(x = betweeness, fill = condition)) +
geom_histogram()+
facet_wrap(.~animal, scale = "free") +
labs(title = "Betweenness Centrality for Individuals in the population")
ggsave(p3, path = "figures", filename = "betweeness_distribution.png", device = "png")
}
plot_individual_distributions(all_ind_data)
plot_all_change <- function(d_f){
final_plot <- d_f %>%
get_difference() %>%
tidyr::pivot_longer(c("density", "eigenvector_centrality",
"betweenness_centrality","n_nodes",
"effective_information"), names_to = "metric",
values_to = "value") %>%
ggplot(aes(x = animal, y = as.numeric(value), fill = animal))+
geom_boxplot()+
theme(axis.text.x = element_text(angle = 20, vjust = 1, hjust = 1))+
facet_wrap(.~metric, scales = "free") +
labs(title = "Comparing Animal Social Networks", x = "",
y = "Change in Value", fill = "Species")
ggsave(final_plot, path = "figures", filename = "all_change_boxplot.png", device = "png")
}
plot_all_change(final_df)
all_individual_plots <- function(){
final_df %>%
ggplot(aes(x = condition, y = as.numeric(eigenvector_centrality),
fill = condition))+
geom_violin(alpha = 0.4) +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
facet_grid(.~animal, scales = "free")+
labs(title = "Comparing Eigenvector Centrality",
y = "Eigenvector Centrality")
final_df %>%
ggplot(aes(x = condition,
y = as.numeric(betweenness_centrality),
fill = condition))+
geom_violin(alpha = 0.4) +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
facet_grid(.~animal, scales = "free")+
labs(title = "Comparing Betweenness Centrality",
y = "Betweenness Centrality")
final_df %>%
ggplot(aes(x = condition, y = as.numeric(density),
fill = condition))+
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
facet_grid(.~animal, scales = "free")+
labs(title = "Comparing Density",
y = "Density")
final_df %>%
ggplot(aes(x = condition, y =as.numeric(n_nodes),
fill = condition))+
# geom_bar(alpha = 0.4, stat = "identity") +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
facet_grid(.~animal, scales = "free")+
labs(title = "Comparing Population (Number of Nodes)",
y = "NUmber of Nodes")
final_df %>%
ggplot(aes(x = condition, y =as.numeric(effective_information),
fill = condition))+
# geom_bar(alpha = 0.4, stat = "identity") +
geom_violin(alpha = 0.4) +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
facet_grid(.~animal, scales = "free")+
labs(title = "Comparing Effective Information Spread",
y = "Effective Information")
### COmparing the change in network metrics.
final_df %>%
get_difference() %>%
ggplot(aes(x = animal, y = as.numeric(eigenvector_centrality),
fill = animal))+
geom_violin(alpha = 0.4) +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
# facet_grid(.~animal, scales = "free")+
labs(title = "Change in Eigenvector Centrality",
y = "Eigenvector Centrality")
final_df %>%
get_difference() %>%
ggplot(aes(x = animal,
y = as.numeric(betweenness_centrality),
fill = animal))+
geom_violin(alpha = 0.4) +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
# facet_grid(.~animal, scales = "free")+
labs(title = "Change in Betweenness Centrality",
y = "Betweenness Centrality")
final_df %>% get_difference() %>%
ggplot(aes(x = animal, y = as.numeric(density),
fill = animal))+
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
# facet_grid(.~animal, scales = "free")+
labs(title = "Change in Density",
y = "Density")
final_df %>% get_difference() %>%
ggplot(aes(x = animal, y =as.numeric(n_nodes),
fill = animal))+
# geom_bar(alpha = 0.4, stat = "identity") +
geom_boxplot(width = 0.1, size = 1.5)+
# facet_grid(.~animal, scales = "free")+
labs(title = "Change in Population (Number of Nodes)",
y = "NUmber of Nodes")
final_df %>%
get_difference() %>%
ggplot(aes(x = animal, y =as.numeric(effective_information),
fill = animal))+
# geom_bar(alpha = 0.4, stat = "identity") +
geom_violin(alpha = 0.4) +
geom_boxplot(width = 0.1, size = 1.5, fill = NA)+
# facet_grid(.~animal, scales = "free")+
labs(title = "Change in Effective Infomation Spread",
y = "Effective Information")
}
<file_sep>/analysis_scripts/beetle_analysis.R
#' Append the beetle analysis for both the population and individual level metrics.
#' Run the effective information criterion.
append_beetle_population_analysis <- function(){
beetles <- readr::read_csv(file.path("analysis_results", "Population_metrics_beetle.csv"))
names(beetles) <- c("replicate_num", "condition", "n_nodes", "density")
beetles$network <- "beetle"
beetles$animal <- "beetle"
beetle_edges <- readr::read_csv(file.path("data",
"Beetles_FormicaEtAl2017","SRI_edgelist_no_control.csv")) %>%
select(-X1)
beetle_nets <- list()
for(treatment in unique(beetle_edges$Group.ID.Populations)){
beetle_nets[[treatment]] <- list()
for(tp in unique(beetle_edges$Treatment.Period)){
data_subset <- beetle_edges %>%
filter(Group.ID.Populations == treatment, Treatment.Period == tp)
beetle_nets[[treatment]][[tp]] <- igraph::graph_from_data_frame(data_subset)
}
}
beetles$effective_information <- NA
for(c in unique(beetles$replicate_num)){
if(c %in% c("C1", "C2", "C3", "C4")){
next()
}
for(tp in unique(beetles$condition)){
print(paste0("Effective INfor: ", einet::effective_information(beetle_nets[[c]][[tp]])))
beetles$effective_information[which((beetles$replicate_num == c) &
beetles$condition == tp)] <- as.character(
einet::effective_information(beetle_nets[[c]][[tp]])/
log2(as.numeric(length(V(beetle_nets[[c]][[tp]])))))
}
}
return(beetles %>%
mutate(condition = as.character(condition),
n_nodes = as.character(n_nodes),
animal = "beetle",
network = "beetle") %>%
filter(!(replicate_num %in% c("C1", "C2", "C3", "C4"))))
}
append_beetle_population_analysis()
append_beetle_ind_analysis <- function(){
beetle <- readr::read_csv(file.path("analysis_results", "Individual_metrics_beetles.csv")) %>%
select(-CLOSENESS_CENTRALITY, -DEGREE_NORMALIZED)
names(beetle) <- c("replicate_num", "condition", "node_ID", 'degree', "eigenvector_centrality", "betweeness")
return(beetle %>% mutate(network = "beetle", animal = "beetle") %>%
filter(!(replicate_num %in% c("C1", "C2", "C3", "C4"))))
}
View(append_beetle_ind_analysis())
get_beetle_nets <- function(){
beetle_edges <- readr::read_csv(file.path("data",
"Beetles_FormicaEtAl2017","SRI_edgelist_no_control.csv")) %>% select(-X1)
# View(beetle_edges)
all_beetles <- list()
for(treatment in unique(beetle_edges$Group.ID.Populations)){
all_beetles[[treatment]] <- list()
for(tp in unique(beetle_edges$Treatment.Period)){
data_subset <- beetle_edges %>%
filter(Group.ID.Populations == treatment, Treatment.Period == tp)
all_beetles[[treatment]][[tp]] <- 2
#igraph::graph_from_data_frame(data_subset)
}
}
return(all_beetles)
}
# beetle_sample <- read_in_beetle_graphs()
# append_beetle_analysis()
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/14_summarise_interactions.R
####14_summarise_interactions.R#####
####Takes an interaction list as an input, and calculates:
### - the total duration of interactions of each ant to each of four categories of individuals (queen, nurses, untreated foragers and treated foragers)
### - the overall distribution of interactions according to task groups and ages
###Created by <NAME>
####################################
to_keep_ori <- to_keep
#################################
options(digits=16) ; options(digits.secs=6) ; options("scipen" = 10)
#### get input file list
input_path <- paste(data_path,"/intermediary_analysis_steps/binned_interaction_lists",sep="")
setwd(input_path)
input_folders <- list.dirs(recursive=T,path="PreTreatment",full.names=F)
input_folders <- input_folders[which(input_folders!="")]
outputfolder1 <- paste(data_path,"/processed_data/individual_behaviour/random_vs_observed",sep="")
if (!file.exists(outputfolder1)){dir.create(outputfolder1,recursive = T)}
summary_dol <- NULL
to_keep <- c(ls(),"to_keep","input_folder","network_file","network_files","summary_interactions","summary_pairs","all_interactions")
for (input_folder in input_folders){
print(input_folder)
setwd(input_path)
network_files <- list.files(path=paste("PreTreatment/",input_folder,sep=""),full.names=T)
if (input_folder=="observed"&grepl("main",data_path)){
network_files <- c(network_files,list.files(path=paste("PostTreatment/",input_folder,sep=""),full.names=T))
}
summary_interactions <- NULL
summary_pairs <- NULL
all_interactions <- NULL
for (network_file in network_files){
print(network_file)
####get file metadata
root_name <- gsub("_interactions.txt","",unlist(strsplit(network_file,split="/"))[grepl("colony",unlist(strsplit(network_file,split="/")))])
components <- unlist(strsplit(root_name,split="_"))
colony <- components[grepl("colony",components)]
colony_number <- as.numeric(gsub("colony","",colony))
treatment <- info[which(info$colony==colony_number),"treatment"]
colony_size <- info[which(info$colony==colony_number),"colony_size"]
if (!all(!grepl("PreTreatment",components))){period <- "before"}else{period <- "after"}
time_hours <- as.numeric(gsub("TH","",components[which(grepl("TH",components))]))
time_of_day <- as.numeric(gsub("TD","",components[which(grepl("TD",components))]))
if (grepl("age",data_path)){
colony_ages <- ages[which(ages$colony==colony),]
}
####get appropriate task_group list, treated list and tag
colony_treated <- treated[which(treated$colony==colony_number),"tag"]
colony_task_group <- task_groups[which(task_groups$colony==colony),]
tagfile <- tag_list[which(grepl(colony,tag_list))]
if (length(tagfile)>1){
tagfile <- tagfile[grepl(components[grepl("Treatment",components)],tagfile)]
}
tag <- read.tag(tagfile)$tag
names(tag)[names(tag)=="#tag"] <- "tag"; tag <- tag[which(tag$tag!="#tag"),]
tag[which(tag$age==0),"age"] <- NA ###unknown ages are coded as 0 in the tag file
tag <-tag[which(tag$final_status=="alive"),] ###remove dead ants from tag file
####read interactions
interactions <- read.table(network_file,header=T,stringsAsFactors = F)
#### add a column contaning interaction duration in min
interactions["duration_min"] <- (interactions$Stoptime - interactions$Starttime + 0.5) /60 ###duration in minutes (one frame = 0.5 second)
#### add a column containing the status of tag 1 and the status of tag2
foragers <- colony_task_group[which(colony_task_group$task_group=="forager"),"tag"]
nurses <- colony_task_group[which(colony_task_group$task_group=="nurse"),"tag"]
#####1. calculate within/between caste interactions for before period
interactions[c("status_Tag1","status_Tag2")] <- NA
interactions[which(interactions$Tag1%in%foragers),"status_Tag1"] <- "forager"
interactions[which(interactions$Tag2%in%foragers),"status_Tag2"] <- "forager"
interactions[which(interactions$Tag1%in%nurses),"status_Tag1"] <- "nurse"
interactions[which(interactions$Tag2%in%nurses),"status_Tag2"] <- "nurse"
interactions[which(interactions$Tag1==queenid),"status_Tag1"] <- "queen"
interactions[which(interactions$Tag2==queenid),"status_Tag2"] <- "queen"
if (period=="before"){
inter <- interactions
inter <- inter[,sort(names(inter))]
all_interactions <- rbind(all_interactions,data.frame(randy=input_folder,colony_size=colony_size,period=period,inter))
}
# #####2. continue calculations for pre vs post
interactions[which(interactions$Tag1%in%colony_treated),"status_Tag1"] <- "treated"
interactions[which(interactions$Tag2%in%colony_treated),"status_Tag2"] <- "treated"
#### use this information to calculate, for each worker, the cumulated duration of interaction with treated workers
aggregated1 <- aggregate(na.rm=T,na.action="na.pass",duration_min~Tag1+status_Tag2,FUN=sum,data=interactions)
names(aggregated1) <- c("tag","partner_status","duration_min")
aggregated2 <- aggregate(na.rm=T,na.action="na.pass",duration_min~Tag2+status_Tag1,FUN=sum,data=interactions)
names(aggregated2) <- c("tag","partner_status","duration_min")
aggregated <- rbind(aggregated1,aggregated2)
aggregated <- aggregate(na.rm=T,na.action="na.pass",duration_min~tag+partner_status,FUN=sum,data=aggregated)
full_table <- expand.grid(tag=tag[which(tag$final_status=="alive"),"tag"],partner_status=c("queen","nurse","forager","treated"),stringsAsFactors = F)
full_table <- merge(full_table,aggregated[c("tag","partner_status","duration_min")],all.x=T,all.y=T)
full_table[is.na(full_table$duration_min),"duration_min"] <- 0
full_table <- merge(full_table,tag[c("tag","group")]); names(full_table)[names(full_table)=="group"] <- "status"
full_table <- merge(full_table,colony_task_group[c("tag","task_group")]); full_table[which(full_table$status=="treated"),"task_group"] <- "treated"
if (!grepl("age",data_path)){
full_table$age <- NA
}else{
full_table <- merge(full_table,colony_ages,all.x=T,all.y=F)
}
full_table <- full_table[c("tag","age","task_group","status","partner_status","duration_min")]
summary_interactions <- rbind(summary_interactions,data.frame(randy=input_folder,colony=colony,colony_size=colony_size,treatment=treatment,period=period,time_of_day=time_of_day,time_hours=time_hours,full_table,stringsAsFactors = F))
#####2. continue calculations for pre vs post
interactions[which(interactions$Tag1%in%colony_treated),"status_Tag1"] <- "treated"
interactions[which(interactions$Tag2%in%colony_treated),"status_Tag2"] <- "treated"
#### use this information to calculate, for each worker, the cumulated duration of interaction with treated workers
aggregated1 <- aggregate(na.rm=T,na.action="na.pass",duration_min~Tag1+status_Tag2,FUN=sum,data=interactions)
names(aggregated1) <- c("tag","partner_status","duration_min")
aggregated2 <- aggregate(na.rm=T,na.action="na.pass",duration_min~Tag2+status_Tag1,FUN=sum,data=interactions)
names(aggregated2) <- c("tag","partner_status","duration_min")
aggregated <- rbind(aggregated1,aggregated2)
aggregated <- aggregate(na.rm=T,na.action="na.pass",duration_min~tag+partner_status,FUN=sum,data=aggregated)
full_table <- expand.grid(tag=tag[which(tag$final_status=="alive"),"tag"],partner_status=c("queen","nurse","forager","treated"),stringsAsFactors = F)
full_table <- merge(full_table,aggregated[c("tag","partner_status","duration_min")],all.x=T,all.y=T)
full_table[is.na(full_table$duration_min),"duration_min"] <- 0
full_table <- merge(full_table,tag[c("tag","group")]); names(full_table)[names(full_table)=="group"] <- "status"
full_table <- merge(full_table,colony_task_group[c("tag","task_group")]); full_table[which(full_table$status=="treated"),"task_group"] <- "treated"
if (!grepl("age",data_path)){
full_table$age <- NA
}else{
full_table <- merge(full_table,colony_ages,all.x=T,all.y=F)
}
full_table <- full_table[c("tag","age","task_group","status","partner_status","duration_min")]
summary_interactions <- rbind(summary_interactions,data.frame(randy=input_folder,colony=colony,colony_size=colony_size,treatment=treatment,period=period,time_of_day=time_of_day,time_hours=time_hours,full_table,stringsAsFactors = F))
clean()
}
#####if folder = observed, use the summary_interactions table to compute inter-caste contacts #####
if (grepl("main",data_path)&input_folder=="observed"){
summary_interactions <- summary_interactions [which(!summary_interactions$partner_status%in%c("treated","queen")),]
summary_interactions <- summary_interactions [which(!summary_interactions$task_group%in%c("treated","queen")),]
summary_interactions["within_vs_between"] <- summary_interactions$partner_status==summary_interactions$task_group
summary_interactions <- aggregate(na.rm=T,na.action="na.pass",duration_min~.,FUN=sum,data=summary_interactions[c("colony","period","time_of_day","time_hours","tag","task_group","status","partner_status","duration_min","within_vs_between")])
summary_interactions_between <- summary_interactions[which(!summary_interactions$within_vs_between),!names(summary_interactions)%in%c("partner_status","within_vs_between")];
names(summary_interactions_between)[names(summary_interactions_between)=="duration_min"] <- "inter_caste_contact_duration"
#####add information to individual behaviour file
behav <- read.table(paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""),header=T,stringsAsFactors = F)
behav <- merge(behav,summary_interactions_between[c("colony","tag","time_hours","inter_caste_contact_duration")],all.x=T,all.y=F,sort=F)
behav <- behav[order(behav$colony,behav$tag,behav$time_hours),]
write.table(behav,file=paste(data_path,"/processed_data/individual_behaviour/pre_vs_post_treatment/individual_behavioural_data.txt",sep=""), row.names=F, col.names=T,append=F,quote=F)
}
###Use all_interactions to obtain information about age-based DoL before treatment
###first check that all_interactions only has Pre-treatment
all_interactions <- all_interactions[which(all_interactions$period=="before"),]
###summ all interactions for each pair of ants
all_interactions <- aggregate(na.rm=T,na.action="na.pass",duration_min~randy+colony+colony_size+period+Tag1+Tag2+status_Tag1+status_Tag2+treatment,FUN=sum,data=all_interactions)
###calculate intra_caste_over_inter_caste_WW_contact_duration
all_interactions["same_caste"] <- all_interactions$status_Tag1==all_interactions$status_Tag2
same_caste_interactions <- aggregate(na.rm=T,na.action="na.pass",duration_min~randy+colony+colony_size+treatment+period,FUN=sum,data=all_interactions[which((all_interactions$status_Tag1!="queen")&(all_interactions$status_Tag2!="queen")&(all_interactions$same_caste)),])
names(same_caste_interactions)[names(same_caste_interactions)=="duration_min"] <- "duration_min_within"
inter_caste_interactions <- aggregate(na.rm=T,na.action="na.pass",duration_min~randy+colony+colony_size+treatment+period,FUN=sum,data=all_interactions[which((all_interactions$status_Tag1!="queen")&(all_interactions$status_Tag2!="queen")&(!all_interactions$same_caste)),])
names(inter_caste_interactions)[names(inter_caste_interactions)=="duration_min"] <- "duration_min_between"
inter_intra_caste_interactions <- merge(same_caste_interactions,inter_caste_interactions,all.x=T,all.y=T)
inter_intra_caste_interactions["intra_caste_over_inter_caste_WW_contact_duration"] <- inter_intra_caste_interactions$duration_min_within/inter_intra_caste_interactions$duration_min_between
dol <- inter_intra_caste_interactions[!names(inter_intra_caste_interactions)%in%c("duration_min_within","duration_min_between")]
###calculate queen contact with nurses vs. workers
queen_interactions <- all_interactions[which(all_interactions$status_Tag1=="queen"|all_interactions$status_Tag2=="queen"),]
queen_interactions[which(queen_interactions$status_Tag1=="queen"),"partner"] <- queen_interactions[which(queen_interactions$status_Tag1=="queen"),"Tag2"]
queen_interactions[which(queen_interactions$status_Tag1=="queen"),"partner_status"] <- queen_interactions[which(queen_interactions$status_Tag1=="queen"),"status_Tag2"]
queen_interactions[which(queen_interactions$status_Tag2=="queen"),"partner"] <- queen_interactions[which(queen_interactions$status_Tag2=="queen"),"Tag1"]
queen_interactions[which(queen_interactions$status_Tag2=="queen"),"partner_status"] <- queen_interactions[which(queen_interactions$status_Tag2=="queen"),"status_Tag1"]
interaction_with_nurses <-aggregate (na.rm=T,na.action="na.pass",duration_min~randy+colony+colony_size+period+treatment,FUN=sum,data=queen_interactions[which(queen_interactions$partner_status=="nurse"),])
names(interaction_with_nurses)[names(interaction_with_nurses)=="duration_min"] <- "duration_min_with_nurses"
interaction_with_forager <-aggregate (na.rm=T,na.action="na.pass",duration_min~randy+colony+colony_size+period+treatment,FUN=sum,data=queen_interactions[which(queen_interactions$partner_status=="forager"),])
names(interaction_with_forager)[names(interaction_with_forager)=="duration_min"] <- "duration_min_with_foragers"
queen_interac <- merge(interaction_with_nurses,interaction_with_forager,all.x=T,all.y=T)
queen_interac["QNurse_over_QForager_contact_duration"] <- queen_interac$duration_min_with_nurses/queen_interac$duration_min_with_foragers
dol <- merge(dol,queen_interac[c("randy","colony","period","QNurse_over_QForager_contact_duration")])
###if necessary: add age
if (grepl("age",data_path)){
partner_ages <- ages; names(partner_ages) <- c("colony","partner","partner_age")
queen_interactions <- merge(queen_interactions,partner_ages,all.x=T,all.y=F)
ages_Tag1 <- ages; names(ages_Tag1) <- c("colony","Tag1","age_Tag1")
ages_Tag2 <- ages; names(ages_Tag2) <- c("colony","Tag2","age_Tag2")
all_interactions <- merge(all_interactions,ages_Tag1,all.x=T,all.y=F)
all_interactions <- merge(all_interactions,ages_Tag2,all.x=T,all.y=F)
all_interactions["age_diff"] <- abs(all_interactions$age_Tag2-all_interactions$age_Tag1)
###write ordered pair of interacting ants
all_interactions["ordered"]<- all_interactions[,"Tag1"]<all_interactions[,"Tag2"]
all_interactions[which(all_interactions$ordered),"new_Tag1"] <- all_interactions[which(all_interactions$ordered),"Tag1"]
all_interactions[which(all_interactions$ordered),"new_Tag2"] <- all_interactions[which(all_interactions$ordered),"Tag2"]
all_interactions[which(!all_interactions$ordered),"new_Tag1"] <- all_interactions[which(!all_interactions$ordered),"Tag2"]
all_interactions[which(!all_interactions$ordered),"new_Tag2"] <- all_interactions[which(!all_interactions$ordered),"Tag1"]
all_interactions["pair"] <- as.character(interaction(all_interactions$colony,all_interactions$new_Tag1,all_interactions$new_Tag2))
###to get slope: get each pair of possibly interacting ants
for (colony in unique(all_interactions$colony)){
colony_ages <- ages[which(ages$colony==colony),]
colony_ages_Tag1 <- colony_ages; names(colony_ages_Tag1) <- c("colony","Tag1","age_Tag1")
colony_ages_Tag2 <- colony_ages; names(colony_ages_Tag2) <- c("colony","Tag2","age_Tag2")
tagfile <- tag_list[which(grepl(colony,tag_list))][1]
tag <- read.tag(tagfile)$tag
names(tag)[names(tag)=="#tag"] <- "tag"; tag <- tag[which(tag$tag!="#tag"),]
####list ants of known ages
known_ages <- colony_ages[which(!is.na(colony_ages$age)),"tag"]
###remove queen fronm list
known_ages <- known_ages[known_ages!=queenid]
###remove dead ants from list
known_ages <- known_ages[which(known_ages%in%tag[which(tag$final_status=="alive"),"tag"])]
### prepare complete pair table
summ_pairs <- data.frame(combinations(n=length(known_ages),r=2,v=known_ages))
summ_pairs["ordered"]<- summ_pairs[,1]<summ_pairs[,2]
summ_pairs[which(summ_pairs$ordered),"Tag1"] <- summ_pairs[which(summ_pairs$ordered),1]
summ_pairs[which(summ_pairs$ordered),"Tag2"] <- summ_pairs[which(summ_pairs$ordered),2]
summ_pairs[which(!summ_pairs$ordered),"Tag1"] <- summ_pairs[which(!summ_pairs$ordered),2]
summ_pairs[which(!summ_pairs$ordered),"Tag2"] <- summ_pairs[which(!summ_pairs$ordered),1]
summ_pairs <- merge(summ_pairs,colony_ages_Tag1,all.x=T,all.y=F)
summ_pairs <- merge(summ_pairs,colony_ages_Tag2,all.x=T,all.y=F)
summ_pairs["age_diff"] <- abs(summ_pairs$age_Tag2-summ_pairs$age_Tag1)
summ_pairs["pair"] <- as.character(interaction(colony,summ_pairs$Tag1,summ_pairs$Tag2))
summ_pairs <- merge(summ_pairs,unique(all_interactions[which(all_interactions$colony==colony),c("colony","randy","colony_size","period","treatment")]))
###merge it with interactions whose age diff is known
summ_pairs <- merge(summ_pairs,all_interactions[which(all_interactions$colony==colony),c("colony","randy","colony_size","period","treatment","pair","duration_min")],all.x=T,all.y=F)
###and fill intreactions which did not happen with 0
summ_pairs[which(is.na(summ_pairs$duration_min)),"duration_min"] <- 0
model_WW <- lm(duration_min~age_diff,data=summ_pairs)
dol[dol$colony==colony,"slope_WW_contact_duration_f_age_diff"] <- coef(model_WW)["age_diff"]
###do the same for queen interactions
colony_ages <- colony_ages[which(!is.na(colony_ages$age)),]
names(colony_ages) <-c("colony","partner","age")
queen_W <- merge(colony_ages,unique(queen_interactions[which(queen_interactions$colony==colony),c("colony","randy","colony_size","period","treatment")]))
###merge it with interactions whose age diff is known
queen_W <- merge(queen_W,queen_interactions[which(queen_interactions$colony==colony),c("colony","randy","colony_size","period","treatment","partner","duration_min")],all.x=T,all.y=F)
###and fill intreactions which did not happen with 0
queen_W[which(is.na(queen_W$duration_min)),"duration_min"] <- 0
model_QW <- lm(duration_min~age,data=queen_W)
dol[dol$colony==colony,"slope_QW_contact_duration_f_W_age"] <- coef(model_QW)["age"]
}
}
summary_dol <- rbind(summary_dol,dol)
}
if(!file.exists(paste(data_path,"/processed_data/collective_behaviour/random_vs_observed",sep=""))){dir.create(paste(data_path,"/processed_data/collective_behaviour/random_vs_observed",sep=""),recursive=T)}
if(!file.exists(paste(data_path,"/processed_data/collective_behaviour/random_vs_observed/interactions.dat",sep=""))){write.table(summary_dol,file=paste(data_path,"/processed_data/collective_behaviour/random_vs_observed/interactions.dat",sep=""),col.names=T,row.names=F,append=F,quote=F)}
to_keep <- to_keep_ori
<file_sep>/data/LattanzioMiles_tree lizards/import LattanzioMiles xls data to R.R
#### Import data Lattanzio & Miles paper ####
library(readxl)
LattanzioMiles_morph_network <- read_excel("~/Postdoc_UC/CNWW workshop/LattanzioMiles/LattanzioMilesJAEdata.xlsx",
sheet = "morph_networks")
LattanzioMiles_contests <- read_excel("~/Postdoc_UC/CNWW workshop/LattanzioMiles/LattanzioMilesJAEdata.xlsx",
sheet = "contests")
LattanzioMiles_strength <- read_excel("~/Postdoc_UC/CNWW workshop/LattanzioMiles/LattanzioMilesJAEdata.xlsx",
sheet = "strength_data")
LattanzioMiles_NBdiet <- read_excel("~/Postdoc_UC/CNWW workshop/LattanzioMiles/LattanzioMilesJAEdata.xlsx",
sheet = "NBdiet")
LattanzioMiles_LBdiet <- read_excel("~/Postdoc_UC/CNWW workshop/LattanzioMiles/LattanzioMilesJAEdata.xlsx",
sheet = "LBdiet")
LattanzioMiles_HBdiet <- read_excel("~/Postdoc_UC/CNWW workshop/LattanzioMiles/LattanzioMilesJAEdata.xlsx",
sheet = "HBdiet")
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/2_define_deaths.R
####2_define_deaths.R#####
### Calls C++ functions define_death (https://github.com/laurentkeller/anttrackingUNIL)
### Takes a datfile and a tagfile has input, infers the frame of death/tag loss of each ant, and fills that information in the relevant column of the tagfile
### Note that all death/tag loss times were further checked manually using the videos. All deaths times provided in the subfolder original_data/tag_files are therefore exact times rather than the times inferred using define_death
###Created by <NAME>
###################################
####Define directories
working_path <- paste(data_path,"intermediary_analysis_steps/datfiles_uncorrected",sep="/")
setwd(working_path)
datlist <-list.files(pattern="dat")
for (datfile in datlist){
tagfile <- gsub("dat","tags",datfile)
logfile <- gsub("dat","log",datfile)
print(paste("finding deaths for",datfile))
Command <- paste(executables_path,"/define_death ",
datfile, " ",
tagfile, " ",
logfile,
sep=""
)
system(Command)
}
<file_sep>/visualizations/reorder.py
from scipy import spatial,sparse,cluster
import numpy as np
import networkx
def get_compressed(mat):
n = len(mat)
return np.array( [mat[i,j] for i in range(1,n) for j in range(i+1,n)] )
#
def get_permutation(mat):
uppertri = get_compressed(mat)
# Z = cluster.hierarchy.median(uppertri)
Z = cluster.hierarchy.centroid(uppertri)
o = cluster.hierarchy.leaves_list(Z)
return o
#
def nx_graph_to_adj(nx_G):
nodelist_orig = nx_G.nodes()
edgelist = nx_G.edges()
edgelist = np.array(edgelist)
n2i = {n:i for i,n in enumerate(nodelist_orig)}
n = len(nodelist_orig)
A = np.zeros( (n,n) )
weights = [nx_G[u][v].get('weight',1) for u,v in edgelist]
weights = np.reshape(weights, (len(edgelist),1) )
edgelist = np.hstack( [edgelist, weights] )
for u,v,w in edgelist:
A[n2i[u],n2i[v]] = w
A[n2i[v],n2i[u]] = w # do we want this?
return A
#
def reorder_nx_Graph(nx_G):
nodelist_orig = np.array( nx_G.nodes() )
A_sym = nx_graph_to_adj(nx_G) # beware: symmetric even if G is directed.
o = get_permutation(A_sym)
nodelist_new = nodelist_orig[o]
G2 = networkx.Graph()
G2.add_nodes_from(nodelist_new)
edgelist = nx_G.edges()
edgelist = np.array(edgelist)
weights = [nx_G[u][v].get('weight',1) for u,v in edgelist]
weights = np.reshape(weights, (len(edgelist),1) )
# edgelist = np.hstack( [edgelist, weights] )
edgelist = [(e[0],e[1],{'weight':w}) for e,w in zip(edgelist,weights)]
G2.add_edges_from( edgelist )
return G2
#<file_sep>/analysis_scripts/beetle_analysis.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Analysis of a nested dictionary of NetworkX graphs to measure network metrics:
1.Average density, Number of nodes, Mean Betweenness Centrality, and Mean Eigenvector Centrality
2.Node Degree centrality, Node Eigenvector Centrality, Node Closeness Centrality, and Node Betweenness Centrality
Metrics are compiled into groups (1,2) then exported into two .csv files
"""
def get_graph_metrics(network):
k3_dict=[]
append_network_mean=[]
append_network_cent=[]
for k1,v1 in network.items():
for k2,v2 in v1.items():
v2=v2[0]
#Average network density values
density = nx.density(v2)
#Number of nodes
tot_nodes = nx.number_of_nodes(v2)
#Total average betweenness values for the entire network
##Listing all individual betweenness values, adding them up and dividing by the full
tot_betweenness=0
betweenness=(nx.betweenness_centrality(v2))
for k, v in list(betweenness.items()):
tot_betweenness=v+tot_betweenness
mean_betweenness = (tot_betweenness/tot_nodes)
#Total Eigenvector centrality values for the entire network
tot_eigenvector=0
eigenvector=(nx.eigenvector_centrality(v2))
for k, v in list(eigenvector.items()):
tot_eigenvector=v+tot_eigenvector
mean_eigengenvector = (tot_eigenvector/tot_nodes)
#take measurements for centrality values and insert into a dictionary under Pandas
df2 = pd.DataFrame(dict(
DEGREE_CENTRALITY = nx.degree_centrality(v2),
EIGENVECTOR = nx.eigenvector_centrality(v2),
CLOSENESS_CENTRALITY = nx.closeness_centrality(v2),
BETWEENNESS_CENTRALITY = nx.betweenness_centrality(v2)))
#compile mean values into dictionary
d={
'TOT_NODES':tot_nodes,
'MEAN_EIGENVECTOR' : mean_eigengenvector,
'MEAN_BETWEENNESS' : mean_betweenness}
k3=k1,k2
k3_dict.append(k3)
df3=pd.DataFrame(data=d,index=[k3])
append_network_mean.append(df3)
append_network_cent.append(df2)
append_network_mean=pd.concat(append_network_mean)
append_network_cent=pd.concat(append_network_cent,keys=k3_dict)
#print(append_network_mean)
print(append_network_cent)
#print(k1,k2,df2)
#print(k1,k2,df3)
#move to a .csv file
append_network_cent.to_csv('centrality_measures.csv')
append_network_mean.to_csv('mean_measures.csv')
# In[ ]:
<file_sep>/pre_made_scripts/ant_code/1_data_post_processing/source/11_randomise_interactions.R
####11_randomise_interactions.R#####
### Sources C++ function randomised_edges
#### Takes an interaction list as an input and returns a the same interaction interaction list in which the interaction partners have been randomised
#### Follows the 'Randomized edges (RE)' algorithm laid out by Holme and Saramäki 2012 (Physics Reports)
###Created by <NAME>
####################################
to_keep_ori <- to_keep
Sys.setenv("PKG_CXXFLAGS"="-std=c++11")
sourceCpp(paste(code_path,"/randomise_edges.cpp",sep=""))
###get input list
interac_list <- NULL
input_path1 <- paste(data_path,"/intermediary_analysis_steps/binned_interaction_lists/PreTreatment/observed",sep="")
setwd(input_path1)
interac_list <- c(interac_list,paste(input_path1,list.files(),sep="/"))
input_path2 <- paste(data_path,"/intermediary_analysis_steps/full_interaction_lists/PreTreatment/observed",sep="")
setwd(input_path2)
interac_list <- c(interac_list,paste(input_path2,list.files(),sep="/"))
to_keep <- c(ls(),"to_keep","i","interac")
for (i in 1:100){#####perform 100 randomisations
print(paste("Performing randomisations",i,"out of 100..."))
for (interac in interac_list){
print(paste("Interaction file",which(interac==interac_list),"out of",length(interac_list)))
root_name <- unlist(strsplit(interac,split="/"))[grepl("colony",unlist(strsplit(interac,split="/")))]
folder_name <- gsub(paste("/",root_name,sep=""),"",interac)
outputfolder <- gsub("observed",paste("random_",paste(rep(0,3-nchar(i)),collapse=""),i,sep=""),folder_name)
if (!file.exists(outputfolder)){dir.create(outputfolder)}
outfile <- paste(outputfolder,root_name,sep="/")
if (!file.exists(outfile)){
#####read-in file
interactions <- read.table(interac,header=T,stringsAsFactors=F)
randomised_partners <- randomise_edges(interactions[c("Tag1","Tag2","Startframe","Stopframe")])
randomised_interactions <- interactions
randomised_interactions$Tag1 <- randomised_partners$Tag1;randomised_interactions$Tag2 <- randomised_partners$Tag2;
write.table(randomised_interactions,file=outfile,col.names=T,row.names=F,quote=F,append=F)
}
clean();
}
}
to_keep <- to_keep_ori<file_sep>/pre_made_scripts/ant_code/2_statistics_and_plotting/source/analysis_parameters.R
########Other non-journal specific plotting parameters ##########
task_group_file <- "task_groups.txt"
refine <- task_group_file
plot_type <- "bars" ####bars or means or bars_points or boxplot or violinplot
if (plot_type=="boxplot"){
relative_function <- "median"
}else{
relative_function <- "mean"
}
par(mgp=c(0.8,0.1,0),mar=c(2,2,0.85,0),tcl=-0.2,lend=2,xpd=T,lwd=line_max)
pars <- par(mgp=c(0.8,0.1,0),mar=c(2,2,0.85,0),tcl=-0.2,lend=2,xpd=T,lwd=line_max)
#######Define general parameters that will be use throughout the analysis
queenid <- 665
night_start <- 18; light_start <- 6
stat_line <- -0.2
pix_to_mm_ratio <- max(c(0.0225877193,0.0229658793))
colour_palette <- c(viridis(10, alpha = 1, begin = 0, end = 1, direction = -1, option = "D")[c(1,3,5,7,9)],"#9ad0f3", "#0072B2")
colour_palette_workers <- viridis(10, alpha = 1, begin = 0, end = 1, direction = -1, option = "D")[1:5]
colour_palette_age <- rep(GetColorHex("lightskyblue"),2)
forager_colour <- colour_palette[1]
occasional_forager_colour <- colour_palette[2]
nurse_colour <- colour_palette[3]
untreated_colour <- GetColorHex("grey60")
treated_colour <- GetColorHex("grey20")
queen_colour <- colour_palette[5]#queen_colour <- "mediumorchid4"
worker_colour <- colour_palette[2]
control_colour <- GetColorHex("skyblue1")
pathogen_colour <- GetColorHex("royalblue2")
random_colour <- GetColorHex("rosybrown1")
observed_colour <- GetColorHex("red4")
high_load_colour <- GetColorHex("springgreen4")
low_load_colour <- GetColorHex("springgreen2")
#####define treatment and status names and labels
treatments <- c("control","pathogen","random","observed")
treatment_colours <-
c(control_colour,pathogen_colour,random_colour,observed_colour)
names(treatment_colours) <- treatments
statuses <- c("treated","untreated","queen"
,
"forager","occasional_forager","nurse","queen"
,
"worker","queen"
,
"control","pathogen"
,
"random","observed"
,
"with_queen","not_with_queen"
,
"high_predicted_load","low_predicted_load"
)
statuses_colours <-
c(treated_colour,untreated_colour,queen_colour
,
forager_colour,occasional_forager_colour,nurse_colour,queen_colour
,
worker_colour,queen_colour
,
control_colour,pathogen_colour
,
random_colour,observed_colour
,
queen_colour,worker_colour
,
high_load_colour,low_load_colour
)
names(statuses_colours) <- statuses
statuses_colours <- statuses_colours[!duplicated(names(statuses_colours))]
full_statuses_names <- c("Treated\nforagers","Untreated\nworkers","Queen\n"
,
"Untreated\nforagers","Occasional\nforagers","Nurses\n","Queen\n"
,
"Workers","Queen\n"
,
"Sham","Path."
,
"Rand.","Obs."
,
"Q\ncomm.","Other\ncomm."
,
"High predicted load","Low predicted load"
);names(full_statuses_names) <- statuses
full_statuses_names <- gsub("Path.","",full_statuses_names)
status_order <- c(
"queen"
,
"nurse","occasional_forager","forager"
,
"worker"
,
"control","pathogen"
,
"treated","untreated"
,
"random","observed"
,
"with_queen","not_with_queen"
,
"high_predicted_load","low_predicted_load"
)
alphas <- c(1,1,0.5,1)
names(alphas) <- c("control","pathogen","random","observed")
high_threshold <- 0.0411
sq_mean_to_spore_nb_ratio <- 804427.048
light_start <- 6
dark_start <- 18
time_ori <- 12;unit <-3
Extended <- F
####keep all those until the end
to_keep <- c(ls(),"to_keep")
clean()<file_sep>/clustering_class/vis_params.py
from matplotlib import rcParams
rcParams['axes.titlesize'] = 14
rcParams['axes.labelsize'] = 14
rcParams['legend.fontsize'] = 8
ANALYSIS_FOLDER = '../analysis_results/'
IMAGES_FOLDER = './images/'
<file_sep>/analysis_scripts/general_analysis.R
# Functions gor general analysis of the scripts, not animal specific
# Import the analysis scripts here, where you import, run the analysis, and return
# the final dataset
library(dplyr)
library(igraph)
source("analysis_scripts/mice_analysis.R", echo = FALSE)
source("analysis_scripts/guppy_analysis.R", echo = FALSE)
get_graph_metrics <- function(g, results_list){
#' Get Graph metrics to be applied generally across all networks.
#'
#' Not specific to an animal network
#'
#' @param g igraph Graph Object
#' @param results_list named list, with the columns outline in the analysis template file.
#'
#' Create a dataframe with the network metrics. This data set will have the
#' following columns:
#'
#' treatement:
#' timepoint:
#' network number
#' population:
#' average degree:
#' clustering coefficient:
#' eigenvalue centrality: Pernode
#' may need to be
#' @return results_list: named list with the additional network metrics
is_g_directed <- is_directed(g)
results_list[["density"]] <- igraph::edge_density(g)
results_list[["eigenvector_centrality"]] <- mean(igraph::eigen_centrality(g, directed = is_g_directed)$vector)
results_list[["betweenness_centrality"]] <- get_normalised_betweenness(g, is_g_directed)
results_list[["n_nodes"]] <- length(V(g))
results_list[['effective_information']] <- einet::effective_information(g, effectiveness = F)
# May need to normalise, if so,
results_list[['effective_information']] <- as.numeric(results_list[['effective_information']])/
log2(as.numeric(length(V(g))))
return(results_list)
}
get_graph_ind_metrics <- function(g){
is_g_directed <- is_directed(g)
ind_level_df <- convert_metric_to_df(
igraph::eigen_centrality(g, directed = is_g_directed)$vector, "eigenvector_centrality") %>%
left_join(
get_normalised_betweenness(g, is_g_directed) %>%
convert_metric_to_df("betweeness"), by = "node_ID") %>%
left_join(igraph::degree(g) %>% convert_metric_to_df("degree"),
by = "node_ID")
return(ind_level_df)
}
convert_metric_to_df <- function(metric, metric_name){
final <- data.frame(names(metric), metric, row.names = NULL)
names(final)<- c("node_ID", metric_name)
return(final)
}
get_graph_pop_metrics <- function(g, results_list){
is_g_directed <- is_directed(g)
results_list[["density"]] <- igraph::edge_density(g)
results_list[["n_nodes"]] <- length(V(g))
results_list[['effective_information']] <- einet::effective_information(g, effectiveness = F)
# May need to normalise, if so,
results_list[['effective_information']] <- as.numeric(results_list[['effective_information']])/
log2(as.numeric(length(V(g))))
return(results_list)
}
get_normalised_betweenness <- function(g, is_directed){
all_betweenness <- igraph::betweenness(g, directed = is_directed)
if(max(all_betweenness) == 0){
normalised_betweenness <- (all_betweenness - min(all_betweenness)) /
(1)
}else{
normalised_betweenness <- (all_betweenness - min(all_betweenness)) /
(max(all_betweenness) - min(all_betweenness))
}
# normalised_betweenness <- all_betweenness
return(normalised_betweenness)
}
run_full_analysis <- function(){
#' Run fulll analysis on all the animal networks
#'
all_individual_analysis <- list()
all_population_analysis <- list()
#' Append the function to iterate through your data structure and get the
#' network metrics here:
# all_analysis[['guppy']] <- guppy_net_analysis()
# all_analysis[['mice']] <- mice_net_analysis()
all_individual_analysis[['guppy']] <- guppy_ind_analysis()# %>% mutate_all(as.character)
all_population_analysis[['guppy']] <- guppy_pop_analysis()# %>% mutate_all(as.character)
all_individual_analysis[['mice']] <- mice_ind_analysis()# %>% mutate_all(as.character)
all_population_analysis[["mice"]] <- mice_pop_analysis()# %>% mutate_all(as.character)
all_individual_analysis[["bats"]] <- import_analysis_results("bats_node_metrics.csv") %>%
select(-`Network ID`, -exp_treatment) %>% group_by(condition, replicate_num) %>%
mutate(betweeness = as.numeric(betweeness)) %>%
mutate(betweeness = (betweeness - min(betweeness))/(max(betweeness) - min(betweeness))) %>%
ungroup() %>% mutate(betweeness = as.character(betweeness))
all_population_analysis[["bats"]] <- import_analysis_results("bats_network_metrics.csv")
all_population_analysis[['tree_lizards']] <- import_analysis_results("network_output_treelizards_0weightexcl.csv") %>%
select(-X1)
all_individual_analysis[['tree_lizards']] <- import_analysis_results("node_output_treelizards_0weightexcl.csv") %>%
select(-X1)
all_population_analysis[['wood_ants']] <- import_analysis_results("network_output_woodants.csv") %>%
select(-X1)
all_individual_analysis[['wood_ants']] <- import_analysis_results("node_output_woodants.csv") %>%
select(-X1)
all_population_analysis[['stickleback']] <- import_analysis_results("stickleback_networkdata.csv") %>%
select(-X1)
all_individual_analysis[['stickleback']] <- import_analysis_results("stickleback_individualdata.csv") %>%
select(-X1, -NetworkID)
all_population_analysis[['great_tits']] <- import_analysis_results("tits_2015_network_metrics.csv") %>%
select(-X1)
all_individual_analysis[['great_tits']] <- import_analysis_results("tits_2015_individual_metrics.csv") %>%
select(-X1, -network_id)
all_population_analysis[['fairy_wrens']] <- import_analysis_results("fairywren_2013_2014_pre_post_population.csv")
all_individual_analysis[['fairy_wrens']] <- import_analysis_results("fairywren_2013_2014_pre_post_individual.csv")
View(all_individual_analysis)
View(all_population_analysis)
# print(names(append_beetle_ind_analysis()))
do.call(rbind, all_individual_analysis) %>%
bind_rows(append_beetle_ind_analysis() %>% mutate_all(as.character)) %>%
write.csv(file.path('analysis_results', "all_individual_results.csv"),
row.names = F)
# print(names(append_beetle_population_analysis()))
do.call(rbind, all_population_analysis) %>%
rbind(append_beetle_population_analysis()) %>%
write.csv(file.path('analysis_results', "all_population_results.csv"),
row.names = F)
# final_df <- do.call(rbind, all_analysis) %>%
# rbind(get_processed_results()) %>% bind_rows(append_beetle_analysis())
# return(final_df)
}
get_processed_results <- function(){
#' Add in processed results uploaded to gihub seperately and append to a final
#' dataset
all_result_dfs <- list()
parent_dir <- "data_prep_scripts"
results_filename <- list.files(path = parent_dir, pattern = ".csv")
results_filename <- c(
)
# FOr every CSV file in analysis scripts/
for(r in 1:length(results_filename)){
# Filepath
results <- file.path(parent_dir, results_filename[r])
results_df <- readr::read_csv(results) %>% select(-X1)
# Convert the names so they're all the same.
results_df <- normalise_names(results_df)
all_result_dfs[[r]] <- results_df
}
return(do.call(rbind, all_result_dfs))
}
normalise_names <- function(d_f){
#' Normalise names for a given dataset.
names_dict <- list(
'network' = c("Study", "study", "Network/Study"),
'animal' = c("Animal", "species"),
'condition' = c('Treatment', "treatment", "Condition"),
'replicate_num' = c("GroupID", "replicate", "Replicate #", "replicate_number", "Year"),
'n_nodes' = c("N_Nodes", "n_nodes", "N Nodes"),
'density' = c("Density"),
'eigenvector_centrality' = c('Mean_Eigenvector_Centrality', "Eignvector Centrality",
"EigenvectorCentrality", "Eigenvector_Centrality"),
'betweeness' = c("Mean_Betweenness_Centrality", "Betweenness Centrality", "betweenness", "Betweenness",
"betweeness", "betweenness_centrality", "betweenness_centrality",
"BetweennessCentrality"),
"effective_information" = c("Effective_Information", "normal_ei", "Effective Information"),
"degree" = c("Degree"),
"node_ID" = c("Node ID", "nodeID", "ID", "NodeID", "node_id")
)
for(n in names(names_dict)){
for(nam in names(d_f)){
if(nam %in% names_dict[[n]]){
names(d_f)[which(names(d_f) == nam)] <- n
}
}
}
return(d_f)
}
import_analysis_results <- function(filename){
imported_data <- readr::read_csv(file.path("analysis_results", filename)) %>%
normalise_names()
if(filename == "bats_node_metrics.csv"){
names(imported_data)[length(names(imported_data))] <- "exp_treatment"
# imported_data <- mutate(betweenness = betweenness_centrality) %>% select(-betweenness_centrality)
}
return(imported_data %>% mutate_all(as.character))
}
run_full_analysis()
<file_sep>/Litsearchr/litsearchr_keyword_extract.R
#ASNWG search terms using litsearchr
#June 28,29 2021
#install packages
install.packages("litsearchr")
install.packages("revtools")
library(litsearchr)
###########################
##THE NAIVE SEARCH STRING##
###########################
## Created a naive search string using terms from three different themes(from PECO framework)
## Population(Animal groups) + Exposure(Pertubation) + Outcome(change in the network shape)
((primate* OR animal* OR mammal*) OR (insect* OR bird* OR reptile OR bat* OR fish* OR amphibian*) )
AND (fire OR disturbance* OR sick OR pathog* OR add* OR remov* OR disrupt* OR manipu*)
AND ((dynamic OR social OR behavio*r* OR spatial OR colon* ) NEAR/2 (Network OR connect*) AND (plasticit* OR change* OR reduce* OR increase* OR association* OR shape* OR cohesiv* OR adapt* OR segregat* OR diffusion OR structure) )
#############################
#Import naive search results#
#############################
library(litsearchr)
library(revtools)
setwd("C://Users//alexp//OneDrive - University of New Brunswick//Grad Studies//Complex Networks Winter Workshop//R_code")
#import articles from the naive search string
ASNWG_import <-
import_results(directory = "./naive_results/", verbose = FALSE)
#remove duplicates
ASNWG_data1 <-
litsearchr::remove_duplicates(ASNWG_import, field = "title", method = "exact")
ASNWG_data <-
litsearchr::remove_duplicates(ASNWG_data1, field = "title", method = "string_osa")
ASNWG_data1$title
ASNWG_data$title
#view in a CSV format
###colnames(ASNWG_data1)
write.csv(ASNWG_data1$title, "./remove_dup_1")
write.csv(ASNWG_data$title,"./remove_dup_2")
#extract potential keywords from <file_sep>/data_prep_scripts/import_mice_networks.R
#' Import Mice Netorks from the partitioned dataset.
#'
#' By <NAME> 10Jan21
#'
#' Imports network into a list of igraph networks. The structure is similar to
#' the structurr outlined in 'import_mice_networks.py' but with a list in place
#' if a python dictionary.
import_mice_networks <- function(){
raw_mice_data <- readr::read_csv(
file.path("data", 'mice', "partitioned_dryad_encounters.csv"))
# Flip the columns to be igraph compatible
all_mice_data <- raw_mice_data %>%
relocate(`IDA[inside_first]`, .before = box) %>%
relocate(`IDB[inside_after_IDA]`, .before = box)
# Create a master list to hold all the networks
all_nets = list()
# For all treatment levels (LPS, Control, on_injection)
for(tr in unique(all_mice_data$treatment)){
all_nets[[tr]] = list()
for(tp in unique(all_mice_data$timepoint)){
# Dataset subset
condition_subset <- all_mice_data %>%
filter(treatment == tr, timepoint == tp)
# Inititalise list
all_nets[[tr]][[tp]] = vector(
mode = "list",
length = length(unique(condition_subset$component_num)))
# For all the components within that condition
for(c in unique(condition_subset$component_num)){
# Make the graph of the component from the dataframe subset
all_nets[[tr]][[tp]][[c + 1]] <- condition_subset %>%
filter(component_num == c) %>%
select(-c("treatment", "timepoint", "component_num")) %>%
graph_from_data_frame()
}
}
}
return(all_nets)
} | 3b801d00b90dee6d58f4f2c68fb7b4a242a16071 | [
"Python",
"Text",
"C++",
"R",
"RMarkdown"
] | 66 | R | connor-klopfer/animal_response_nets | 31f9a561196f46a2a71224f77bf52c0deeb6e76e | 421fe4319ad8524fd42432eab5967162dd7df032 |
refs/heads/master | <file_sep>package client;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class PanelGame extends JPanel{
private static final long serialVersionUID = 3L;
private Morpion morpion;
private JButton b1 = new JButton("");
private JButton b2 = new JButton("");
private JButton b3 = new JButton("");
private JButton b4 = new JButton("");
private JButton b5 = new JButton("");
private JButton b6 = new JButton("");
private JButton b7 = new JButton("");
private JButton b8 = new JButton("");
private JButton b9 = new JButton("");
public PanelGame(Morpion morpion) {
this.morpion = morpion;
//Gestion du layout
this.setLayout(new GridLayout(3, 3, 10, 10));
//L'ajout des boutons à la fenetre
this.add(b1);
this.add(b2);
this.add(b3);
this.add(b4);
this.add(b5);
this.add(b6);
this.add(b7);
this.add(b8);
this.add(b9);
//L'ajout d'action aux boutons
b1.addActionListener(e -> this.morpion.updateOnClick(0, 0));
b2.addActionListener(e -> this.morpion.updateOnClick(0, 1));
b3.addActionListener(e -> this.morpion.updateOnClick(0, 2));
b4.addActionListener(e -> this.morpion.updateOnClick(1, 0));
b5.addActionListener(e -> this.morpion.updateOnClick(1, 1));
b6.addActionListener(e -> this.morpion.updateOnClick(1, 2));
b7.addActionListener(e -> this.morpion.updateOnClick(2, 0));
b8.addActionListener(e -> this.morpion.updateOnClick(2, 1));
b9.addActionListener(e -> this.morpion.updateOnClick(2, 2));
}
/**
* Met � jour le l'affichage du plateau
* @param tab le plateau contenant les données à afficher
*/
public void update(String[][] tab) {
this.b1.setText(tab[0][0]);
this.b2.setText(tab[0][1]);
this.b3.setText(tab[0][2]);
this.b4.setText(tab[1][0]);
this.b5.setText(tab[1][1]);
this.b6.setText(tab[1][2]);
this.b7.setText(tab[2][0]);
this.b8.setText(tab[2][1]);
this.b9.setText(tab[2][2]);
}
}
<file_sep>package client;
import java.io.IOException;
import java.net.SocketTimeoutException;
import javax.swing.JFrame;
public class MorpionUI extends JFrame{
private static final long serialVersionUID = 1L;
private Morpion morpion;
private PanelGame game;
private PanelConnection connection;
public MorpionUI(Morpion morpion) {
super();
this.morpion = morpion;
this.connection = new PanelConnection(this);
this.game = new PanelGame(morpion);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
this.setSize(800, 600);
this.setTitle("Morpion : se connecter");
this.add(this.connection);
}
/**
* Accesseur à l'instance de Morpion
* @return l'instance de Morpion
*/
public Morpion getMorpion() {
return this.morpion;
}
/**
* Change le panel actuellement affiché et met à jour le titre de la fenetre
*/
private void startGame() {
this.remove(this.connection);
this.setTitle("Morpion : debut de la partie");
this.add(this.game);
this.validate();
}
public void updateTitle() {
this.setTitle("Morpion : " + this.morpion.getName() + " VERSUS " + this.morpion.getAdversaireName());
}
/**
* Met � jour le plateau
* @param plateau les données du plateau
*/
public void update(String[][] plateau) {
this.game.update(plateau);
}
/**
* Permat d'afficher le nom du vainqueur à la fin de la partie
* @param nom
*/
public void afficherVainqueur(String nom){
}
/**
* Methode qui se connecte au serveur et lance la partie si c'est possible sinon ...
* @param ip l'ip du serveur auquel se connecter
* @param name le pseudo de l'utilisateur
* @throws Exception
* @throws IOException
* @throws SocketTimeoutException
*/
public void connect(String ip, String name) throws SocketTimeoutException, IOException, Exception {
this.morpion.setName(name);
this.morpion.connectToServ(ip);
this.startGame();
}
}
| 45d3da3aa6a61f88bdb51065d33921f660efd79c | [
"Java"
] | 2 | Java | etienne02/Morpion | ef192e68c6b10666950813acda090f18a12307f1 | 68604cdf4b323d433cddf7bacac32f8a68de6951 |
refs/heads/master | <repo_name>npmRangers/TypeParcel<file_sep>/README.md
# TypeParcel
> Typings generator for TypeScript projects.
[](https://travis-ci.org/npmRangers/TypeParcel) [](https://coveralls.io/github/npmRangers/TypeParcel)
Squash all the ***.d.ts*** typings in a single file with additional post-processing features.
## Installation
```bash
$ npm install typeparcel --save-dev
```<file_sep>/test/index.spec.ts
import { expect } from 'chai'
describe('First suit', () => {
it('First test', () => {
expect(1).to.be.equal(1)
})
})
| a1b8ce3f59c90918565262051047031bd29ab1ae | [
"Markdown",
"TypeScript"
] | 2 | Markdown | npmRangers/TypeParcel | 3a0533829ea7844ef5d7aea96b25520d6db032b5 | efaec2d59250794fa113abe74df378283e403310 |
refs/heads/master | <file_sep>/**
* Created by zhang on 17-6-22.
*/
import { Component } from '@angular/core';
@Component({
selector: 'app-home3',
template: `home`,
})
export class Home3Component { }
<file_sep>/**
* Created by zhang on 17-6-22.
*/
import {trigger, state, style, transition, animation, keyframes, animate} from '@angular/animations';
import {Component} from '@angular/core';
@Component({
selector: 'app-animation',
styles: [`
p{
width:200px;
height:100px;
background:lightgray;
margin:100px auto;
text-align:center;
font-size:1.5em;
}
`],
template: `
<p [@myAwesomeAnimation]="state" (mouseover)="animateMe()" (mouseout)="animateMe()">sdf</p>
`,
animations: [
trigger('myAwesomeAnimation', [
state('small', style({
transform: 'scale(1)',
})),
state('large', style({
transform: 'scale(1)',
})),
transition('small <=> large', animate(100, style({ width: '0px'}))),
]),
]
})
// keyframes([
// style({opacity: 0, transform: 'translateY(-75%)', offset: 0}),
// style({opacity: 1, transform: 'translateY(35px)', offset: 0.5}),
// style({opacity: 1, transform: 'translateY(0)', offset: 1}),
// ])
export class AnimationComponent {
state: string = 'small';
animateMe() {
this.state = (this.state === 'small' ? 'large' : 'small');
}
}
<file_sep>/**
* Created by zhang on 17-6-29.
*/
import {
Component, ViewChild, Input, Output, EventEmitter,
} from '@angular/core';
import {Subscription} from "rxjs/Subscription";
@Component({
selector: 'app-address2',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css']
})
export class Address2Component {
@Input() busy: Subscription;
private show = false;
private selectedCity = false;
private selectedCount = false;
private selectedStreet = false;
private prov = '请选择';
private city = '请选择';
private county = '请选择';
private street = '请选择';
@Input() public provDic = [];
@Input() public cityDic = [];
@Input() public countDic = [];
@Input() public streetDic = [];
@Input() public model = {'id': '', 'value': ''};
@Output() public event: EventEmitter<any> = new EventEmitter();
@ViewChild('t') tab: any;
constructor() {}
showon() {
this.show = true;
}
showoff() {
setTimeout(() => this.show = false, 300);
}
selectProv($event) {
this.prov = $event.target.innerHTML;
setTimeout(() => this.tab.select('tab2'));
this.event.emit({'id': $event.target.id, 'value': $event.target.innerHTML, 'level': '0'});
this.selectedCity = true;
this.city = '请选择';
this.selectedCount = false;
this.selectedStreet = false;
}
selectCity($event) {
this.city = $event.target.innerHTML;
setTimeout(() => this.tab.select('tab3'));
this.event.emit({'id': $event.target.id, 'value': $event.target.innerHTML, 'level': '1'});
this.selectedCount = true;
this.county = '请选择';
this.selectedStreet = false;
}
selectCount($event) {
this.county = $event.target.innerHTML;
setTimeout(() => this.tab.select('tab4'));
this.event.emit({'id': $event.target.id, 'value': $event.target.innerHTML, 'level': '2'});
this.selectedStreet = true;
this.street = '请选择';
}
selectStreet($event) {
this.street = $event.target.innerHTML;
this.showoff();
this.model.value = this.prov + this.city + this.county + this.street;
this.event.emit({'id': $event.target.id, 'value': this.model.value, 'level': '3'});
this.model.id = $event.target.id;
}
}
// 地区id字符串截取
function substringId(fullid: string, no: number) {
let id = '';
if (fullid) {
for (let i = 0; i < fullid.length; i++) {
if (i >= no) {
id += '0';
} else {
id += fullid.charAt(i);
}
}
}
return id;
}
<file_sep>/**
* Created by zhang on 17-6-22.
*/
import { Component } from '@angular/core';
import {NguiScrollableDirective} from "@ngui/scrollable";
@Component({
selector: 'app-scrollable',
templateUrl: './scrollable.html',
styleUrls: ['./scrollable.css']
})
export class ScrollableComponent {
id: string = 's1';
hid: string = 'h1';
wid: string = 'w1';
scrollTo(selector: string, parentSelector: string, horizontal: boolean) {
NguiScrollableDirective.scrollTo(
selector, // scroll to this
parentSelector, // scroll within (null if window scrolling)
horizontal, // is it horizontal scrolling
0 // distance from top or left
);
}
}
<file_sep>import {RouterModule, Routes} from "@angular/router";
import {HomeComponent} from "./home/home.component";
import {Home2Component} from "./home/home2.component";
import {Home3Component} from "./home/home3.component";
import {ModuleWithProviders} from "@angular/core";
/**
* Created by zhang on 17-6-22.
*/
export const routes: Routes =
[
{ path: '', redirectTo: '/home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent },
{ path: 'home/home2', component: Home2Component },
{ path: 'home/home2/home3', component: Home3Component },
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
<file_sep>/**
* Created by zhang on 17-7-7.
*/
import {Component} from '@angular/core';
@Component({
selector: 'progress-spinner',
templateUrl: 'progress-spinner.component.html',
styles: [`.example-h2 {
margin: 10px;
}
.example-section {
display: flex;
align-content: center;
align-items: center;
height: 60px;
}
.example-margin {
margin: 0 10px;
}`],
})
export class ProgressSpinnerComponent {
color = 'primary';
mode = 'indeterminate';
value = 100;
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {RouterModule} from "@angular/router";
import {HomeComponent} from "./home/home.component";
import {Home2Component} from "./home/home2.component";
import {Home3Component} from "./home/home3.component";
import {Ng2BreadcrumbModule} from "ng2-breadcrumb/bundles/app.module";
import {BreadcrumbService} from "ng2-breadcrumb/bundles/components/breadcrumbService";
import {appRoutingProviders, routing} from "./app.route";
import {ScrollableComponent} from "./scrollable/scrollable.component";
import {NguiScrollableModule} from "@ngui/scrollable";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {AnimationComponent} from "./animation/animation.component";
import {AddressComponent} from "./address/address.component";
import {NgbModule} from "@ng-bootstrap/ng-bootstrap";
import {TabsModule} from "ngx-bootstrap";
import {AddressService} from "./address/address.service";
import {Http, HttpModule} from "@angular/http";
import {Address2Component} from "./address2/address.component";
import {NgxTreeSelectModule} from "ngx-tree-select";
import {FormsModule} from "@angular/forms";
import 'hammerjs';
import {InputFormExample} from "./form/form.component";
import {MdInputModule, MdProgressBarModule, MdProgressSpinnerModule, MdSelectModule} from "@angular/material";
import {ProgressSpinnerComponent} from "./progress-spinner/progress-spinner.component";
import {ProgressBarComponent} from "app/progress-bar/progress-bar.component";
import {BusyModule} from "angular2-busy";
import {AddressModule} from "./address2/address.module";
@NgModule({
declarations: [
AppComponent,
HomeComponent,
Home2Component,
Home3Component,
ScrollableComponent,
AnimationComponent,
AddressComponent,
InputFormExample,
ProgressSpinnerComponent,
ProgressBarComponent
],
imports: [
RouterModule,
BrowserModule,
Ng2BreadcrumbModule,
routing,
HttpModule,
NguiScrollableModule,
BrowserAnimationsModule,
NgbModule.forRoot(),
TabsModule.forRoot(),
FormsModule,
NgxTreeSelectModule.forRoot([]),
MdInputModule,
MdSelectModule,
MdProgressSpinnerModule,
MdProgressBarModule,
BusyModule,
AddressModule
],
providers: [BreadcrumbService,
appRoutingProviders,
AddressService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/**
* Created by zhang on 17-7-18.
*/
import {NgModule} from "@angular/core";
import {Address2Component} from "./address.component";
import {NgbModule} from "@ng-bootstrap/ng-bootstrap";
import {BusyModule} from "angular2-busy";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {CommonModule} from "@angular/common";
@NgModule({
declarations: [
Address2Component
],
imports: [
CommonModule,
NgbModule,
BrowserAnimationsModule,
BusyModule,
],
exports: [
Address2Component
]
})
export class AddressModule {}
<file_sep>/**
* Created by zhang on 17-7-4.
*/
import { Injectable } from '@angular/core';
import {Http, RequestOptions, ResponseContentType} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
@Injectable()
export class AddressService {
private baseUrl = 'http://localhost:8888/mdt/v1';
constructor(private http: Http) { }
public get(url: any, options: any): Observable<any> {
const urls = `${this.baseUrl}/${url}`;
return this.http
.get(urls, options)
.map(response => {
return response.json()})
.catch(this.handleError)
}
public handleError(error: Response | any) {
return Observable.throw(error.message || error);
}
}
<file_sep>/**
* Created by zhang on 17-6-29.
*/
import {Component, ElementRef, ViewChild, Renderer2, OnInit, Input} from '@angular/core';
import {AddressService} from './address.service';
import {Subscription} from "rxjs/Subscription";
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css']
})
export class AddressComponent implements OnInit {
private busy: Subscription;
private address = '';
private addressId = '';
private show = false;
private selectedCity = false;
private selectedCount = false;
private selectedStreet = false;
private prov = '请选择';
private city = '请选择';
private county = '请选择';
private street = '请选择';
@Input() private provDic = [];
@Input() private cityDic = [];
@Input() private countDic = [];
@Input() private streetDic = [];
@ViewChild('t') tab: any;
constructor(private addressService: AddressService) {}
ngOnInit() {
const url = '/systemsetting/address/getchildrenbyaddresslevel/0'; // 查询省份url
this.addressService.get(url, '').subscribe(
response => { this.provDic = response},
error => {console.log(error)}
)
}
showon() {
this.show = true;
if (this.addressId === '') {
this.selectedCity = false;
this.selectedCount = false;
this.selectedStreet = false;
this.city = '请选择';
this.county = '请选择';
this.street = '请选择';
}
}
showoff() {
setTimeout(() => this.show = false, 300);
}
selectProv($event) {
this.prov = $event.target.innerHTML;
setTimeout(() => this.tab.select('tab2'));
const url = '/systemsetting/address/getchildrenbycodeparent/' + $event.target.id; // 查询市的url
this.busy = this.addressService.get(url, '').subscribe(
response => {this.cityDic = response},
error => {console.log(error)}
)
this.selectedCity = true;
this.city = '请选择';
this.selectedCount = false;
this.selectedStreet = false;
}
selectCity($event) {
this.city = $event.target.innerHTML;
setTimeout(() => this.tab.select('tab3'));
const url = '/systemsetting/address/getchildrenbycodeparent/' + $event.target.id; // 查询区的url
this.busy = this.addressService.get(url, '').subscribe(
response => {this.countDic = response},
error => {console.log(error)}
)
this.selectedCount = true;
this.county = '请选择';
this.selectedStreet = false;
}
selectCount($event) {
this.county = $event.target.innerHTML;
setTimeout(() => this.tab.select('tab4'));
const url = '/systemsetting/address/getchildrenbycodeparent/' + $event.target.id; // 查询街道url
this.busy = this.addressService.get(url, '').subscribe(
response => {this.streetDic = response},
error => {console.log(error)}
)
this.selectedStreet = true;
this.street = '请选择';
}
selectStreet($event) {
this.street = $event.target.innerHTML;
this.showoff();
this.address = this.prov + this.city + this.county + this.street;
this.addressId = $event.target.id;
}
}
<file_sep>/**
* Created by zhang on 17-6-22.
*/
import {Component, OnInit} from '@angular/core';
import {AddressService} from "../address/address.service";
import {Subscription} from "rxjs/Subscription";
@Component({
selector: 'app-home2',
template: `<app-address2 [provDic]="provDic" [cityDic]="cityDic" [countDic]="countDic" [streetDic]="streetDic"
(event)="select($event)" [model]="model" [busy]="busy"></app-address2>`,
})
export class HomeComponent implements OnInit {
private busy: Subscription;
private provDic = [];
private cityDic = [];
private countDic = [];
private streetDic = [];
private model = {'id': '', 'value': ''};
private url = '/systemsetting/address/getchildrenbycodeparent/';
constructor(private addressService: AddressService) {}
ngOnInit() {
const url = '/systemsetting/address/getchildrenbyaddresslevel/0'; // 查询省份url
this.busy = this.addressService.get(url, '').subscribe(
response => { this.provDic = response.data;
console.log(this.provDic)},
error => {console.log(error)}
)
}
select($event) {
if ($event.level === '0') {
this.busy = this.addressService.get(this.url + $event.id, '').subscribe(
response => { this.cityDic = response.data},
error => {console.log(error)}
)
}else if ($event.level === '1') {
this.busy = this.addressService.get(this.url + $event.id, '').subscribe(
response => { this.countDic = response.data},
error => {console.log(error)}
)
}else if ($event.level === '2') {
this.busy = this.addressService.get(this.url + $event.id, '').subscribe(
response => { this.streetDic = response.data},
error => {console.log(error)}
)
}else {
this.model.id = $event.id;
this.model.value = $event.value;
}
}
}
<file_sep>/**
* Created by zhang on 17-7-7.
*/
import {Component} from '@angular/core';
@Component({
selector: 'input-form-example',
templateUrl: 'form.component.html',
styleUrls: ['form.component.css'],
})
export class InputFormExample {}
<file_sep>import {Component, OnInit} from '@angular/core';
import {BreadcrumbService} from 'ng2-breadcrumb/bundles/components/breadcrumbService';
import {AddressService} from './address/address.service';
import * as FileSaver from 'file-saver';
import {Http, RequestOptions, Headers, ResponseType} from "@angular/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// title = 'app';
// constructor(private breadcrumbService: BreadcrumbService,
// private addressService: AddressService) {
// breadcrumbService.addFriendlyNameForRoute('/home', 'home');
// breadcrumbService.addFriendlyNameForRoute('/home/users', 'All users');
// breadcrumbService.addFriendlyNameForRouteRegex('/home/users/[0-9]/info', 'Information');
// breadcrumbService.addCallbackForRoute('/home/users/1', this.getNameForUser);
// breadcrumbService.addCallbackForRouteRegex('^/home/users/[0-9]$', this.getNameForUser);
// }
// getNameForUser(id: string): string {
// return 'specific name for user with id';
// }
private infoCheck = true;
private tumCheck = true;
private pacCheck = true;
private pathoCheck = true;
private opsCheck = true;
private chemoCheck = true;
private radioCheck = true;
constructor(private addressService: AddressService,
private http: Http) {}
public selectedItems1: any = null;
items= [
{ id: 1, text: 'item 1'},
{ id: 2, text: 'item 2'},
{ id: 3, text: 'item 3'},
{ id: 4, text: 'item 4'},
{ id: 5, text: 'item 5'},
];
download() {
let thefile = {};
const data = [];
data.push('info:' + this.infoCheck);
data.push('tum:' + this.tumCheck);
data.push('pac:' + this.pacCheck);
data.push('patho:' + this.pathoCheck);
data.push('ops:' + this.opsCheck);
data.push('chemo:' + this.chemoCheck);
data.push('radio:' + this.radioCheck);
const url = 'http://localhost:8888/mdt/v1/registrationsys/patient/exportcsv/0000489765/' + data;
let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/octet-stream' });
let options = new RequestOptions({ headers: headers, responseType: 2 });
this.http.get(url, options).subscribe(
data => {
thefile = new Blob([data.arrayBuffer()], {type: 'application/octet-stream'});
const urls = window.URL.createObjectURL(thefile);
window.open(urls, "_blank");
// FileSaver.saveAs(thefile, 'fff.zip');
}
);
// this.addressService.get('/registrationsys/patient/export/0000489765', '').subscribe(
// res => {console.log(res)},
// error => {console.log(error)}
// )
}
}
<file_sep>/**
* Created by zhang on 17-7-7.
*/
import {Component} from '@angular/core';
@Component({
selector: 'progress-bar',
template: `
<md-progress-bar
class="example-margin"
[color]="color"
[mode]="mode"
[value]="value"
[bufferValue]="bufferValue">
</md-progress-bar>
`,
styles: [`
.example-h2 {
margin: 10px;
}
.example-section {
display: flex;
align-content: center;
align-items: center;
height: 60px;
}
.example-margin {
margin: 0 10px;
}
`],
})
export class ProgressBarComponent {
color = 'primary';
mode = 'indeterminate';
value = 50;
bufferValue = 75;
}
| 9e94ebf1888913db6799fbc9c9dba3f4fa111203 | [
"TypeScript"
] | 14 | TypeScript | kobe24v/angular4 | 0b44b34b0e66c02d0a897c522845aa1cb5dc9f48 | 4a0d6a239aa0087407249553d0ebad536efd2f4d |
refs/heads/feature/Index | <file_sep>import React from "react"
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "./Navbar.css"
// components
import RegisterUser from "../../RegisterUser/index"
import MainComponent from "../../MainComponent/index"
function Navbar() {
return (
<Router>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<a className="navbar-brand" href="/">
Pyramid Scheme
</a>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav">
<li className="nav-item active">
<Link className="nav-link" to="/">
Home <span className="sr-only">(current)</span>
</Link>
</li>
<li className="nav-item active">
<Link className="nav-link" to="/register-user">
Register
</Link>
</li>
</ul>
</div>
</nav>
<Route exact path="/register-user" component={RegisterUser} />
<Route exact path="/" component={MainComponent} />
</Router>
)
}
export default Navbar
<file_sep>import React, {useState} from "react"
import "./sub-components/RegisterUser.css"
import {bindActionCreators} from "redux"
import {connect} from "react-redux"
import {registerNewUserAction} from "./redux/actionCreators"
import {getNewUser} from "./redux/newUserReducer"
function RegisterUser(props){
const {registerUser} = props
const [userData, setUserData] = useState({})
let userName
let {firstName, lastName, emailAddress, phoneNumber} = userData
let submitBtn
if(firstName && lastName){
userName = <div className = "alert alert-warning">{firstName} {lastName}</div>
}
if(firstName && lastName && emailAddress){
userName = <div className = "alert alert-primary">{firstName} {lastName} <b className = "float-right">{emailAddress}</b></div>
}
if(firstName && lastName && emailAddress && phoneNumber){
userName = (
<div className = "alert alert-success">
{firstName} {lastName} <b className = "float-right">All Details available. <span role="img" aria-label = "check">✔️</span></b>
<hr/>
<i>{phoneNumber}</i>
</div>
)
submitBtn = <button type = "text" className = "form-control btn-success btn my-2" onClick = {() => registerUser(userData)}>Enter</button>
}else{
submitBtn = <button type = "text" className = "form-control btn-danger btn my-2" disabled>Enter All Details To Submit</button>
}
if((firstName && lastName && emailAddress && phoneNumber)===false){
userName = <div className = "alert alert-danger">Enter <b>ALL</b> Details.</div>
}
return (
<div className = "row d-flex justify-content-center mid-level">
<div className = "col-md-6">
<div className = "alert alert-primary">Register User</div>
{userName}
<div className = "row">
<div className = "col-md-6">
<input type = "text" className = "form-control my-1" placeholder = "<NAME>" onChange={(e) => setUserData({...userData,firstName : e.target.value})}/>
</div>
<div className = "col-md-6">
<input type = "text" className = "form-control my-1" placeholder = "<NAME>" onChange={(e) => setUserData({...userData,lastName : e.target.value})}/>
</div>
</div>
<input type = "text" className = "form-control my-1" placeholder = "Email Address" onChange={(e) => setUserData({...userData,emailAddress : e.target.value})}/>
<input type = "text" className = "form-control my-1" placeholder = "Phone Number" onChange={(e) => setUserData({...userData,phoneNumber : e.target.value})}/>
<hr/>
<div className = "row">
<div className = "col-md-6">
{submitBtn}
</div>
<div className = "col-md-6">
<button type = "text" className = "form-control btn-secondary btn my-2">Clear</button>
</div>
</div>
</div>
</div>)
}
const mapStateToProps = state => {
return {
newUser: getNewUser(state)
}
}
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
registerUser: registerNewUserAction
},
dispatch
)
export default connect(
mapStateToProps,
mapDispatchToProps
)(RegisterUser)
<file_sep>import fetch from "node-fetch"
import actionTypes from "../../../redux/actionTypes"
import {endpoints} from "../../../config"
export function fetchAllUsersAction() {
return dispatch => {
console.log(endpoints.fetchUsers)
fetch(endpoints.fetchUsers)
.then(users => users.json())
.then(users => {
dispatch(fetchAllUsers(actionTypes.FETCH_ALL_USERS, users))
})
.catch(error => {
const payload = {
code: 0,
msg: {error}
}
dispatch(errorFetchingAllUsers(actionTypes.ERROR_FETCHING_ALL_USERS, payload))
})
}
}
export function fetchAllUsers(type, payload) {
return {
type,
payload
}
}
export function errorFetchingAllUsers(type, payload){
return {
type,
payload
}
}
<file_sep>import fetch from "node-fetch"
import actionTypes from "../../../redux/actionTypes"
import {endpoints} from "../../../config"
export function registerNewUserAction(userData) {
return dispatch => {
console.log(userData)
let {firstName, lastName, emailAddress, phoneNumber} = userData
console.log(endpoints.newUser)
const body = {
first_name: firstName,
last_name : lastName,
email_address: emailAddress,
phone_number: phoneNumber
}
fetch(endpoints.newUser, {
method: 'post',
body: JSON.stringify(body),
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
})
.then(user => user.json())
.then(user => {
dispatch(registerUser(actionTypes.REGISTER_USER, user))
})
.catch(error => {
console.log('error occurred', error);
const payload = {
code: 0,
msg: {error}
}
dispatch(errorRegisteringUser(actionTypes.ERROR_REGISTERING_USER, payload))
})
}
}
export function registerUser(type, payload) {
return {
type,
payload
}
}
export function errorRegisteringUser(type, payload){
return {
type,
payload
}
}
<file_sep>export const host = "http://localhost"
export const port = 8000
export const url = `${host}:${port}`
export const endpoints = {
fetchUsers: `${url}/api/fetch-users`,
newUser: `${url}/api/new-user`
}
<file_sep>import actionTypes from "../../../redux/actionTypes"
export function allUsersReducer(state = [], action) {
switch (action.type) {
case actionTypes.FETCH_ALL_USERS:
return {
...state,
users: action.payload
}
case actionTypes.ERROR_FETCHING_ALL_USERS:
return {
...state,
users: action.payload
}
case actionTypes.REGISTER_USER:
return {
...state,
newUser: action.payload
}
default:
return state
}
}
export const fetchAllUsers = state => {
return state.allUsers
}
<file_sep>import { createStore, applyMiddleware } from "redux"
import thunk from "redux-thunk"
import logger from "redux-logger"
import allReducers from "./allReducers"
const middlewares = [thunk, logger]
const middleware = applyMiddleware(...middlewares)
const store = createStore(allReducers, middleware)
export default store
| 96abd174d61b799e650aea98acb830eeb1b40baf | [
"JavaScript"
] | 7 | JavaScript | ChrisMuga/pyramid-scheme-react | fda5ceec7fed66a0f0586f6207ff1d9643de73ec | 341fd9249ee7b8d45bdb5cbad6adaa0574609a53 |
refs/heads/master | <file_sep>package com.guitar.model;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
@Data
@Entity
public class Location {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String state;
private String country;
@OneToMany(mappedBy = "headquarters", cascade=CascadeType.ALL)
private List<Manufacturer> manufacturers = new ArrayList<Manufacturer>();
}
<file_sep>package com.guitar.repository;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.guitar.Main;
import com.guitar.model.Manufacturer;
import com.guitar.repository.ManufacturerJpaRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class ManufacturerPersistenceTests {
@Autowired
private ManufacturerJpaRepository manufacturerJpaRepository;
@Test
public void testGetManufacturersFoundedBeforeDate() throws Exception {
List<Manufacturer> mans = manufacturerJpaRepository.findByFoundedDateBefore(new Date());
assertEquals(2, mans.size());
}
@Test
public void testTrueFalse() throws Exception {
List<Manufacturer> mans = manufacturerJpaRepository.findByActiveTrue();
assertEquals("Fender Musical Instruments Corporation", mans.get(0).getName());
mans = manufacturerJpaRepository.findByActiveFalse();
assertEquals("Gibson Guitar Corporation", mans.get(0).getName());
}
}
<file_sep>Spring-rest-demo
============
A Basic Spring Data JPA app with an H2 DB running on Spring Boot
| d6879b9d2eb26c2f20e92ceb47f0ea90758c3083 | [
"Markdown",
"Java"
] | 3 | Java | TeroTS/spring-rest-data-demo | 208cee3c9e507432d609bc12c28e3c7cdc61e9e3 | 31f5624130b512b656177cb1fb59ad073b6ebe68 |
refs/heads/master | <repo_name>Silpelit/Logzy<file_sep>/Logzy/Logzy/Mod/LogzyLevel.cs
namespace LogzyImpl.Mod
{
/// <summary>
/// This enum is used inside Logzy for log level support.
/// </summary>
public enum LogzyLevel
{
Debug,
Info,
Warn,
Error
}
}<file_sep>/Logzy/Logzy/Intf/ILogEntity.cs
using System;
namespace LogzyImpl.Intf
{
public interface ILogEntity
{
ILogEntity Debug { get; }
ILogEntity Info { get; }
ILogEntity Warn { get; }
ILogEntity Error { get; }
ILogEntity WithDetail(string detail);
ILogEntity WithNamespace(string @namespace);
T ReturnAndLog<T>(T item);
T ReturnAndLog<T>(T item, ILogDestination destination);
T CatchExceptionAndLog<T>(Exception ex);
T CatchExceptionAndLog<T>(Exception ex, ILogDestination destination);
T CatchExceptionAndLog<T>(Exception ex, T item);
T CatchExceptionAndLog<T>(Exception ex, T item, ILogDestination destination);
void ThrowExceptionAndLog<T>(Exception ex);
void ThrowExceptionAndLog<T>(Exception ex, ILogDestination destination);
void Log();
void Log<T>(T item);
void Log(ILogDestination destination);
void Log<T>(T item, ILogDestination destination);
}
}<file_sep>/Logzy/Logzy/Logzy.cs
using LogzyImpl.Impl;
using LogzyImpl.Intf;
using LogzyImpl.Mod;
namespace LogzyImpl
{
public static class Logzy
{
public static LogzyConfiguration Configuration = LogzyConfiguration.InitializeLogzyConfiguration(LogzyConfiguration.DefaultConfiguration);
public static ILogEntity Create(params object[] values)
{
return LogEntity.Create(values);
}
}
}<file_sep>/Logzy/Logzy/Mod/LogzyConfiguration.cs
using System;
using System.Collections.Generic;
using System.Dynamic;
using LogzyImpl.Impl.Destinations;
using LogzyImpl.Intf;
namespace LogzyImpl.Mod
{
public class LogzyConfiguration
{
public const string TimeParameter = "%Time%";
public const string LevelParameter = "%Level%";
public const string MethodNameParameter = "%MethodName%";
public const string ParametersParameter = "%Parameters%";
public const string ReturnObjectParameter = "%ReturnObject%";
public const string NameParameters = "%Name%";
public const string DetailsParameter = "%Details%";
public const string ValueParameter = "%Value%";
public const string NamespaceParameter = "%Namespace%";
public static readonly LogzyConfiguration DefaultConfiguration = new LogzyConfiguration()
{
LogLineFormat = "[%Time%][%Level%] - %MethodName%(%Parameters%) -> (%ReturnObject%) %Details%",
ParameterFormat = "%Name% = '%Value%'",
TimeFormat = string.Empty,
EventSource = "Logzy",
EventLog = "Logzy",
StackFrameDepth = 3,
MaximumArrayLength = 20,
LoggedLevels = new List<LogzyLevel>() { LogzyLevel.Debug, LogzyLevel.Error, LogzyLevel.Info, LogzyLevel.Warn }
};
/// <summary>
/// This property defines the structure of the log lines created by Logzy.
/// The available placeholder parameter list can be found below.
/// </summary>
public string LogLineFormat { get; set; }
/// <summary>
/// This property defines the format of the logged time value.
/// </summary>
///
public string TimeFormat { get; set; }
///<summary>
///This property defines the log structure of function parameters and properties.
/// </summary>
public string ParameterFormat { get; set; }
/// <summary>
/// If the built-in event logger is used, this specifies the event source for the logs.
/// </summary>
public string EventSource { get; set; }
/// <summary>
/// If the built-in event logger is used, this specifies the event name for the logs.
/// </summary>
public string EventLog { get; set; }
/// <summary>
/// If a given array has more elements than this defined value, do not serialize it.
/// </summary>
public int MaximumArrayLength { get; set; }
/// <summary>
/// This specifies the stack frame depth which is used during function serialization.
/// Should not be changed if not necessary.
/// </summary>
public int StackFrameDepth { get; set; }
/// <summary>
/// Enables log filtering by level. If the level is not present in the list it will be ignored.
/// </summary>
private List<LogzyLevel> LoggedLevels { get; set; }
/// <summary>
/// These destinations will be used to deliver the created log lines.
/// </summary>
private List<ILogDestination> LogDestinations { get; set; }
public LogzyConfiguration()
{
LogDestinations = new List<ILogDestination>();
LoggedLevels = new List<LogzyLevel>();
}
/// <summary>
/// This method registers a destination to Logzy. The destination will be used
/// to deliver created log lines.
/// </summary>
/// <param name="destination">An ILogDestination implementation.</param>
/// <returns>The registered ILogDestination instance.</returns>
public ILogDestination RegisterDestination(ILogDestination destination)
{
LogDestinations.Add(destination);
return destination;
}
/// <summary>
/// This method registers a destination to Logzy. The destination will be used
/// to deliver created log lines.
/// </summary>
/// <param name="logMethod">An Action which will receive the created ILogInformation instance.</param>
/// <returns>The registered ILogDestination instance.</returns>
public ILogDestination RegisterDestination(Action<ILogInformation> logMethod)
{
var customDestination = new CustomDestination(logMethod);
LogDestinations.Add(customDestination);
return customDestination;
}
/// <summary>
/// Unregisters an ILogDestination instance from the list of destinations.
/// </summary>
/// <param name="destination"></param>
public void UnregisterDestination(ILogDestination destination)
{
LogDestinations.Remove(destination);
}
/// <summary>
/// Returns an enumerable with the currently registered destinations.
/// </summary>
/// <returns></returns>
public IEnumerable<ILogDestination> GetDestinations()
{
return LogDestinations as IEnumerable<ILogDestination>;
}
/// <summary>
/// Registers the specified log level into Logzy. Log entries with the
/// registered log levels will be sent to the destinations.
/// </summary>
/// <param name="level">The level to be registered.</param>
public void RegisterLogLevel(LogzyLevel level)
{
if (!LoggedLevels.Contains(level))
{
LoggedLevels.Add(level);
}
}
/// <summary>
/// Registers the specified log levels into Logzy. Log entries with the
/// registered log levels will be sent to the destinations.
/// </summary>
/// <param name="levels">The levels to be registered.</param>
public void RegisterLogLevels(params LogzyLevel[] levels)
{
foreach (var level in levels)
{
RegisterLogLevel(level);
}
}
/// <summary>
/// Unregisters the specified log level from Logzy. Log entries which have
/// unregistered log levels will not be sent to the destinations.
/// </summary>
/// <param name="level">The level to be unregistered.</param>
public void UnregisterLogLevel(LogzyLevel level)
{
if (LoggedLevels.Contains(level))
{
LoggedLevels.Remove(level);
}
}
/// <summary>
/// Unregisters the specified log levels from Logzy. Log entries which have
/// unregistered log levels will not be sent to the destinations.
/// </summary>
/// <param name="levels">The levels to be unregistered.</param>
public void UnregisterLogLevels(params LogzyLevel[] levels)
{
foreach (var level in levels)
{
UnregisterLogLevel(level);
}
}
/// <summary>
/// Returns an enumerable containing the currently registered log levels.
/// </summary>
/// <returns></returns>
public IEnumerable<LogzyLevel> GetLoggedLevels()
{
return LoggedLevels;
}
internal static LogzyConfiguration InitializeLogzyConfiguration(LogzyConfiguration config)
{
var newConfig = new LogzyConfiguration();
newConfig.LogLineFormat = config.LogLineFormat;
newConfig.TimeFormat = config.TimeFormat;
newConfig.ParameterFormat = config.ParameterFormat;
newConfig.EventSource = config.EventSource;
newConfig.EventLog = config.EventLog;
newConfig.MaximumArrayLength = config.MaximumArrayLength;
newConfig.LoggedLevels = config.LoggedLevels;
newConfig.StackFrameDepth = config.StackFrameDepth;
return newConfig;
}
}
}<file_sep>/Logzy/Logzy/Intf/ILogInformation.cs
using System;
using LogzyImpl.Mod;
namespace LogzyImpl.Intf
{
public interface ILogInformation
{
string MethodName { get; }
string LogzyFormattedParameterString { get; }
string LogzyFormattedReturnObject { get; }
string LogzyFormattedTime { get; }
string LogzyFormattedLogLine { get; }
string Details { get; }
LogzyLevel Level { get; }
DateTime Time { get; }
}
}<file_sep>/Logzy/Logzy/Mod/ParameterInfo.cs
namespace LogzyImpl.Mod
{
internal class ContextParameterInfo
{
public string ParameterName { get; private set; }
public string ParameterValue { get; private set; }
public ContextParameterInfo(string name, string value)
{
ParameterName = name;
ParameterValue = value;
}
public override string ToString()
{
return Logzy.Configuration.ParameterFormat.Replace(LogzyConfiguration.NameParameters, ParameterName).Replace(LogzyConfiguration.ValueParameter, ParameterValue);
}
}
}<file_sep>/README.md
# Logzy
Developer friendly logging library which makes you forget about the use of manual string formatted logging in your projects.
Logzy marks the entry point values of your function and also the return value of the function to create a very verbose log line containing every possible information you would need from the function during execution. You can also change every option which Logzy uses to create these lines and also specify a given number of destinations where the created log line will be stored. Logzy is capable of managing your application logging on its own, but it is also capable of working together with existing log libraries by removing the overhead of creating self-formatted log lines everywhere.
Here is a small example of how Logzy manages logging in your function:
```c#
//Initialize Logzy by adding a log destination
public static void InitializeLogzy()
{
Logzy.Configuration.RegisterDestination((logInfo) =>
{
Console.WriteLine(logInfo);
});
}
public List<int> GetEntryIds(string email, string section, int subsection)
{
var logEntry = Logzy.Create(email, section, subsection);
var entries = new List<int>();
...
return logEntry.Info.ReturnAndLog(entries);
}
...
InitializeLogzy();
var entries = GetEntryIds("<EMAIL>", "rights", 559);
```
Outputs the following to the application console:
[2015.11.07. 15:27:13][Debug] - GetEntryIds(email = '<EMAIL>', section = 'rights', subsection = '559') -> (result[0] = '5', result[1] = '4', result[2] = '3', result[3] = '2', result[4] = '1')
#Characteristics
Heres a quick summary about the most important properties of Logzy:
* One painless line of code per function creates the most verbose log entry which you would need from your function, including passed parameter values and return value.
* Serializes everything ranging from classes to arrays or arrays inside classes. Ignore attribute to customize what gets serialized.
* Custom destinations allow you to use Logzy on its own, or to connect it to an existing logging library.
* Configure every option to customize the created log lines.
* Log level and namespace support.
#Two additional examples
Here are two additinal examples on how can Logzy be used in your application.
The first example is extended with exception catching and logging.
```c#
public TestClass RetrieveTestClass(string user, string details)
{
var logEntry = Logzy.Create(user, details);
try
{
var testClass = new TestClass();
...
return logEntry.Info.ReturnAndLog(testClass);
}
catch (Exception ex)
{
return logEntry.Error.CatchExceptionAndLog<TestClass>(ex);
}
}
```
This code would produce the following log line with default configuration:
```
[2015.11.07. 16:34:01][Info] - RetrieveTestClass(user = '<EMAIL>', details = 'details') -> (TestString = 'null', TestInt = '0')
```
The second example deals with the situation that, for example, the function return value is changed several times before returning, and we would like to log down every one of these steps.
```c#
public TestClass RetrieveTestClass2(string user, string details)
{
var logEntry = Logzy.Create(user, details);
try
{
var testClass = new TestClass();
...
logEntry.Debug.WithDetail("Class retrieved").Log(testClass);
...
logEntry.Debug.WithDetail("Class modified").Log(testClass);
...
return logEntry.Info.ReturnAndLog(testClass);
}
catch (Exception ex)
{
return logEntry.Error.CatchExceptionAndLog<TestClass>(ex);
}
}
```
This code would produce the following log lines with default configuration:
```
[2015.11.07. 16:43:15][Debug] - RetrieveTestClass(user = '<EMAIL>', details = 'details') -> (TestString = 'null', TestInt = '0') Class retrieved
[2015.11.07. 16:43:15][Debug] - RetrieveTestClass(user = '<EMAIL>', details = 'details') -> (TestString = 'TEST', TestInt = '0') Class modified
[2015.11.07. 16:43:15][Info] - RetrieveTestClass(user = '<EMAIL>', details = 'details') -> (TestString = 'TEST', TestInt = '5')
```
#Configuration
The static configuration class instance can be accessed by calling
```c#
Logzy.Configuration
```
in your code. This configuration class instance contains every option which defines the behaviour of Logzy. Currently there is no support to change these settings from config files, only manual changing is supported, which should be done during application start. However, changes during execution can also be done and these changes will be applied to the new log lines immediately.
The following code snippet is the default configuration class instance, the comments in the code explain the purpose of every property inside the class.
```c#
public static readonly LogzyConfiguration DefaultConfiguration = new LogzyConfiguration()
{
//This property defines the structure of the log lines created by Logzy.
//The available placeholder parameter list can be found below.
LogLineFormat = "[%Time%][%Level%] - %MethodName%(%Parameters%) -> (%ReturnObject%) %Details%",
//This property defines the log structure of function parameters and properties.
ParameterFormat = "%Name% = '%Value%'",
//This property defines the format of the logged time value.
TimeFormat = string.Empty,
//If the built-in event logger is used, this specifies the event source for the logs.
EventSource = "Logzy",
//If the built-in event logger is used, this specifies the event name for the logs.
EventLog = "Logzy",
//This specifies the stack frame depth which is used during function serialization.
//Should not be changed if not necessary.
StackFrameDepth = 3,
//If a given array has more elements than this defined value, do not serialize it.
MaximumArrayLength = 20,
//Enables log filtering by level. If the level is not present in the list it will be ignored.
LoggedLevels = new List<LogzyLevel>() { LogzyLevel.Debug, LogzyLevel.Error, LogzyLevel.Info, LogzyLevel.Warn }
};
```
The following placeholder parameters can be used to modify the log line structure:
```
%Time% - The time when the log entry was created. Formatted by the TimeFormat property.
%Level% - The log level of the log entry.
%MethodName% - The function or method name.
%Parameters% - A serialized string of the method parameters and their values.
%ReturnObject% - A serialized string of the return object and its properties.
%Name% - The parameter or property name. Used by the ParameterFormat property.
%Details% - Contains the details which can be specified for the log entry.
%Value% - The parameter or property value. Used by the ParameterFormat property.
%Namespace% - Contains the namespace which can be specified for the log entry.
```
Namespace logging is not part of the default log line format, but can be easily added by using the aformentioned parameters.
Log level filtering can be done using the
```c#
Logzy.Configuration.RegisterLogLevel
Logzy.Configuration.UnregisterLogLevel
```
methods.
#Destinations
Destinations are the endpoints of Logzy. Several destinations can be registered to Logzy by calling the
```c#
Logzy.Configuration.RegisterDestination
```
method. The destination must implement the following method:
```c#
void Log(ILogInformation info);
```
The **ILogInformation** instance passed to the method contains every information available in the log entry. By default, the **LogzyFormattedLogLine** property creates a log line using the actual configuration, but calling **ToString()** on the instance produce the same log line. However, the different parts of the log lines are also available as properties to enable custom modification or custom operations during logging.
Simple endpoints can be added by just passing an Action to the method. Complex endpoints can implement the **ILogDestination** interface and then an instance can be passed to the method. Destinations can be used to connect Logzy to existing logging libraries by registering their functionality as a Logzy destination.
#Built-in destinations
Currently the only built-in log destination is an event logger which creates Event Viewer entries. A static instance of this logger can be accessed and registered using the following line of code:
```c#
Logzy.Configuration.RegisterDestination(EventDestination.Instance);
```
#Attributes
Currently the only available control attribute is the **LogzyIgnore** attribute which can be applied to class properties or parameters. This attribute, if present, prevents Logzy from serializing the item during logging. This can be useful if the item contains sensitive information or just not relevant enough to be logged.
Here is an example on how can the LogzyIgnore attribute be used:
```c#
public class TestClass
{
...
[LogzyIgnore]
public string IgnoreString { get; set; }
...
public TestClass RetrieveTestClass(string user, [LogzyIgnore] string details)
{
...
}
...
}
```
#License
(MIT License)
Copyright (c) 2015 <NAME> <EMAIL> (Silpelit@GitHub)
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.
<file_sep>/Logzy/Logzy/Impl/Destinations/CustomDestination.cs
using System;
using LogzyImpl.Intf;
namespace LogzyImpl.Impl.Destinations
{
internal class CustomDestination : ILogDestination
{
private Action<ILogInformation> LogMethod { get; set; }
public CustomDestination(Action<ILogInformation> method)
{
LogMethod = method;
}
public void Log(ILogInformation info)
{
LogMethod(info);
}
}
}
<file_sep>/Logzy/Logzy/Impl/LogEntity.cs
using LogzyImpl.Intf;
using LogzyImpl.Mod;
using LogzyImpl.Mod.Attr;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
namespace LogzyImpl.Impl
{
internal class LogEntity : ILogEntity, ILogInformation
{
private const string NullString = "null";
public string MethodName { get; private set; }
public string Details { get; private set; }
public List<ContextParameterInfo> Parameters { get; private set; }
public LogzyLevel Level { get; private set; }
public DateTime Time { get; private set; }
public string Namespace { get; private set; }
public object ReturnObject { get; set; }
internal LogEntity(string methodName)
{
MethodName = methodName;
Parameters = new List<ContextParameterInfo>();
}
internal LogEntity(string methodName, IEnumerable<ContextParameterInfo> parameters)
: this(methodName)
{
Parameters = new List<ContextParameterInfo>(parameters);
}
#region Logzy Configuration
public string LogzyFormattedParameterString
{
get { return string.Join(", ", Parameters.Select(p => p.ToString())); }
}
public string LogzyFormattedReturnObject
{
get
{
var infos = new List<ContextParameterInfo>();
GetObjectInformation(ReturnObject, infos);
return string.Join(", ", infos.Select(p => p.ToString()));
}
}
public string LogzyFormattedTime
{
get { return Time.ToString(Logzy.Configuration.TimeFormat); }
}
public string LogzyFormattedLogLine
{
get
{
return Logzy.Configuration.LogLineFormat
.Replace(LogzyConfiguration.DetailsParameter, Details)
.Replace(LogzyConfiguration.LevelParameter, Level.ToString())
.Replace(LogzyConfiguration.MethodNameParameter, MethodName)
.Replace(LogzyConfiguration.TimeParameter, LogzyFormattedTime)
.Replace(LogzyConfiguration.ReturnObjectParameter, LogzyFormattedReturnObject)
.Replace(LogzyConfiguration.NamespaceParameter, Namespace)
.Replace(LogzyConfiguration.ParametersParameter, LogzyFormattedParameterString);
}
}
public ILogEntity Debug
{
get
{
Level = LogzyLevel.Debug;
return this;
}
}
public ILogEntity Info
{
get
{
Level = LogzyLevel.Info;
return this;
}
}
public ILogEntity Warn
{
get
{
Level = LogzyLevel.Warn;
return this;
}
}
public ILogEntity Error
{
get
{
Level = LogzyLevel.Error;
return this;
}
}
public static LogEntity Create(params object[] values)
{
return GetMethodInformation(values);
}
public override string ToString()
{
return LogzyFormattedLogLine;
}
public ILogEntity WithDetail(string detail)
{
Details = detail;
return this;
}
public ILogEntity WithNamespace(string @namespace)
{
Namespace = @namespace;
return this;
}
#endregion
#region ILogEntity Log Methods
public T ReturnAndLog<T>(T item)
{
ReturnObject = item;
Log();
return item;
}
public T ReturnAndLog<T>(T item, ILogDestination destination)
{
ReturnObject = item;
Log(destination);
return item;
}
public T CatchExceptionAndLog<T>(Exception ex)
{
Details = ex.Message;
Log();
return default(T);
}
public T CatchExceptionAndLog<T>(Exception ex, ILogDestination destination)
{
Details = ex.Message;
Log(destination);
return default(T);
}
public T CatchExceptionAndLog<T>(Exception ex, T item)
{
Details = ex.Message;
ReturnObject = item;
Log();
return item;
}
public T CatchExceptionAndLog<T>(Exception ex, T item, ILogDestination destination)
{
Details = ex.Message;
ReturnObject = item;
Log(destination);
return item;
}
public void ThrowExceptionAndLog<T>(Exception ex)
{
Details = ex.Message;
Log();
throw ex;
}
public void ThrowExceptionAndLog<T>(Exception ex, ILogDestination destination)
{
Details = ex.Message;
Log(destination);
throw ex;
}
public void Log()
{
if (IsLoggable())
{
Time = DateTime.Now;
foreach (var logDestination in Logzy.Configuration.GetDestinations())
{
logDestination.Log(this);
}
Details = null;
}
}
public void Log<T>(T item)
{
ReturnObject = item;
Log();
}
public void Log<T>(T item, ILogDestination destination)
{
ReturnObject = item;
Log(destination);
}
public void Log(ILogDestination destination)
{
if (IsLoggable())
{
Time = DateTime.Now;
destination.Log(this);
Details = null;
}
}
#endregion
#region Reflection Methods
private static LogEntity GetMethodInformation(params object[] values)
{
var stackFrame = new StackFrame(Logzy.Configuration.StackFrameDepth, false);
var methodInfo = stackFrame.GetMethod();
var context = new LogEntity(methodInfo.Name);
var methodParameters = methodInfo.GetParameters();
if (methodParameters.Length != values.Length && values.Length != 0)
{
throw new InvalidOperationException("The length of the value and method declaration array does not match");
}
else
{
if (methodParameters.Length != values.Length)
{
return context;
}
for (var i = 0; i < methodParameters.Length; i++)
{
var ignore = methodParameters[i].GetCustomAttribute<LogzyIgnoreAttribute>();
if(ignore != null)
{
continue;
}
GetContextParameterInfo(values[i], context.Parameters, methodParameters[i].Name);
}
return context;
}
}
private static void GetObjectInformation(object obj, ICollection<ContextParameterInfo> infos)
{
if (obj == null)
{
infos.Add(new ContextParameterInfo("result", NullString));
}
else
{
GetContextParameterInfo(obj, infos);
}
}
private static void GetContextParameterInfo(object value, ICollection<ContextParameterInfo> infos,
string name = null)
{
if (value == null)
{
infos.Add(new ContextParameterInfo(name, NullString));
}
else
{
var valueType = value.GetType();
if (IsPrimitiveOrSimple(valueType))
{
infos.Add(new ContextParameterInfo(name ?? "result", value.ToString()));
}
else if (valueType == typeof(DataTable))
{
infos.Add(new ContextParameterInfo(name ?? "result", Represent(value as DataTable)));
}
else if (typeof(IEnumerable).IsAssignableFrom(valueType))
{
var values = value as IEnumerable;
if (values != null)
{
int count;
if (values is ICollection &&
Logzy.Configuration.MaximumArrayLength < (count = ((ICollection)values).Count))
{
infos.Add(new ContextParameterInfo(name ?? "result", "Array[" + count + "]"));
}
else
{
var counter = 0;
foreach (var v in values)
{
GetContextParameterInfo(v, infos, string.Format("{0}[{1}]", name ?? "result", counter++));
}
}
}
}
else if (valueType.IsClass)
{
if (typeof(IDisposable).IsAssignableFrom(valueType) || valueType == typeof(DataSet))
{
infos.Add(new ContextParameterInfo(name, value.ToString()));
}
else
{
var properties = valueType.GetProperties();
foreach (var property in properties)
{
var ignore = property.GetCustomAttribute<LogzyIgnoreAttribute>();
if (ignore != null)
{
continue;
}
GetContextParameterInfo(property.GetValue(value), infos,
name == null ? property.Name : string.Format("{0}.{1}", name, property.Name));
}
}
}
}
}
private static bool IsPrimitiveOrSimple(Type type)
{
return type.IsEnum || type.IsPrimitive || typeof(string) == type || typeof(DateTime) == type;
}
private static string Represent(DataTable table)
{
try
{
var output = new StringBuilder();
if (table != null)
{
foreach (DataRow rows in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
}
return output.ToString();
}
catch (Exception ex)
{
return "EX: " + ex;
}
}
#endregion
private bool IsLoggable()
{
return Logzy.Configuration.GetLoggedLevels().Contains(Level);
}
}
}<file_sep>/Logzy/Logzy/Impl/Destinations/EventDestination.cs
using System.Diagnostics;
using LogzyImpl.Intf;
using LogzyImpl.Mod;
namespace LogzyImpl.Impl.Destinations
{
public class EventDestination : ILogDestination
{
public static EventDestination Instance = new EventDestination();
private EventDestination() { }
public void Log(ILogInformation info)
{
if (!EventLog.SourceExists(Logzy.Configuration.EventSource))
{
EventLog.CreateEventSource(Logzy.Configuration.EventSource, Logzy.Configuration.EventLog);
}
EventLogEntryType type;
switch (info.Level)
{
case LogzyLevel.Debug:
case LogzyLevel.Info:
type = EventLogEntryType.Information;
break;
case LogzyLevel.Error:
case LogzyLevel.Warn:
type = EventLogEntryType.Error;
break;
default:
type = EventLogEntryType.Information;
break;
}
EventLog.WriteEntry(Logzy.Configuration.EventSource, info.ToString(), type);
}
}
}<file_sep>/Logzy/Logzy/Intf/ILogDestination.cs
namespace LogzyImpl.Intf
{
public interface ILogDestination
{
void Log(ILogInformation info);
}
}<file_sep>/Logzy/Logzy/Impl/Deserializer.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using LogzyImpl.Mod;
namespace LogzyImpl.Impl
{
internal class Deserializer
{
private const string LoggingContextOuterRegex = @"(.*?)\(.*?\)";
private const string LoggingContextInnerRegex = "[(, ](.*?) = '(.*?)'";
public Deserializer()
{
}
internal static LogEntity Dezerialize(string contextString)
{
var match = Regex.Match(contextString, LoggingContextOuterRegex);
if (match.Success == false || match.Groups.Count != 2)
{
throw new InvalidOperationException("The contextString is not a valid context string! look for examples in the summary of the unit test method!");
}
else
{
var methodName = match.Groups[1].ToString();
var loggingContext = new LogEntity(methodName);
var parameterMatch = Regex.Matches(contextString, LoggingContextInnerRegex);
foreach (var param in parameterMatch)
{
var p = CleanParameterString(param.ToString());
var equalIndex = p.IndexOf('=');
var propertyPart = p.Substring(0, equalIndex);
var valuePart = p.Substring(equalIndex + 1, p.Length - (equalIndex + 1));
propertyPart = propertyPart.Trim();
valuePart = CleanValueString(valuePart);
loggingContext.Parameters.Add(new ContextParameterInfo(propertyPart, valuePart));
}
return loggingContext;
}
}
internal void ExecuteMethod<T>(string contextString, T obj) where T : class
{
var loggingContext = Dezerialize(contextString);
var classType = typeof(T);
var method = classType.GetMethod(loggingContext.MethodName);
if (method == null)
{
throw new InvalidOperationException("No method found in the supplied generic class! Check the generic type!");
}
else if (obj == null)
{
throw new InvalidOperationException("You must supply an instance of the class for the method!");
}
else
{
var parameterList = new List<object>();
var methodParameters = method.GetParameters();
if (methodParameters.Any())
{
foreach (var param in methodParameters)
{
var paramObj = ParseParameterObject(param.ParameterType, param.Name, loggingContext);
if (paramObj == null && param.DefaultValue != null)
{
parameterList.Add(param.DefaultValue);
}
else if (paramObj != null)
{
parameterList.Add(paramObj);
}
}
}
try
{
method.Invoke(obj, parameterList.ToArray());
}
catch (Exception ex)
{
throw new InvalidOperationException("Could not execute method! Check the logging context string and the generic class! Error: " + ex.Message);
}
}
}
private object ParseParameterObject(Type objectType, string paramName, LogEntity context, int counter = -1)
{
if (typeof(IEnumerable).IsAssignableFrom(objectType))
{
try
{
var enumerableCount = GetEnumerableCount(paramName, context);
if (typeof(IList).IsAssignableFrom(objectType))
{
var genericType = objectType.GetGenericArguments()[0];
var obj = Activator.CreateInstance(objectType) as IList;
for (var i = 0; i < enumerableCount; i++)
{
var parsedObj = ParseParameterObject(genericType, paramName + "[" + i + "]", context, i);
if (parsedObj != null)
{
obj.Add(parsedObj);
}
}
return obj;
}
else if (objectType.IsArray)
{
var elementType = objectType.GetElementType();
var array = Array.CreateInstance(elementType, enumerableCount);
for (var i = 0; i < enumerableCount; i++)
{
var parsedObj = ParseParameterObject(elementType, paramName + "[" + i + "]", context, i);
if (parsedObj != null)
{
array.SetValue(parsedObj, i);
}
}
return array;
}
else
{
throw new InvalidDataException(string.Format("The parameter {0} is neither a list or an array!", paramName));
}
}
catch (TargetInvocationException)
{
throw new Exception(string.Format("The class {0} hasn't got a parameterless constructor!", objectType.Name));
}
catch (Exception)
{
throw new Exception(string.Format("Could not parse class {0} property {1}! Check the values and the logging context string!", objectType, paramName));
}
}
else
{
var loggingParameters = context.Parameters.Where(p => p.ParameterName.StartsWith(paramName)).ToList();
if (objectType.IsEnum)
{
var paramInfo = loggingParameters.First();
if (paramInfo == null)
{
throw new Exception(string.Format("Could not find parameter info for type {0}!", objectType.Name));
}
else
{
try
{
var value = paramInfo.ParameterValue;
var obj = Enum.Parse(objectType, value);
return Convert.ChangeType(obj, objectType);
}
catch (Exception)
{
throw new Exception(string.Format("Could not parse {0} into {1}! Check the values and the logging context string!", paramInfo.ParameterValue, paramName));
}
}
}
else if (objectType.IsPrimitive || typeof(string) == objectType || typeof(DateTime) == objectType)
{
var paramInfo = loggingParameters.First();
if (paramInfo == null)
{
throw new Exception(string.Format("Could not find parameter info for type {0}!", objectType.Name));
}
else
{
try
{
var value = loggingParameters.First().ParameterValue;
return Convert.ChangeType(value, objectType);
}
catch (Exception)
{
throw new Exception(string.Format("Could not parse {0} into {1}! Check the values and the logging context string!", paramInfo.ParameterValue));
}
}
}
else if (objectType.IsClass)
{
var classProperties = objectType.GetProperties();
try
{
var obj = Activator.CreateInstance(objectType);
foreach (var prop in classProperties)
{
if (counter == -1)
{
var paramInfo = context.Parameters.FirstOrDefault(p => p.ParameterName.StartsWith(paramName) && p.ParameterName.EndsWith(prop.Name));
if (paramInfo != null)
{
var parsedObj = ParseParameterObject(prop.PropertyType, paramInfo.ParameterName, context);
if (parsedObj != null)
{
prop.SetValue(obj, Convert.ChangeType(parsedObj, prop.PropertyType));
}
}
}
else
{
var paramInfo = context.Parameters.FirstOrDefault(p => p.ParameterName.StartsWith(paramName) && p.ParameterName.EndsWith(prop.Name));
if (paramInfo != null)
{
var parsedObj = ParseParameterObject(prop.PropertyType, paramInfo.ParameterName, context);
if (parsedObj != null)
{
prop.SetValue(obj, Convert.ChangeType(parsedObj, prop.PropertyType));
}
}
}
}
return obj;
}
catch (TargetInvocationException)
{
throw new Exception(string.Format("The class {0} hasn't got a parameterless constructor!", objectType.Name));
}
catch (Exception)
{
throw new Exception(string.Format("Could not parse class {0} property {1}! Check the values and the logging context string!", objectType, paramName));
}
}
}
throw new NotImplementedException("NOT DONE YET!");
}
private static int GetEnumerableCount(string paramName, LogEntity context)
{
var maxCount = 0;
var current = -1;
foreach (var param in context.Parameters)
{
var match = Regex.Match(param.ParameterName, paramName + @"\[(\d+)\]");
if (match.Success && match.Groups.Count == 2)
{
var count = int.Parse(match.Groups[1].ToString());
if (count > current)
{
current = count;
maxCount++;
}
}
}
return maxCount;
}
private static string CleanParameterString(string parameterString)
{
parameterString = parameterString.Trim(new[] { ' ', '(', ',' });
return parameterString;
}
private static string CleanValueString(string valueString)
{
valueString = valueString.Trim('\'', ' ');
return valueString;
}
}
}<file_sep>/Logzy/LogzyTest/UnitTest1.cs
using System;
using System.Diagnostics;
using LogzyImpl;
using LogzyImpl.Mod;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LogzyTest
{
[TestClass]
public class UnitTest1
{
public static TestClass TestClass = new TestClass()
{
TestString = "TEST",
IgnoreString = "IGNORE",
TestInts = { 1, 2, 4 },
TestInt = 5
};
[TestMethod]
public void UnitTestMethodTest1()
{
Logzy.Configuration.RegisterDestination((info) =>
{
Debug.WriteLine(info);
});
Logzy.Create().Debug.Log();
TestClass.TestMethodInnerTestMethod(1, 2);
}
[TestMethod]
public void UnitTestMethodTest2()
{
Logzy.Configuration.RegisterDestination((info) =>
{
Debug.WriteLine(info);
});
Logzy.Create().Debug.Log();
var tClass = new TestClass() { TestString = "TEST2", TestInt = 4 };
tClass.TestMethodListRet(tClass);
}
}
}
<file_sep>/Logzy/Logzy/Mod/Attr/LogzyIgnoreAttribute.cs
using System;
namespace LogzyImpl.Mod.Attr
{
/// <summary>
/// This attribute can be used to prevent Logzy from serializing the class property or function parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
public class LogzyIgnoreAttribute : Attribute
{
}
}<file_sep>/Logzy/LogzyTest/TestClass.cs
using System.Collections.Generic;
using LogzyImpl;
using LogzyImpl.Mod;
using LogzyImpl.Mod.Attr;
namespace LogzyTest
{
public class TestClass
{
public string TestString { get; set; }
public List<int> TestInts { get; set; }
public int TestInt { get; set; }
[LogzyIgnore]
public string IgnoreString { get; set; }
public TestClass()
{
TestInts = new List<int>();
}
public string TestMethodTestString()
{
var logzy = Logzy.Create();
return logzy.ReturnAndLog(TestString);
}
public TestClass TestMethodThis()
{
var logzy = Logzy.Create();
return logzy.ReturnAndLog(this);
}
public string TestMethodTestStringParameters(int param1, int param2)
{
var logzy = Logzy.Create(param1, param2);
return logzy.ReturnAndLog(TestString);
}
public string TestMethodTestStringParameters(int param1, string param2, int[] param3)
{
var logzy = Logzy.Create(param1, param2, param3);
return logzy.ReturnAndLog(TestString);
}
public TestClass TestMethodTestClassParameters(string param1)
{
var logzy = Logzy.Create(param1);
return logzy.ReturnAndLog(this);
}
public List<string> TestMethodListRet(TestClass t)
{
var logzy = Logzy.Create(t);
return logzy.ReturnAndLog(new List<string>() { "L1", "L2", "L3" });
}
public string TestMethodInnerTestMethod(int param1, int param2)
{
var logzy = Logzy.Create(param1, param2);
logzy.Debug.WithDetail("").Log("TEST#");
return logzy.Info.ReturnAndLog(TestMethodTestString());
}
}
}
| 893a2dfca7ccf9567d595fb8be57d5370f776a2f | [
"Markdown",
"C#"
] | 15 | C# | Silpelit/Logzy | ca34cac95b782db5ceaed473113c7ff7f54743ca | 22caf0e6d2a6c3f34f67159b7488867991ddd60e |
refs/heads/master | <file_sep>"""Timestamp-related functions for discerning runs."""
from datetime import datetime
def get_timestamp(timestamp_format="%Y%m%d_%H%M%S"):
"""Return timestamp with the given format."""
return datetime.now().strftime(timestamp_format)
<file_sep>"""Useful miscellaneous functions."""
from typing import Callable
def get_linear_anneal_func(
start_value: float, end_value: float, start_step: int, end_step: int
) -> Callable:
"""Create a linear annealing function.
Parameters
----------
start_value : float
Initial value for linear annealing.
end_value : float
Terminal value for linear annealing.
start_step : int
Step to start linear annealing.
end_step : int
Step to end linear annealing.
Returns
-------
linear_anneal_func : Callable
A function that returns annealed value given a step index.
"""
def linear_anneal_func(step):
if step <= start_step:
return start_value
if step >= end_step:
return end_value
# Formula for line when two points are known:
# y1 - y0
# y - y0 = --------- (x - x0)
# x1 - x0
return (end_value - start_value) / (end_step - start_step) * (
step - start_step
) + start_value
return linear_anneal_func
<file_sep>"""Ensure reproducibility."""
import random
def set_global_random_seeds(seed, use_numpy=False, use_torch=False):
"""Set random seeds for modules and packages to ensure reproducibility."""
random.seed(seed)
if use_numpy:
import numpy as np
np.random.seed(seed)
if use_torch:
import torch
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def set_env_random_seeds(env, seed):
"""Set random seeds for given OpenAI Gym environment to ensure reproducibility."""
env.seed(seed)
env.observation_space.seed(seed)
env.action_space.seed(seed)
<file_sep>"""Save and load trained PyTorch models.
A directory is given for save since multiple models
can be saved in one run, but a path (including filname)
is given for load since only one model is loaded.
"""
import os
import torch
def load_models(load_path: str, **kwargs):
"""Load specified models.
Parameters
----------
load_path : str
Load path including the filename.
"""
state_dict = torch.load(load_path)
for key, value in kwargs.items():
value.load_state_dict(state_dict[key])
def save_models(save_dir: str, filename: str = "net", **kwargs):
"""Save specified models.
Parameters
----------
save_dir : str
Save directory, not excluding the filename.
filename : str
Save filename.
"""
# Create specified directory if it does not exist yet
if not os.path.exists(save_dir):
os.makedirs(save_dir)
torch.save(
{key: value.state_dict() for key, value in kwargs.items()},
f"{save_dir}/{filename}.pt",
)
| 97dc3a722f93114028533d4c6f6a2f8a9edc5677 | [
"Python"
] | 4 | Python | seungjaeryanlee/implementations-utils | d60ca4edd777e3033e00e8cae83557bb843130ec | 9cb92576d3550bd5b7628f5037fa20425dec52ae |
refs/heads/master | <repo_name>sancarbar/firebase-android<file_sep>/app/src/main/java/com/gdg/bogota/firebaseandroid/ui/activity/MainActivity.java
package com.gdg.bogota.firebaseandroid.ui.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.gdg.bogota.firebaseandroid.R;
import com.gdg.bogota.firebaseandroid.model.Message;
import com.gdg.bogota.firebaseandroid.ui.adapter.MessagesAdapter;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.util.UUID;
public class MainActivity
extends AppCompatActivity
{
static final int REQUEST_IMAGE_CAPTURE = 1;
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference databaseReference = database.getReference( "messages" );
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl( "gs://funchat-ef3ed.appspot.com" );
@BindView( R.id.messages_layout )
View messagesLayout;
@BindView( R.id.message )
EditText message;
@BindView( R.id.recycler_view )
RecyclerView recyclerView;
private MessagesAdapter messagesAdapter;
private final ChildEventListener messagesListener = new ChildEventListener()
{
@Override
public void onChildAdded( DataSnapshot dataSnapshot, String s )
{
updateMessage( dataSnapshot );
}
@Override
public void onChildChanged( DataSnapshot dataSnapshot, String s )
{
updateMessage( dataSnapshot );
}
@Override
public void onChildRemoved( DataSnapshot dataSnapshot )
{
Message message = dataSnapshot.getValue( Message.class );
if ( message != null )
{
messagesAdapter.removeMessage( message );
}
}
@Override
public void onChildMoved( DataSnapshot dataSnapshot, String s )
{
}
@Override
public void onCancelled( DatabaseError databaseError )
{
}
};
private void updateMessage( DataSnapshot dataSnapshot )
{
final Message message = dataSnapshot.getValue( Message.class );
if ( message != null )
{
runOnUiThread( new Runnable()
{
@Override
public void run()
{
messagesAdapter.addMessage( message );
}
} );
}
}
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
ButterKnife.bind( this );
Toolbar toolbar = findViewById( R.id.toolbar );
setSupportActionBar( toolbar );
messagesAdapter = new MessagesAdapter( this );
configureRecyclerView();
databaseReference.addChildEventListener( messagesListener );
setTitle( getCurrentUserDisplayName() );
}
private String getCurrentUserDisplayName()
{
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
return currentUser != null ? currentUser.getDisplayName() : "";
}
private void configureRecyclerView()
{
recyclerView.setHasFixedSize( true );
LinearLayoutManager linearLayoutManager = new LinearLayoutManager( this );
linearLayoutManager.setReverseLayout( true );
recyclerView.setLayoutManager( linearLayoutManager );
recyclerView.setAdapter( messagesAdapter );
}
@Override
public boolean onCreateOptionsMenu( Menu menu )
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
@Override
public boolean onOptionsItemSelected( MenuItem item )
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if ( id == R.id.action_logout )
{
firebaseAuth.signOut();
startActivity( new Intent( this, LoginActivity.class ) );
finish();
return true;
}
return super.onOptionsItemSelected( item );
}
public void onSendClicked( View view )
{
String text = message.getText().toString();
message.setText( null );
Message message = new Message( getCurrentUserDisplayName(), text );
databaseReference.push().setValue( message );
}
@OnClick( R.id.add_picture )
public void onAddImageClicked()
{
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent()
{
Intent takePictureIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
if ( takePictureIntent.resolveActivity( getPackageManager() ) != null )
{
startActivityForResult( takePictureIntent, REQUEST_IMAGE_CAPTURE );
}
}
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data )
{
if ( resultCode == RESULT_OK && requestCode == REQUEST_IMAGE_CAPTURE )
{
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get( "data" );
UploadPostTask uploadPostTask = new UploadPostTask();
uploadPostTask.execute( imageBitmap );
}
}
@SuppressWarnings( "VisibleForTests" )
private class UploadPostTask
extends AsyncTask<Bitmap, Void, Void>
{
@Override
protected Void doInBackground( Bitmap... params )
{
Bitmap bitmap = params[0];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress( Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream );
storageRef.child( UUID.randomUUID().toString() + "jpg" ).putBytes(
byteArrayOutputStream.toByteArray() ).addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>()
{
@Override
public void onSuccess( UploadTask.TaskSnapshot taskSnapshot )
{
if ( taskSnapshot.getDownloadUrl() != null )
{
String imageUrl = taskSnapshot.getDownloadUrl().toString();
final Message message = new Message( imageUrl );
databaseReference.push().setValue( message );
}
}
} );
return null;
}
}
}
| caac5254c32020241c67ee781f1c3b3128588a74 | [
"Java"
] | 1 | Java | sancarbar/firebase-android | 817d01d67dc7981e73ae51b6ff6ef1a3777f0cc5 | eff666ead0c5c73ac2acc84f5899bb5df8c90012 |
refs/heads/master | <file_sep>import { module, test } from 'qunit';
import { visit, currentURL, fillIn, find, click } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import MockAuthService from '../stubs/auth-stub';
module('Acceptance | login test', function(hooks) {
setupApplicationTest(hooks);
hooks.beforeEach(function() {
this.owner.register("service:auth", MockAuthService);
})
test('visiting /login and selecting the user and logging in the user', async function(assert) {
this.owner.lookup("service:auth").currentUserId = null;
await visit('/login');
assert.equal(currentURL(), '/login');
await fillIn("select", "1");
let button = /** @type { HTMLInputElement} */ (find("input[type='submit']"));
if(!button.disabled) {
await click((find("input[type='submit']")));
}
assert.ok(currentURL().startsWith('/teams'));
});
});
| 1ad4b52a724a1ad125eaadcb141335ba1db9aab5 | [
"JavaScript"
] | 1 | JavaScript | SanthoshRaju91/ember-octane | d803094a228c571fb73dd5a24494a1a8da1c7734 | 7b7ffd139649785b40bfa9a535c5390736cbdea4 |
refs/heads/master | <repo_name>fantomitechno/NSI-Bot<file_sep>/src/commands/test.ts
import { Command } from '../bases';
export default new Command(
{
name: 'test',
description: 'test'
},
(client, interaction) => {
client.interaction.createInteractionResponse(
interaction.id,
interaction.token,
{
type: 4,
data: {
content: 'Test passed'
}
}
);
}
);
<file_sep>/README.md
# NSI-Bot
NSI Bot est le bot Discord utilisé pour faire tourner les codes python envoyer sur le serveur (si on le lui demande)
### Comment ça marche ?
A l'envoie d'un message sous le format
\`\`\`py
<code>
\`\`\`
ou
\`\`\`
<code>
\`\`\`
le bot répondra avec deux boutons : un pour qu'il exectue le code donné, l'autre pour supprimer la dite réponse<file_sep>/src/bases.ts
import { ApplicationCommandOptions, Interaction } from 'higa/types';
import { Bot } from './client';
export class Command {
data: ApplicationCommandOptions;
run: (client: Bot, interaction: Interaction) => void;
constructor(
data: ApplicationCommandOptions,
run: (client: Bot, interaction: Interaction) => void
) {
this.data = data;
this.run = run;
}
}
export class Button {
custom_id_start: string;
run: (client: Bot, interaction: Interaction) => void;
constructor(
custom_id_start: string,
run: (client: Bot, interaction: Interaction) => void
) {
this.custom_id_start = custom_id_start;
this.run = run;
}
}
<file_sep>/src/buttons/oui.ts
import { Button } from '../bases';
export default new Button('end', (_client, _interaction) => {
console.log('t');
});
<file_sep>/src/client.ts
import { Client, ClientOptions } from 'higa';
import { Button, Command } from './bases';
import { readdirSync } from 'fs';
export class Bot extends Client {
cache = new Map<string, string>();
commands = new Map<string, Command>();
buttons = new Map<string, Button>();
appId = '';
constructor(options: ClientOptions) {
super(options);
}
init = async () => {
const rootDir = process.argv[3] === 'true' ? './src' : './build';
const pathCommands = `${rootDir}/commands`;
readdirSync(pathCommands).forEach(async (file) => {
if (file.endsWith('.ts') || file.endsWith('.js')) {
const { default: command } = await import(`./commands/${file}`);
this.commands.set(command.data?.name ?? '', command);
}
});
const pathButtons = `${rootDir}/buttons`;
readdirSync(pathButtons).forEach(async (file) => {
if (file.endsWith('.ts') || file.endsWith('.js')) {
const { default: button } = await import(`./buttons/${file}`);
this.buttons.set(button.custom_id_start ?? '', button);
}
});
};
syncCommands = async () => {
this.appId = (await this.user.getCurrentUser()).id;
for (const c of this.commands.values()) {
this.applicationCommand.createGlobalApplicationCommand(
this.appId,
c.data
);
}
const currentCommands =
await this.applicationCommand.getGlobalApplicationCommands(this.appId);
for (const c of currentCommands) {
if (!this.commands.has(c.name)) {
this.applicationCommand.deleteGlobalApplicationCommand(
this.appId,
c.id
);
}
}
};
}
<file_sep>/src/index.ts
import { config } from 'dotenv';
import { Button } from './bases';
import { Bot } from './client';
config();
const client = new Bot({
token: process.env.TOKEN ?? '',
tokenType: 'Bot',
version: '9',
intents: ['GUILD_MESSAGES']
});
client.on('READY', async () => {
client.init();
const user = await client.user.getCurrentUser();
console.log(`Logged in as ${user.username}!`);
client.syncCommands();
});
client.on('INTERACTION_CREATE', (interaction) => {
if (interaction.type === 2) {
const command = client.commands.get(interaction.data?.name ?? '');
if (!command) return;
command.run(client, interaction);
} else if (interaction.type === 3) {
if (interaction.data?.component_type === 2) {
const buttons = client.buttons.keys();
let buttonCommand: Button | undefined;
for (const button of buttons) {
if (interaction.data?.custom_id?.startsWith(button)) {
buttonCommand = client.buttons.get(button);
break;
}
}
if (!buttonCommand) return;
buttonCommand.run(client, interaction);
}
}
});
client.on('MESSAGE_CREATE', (message) => {
if (message.content.includes('```')) {
const raw_codes = message.content.split('```');
if (raw_codes.length === 2) return;
client.channel
.createMessage(message.channel_id, {
message_reference: {
message_id: message.id
},
content: "Voulez vous que j'execute le(s) code(s) de ce message ?",
components: [
{
type: 1,
components: [
{
type: 1,
style: 3,
custom_id: 'yes',
emoji: {
id: '888076372981993512'
}
},
{
type: 1,
style: 4,
custom_id: 'no',
emoji: {
id: '888076372981993512'
}
}
]
}
]
})
.catch((err) => {
console.log(JSON.stringify(err));
});
}
});
| 8a8402ff9145e41ca381c460ba4e4e7ff00f82e9 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | fantomitechno/NSI-Bot | 371b7159cfc28dda16ddc1f57171a0c410908685 | a958dfc867681b5b0678c916411563137367ee32 |
refs/heads/v2.x | <file_sep>###############################################################################
#
# Copyright (c) 2017-2023 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
A small parser to be able to use the Buzzer language on the Fleet 2 and Virtual Cars.
"""
NOTE_NAMES = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
LEN_MULTIPLIER = 2000
TEMPO = 0
STACCATO = 1
VELOCITY = 2
OCTAVE = 3
DEFAULT_DURATION = 4
DEFAULT_SETTINGS = [120, False, 127, 4, 4]
## CMD TYPES:
## 0: note
## 1: octave
## 2: tempo
## 3: default durations
## 4: velocity
## 5: staccato/legato
## 6: rest
class BuzzParser:
def __init__(self):
self.cmd_type = None
self.config = [*DEFAULT_SETTINGS]
def get_note(self, note_letter, octave, accidentals):
note_pitches = {
'C': 0,
'D': 2,
'E': 4,
'F': 5,
'G': 7,
'A': 9,
'B': 11,
}
return 12 + (octave * 12) + note_pitches[note_letter] + accidentals
def get_freq(self, note_letter, octave, accidentals):
return (2 ** ((self.get_note(note_letter, octave, accidentals) - 69) / 12.0)) * 440
def calculate_note_duration(self, base_duration, num_dots):
return sum(base_duration / (2**i) for i in range(num_dots + 1))
def process_cmd(self):
if self.cmd_type is None:
self.args.clear()
return
if self.cmd_type == 0:
try:
note_len = int(self.args[1])
except ValueError:
note_len = self.config[DEFAULT_DURATION]
t = self.calculate_note_duration(4 / note_len, self.args[4]) * (60 / (self.config[TEMPO]) * 1000)
self.notes.append((
self.get_freq(self.args[0], self.config[OCTAVE] + self.args[3], self.args[2]),
t / 2 if self.config[STACCATO] else t,
self.config[VELOCITY],
))
if self.config[STACCATO]:
self.notes.append((
None,
t / 2,
None,
))
self.total_ms += t
elif self.cmd_type == 1:
self.config[OCTAVE] = int(self.args[1])
elif self.cmd_type == 2:
self.config[TEMPO] = int(self.args[1])
elif self.cmd_type == 3:
self.config[DEFAULT_DURATION] = int(self.args[1])
elif self.cmd_type == 4:
self.config[VELOCITY] = int(0.2 / 3 * 127 * int(self.args[1]))
elif self.cmd_type == 5:
## This is already handled
pass
elif self.cmd_type == 6:
try:
rest_len = int(self.args[1])
except ValueError:
rest_len = self.config[DEFAULT_DURATION]
t = self.calculate_note_duration(4 / rest_len, self.args[4]) * (60 / (self.config[TEMPO]) * 1000)
self.notes.append((
None,
t,
None,
))
self.total_ms += t
self.args.clear()
def convert(self, notes_str):
self.notes = []
self.total_ms = 0
self.cmd_type = None
self.args = []
octave_diff = 0
for c in notes_str.upper():
if c == '!':
self.config = [*DEFAULT_SETTINGS]
elif c in NOTE_NAMES:
self.process_cmd()
self.cmd_type = 0
self.args = [c, '', 0, octave_diff, 0]
octave_diff = 0
elif c == 'O':
self.process_cmd()
self.cmd_type = 1
self.args = [None, '']
elif c == 'T':
self.process_cmd()
self.cmd_type = 2
self.args = [None, '']
elif c == 'L':
if self.cmd_type == 5:
self.config[STACCATO] = False
self.cmd_type = None
else:
self.process_cmd()
self.cmd_type = 3
self.args = [None, '']
elif c == 'V':
self.process_cmd()
self.cmd_type = 4
self.args = [None, '']
elif c == 'M':
self.process_cmd()
self.cmd_type = 5
elif c == 'S' and self.cmd_type == 5:
self.config[STACCATO] = True
self.cmd_type = None
elif c == 'R':
self.process_cmd()
self.cmd_type = 6
self.args = [None, '', None, None, 0]
elif c.isnumeric():
if len(self.args) >= 2:
self.args[1] += c
elif c == '>':
octave_diff = 1
elif c == '<':
octave_diff = -1
elif (c == '+' or c == '#') and self.cmd_type == 0:
self.args[2] += 1
elif c == '-' and self.cmd_type == 0:
self.args[2] -= 1
elif c == '.' and (self.cmd_type == 0 or self.cmd_type == 6):
self.args[4] += 1
self.process_cmd()
return self.notes, self.total_ms / 1000
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
def _crc_xmodem_update(crc, data):
"""
See `integrity.cpp` for details on this function.
"""
crc = (crc ^ (data << 8)) & 0xFFFF
for i in range(8):
if crc & 0x8000:
crc = ((crc << 1) ^ 0x1021) & 0xFFFF
else:
crc = (crc << 1) & 0xFFFF
return crc
def put_integrity(buf, type_=bytes):
"""
Put integrity bytes into `buf`.
Return a new buffer of type `type_` having the
integrity bytes appended.
"""
if len(buf) == 0:
return type_([0xAA])
elif len(buf) == 1:
return type_([buf[0], buf[0] ^ 0xD6])
else:
crc = 0x0000
for byte in buf:
crc = _crc_xmodem_update(crc, byte)
return type_(buf) + type_([ ((crc >> 8) & 0xFF), (crc & 0xFF) ])
def check_integrity(buf):
"""
Check the integrity of `buf`. Return `None` if `buf`
has no integrity, else return a new buffer having
the integrity bytes removed.
"""
if len(buf) == 0:
return None
elif len(buf) == 1:
if buf[0] != 0xAA:
return None
return buf[:-1]
elif len(buf) == 2:
if buf[0] ^ buf[1] ^ 0xD6:
return None
return buf[:-1]
elif len(buf) == 3:
return None
else:
crc = 0x0000
for byte in buf:
crc = _crc_xmodem_update(crc, byte)
if crc == 0:
return buf[:-2]
return None
def read_len_with_integrity(n):
"""
Return the number of bytes needed to read
a buffer of length `n` where the buffer
that is read will have integrity bytes added.
"""
if n == 0:
return 1
elif n == 1:
return 2
else:
return n+2
if __name__ == "__main__":
def to_list(line):
line = line.replace("<done>", "")
line = line.strip()
return [int(b) for b in line.split()]
with open("integrity_tests.txt") as f:
while True:
one = f.readline()
two = f.readline()
if not one: break
orig = to_list(one)
encoded = to_list(two)
print(orig)
print(encoded)
print()
assert(put_integrity(orig, list) == encoded)
assert(check_integrity(encoded) == orig)
assert(read_len_with_integrity(len(orig)) == len(encoded))
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module is used to dynamically build Python types, methods, and functions
which conform to an interface description. These types, methods, and functions
delegate the implementation to a remote server. The goal is that, using this
module, you can construct a Python interface that feels like the "real deal"
but is actually delegate over a wire in the background (doing RPC).
"""
import types
def build_interface(iface, impl_transport, is_method=False):
"""
This is the entry-point function for building the Python interface from
the given description (`iface`). All operations are delegated to the
back-end server by invoking the `impl_transport` function.
"""
if 'typename' in iface:
# This is an object with inner stuff.
typename = iface['typename']
TheDynamicType = type(typename, (object,), {})
instance = TheDynamicType()
for i in iface['ifaces']:
if i['ismethod']:
sub_name, attr = build_interface(i, impl_transport, is_method=True)
setattr(TheDynamicType, sub_name, attr)
else:
sub_name, attr = build_interface(i, impl_transport, is_method=False)
setattr(instance, sub_name, attr)
TheDynamicType.__module__ = iface['module']
TheDynamicType.__doc__ = iface['doc']
return iface['name'], instance
else:
# This is just a single callable.
name = iface['name']
args = iface['args']
default_args = iface['defaults']
module = iface['module']
doc = iface['doc']
filename = iface['filename']
firstlineno = iface['firstlineno']
path = iface['path']
is_async = iface['is_async']
if is_method:
args = ['self'] + list(args)
template = _brute_force_method_params(path, impl_transport, len(args), is_async)
else:
template = _brute_force_function_params(path, impl_transport, len(args), is_async)
code = _build_code(name, args, template.__code__, filename, firstlineno)
func = _build_function(code, template, default_args)
func.__module__ = module
func.__doc__ = doc
return name, func
def _build_code(name, args, template_code, filename, firstlineno):
template_inner_var_names = template_code.co_varnames[template_code.co_argcount:]
new_varnames = tuple(args) + template_inner_var_names
code = types.CodeType(
len(args), # argcount
template_code.co_kwonlyargcount, # kwonlyargcount
template_code.co_nlocals, # nlocals
template_code.co_stacksize, # stacksize
template_code.co_flags, # flags
template_code.co_code, # codestring
template_code.co_consts, # constants
template_code.co_names, # names
new_varnames, # varnames
filename, # filename
name, # name
firstlineno, # firstlineno
template_code.co_lnotab, # lnotab
template_code.co_freevars, # freevars
template_code.co_cellvars, # cellvars
)
return code
def _build_function(code, template_func, default_args):
func = types.FunctionType(code, template_func.__globals__, code.co_name, default_args, template_func.__closure__)
return func
def _brute_force_function_params(path, impl_transport, argcount, is_async):
if is_async:
async def params_0():
return await impl_transport(path, [])
async def params_1(a_0):
return await impl_transport(path, [a_0])
async def params_2(a_0, a_1):
return await impl_transport(path, [a_0, a_1])
async def params_3(a_0, a_1, a_2):
return await impl_transport(path, [a_0, a_1, a_2])
async def params_4(a_0, a_1, a_2, a_3):
return await impl_transport(path, [a_0, a_1, a_2, a_3])
async def params_5(a_0, a_1, a_2, a_3, a_4):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4])
async def params_6(a_0, a_1, a_2, a_3, a_4, a_5):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5])
async def params_7(a_0, a_1, a_2, a_3, a_4, a_5, a_6):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6])
async def params_8(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7])
async def params_9(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8])
async def params_10(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9])
async def params_11(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10])
async def params_12(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11])
async def params_13(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12])
async def params_14(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13])
async def params_15(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14])
async def params_16(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15])
async def params_17(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16])
async def params_18(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17])
async def params_19(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18])
async def params_20(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19])
async def params_21(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20])
async def params_22(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21])
async def params_23(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22])
async def params_24(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23])
async def params_25(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24])
async def params_26(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25])
async def params_27(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26])
async def params_28(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27])
async def params_29(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28])
async def params_30(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29])
async def params_31(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30])
async def params_32(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31])
async def params_33(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32])
async def params_34(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33])
async def params_35(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34])
async def params_36(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35])
async def params_37(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36])
async def params_38(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37])
async def params_39(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38])
async def params_40(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39):
return await impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39])
else:
def params_0():
return impl_transport(path, [])
def params_1(a_0):
return impl_transport(path, [a_0])
def params_2(a_0, a_1):
return impl_transport(path, [a_0, a_1])
def params_3(a_0, a_1, a_2):
return impl_transport(path, [a_0, a_1, a_2])
def params_4(a_0, a_1, a_2, a_3):
return impl_transport(path, [a_0, a_1, a_2, a_3])
def params_5(a_0, a_1, a_2, a_3, a_4):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4])
def params_6(a_0, a_1, a_2, a_3, a_4, a_5):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5])
def params_7(a_0, a_1, a_2, a_3, a_4, a_5, a_6):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6])
def params_8(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7])
def params_9(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8])
def params_10(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9])
def params_11(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10])
def params_12(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11])
def params_13(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12])
def params_14(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13])
def params_15(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14])
def params_16(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15])
def params_17(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16])
def params_18(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17])
def params_19(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18])
def params_20(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19])
def params_21(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20])
def params_22(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21])
def params_23(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22])
def params_24(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23])
def params_25(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24])
def params_26(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25])
def params_27(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26])
def params_28(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27])
def params_29(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28])
def params_30(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29])
def params_31(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30])
def params_32(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31])
def params_33(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32])
def params_34(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33])
def params_35(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34])
def params_36(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35])
def params_37(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36])
def params_38(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37])
def params_39(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38])
def params_40(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39):
return impl_transport(path, [a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39])
return {
0: params_0,
1: params_1,
2: params_2,
3: params_3,
4: params_4,
5: params_5,
6: params_6,
7: params_7,
8: params_8,
9: params_9,
10: params_10,
11: params_11,
12: params_12,
13: params_13,
14: params_14,
15: params_15,
16: params_16,
17: params_17,
18: params_18,
19: params_19,
20: params_20,
21: params_21,
22: params_22,
23: params_23,
24: params_24,
25: params_25,
26: params_26,
27: params_27,
28: params_28,
29: params_29,
30: params_30,
31: params_31,
32: params_32,
33: params_33,
34: params_34,
35: params_35,
36: params_36,
37: params_37,
38: params_38,
39: params_39,
40: params_40,
}[argcount]
def _brute_force_method_params(path, impl_transport, argcount, is_async):
if is_async:
async def params_1(self):
return await impl_transport(path, [])
async def params_2(self, a_1):
return await impl_transport(path, [a_1])
async def params_3(self, a_1, a_2):
return await impl_transport(path, [a_1, a_2])
async def params_4(self, a_1, a_2, a_3):
return await impl_transport(path, [a_1, a_2, a_3])
async def params_5(self, a_1, a_2, a_3, a_4):
return await impl_transport(path, [a_1, a_2, a_3, a_4])
async def params_6(self, a_1, a_2, a_3, a_4, a_5):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5])
async def params_7(self, a_1, a_2, a_3, a_4, a_5, a_6):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6])
async def params_8(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7])
async def params_9(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8])
async def params_10(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9])
async def params_11(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10])
async def params_12(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11])
async def params_13(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12])
async def params_14(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13])
async def params_15(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14])
async def params_16(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15])
async def params_17(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16])
async def params_18(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17])
async def params_19(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18])
async def params_20(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19])
async def params_21(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20])
async def params_22(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21])
async def params_23(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22])
async def params_24(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23])
async def params_25(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24])
async def params_26(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25])
async def params_27(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26])
async def params_28(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27])
async def params_29(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28])
async def params_30(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29])
async def params_31(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30])
async def params_32(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31])
async def params_33(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32])
async def params_34(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33])
async def params_35(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34])
async def params_36(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35])
async def params_37(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36])
async def params_38(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37])
async def params_39(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38])
async def params_40(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39):
return await impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39])
else:
def params_1(self):
return impl_transport(path, [])
def params_2(self, a_1):
return impl_transport(path, [a_1])
def params_3(self, a_1, a_2):
return impl_transport(path, [a_1, a_2])
def params_4(self, a_1, a_2, a_3):
return impl_transport(path, [a_1, a_2, a_3])
def params_5(self, a_1, a_2, a_3, a_4):
return impl_transport(path, [a_1, a_2, a_3, a_4])
def params_6(self, a_1, a_2, a_3, a_4, a_5):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5])
def params_7(self, a_1, a_2, a_3, a_4, a_5, a_6):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6])
def params_8(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7])
def params_9(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8])
def params_10(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9])
def params_11(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10])
def params_12(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11])
def params_13(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12])
def params_14(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13])
def params_15(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14])
def params_16(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15])
def params_17(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16])
def params_18(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17])
def params_19(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18])
def params_20(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19])
def params_21(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20])
def params_22(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21])
def params_23(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22])
def params_24(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23])
def params_25(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24])
def params_26(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25])
def params_27(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26])
def params_28(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27])
def params_29(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28])
def params_30(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29])
def params_31(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30])
def params_32(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31])
def params_33(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32])
def params_34(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33])
def params_35(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34])
def params_36(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35])
def params_37(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36])
def params_38(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37])
def params_39(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38])
def params_40(self, a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39):
return impl_transport(path, [a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12, a_13, a_14, a_15, a_16, a_17, a_18, a_19, a_20, a_21, a_22, a_23, a_24, a_25, a_26, a_27, a_28, a_29, a_30, a_31, a_32, a_33, a_34, a_35, a_36, a_37, a_38, a_39])
return {
1: params_1,
2: params_2,
3: params_3,
4: params_4,
5: params_5,
6: params_6,
7: params_7,
8: params_8,
9: params_9,
10: params_10,
11: params_11,
12: params_12,
13: params_13,
14: params_14,
15: params_15,
16: params_16,
17: params_17,
18: params_18,
19: params_19,
20: params_20,
21: params_21,
22: params_22,
23: params_23,
24: params_24,
25: params_25,
26: params_26,
27: params_27,
28: params_28,
29: params_29,
30: params_30,
31: params_31,
32: params_32,
33: params_33,
34: params_34,
35: params_35,
36: params_36,
37: params_37,
38: params_38,
39: params_39,
40: params_40,
}[argcount]
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
pwm = await c.acquire('PWMs')
n = await pwm.num_pins()
print("# PWM-capable pins:", n)
frequency = 50 # Hz
for pin_index in range(n):
print('Running on pin #', pin_index)
await pwm.enable(pin_index, frequency)
for i in range(10):
for duty in range(5, 10):
await pwm.set_duty(pin_index, duty)
await asyncio.sleep(0.1)
await asyncio.sleep(2)
await pwm.disable(pin_index)
await c.release(pwm)
await c.close()
async def run01():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
pwm = await c.acquire('PWMs')
frequency = 20000 # Hz
await pwm.enable(0, frequency)
await pwm.enable(1, frequency)
for j in range(100):
for i in range(41):
await pwm.set_duty(0, 15+i)
await pwm.set_duty(1, 40+i)
await asyncio.sleep(0.1)
for i in range(40, -1, -1):
await pwm.set_duty(0, 15+i)
await pwm.set_duty(1, 40+i)
await asyncio.sleep(0.1)
#await asyncio.sleep(100)
await pwm.disable(0)
await pwm.disable(1)
await c.release(pwm)
await c.close()
async def run13():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
pwm = await c.acquire('PWMs')
frequency = 20000 # Hz
await pwm.enable(1, frequency)
await pwm.enable(3, frequency//2)
for j in range(100):
for i in range(41):
await pwm.set_duty(1, 15+i)
await pwm.set_duty(3, 40+i)
await asyncio.sleep(0.1)
for i in range(40, -1, -1):
await pwm.set_duty(1, 15+i)
await pwm.set_duty(3, 40+i)
await asyncio.sleep(0.1)
#await asyncio.sleep(100)
await pwm.disable(1)
await pwm.disable(3)
await c.release(pwm)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
#asyncio.run(run01())
#asyncio.run(run13())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This script runs Jupyter in the background.
"""
import os
import sys
import pwd
import time
import socket
import subprocess
from threading import Thread
from auto.capabilities import list_caps, acquire, release
from auto import logger
log = logger.init(__name__, terminal=True)
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
JUPYTER_CONFIG_TEMPLATE = os.path.join(CURR_DIR, "jupyter_notebook_config_template.py")
JUPYTER_CONFIG_OUTPUT = "/tmp/jupyter_notebook_config.py"
JUPYTER_LAUNCH_SHIM = os.path.join(CURR_DIR, "jupyter_launch_shim")
def _write_config_file(run_as_user):
caps = list_caps()
if 'Credentials' not in caps:
log.warning('Cannot obtain Jupyter password; will bail.')
sys.exit(1)
creds = acquire('Credentials')
jupyter_password = None
while True:
jupyter_password = creds.get_jupyter_password()
if jupyter_password is not None:
break
log.info('Waiting for Jupyter password to be set...')
time.sleep(1)
release(creds)
log.info('Got Jupyter password.')
user_home_dir_path = pwd.getpwnam(run_as_user).pw_dir
with open(JUPYTER_CONFIG_TEMPLATE, 'r') as f_template:
template = f_template.read()
with open(JUPYTER_CONFIG_OUTPUT, 'w') as f_out:
final_config = template
final_config = final_config.replace(r'<JUPYTER_PASSWORD>', repr(jupyter_password))
final_config = final_config.replace(r'<JUPYTER_START_DIR>', repr(user_home_dir_path))
f_out.write(final_config)
def _thread_main(run_as_user):
_write_config_file(run_as_user)
log.info('Write Jupyter config file; will launch Jupyter!')
cmd = ['sudo', '-u', run_as_user, '-i', JUPYTER_LAUNCH_SHIM, JUPYTER_CONFIG_OUTPUT]
proc = subprocess.run(cmd) # stdin/out/err are inherited, and this command blocks until the subprocess exits
def _is_local_port_serving(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', port))
sock.close()
if result == 0:
return True
else:
return False
def run_jupyter_in_background(run_as_user):
if _is_local_port_serving(8888):
log.warning('Port 8888 is already in use. Is Jupyter already running from a previous invocation?')
return
thread = Thread(target=_thread_main, args=(run_as_user,))
thread.daemon = True
thread.start()
return thread
if __name__ == '__main__':
if len(sys.argv) > 1:
run_as_user = sys.argv[1]
else:
run_as_user = os.environ['USER']
thread = run_jupyter_in_background(run_as_user)
if thread is not None:
thread.join()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides a list of known implementations of the cui interface.
"""
known_impls = [
'cui.pygame_impl',
'cui.mock_impl',
]
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This RPC server provides the standard CIO interface, allowing multiple
processes to share the CIO resources.
"""
from auto.rpc.server import serve, SerializeIface
import cio
from cio.known_impls import known_impls
import os
import uuid
import asyncio
import inspect
import importlib
from auto import logger
log = logger.init(__name__, terminal=True)
from auto.services.controller.cio_inspector import build_cio_method_map, get_abc_superclass_name
async def _get_cio_implementation():
fixed_impl = os.environ.get('MAI_CIO_IMPLEMENTATION', None)
if fixed_impl is not None:
list_of_impls = [fixed_impl]
log.info('Environment specifies cio implementation: {}'.format(fixed_impl))
else:
list_of_impls = known_impls
log.info('Environment does not specify cio implementation, using known list: {}'.format(known_impls))
for impl in list_of_impls:
try:
impl_module = importlib.import_module(impl)
except Exception as e:
log.info('Failed to import cio implementation: {}; error: {}'.format(impl, e))
continue
impl_classes = inspect.getmembers(impl_module, predicate=inspect.isclass)
cio_root_class_types = []
for class_name, class_type in impl_classes:
superclass_type = inspect.getmro(class_type)[1] # first superclass
if superclass_type is cio.CioRoot:
cio_root_class_types.append(class_type)
if len(cio_root_class_types) == 0:
log.error('Failed to find cio.CioRoot implementation in module: {}'.format(impl))
continue
if len(cio_root_class_types) > 1:
log.warn('There are more than one cio.CioRoot implementation in module: {}'.format(impl))
for cio_root_class_type in cio_root_class_types:
cio_root = cio_root_class_type()
try:
log.info('Will attempt to initialize cio implementation: {} from module: {}'.format(type(cio_root), impl))
caps = await cio_root.init()
log.info('Successfully initialized cio implementation: {} from module: {}'.format(type(cio_root), impl))
return cio_root, caps
except Exception as e:
log.info('Failed to initialize cio implementation: {} from module: {}; error: {}'.format(type(cio_root), impl, e))
return None, None
def _wrap_value_in_async_func(val):
async def get():
return val
return get
async def init():
cio_root, caps = await _get_cio_implementation()
if caps is None:
log.error('Failed to find cio implementation, quitting...')
return
cio_map = build_cio_method_map()
class CioIface:
async def setup(self, ws):
self.ws = ws
self.acquired = {}
log.info('CLIENT CONNECTED: {}'.format(self.ws.remote_address))
async def export_init(self):
return caps
async def export_acquire(self, capability_id):
capability_obj = await cio_root.acquire(capability_id)
rpc_guid = str(uuid.uuid4())
self.acquired[rpc_guid] = capability_obj
capability_obj.export_get_rpc_guid = _wrap_value_in_async_func(rpc_guid)
superclass_name = get_abc_superclass_name(capability_obj)
cap_methods = cio_map[superclass_name]
raise SerializeIface(capability_obj, whitelist_method_names=cap_methods)
async def export_release(self, rpc_guid):
if rpc_guid in self.acquired:
capability_obj = self.acquired[rpc_guid]
del self.acquired[rpc_guid]
await cio_root.release(capability_obj)
async def export_close(self):
# Don't call `close()` on the actual `cio_root`, because it is a shared
# resource and needs to stay open. Instead, we just release all the
# components which have been acquired by this client (this ensures
# the ref count on the underlying `cio_root` stays accurate). Note
# this is also what happens when the client disconnects.
for rpc_guid in list(self.acquired): # copy keys
await self.export_release(rpc_guid)
async def cleanup(self):
for rpc_guid in list(self.acquired): # copy keys
await self.export_release(rpc_guid)
log.info('CLIENT DISCONNECTED: {}'.format(self.ws.remote_address))
pubsub_iface = None
server = await serve(CioIface, pubsub_iface, '127.0.0.1', 7002)
log.info("RUNNING!")
return server
if __name__ == '__main__':
loop = asyncio.get_event_loop()
server = loop.run_until_complete(init())
if server is not None:
loop.run_forever()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import os
import base64
import hashlib
import asyncio
from notebook.auth import passwd as jupyter_passwd_hasher
from auto.services.scripts import SCRIPTS_DIRECTORY, run_script
async def change_system_password(system_user, new_password):
loop = asyncio.get_running_loop()
output = await loop.run_in_executor(None, _change_system_password, system_user, new_password)
return 'success' in output.lower()
def _change_system_password(system_user, new_password):
path = os.path.join(SCRIPTS_DIRECTORY, 'set_password')
return run_script(path, new_password, system_user)
def derive_system_password(token):
return _hashed_token(token, 'AutoAuto privileged system password salt value!', 12)
def derive_jupyter_password(token):
jupyter_password = _hashed_token(token, 'AutoAuto Jupyter server password salt value!', 24)
return jupyter_passwd_hasher(jupyter_password)
def derive_labs_auth_code(token):
return _hashed_token(token, 'AutoAuto Lab single device authentication code!', 24)
def _hashed_token(token, salt, length):
# The `token` is the "DEVICE_TOKEN" that this device uses to authenticate
# with the Labs servers. It is stored in a permission-locked file that
# only `root` can access. The `token` is unique to this device; it is set
# _once_ when the device is first configured, and it should remain secret
# for all of eternity.
#
# This function takes that `token`, and uses it to generate other secrets.
# Namely, it is used to generate two other secrets:
#
# 1. It will be used to generate the default password for the privileged
# system user on this device (e.g. used by the owner of the device to
# `ssh` into the device). It is important that every device has a
# strong & unique default system password [1], thus using the `token`
# to generate it is a good solution.
#
# 2. It will be used to generate the password used to access this device's
# Jupyter server. It is important that the Jupyter server is locked-down
# (for obvious reasons), so once again, we'll use the `token` to create
# a strong & unique password to protect the Jupyter server running on this
# device.
#
# Note that the passwords generated here are one-way hashes of the `token`,
# thus these passwords will not reveal any information about the original
# token, which is highly important.
#
# It is also important that the two uses above result in _different_ passwords.
# To achieve this we will salt each differently (using the `salt` parameter
# passed here). They should be _different_ because each grants a different
# level of access to the device (the first is a _privileged_ system user, while
# the second is an _unprivileged_ Jupyter server).
#
# The password generated by the first usage above will be written-down and
# sent with the physical device to its owner. It is the responsibility of the
# owner to (1) keep it secret, and (2) change it (using `passwd`) for the highest
# amount of security. (Note: This is similar to what WiFi routers do with
# their devices.)
#
# The password generated by the second usage above will not be written-down.
# Instead it will be used to generate a link to the Jupyter server from the
# owner's AutoAuto Labs account. Again, it is the owner's responsibility to not
# share that link.
#
# [1] The reason it's important to have strong & unique default passwords
# is because we really don't want AutoAuto devices used in an IoT botnet...
# we assume you agree :) For example, see [this story](http://goo.gl/sbq4it).
m = hashlib.sha256()
m.update(salt.encode('utf-8'))
m.update(token.encode('utf-8'))
hash_bytes = m.digest()
hash_base64 = base64.b64encode(hash_bytes)
password = hash_base64[:length].decode('utf-8')
password = password.replace('/', '_').replace('+', '_') # '/' and '+' are confusing for users to see in a password; this replacement is easier on the eyes and only decreases the level of security by a miniscule amount (the password length is plenty long, and we're just giving up 1 character from an alphabet of 64.)
return password
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides a list of known implementations of the cio interface.
"""
known_impls = [
'cio.aa_controller_v1',
'cio.aa_controller_v2',
'cio.aa_controller_v3',
'cio.mock_impl',
]
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
The synchronous version of `easyi2c`.
"""
import os
import time
import errno
from fcntl import ioctl
from functools import wraps
from . import integrity
from .easyi2c import LOCK
def open_i2c(device_index, slave_address):
"""
Open and configure a file descriptor to the given
slave (`slave_address`) over the given Linux device
interface index (`device_index`).
"""
path = "/dev/i2c-{}".format(device_index)
flags = os.O_RDWR
fd = os.open(path, flags)
I2C_SLAVE = 0x0703 # <-- a constant from `linux/i2c-dev.h`.
ioctl(fd, I2C_SLAVE, slave_address)
return fd
def close_i2c(fd):
"""
Close a file descriptor returned by `open_i2c()`.
"""
os.close(fd)
def _read_i2c(fd, n):
"""
Read `n` bytes from the I2C slave connected to `fd`.
"""
if n == 0:
return b''
buf = os.read(fd, n)
if len(buf) != n:
raise OSError(errno.EIO, os.strerror(errno.EIO))
return buf
def _write_i2c(fd, buf):
"""
Write the `buf` (a `bytes`-buffer) to the I2C slave at `fd`.
"""
w = os.write(fd, buf)
if len(buf) != w:
raise OSError(errno.EIO, os.strerror(errno.EIO))
def write_read_i2c(fd, write_buf, read_len):
"""
Write-to then read-from the I2C slave at `fd`.
Note: The Pi's I2C bus isn't the best, and it fails sometimes.
See: http://www.advamation.com/knowhow/raspberrypi/rpi-i2c-bug.html
Therefore you will want to incorporate integrity checks
when you read/write to the I2C bus. See the next function
in this module for how to do this.
"""
with LOCK:
_write_i2c(fd, write_buf)
return _read_i2c(fd, read_len)
def write_read_i2c_with_integrity(fd, write_buf, read_len):
"""
Same as `write_read_i2c` but uses integrity checks for
both the outgoing and incoming buffers. See the `integrity`
module for details on how this works.
"""
read_len = integrity.read_len_with_integrity(read_len)
write_buf = integrity.put_integrity(write_buf)
with LOCK:
_write_i2c(fd, write_buf)
read_buf = _read_i2c(fd, read_len)
read_buf = integrity.check_integrity(read_buf)
if read_buf is None:
raise OSError(errno.ECOMM, os.strerror(errno.ECOMM))
return read_buf
def i2c_retry(n):
"""
Decorator for I2C-dependent functions which allows them to retry
the I2C transaction up to `n` times before throwing an error.
"""
def decorator(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
for _ in range(n-1):
try:
return func(*args, **kwargs)
except OSError:
time.sleep(0.05) # <-- allow the I2C bus to chill-out before we try again
return func(*args, **kwargs)
return func_wrapper
return decorator
def i2c_poll_until(func, desired_return_value, timeout_ms):
"""
Helper for I2C-dependent functions which polls the `func`
until its return value is the `desired_return_value`. It
ignores other return values and exceptions while polling,
until the `timeout_ms` is reached in which case it raises
a `TimeoutError`. If `func` returns the `desired_return_value`
before `timeout_ms` have elapsed, this function returns
instead of raising.
"""
start_time = time.time()
while True:
try:
ret = func()
if ret == desired_return_value:
return ret, (time.time() - start_time) * 1000
except OSError:
pass
if (time.time() - start_time) * 1000 > timeout_ms:
raise TimeoutError("{} did not return {} before {} milliseconds".format(func, desired_return_value, timeout_ms))
def read_byte(fd, reg):
"""Read a single byte from the register `reg`."""
b, = write_read_i2c(fd, bytes([reg]), 1)
return b
def read_bits(fd, reg, bitStart, length):
"""
Read bits from the register `reg`.
LSB is 0. E.g.
76543210
^^^ <-- bitStart=6, length=3
^^^^ <-- bitStart=5, length=4
"""
b = read_byte(fd, reg)
mask = ((1 << length) - 1) << (bitStart - length + 1)
b &= mask;
b >>= (bitStart - length + 1);
return b
def write_byte(fd, reg, b):
"""Write a single byte `b` to the register `reg`."""
write_read_i2c(fd, bytes([reg, b]), 0)
def write_bits(fd, reg, bitStart, length, data):
"""
Write bits to the register `reg`. See `read_bits()`
for an explanation of `bitStart` and `length`.
"""
b = read_byte(fd, reg)
mask = ((1 << length) - 1) << (bitStart - length + 1);
data <<= (bitStart - length + 1);
data &= mask;
b &= ~(mask);
b |= data;
write_byte(fd, reg, b)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
leds = await c.acquire('LEDs')
mode_map = await leds.mode_map()
print(mode_map)
for mode, _ in mode_map.items():
print('Setting to mode', mode)
await leds.set_mode(mode)
await asyncio.sleep(3)
print('Clearing the mode...')
await leds.set_mode(None)
led_map = await leds.led_map()
print(led_map)
print('Turning on red...')
await leds.set_led('red', True)
await asyncio.sleep(2)
print('Turning off red...')
await leds.set_led('red', False)
await asyncio.sleep(1)
for i in range(8):
binary = "{0:{fill}3b}".format(i, fill='0')
print('Showing binary:', binary)
red, green, blue = [int(b) for b in binary]
await leds.set_many_leds(zip(['red', 'green', 'blue'], [red, green, blue]))
await asyncio.sleep(1)
await c.release(leds)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import re
import asyncio
class Verification:
def __init__(self, console):
self.console = console
async def init(self):
pass
async def connected_cdp(self):
pass
async def new_device_session(self, vin):
pass
async def new_user_session(self, username, user_session):
pass
async def got_message(self, msg, send_func):
if 'origin' in msg and msg['origin'] == 'server':
if 'verification_text' in msg:
username = msg['username']
verification_text = msg['verification_text']
expire_minutes = msg['expire_minutes']
coro = self._show_verification_text(username, verification_text, expire_minutes)
elif 'verification_success' in msg:
if msg['verification_success']:
username = msg['username']
coro = self._show_verification_success(username)
else:
reason = msg['reason']
coro = self._show_verification_failed(reason)
else:
return
asyncio.create_task(coro)
async def end_device_session(self, vin):
pass
async def end_user_session(self, username, user_session):
pass
async def disconnected_cdp(self):
pass
async def _show_verification_text(self, username, verification_text, expire_minutes):
text = "Hi {}!\nAuthentication Code:\n{}\n".format(username, verification_text)
await self.console.big_image('pair_pending')
await self.console.big_status(text)
await self.console.write_text(text + "\n\n")
# TODO Use the `expire_minutes`. E.g. Put a countdown on the screen
# and auto-close the pairing image when the countdown expires.
async def _show_verification_success(self, username):
text = "Congrats {}!\nYou are now paired\nwith this device.\n".format(username)
await self.console.big_image('pair_success')
await self.console.big_status(text)
await self.console.write_text(text + "\n\n")
await asyncio.sleep(5)
await self.console.big_clear()
async def _show_verification_failed(self, reason):
reason = re.sub(r'\<.*?\>', '', reason)
text = "Error:\n{}\n\n".format(reason)
await self.console.big_image('pair_error')
await self.console.big_status("Error:\nTry again.")
await self.console.write_text(text + "\n\n")
await asyncio.sleep(5)
await self.console.big_clear()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module serializes Python objects into a human-readable interface
description. This interface description will be sent over the wire so that
the client may construct Python objects which look and feel like the original
objects.
"""
import inspect
EXPORT_PREFIX = 'export_'
def serialize_interface(thing, name='root', whitelist_method_names=()):
"""
This is the main entry-point for serializing a Python object (`thing`).
Not all methods/attributes of the object will be serialized; only those
whose name starts with "export_" or which are listed in `whitelist_method_names`
will be serialized. This is so that we are explicit about which operations
become part of the RPC system, and we avoid accidental exposure of hidden/
private/vulnerable methods.
"""
iface = _serialize_interface(thing, name, set(whitelist_method_names))
impl = _separate_implementation(iface)
return iface, impl
def _serialize_interface(thing, name, whitelist_method_names):
if inspect.isfunction(thing):
return _serialize_function(thing, name)
elif inspect.ismethod(thing):
return _serialize_method(thing, name)
elif inspect.isclass(thing):
raise Exception('You may not serialize a class.')
else:
# We have some other type of object... maybe
# a custom object, maybe a module, we don't know.
# For these generic objects, we'll only export
# methods/functions which have 'export_' in the
# name (for security reasons!).
extra_export_names = (_get_extra_export_names(thing) | whitelist_method_names)
exported = []
for attr_name in dir(thing):
if attr_name.startswith(EXPORT_PREFIX) or attr_name in extra_export_names:
if attr_name.startswith(EXPORT_PREFIX):
cropped_name = attr_name[len(EXPORT_PREFIX):]
else:
cropped_name = attr_name
attr = getattr(thing, attr_name)
iface = _serialize_interface(attr, cropped_name, whitelist_method_names)
exported.append(iface)
return {
'name': name,
'typename': type(thing).__name__,
'module': type(thing).__module__,
'doc': inspect.getdoc(type(thing)), # <-- uses the super-class's __doc__ as needed
'ifaces': exported,
}
def _serialize_function(f, name=None):
# We can use the _serialize_method function, no worries.
return _serialize_method(f, name)
def _serialize_method(f, name=None, send_wrapped_docs=True):
# If `f` is a decorator, we want to dig in and find the inter-most "wrapped" function.
#
# **Note**: You may not always want to dig in and find the inter-most wrapped function,
# thus we've included the `send_wrapped_docs` parameter to this function.
# The only time you do *not* want to dig for the wrapped function is if the
# decorator changes the parameter list. For our use cases, this will not
# be the case thus we set `send_wrapped_docs` to True by default.
f_outer = f
f_inner = f
while hasattr(f_inner, '__wrapped__') and send_wrapped_docs:
f_inner = f_inner.__wrapped__
if name is None:
name = f_inner.__name__
args = f_inner.__code__.co_varnames[:f_inner.__code__.co_argcount] # consider instead: inspect.getfullargspec()
is_method = False
if hasattr(f_outer, '__self__'):
# A bound method. Remove the first parameter from the signature
# since it is included through python's crazy method binding
# behavior. The other side of the RPC doesn't need to see this
# first parameter.
args = tuple(args[1:])
is_method = True
return {
'name': name,
'args': args,
'defaults': f_inner.__defaults__,
'module': f_inner.__module__,
'doc': inspect.getdoc(f_inner) or inspect.getdoc(f_outer), # <-- uses the super-method's __doc__ as needed
'filename': f_inner.__code__.co_filename,
'firstlineno': f_inner.__code__.co_firstlineno,
'ismethod': is_method,
'impl': f_outer,
'is_async': inspect.iscoroutinefunction(f_outer),
}
def _separate_implementation(iface, prefix=''):
if 'typename' in iface:
# This is an object with inner stuff.
name = iface['name']
path = _build_path(prefix, name)
iface['path'] = path
impls = {}
for iface in iface['ifaces']:
impls.update(_separate_implementation(iface, path))
return impls
else:
# This is just a single callable.
name = iface['name']
impl = iface.pop('impl')
path = _build_path(prefix, name)
iface['path'] = path
return {path: impl}
def _build_path(prefix, name):
if prefix == '':
return name
else:
return prefix + '.' + name
def _get_extra_export_names(thing):
m = getattr(thing, 'rpc_extra_exports', None)
if m is None:
return set()
return set(m())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides an easy way to control the LEDs on your device.
This module provides a fully **synchronous** interface.
"""
from auto.asyncio_tools import thread_safe
from auto.capabilities import list_caps, acquire
def led_map():
"""
Return identifiers and descriptions of the LEDs
available on this controller as a dictionary.
The keys are the identifiers used to control the LEDs
via the `set_led()` method.
"""
return _get_leds().led_map()
def set_led(led_identifier, val):
"""
Set the LED on/off value.
"""
return _get_leds().set_led(led_identifier, val)
def set_many_leds(id_val_list):
"""
Pass a list of tuples, where each tuple is an LED identifier
and the value you want it set to.
"""
return _get_leds().set_many_leds(id_val_list)
def mode_map():
"""
Return identifiers and descriptions of the LED modes
that are available as a dictionary.
The keys are the identifiers used to set the mode
via the `set_mode()` method.
"""
return _get_leds().mode_map()
def set_mode(mode_identifier):
"""
Set the `mode` of the LEDs.
Pass `None` to clear the mode, thereby commencing
basic on/off control via the `set_led()` method.
"""
return _get_leds().set_mode(mode_identifier)
def set_brightness(brightness):
"""
Set the brightness of the LEDs, in the range [0-255].
Raises if not supported by the hardware you have.
"""
return _get_leds().set_brightness(brightness)
@thread_safe
def _get_leds():
global _LEDs
try:
_LEDs
except NameError:
caps = list_caps()
if 'LEDs' not in caps:
raise AttributeError("This device does not have LEDs.")
_LEDs = acquire('LEDs')
return _LEDs
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from auto.services.console.client import CuiRoot
from auto.services.controller.client import CioRoot
from auto.services.wifi import util
from auto.inet import Wireless, list_wifi_ifaces, get_ip_address, has_internet_access
from auto.qrcode import qr_scan
import itertools
import asyncio
import json
import cv2
import sys
import os
import numpy as np
from auto import logger
log = logger.init(__name__, terminal=True)
NUM_INTERNET_ATTEMPTS = 5
INTERNET_ATTEMPT_SLEEP = 4
async def _has_internet_access_multi_try():
loop = asyncio.get_running_loop()
for i in range(NUM_INTERNET_ATTEMPTS-1):
success = await loop.run_in_executor(None, has_internet_access)
if success:
return True
log.info("Check for internet FAILED.")
await asyncio.sleep(INTERNET_ATTEMPT_SLEEP)
success = await loop.run_in_executor(None, has_internet_access)
if success:
return True
log.info("Check for internet FAILED last attempt. Concluding there is no internet access.")
return False
async def _stream_frame(frame, console):
if frame.ndim == 2:
height, width = frame.shape
channels = 1
elif frame.ndim == 3:
height, width, channels = frame.shape
else:
return # :(
shape = [width, height, channels]
rect = [22, 20, width, height]
await console.stream_image(rect, shape, frame.tobytes())
async def _current(wireless):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, wireless.current)
async def _get_wifi_info_from_user(wireless, console, controller):
loop = asyncio.get_running_loop()
camera = await controller.acquire('Camera')
for i in itertools.count():
buf, shape = await camera.capture()
frame = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
frame = await loop.run_in_executor(None, cv2.cvtColor, frame, cv2.COLOR_RGB2GRAY)
await _stream_frame(frame, console)
qr_data = await loop.run_in_executor(None, qr_scan, frame)
if qr_data is not None:
try:
qr_data = json.loads(qr_data)
ssid = qr_data['s']
password = qr_data['p']
break
except:
# We got invalid data from the QR code, which is
# fine, we'll just move on with life and try again.
pass
if (i % 100) == 99:
# Every 100 frames, we'll check to see if WiFi magically came back.
if (await _current(wireless)) is not None:
ssid = None
password = <PASSWORD>
break
await console.clear_image()
await controller.release(camera) # [1]
return ssid, password
async def _get_labs_auth_code(controller):
auth = await controller.acquire('Credentials')
auth_code = await auth.get_labs_auth_code()
await controller.release(auth)
return auth_code
async def _store_labs_auth_code(controller, auth_code):
auth = await controller.acquire('Credentials')
did_save = await auth.set_labs_auth_code(auth_code)
await controller.release(auth)
return did_save
async def _store_jupyter_password(controller, jupyter_password):
auth = await controller.acquire('Credentials')
did_save = await auth.set_jupyter_password(jupyter_password)
await controller.release(auth)
return did_save
async def _ensure_token(console, controller, system_priv_user):
loop = asyncio.get_running_loop()
auth_code = await _get_labs_auth_code(controller)
if auth_code is not None:
# We have an auth code which means this device was set with a token already. All is well.
return
await asyncio.sleep(20) # [1]
await console.big_image('token_error')
await console.big_status('Ready to receive login token.')
camera = await controller.acquire('Camera')
system_password = None
for i in itertools.count():
buf, shape = await camera.capture()
frame = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
frame = await loop.run_in_executor(None, cv2.cvtColor, frame, cv2.COLOR_RGB2GRAY)
await _stream_frame(frame, console)
qr_data = await loop.run_in_executor(None, qr_scan, frame)
if qr_data is not None:
try:
qr_data = json.loads(qr_data)
token = qr_data['t']
if 'p' in qr_data:
# This allows us to override the default system_password for special-purpose devices.
# The default is just... a default. No matter what is set here, it can be changed later.
system_password = qr_data['p']
break
except:
pass
await controller.release(camera) # [1]
await console.clear_image()
await console.big_image('token_success')
await console.big_status('Success. Token: {}...'.format(token[:4]))
await console.write_text("Received token: {}...\n".format(token[:4]))
if system_password is None:
# If a particular default system_password was not specified, we will generate a good
# default system_password from the token. This is a good thing, since it ensures that
# each device is given a strong, unique default system_password.
system_password = util.derive_system_password(token)
jupyter_password = util.derive_jupyter_password(token)
auth_code = util.derive_labs_auth_code(token)
if await util.change_system_password(system_priv_user, system_password):
await console.write_text("Successfully changed {}'s password!\n".format(system_priv_user))
else:
await console.write_text("Failed to change {}' password.\n".format(system_priv_user))
if await _store_jupyter_password(controller, jupyter_password):
await console.write_text("Stored Jupyter password: {}...\n".format(jupyter_password[:4]))
else:
await console.write_text("Failed to store Jupyter password.\n")
if await _store_labs_auth_code(controller, auth_code):
await console.write_text("Stored Labs Auth Code: {}...\n".format(auth_code[:4]))
else:
await console.write_text("Failed to store Labs Auth Code.\n")
await asyncio.sleep(2)
await console.big_clear()
async def _print_connection_info(wireless, console):
loop = asyncio.get_running_loop()
iface = wireless.interface
await console.write_text("WiFi interface name: {}\n".format(iface))
current = await _current(wireless)
await console.write_text("Connected to WiFi SSID: {}\n".format(current))
if iface and current:
ip_address = await loop.run_in_executor(None, get_ip_address, iface)
await console.write_text("Current IP address: {}\n".format(ip_address))
async def _main_loop(wireless, console, controller, system_priv_user):
loop = asyncio.get_running_loop()
last_wifi_seen = None
confident_about_token = False
# Repeat forever: Check to see if we are connected to WiFi. If not, wait 10 seconds
# to see if anything changes. If after 10 seconds we still don't have
# WiFi, initiate the WiFi connection screen. If we _do_ have WiFi, then
# we'll repeat this whole process after 5 seconds.
while True:
current = await _current(wireless)
if current != last_wifi_seen:
log.info("Current WiFi network: {}".format(current))
last_wifi_seen = current
if current is None:
log.info("No WiFi!")
await asyncio.sleep(10)
if (await _current(wireless)) is None:
log.info("Still no WiFi after 10 seconds... will ask user to connect.")
await console.big_image('wifi_error')
await console.big_status('https://labs.autoauto.ai/wifi')
while (await _current(wireless)) is None:
ssid, password = await _get_wifi_info_from_user(wireless, console, controller)
if ssid is None:
log.info("WiFi magically came back before user input.")
break
log.info("Will try to connect to SSID: {}".format(ssid))
await console.big_image('wifi_pending')
await console.big_status('Trying to connect...')
await asyncio.sleep(3) # [1]
did_connect = await loop.run_in_executor(None, wireless.connect, ssid, password)
has_internet = (await _has_internet_access_multi_try()) if did_connect else False
if not did_connect or not has_internet:
if did_connect:
await loop.run_in_executor(None, wireless.delete_connection, ssid)
msg = 'Connected to WiFi...\nbut no internet detected.\nPlease use another network.'
else:
msg = 'WiFi credentials did not work.\nDid you type them correctly?\nPlease try again.'
log.info(msg)
await console.big_image('wifi_error')
await console.big_status(msg)
else:
log.info("Success! Connected to SSID: {}".format(ssid))
await console.big_image('wifi_success')
await console.big_status('WiFi connection success!')
await asyncio.sleep(5)
await _print_connection_info(wireless, console)
break
await console.big_clear()
else:
# We have WiFi.
# After WiFi, we care that we have a Token so that we can authenticate with the Labs servers.
if not confident_about_token:
await _ensure_token(console, controller, system_priv_user)
confident_about_token = True
log.info('Ensured token.')
await asyncio.sleep(5)
async def run_forever(system_priv_user):
loop = asyncio.get_running_loop()
log.info("Starting Wifi controller using the privileged user: {}".format(system_priv_user))
wifi_interfaces = await loop.run_in_executor(None, list_wifi_ifaces)
if not wifi_interfaces:
log.info("No WiFi interfaces, so not running the WiFi monitor script...")
return
wifi_interface = wifi_interfaces[0]
wireless = Wireless(wifi_interface)
console = CuiRoot()
controller = CioRoot()
await console.init()
await controller.init()
await _print_connection_info(wireless, console)
await _main_loop(wireless, console, controller, system_priv_user)
async def _mock_wifi_run_forever(system_priv_user):
loop = asyncio.get_running_loop()
log.info("Starting Mock Wifi controller!!!")
class MockWireless:
def __init__(self, interface):
self.interface = interface
self.curr = None
self.fail_count = 2
def connect(self, ssid, password):
log.info('Calling Mock Wireless: connect({}, {})'.format(repr(ssid), repr(password)))
if self.fail_count > 0:
self.fail_count -= 1
return False
self.curr = ssid
return True
def current(self):
log.info('Calling Mock Wireless: current()')
return self.curr
def delete_connection(self, ssid_to_delete):
log.info('Calling Mock Wireless: delete_connection({})'.format(repr(ssid_to_delete)))
if ssid_to_delete == self.curr:
self.curr = None
wifi_interfaces = await loop.run_in_executor(None, list_wifi_ifaces)
if not wifi_interfaces:
log.info("No WiFi interfaces, so not running the WiFi monitor script...")
return
wifi_interface = wifi_interfaces[0]
wireless = MockWireless(wifi_interface)
console = CuiRoot()
controller = CioRoot()
await console.init()
await controller.init()
await _print_connection_info(wireless, console)
await _main_loop(wireless, console, controller, system_priv_user)
if __name__ == '__main__':
if len(sys.argv) > 1:
system_priv_user = sys.argv[1] # the "Privileged" system user
else:
system_priv_user = os.environ['USER']
#asyncio.run(_mock_wifi_run_forever(system_priv_user))
asyncio.run(run_forever(system_priv_user))
"""
[1] There's a subtle bug with the PiCamera library (see https://github.com/waveform80/picamera/issues/527).
Basically, when you connect to WiFi, it can set the system time, and setting the system time to a
point in the future will cause the PiCamera library to blow up. We can work around this by closing
PiCamera's connection to the camera before connecting to WiFi (via the `release` method on the camera),
and by sleeping for an extra few seconds before attempting to connect to WiFi (to allow the camera time
to fully release itself), and by sleeping _more_ before we reengage the camera to get the token (because
we need to the system time to be updated _before_ turning the camera back on)..
"""
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
Module to interface with your AutoAuto device's front-panel console via RPC.
This is a **synchronous** interface.
"""
from auto.asyncio_tools import get_loop, thread_safe
from auto.services.console.client_sync import CuiRoot
_built_in_print = print
@thread_safe
def _get_console():
global _CONSOLE
try:
return _CONSOLE
except:
pass # we can fix this
loop = get_loop()
_CONSOLE = CuiRoot(loop)
_CONSOLE.init()
return _CONSOLE
def print(*objects, sep=' ', end='\n'):
"""
Print to the AutoAuto console! This function works the same
as the build-in `print()` function in Python, but it prints
to the AutoAuto console instead of to `stdout`.
"""
all_text = []
class Writable:
def write(self, text):
all_text.append(text)
def flush(self):
pass
ret = _built_in_print(*objects, sep=sep, end=end, file=Writable())
full_text = ''.join(all_text)
_get_console().write_text(full_text)
return ret
def write_text(text):
"""
Write text to the AutoAuto console. This is a more "manual" version
of the `print()` function above.
"""
return _get_console().write_text(text)
def clear_text():
"""
Clear the text off the AutoAuto console.
"""
return _get_console().clear_text()
def big_image(image_id):
"""
Display a full-screen ("big") image on the AutoAuto console.
See `cui.CuiRoot.big_image()` for details on `image_id`.
"""
return _get_console().big_image(image_id)
def big_status(status):
"""
Display a large status atop the "big image". This should
only be used after using the `big_image()`function above.
"""
return _get_console().big_status(status)
def big_clear():
"""
Clear the big image and big status off the AutoAuto console.
"""
return _get_console().big_clear()
def stream_image(rect_vals, shape, image_buf):
"""
Steam an image buffer (`image_buf` to the AutoAuto console, specifying
where it should show up via the `rect_vals` variable. A special
`rect_vals` of `(0, 0, 0, 0)` indicates that the image should be
full-screen. The `image_buf` should be either a grayscale or RGB image.
"""
return _get_console().stream_image(tuple(rect_vals), tuple(shape), image_buf)
def clear_image():
"""
Clear the streamed image (streamed via the `stream_image()` function above)
off the AutoAuto console.
"""
return _get_console().clear_image()
def clear():
"""
Clear the AutoAuto console of all text and images.
"""
clear_text()
big_clear()
clear_image()
# We won't support closing at this level (no need?),
# but if we did it would look like this:
#
#def close():
# """
# Close our connection to the console.
# """
# c = _get_console()
# c.close()
# global _CONSOLE
# del _CONSOLE
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides an RPC service which listens and communicates through a
websockets server.
"""
import asyncio
import websockets
import uuid
from auto.rpc.packer import pack, unpack
from auto.rpc.serialize_interface import serialize_interface
class SerializeIface(Exception):
"""
Raise this exception from your exported service to cause a sub-interface
to be serialized and sent to the client. This is useful when you cannot
serialize the full interface from the beginning, and you must instead
serialize part of the interface at runtime.
"""
def __init__(self, obj, whitelist_method_names=()):
self.obj = obj
self.whitelist_method_names = whitelist_method_names
async def serve(root_factory, pubsub=None, inet_addr='127.0.0.1', inet_port=7000):
"""
Serve an RPC server for objects created by `root_factory`. Each new client will
receive its own copy of the root object as created by the `root_factory`. Clients
may also subscribe to events which appear in the `pubsub` list of available
catalogs. The websockets server will listen on the given `inet_addr` and `inet_port`.
The `root_factory` may return a tuple of `(root, whitelist_method_names)` if it
so chooses; otherwise it is assumed it only returns the `root` instance and does
not specify `whitelist_method_names`. Also, the `root_factory` might return the same
object on each invocation; that is the choice of the `root_factory`.
"""
subscribers = {}
handle_client = _build_client_handler(root_factory, pubsub, subscribers)
start_server = websockets.serve(handle_client, inet_addr, inet_port)
server = await start_server
async def publish_func(channel, payload, wait=False):
client_list = subscribers.get(channel, [])
if client_list:
message = {
'type': 'publish',
'channel': channel,
'payload': payload,
}
message_buf = pack(message)
tasks = []
for client in client_list:
task = asyncio.create_task(client.send(message_buf))
tasks.append(task)
if wait:
await asyncio.wait(tasks)
return server, publish_func
def _build_client_handler(root_factory, pubsub, subscribers):
channels = pubsub['channels'] if pubsub is not None else []
channels_buf = pack(channels)
async def handle_client(ws, path):
root = root_factory()
whitelist_method_names = ()
if isinstance(root, tuple):
root, whitelist_method_names = root
iface, impl = serialize_interface(root, name='root', whitelist_method_names=whitelist_method_names)
iface_buf = pack(iface)
await ws.send(iface_buf)
await ws.send(channels_buf)
return await _handle_client(root, ws, impl, pubsub, subscribers)
return handle_client
async def _safe_invoke(func, *args):
if asyncio.iscoroutinefunction(func):
return await func(*args)
else:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, func, *args)
async def _handle_client(root, ws, impl, pubsub, subscribers):
setup = getattr(root, 'setup', None)
if setup is not None:
await _safe_invoke(setup, ws)
try:
while True:
cmd = await ws.recv()
cmd = unpack(cmd)
type_ = cmd['type']
if type_ == 'invoke':
asyncio.create_task(_handle_client_invoke(ws, cmd, impl))
elif type_ == 'subscribe':
await _handle_client_subscribe(ws, cmd, pubsub, subscribers)
elif type_ == 'unsubscribe':
await _handle_client_unsubscribe(ws, cmd, pubsub, subscribers)
except websockets.exceptions.ConnectionClosed:
pass # We consider this normal; fall through.
await _handle_client_unsubscribe_all(ws, pubsub, subscribers)
cleanup = getattr(root, 'cleanup', None)
if cleanup is not None:
await _safe_invoke(cleanup)
async def _handle_client_invoke(ws, cmd, impl):
id_ = cmd['id']
path = cmd['path']
args = cmd['args']
func = impl[path]
result = {
'type': 'invoke_result',
'id': id_,
}
try:
val = await _safe_invoke(func, *args)
result['val'] = val
except SerializeIface as s:
sub_obj = s.obj
sub_whitelist = s.whitelist_method_names
sub_name = path + '.' + str(uuid.uuid4())
sub_iface, sub_impl = serialize_interface(sub_obj, name=sub_name, whitelist_method_names=sub_whitelist)
impl.update(sub_impl)
result['iface'] = sub_iface
except Exception as e:
result['exception'] = str(e) # TODO: Serialize the exception more fully so it can be stacktraced on the other side.
result_buf = pack(result)
await ws.send(result_buf)
async def _handle_client_subscribe(ws, cmd, pubsub, subscribers):
channel = cmd['channel']
if (pubsub is None) or (channel not in pubsub['channels']):
return # TODO: send an error to the client so they know they messed up.
if channel not in subscribers:
subscribers[channel] = set()
if ws not in subscribers[channel]:
subscribers[channel].add(ws)
sub_callback = pubsub['subscribe']
if sub_callback is not None:
await _safe_invoke(sub_callback, channel)
async def _handle_client_unsubscribe(ws, cmd, pubsub, subscribers):
channel = cmd['channel']
if (pubsub is None) or (channel not in pubsub['channels']):
return # TODO: send an error to the client so they know they messed up.
if (channel in subscribers) and (ws in subscribers[channel]):
subscribers[channel].remove(ws)
if len(subscribers[channel]) == 0:
del subscribers[channel]
unsub_callback = pubsub['unsubscribe']
if unsub_callback is not None:
await _safe_invoke(unsub_callback, channel)
async def _handle_client_unsubscribe_all(ws, pubsub, subscribers):
if pubsub is None:
return
unsub_callback = pubsub['unsubscribe']
channels = [c for c, ws_set in subscribers.items() if ws in ws_set]
for c in channels:
subscribers[c].remove(ws)
if len(subscribers[c]) == 0:
del subscribers[c]
if unsub_callback is not None:
for c in channels:
await _safe_invoke(unsub_callback, c)
async def _demo():
class Thing:
async def setup(self, ws):
# This method is optional, but if implemented it will
# be invoked for each new client.
self.ws = ws
print('NEW CONNECTION:', self.ws.remote_address)
async def export_foo(self, x):
print('I am foo.')
return x ** 3
async def cleanup(self):
# This method is optional, but if implemented it will
# be invoked once the client disconnects.
print('DEAD CONNECTION:', self.ws.remote_address)
pubsub = {
'channels': [
'ping',
],
'subscribe': None,
'unsubscribe': None,
}
server, publish_func = await serve(Thing, pubsub)
for i in range(1, 1000000):
await publish_func('ping', f'Ping #{i}')
await asyncio.sleep(1)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(_demo())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from auto.rpc.server import serve
from auto import logger
log = logger.init(__name__, terminal=True)
class LabsService:
def __init__(self):
self.send_func = None
async def export_send(self, msg):
if self.send_func is not None:
return await self.send_func(msg)
else:
return False
async def init(pubsub_channels):
interface = LabsService()
interface_factory = lambda: interface # we want to always return the same instance
pubsub = {
'channels': pubsub_channels,
'subscribe': None,
'unsubscribe': None,
}
server, publish_func = await serve(interface_factory, pubsub, '127.0.0.1', 7004)
return server, interface, publish_func
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This subpackage contains demos for the car. Things in this subpackage
are just used for demos and they should *not* be imported into any other
part of libauto.
"""
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from .easyi2c import (write_read_i2c_with_integrity,
i2c_retry,
i2c_poll_until)
from . import N_I2C_TRIES
from auto import logger
log = logger.init(__name__, terminal=True)
import struct
CAPABILITIES_REG_NUM = 0x01
# We hard-code the capabilities of this controller.
CAPABILITIES_LIST = [
(0, 'VersionInfo'),
(1, 'Capabilities'),
(2, 'LEDs'),
(3, 'ADC'),
(3, 'Photoresistor'),
(4, 'CarMotors'),
(None, 'Credentials'),
(None, 'Calibrator'),
(None, 'Camera'),
(None, 'PushButtons'),
]
@i2c_retry(N_I2C_TRIES)
async def soft_reset(fd):
"""
Instruct the controller's capabilities module to do a soft-reset.
"""
await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x00], 0)
@i2c_retry(N_I2C_TRIES)
async def is_ready(fd):
"""
Check to see if the controller is ready for normal operation. This
is important to do on startup and after a hard- or soft-reset. It's
even better to poll this function to wait for the controller to be
ready, i.e.
| await soft_reset(fd)
|
| async def _is_ready():
| return await is_ready(fd)
|
| await i2c_poll_until(_is_ready, True, timeout_ms=1000)
"""
ready, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x01], 1)
return ready == 1
@i2c_retry(N_I2C_TRIES)
async def _eeprom_store(fd, addr, buf):
if not isinstance(buf, bytes):
raise Exception('`buf` should be `bytes`')
if len(buf) > 4:
raise Exception('you may only store 4 bytes at a time')
if addr < 0 or addr + len(buf) > 1024:
raise Exception('invalid `addr`: EEPROM size is 1024 bytes')
payload = list(struct.pack('1H', addr)) + [len(buf)] + list(buf)
await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x08] + payload, 0)
@i2c_retry(N_I2C_TRIES)
async def _is_eeprom_store_finished(fd):
status, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x09], 1)
return status == 0
@i2c_retry(N_I2C_TRIES)
async def _eeprom_query(fd, addr, length):
if length > 4:
raise Exception('you may only retrieve 4 bytes at a time')
if addr < 0 or addr + length > 1024:
raise Exception('invalid `addr`: EEPROM size is 1024 bytes')
payload = list(struct.pack('1H', addr)) + [length]
await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x0A] + payload, 0)
@i2c_retry(N_I2C_TRIES)
async def _is_eeprom_query_finished(fd):
status, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x0B], 1)
return status == 0
@i2c_retry(N_I2C_TRIES)
async def _retrieve_eeprom_query_buf(fd, length):
buf = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x0C], length)
return buf
async def eeprom_store(fd, addr, buf):
for i in range(0, len(buf), 4):
buf_here = buf[i:i+4]
await _eeprom_store(fd, addr + i, buf_here)
async def is_eeprom_store_finished():
return await _is_eeprom_store_finished(fd)
await i2c_poll_until(is_eeprom_store_finished, True, timeout_ms=1000)
async def eeprom_query(fd, addr, length):
bufs = []
i = 0
while length > 0:
length_here = min(length, 4)
await _eeprom_query(fd, addr + i, length_here)
async def is_eeprom_query_finished():
return await _is_eeprom_query_finished(fd)
await i2c_poll_until(is_eeprom_query_finished, True, timeout_ms=1000)
buf_here = await _retrieve_eeprom_query_buf(fd, length_here)
bufs.append(buf_here)
length -= length_here
i += length_here
return b''.join(bufs)
async def get_capabilities(fd, soft_reset_first=False, only_enabled=False):
"""
Return a dictionary representing the capabilities of the connected controller.
"""
if soft_reset_first:
await soft_reset(fd)
async def _is_ready():
return await is_ready(fd)
await i2c_poll_until(_is_ready, True, timeout_ms=1000)
caps = {}
for reg, name in CAPABILITIES_LIST:
if name != "Capabilities":
caps[name] = {
'fd': fd,
'register_number': reg,
}
return caps
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This modules provides a **synchronous** LabsServiceIface implementation.
"""
import asyncio
from auto.services.labs.rpc.client import LabsService as LabsService_async
from auto.services.labs.rpc import LabsServiceIface
class LabsService(LabsServiceIface):
def __init__(self, loop, inet_addr='127.0.0.1', inet_port=7004):
self.labs = LabsService_async(inet_addr, inet_port)
self.loop = loop
def connect(self):
future = asyncio.run_coroutine_threadsafe(self.labs.connect(), self.loop)
return future.result()
def send(self, msg):
future = asyncio.run_coroutine_threadsafe(self.labs.send(msg), self.loop)
return future.result()
def receive(self):
future = asyncio.run_coroutine_threadsafe(self.labs.receive(), self.loop)
return future.result()
def close(self):
future = asyncio.run_coroutine_threadsafe(self.labs.close(), self.loop)
return future.result()
def _demo():
from threading import Thread
import time
loop = asyncio.new_event_loop()
def _run_event_loop():
asyncio.set_event_loop(loop)
loop.run_forever()
loop_thread = Thread(target=_run_event_loop)
loop_thread.start()
labs = LabsService(loop)
labs.connect()
for i in range(5):
did_send = labs.send({'hi': 'there'})
print('Did Send?', did_send)
labs.close()
async def _stop_loop():
loop.stop()
asyncio.run_coroutine_threadsafe(_stop_loop(), loop)
loop_thread.join()
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
if __name__ == '__main__':
_demo()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This client connects to the CUI RPC server. This is a **synchronous** client.
"""
import asyncio
from auto.services.console.client import CuiRoot as CuiRoot_async
import cui
class CuiRoot(cui.CuiRoot):
def __init__(self, loop, inet_addr='127.0.0.1', inet_port=7003):
self.cui_root = CuiRoot_async(inet_addr, inet_port)
self.loop = loop
def init(self):
future = asyncio.run_coroutine_threadsafe(self.cui_root.init(), self.loop)
return future.result()
def write_text(self, text):
future = asyncio.run_coroutine_threadsafe(self.cui_root.write_text(text), self.loop)
return future.result()
def clear_text(self):
future = asyncio.run_coroutine_threadsafe(self.cui_root.clear_text(), self.loop)
return future.result()
def big_image(self, image_id):
future = asyncio.run_coroutine_threadsafe(self.cui_root.big_image(image_id), self.loop)
return future.result()
def big_status(self, status):
future = asyncio.run_coroutine_threadsafe(self.cui_root.big_status(status), self.loop)
return future.result()
def big_clear(self):
future = asyncio.run_coroutine_threadsafe(self.cui_root.big_clear(), self.loop)
return future.result()
def stream_image(self, rect_vals, shape, image_buf):
future = asyncio.run_coroutine_threadsafe(self.cui_root.stream_image(rect_vals, shape, image_buf), self.loop)
return future.result()
def clear_image(self):
future = asyncio.run_coroutine_threadsafe(self.cui_root.clear_image(), self.loop)
return future.result()
def set_battery(self, state, minutes, percentage):
future = asyncio.run_coroutine_threadsafe(self.cui_root.set_battery(state, minutes, percentage), self.loop)
return future.result()
def close(self):
future = asyncio.run_coroutine_threadsafe(self.cui_root.close(), self.loop)
return future.result()
def _run():
from threading import Thread
import time
loop = asyncio.new_event_loop()
def _run_event_loop():
asyncio.set_event_loop(loop)
loop.run_forever()
loop_thread = Thread(target=_run_event_loop)
loop_thread.start()
cui_root = CuiRoot(loop)
cui_root.init()
cui_root.write_text('Hi!')
time.sleep(3)
cui_root.close()
async def _stop_loop():
loop.stop()
asyncio.run_coroutine_threadsafe(_stop_loop(), loop)
loop_thread.join()
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
if __name__ == '__main__':
_run()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
Module to interface with your AutoAuto Labs account.
This is a **synchronous** interface.
"""
import os
from threading import Lock
from auto.asyncio_tools import get_loop, thread_safe
from auto.services.labs.rpc.client_sync import LabsService
def send_message_to_labs(msg):
"""
Send a message `msg` to your AutoAuto Labs account.
Return True if the message was sent, else return False.
"""
client = _global_client()
if 'to_vin' not in msg:
to_user_session = os.environ.get('TO_USER_SESSION', None)
to_username = os.environ.get('TO_USERNAME', None)
if to_user_session:
msg['to_user_session'] = to_user_session
elif to_username:
msg['to_username'] = to_username
did_send = client.send(msg)
return did_send
def receive_message_from_labs():
"""
Wait for the next message from the Labs server, then return it.
"""
client = _global_client()
return client.receive()
# Alias
send = send_message_to_labs
receive = receive_message_from_labs
_GLOBAL_LOCK = Lock()
@thread_safe
def _global_client():
global _CLIENT
with _GLOBAL_LOCK:
try:
_CLIENT
except NameError:
_CLIENT = LabsService(get_loop())
_CLIENT.connect()
return _CLIENT
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import os
import subprocess
SCRIPTS_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
def run_script(path, *args, timeout=5):
if not os.path.isfile(path):
return 'Error: The script or program at the specified path is not installed on your system.'
try:
cmd = [path, *args]
output = subprocess.run(cmd,
timeout=timeout,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).stdout.decode('utf-8')
return output
except subprocess.TimeoutExpired:
return 'Error: Command timed out...'
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import os
import sys
import time
import pygame
import numpy as np
from collections import deque
from auto import logger
log = logger.init(__name__, terminal=True)
RESOURCE_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources')
def hex_to_rgb(hex_str):
assert hex_str[0] == '#'
assert len(hex_str) == 7
r = int(hex_str[1:3], 16)
g = int(hex_str[3:5], 16)
b = int(hex_str[5:], 16)
return r, g, b
# Pallets
# #0c0032 #190061 #240090 #3500d3 #282828
# #0b0c10 #1f2833 #c5c6c7 #66fcf1 #45a29e
# #2c3531 #116466 #d9b08c #ffcb9a #d1e8e2
# Settings:
CONSOLE_FONT_SIZE = 20
HEADER_FONT_SIZE = 25
BIG_STATUS_FONT_SIZE = 25
BG_COLOR = hex_to_rgb("#000000")
HEADER_BG_COLOR = hex_to_rgb("#53900f") # 88cc88
HEADER_TXT_COLOR = hex_to_rgb("#1f2605") # 004400
CONSOLE_BG_COLOR = hex_to_rgb("#e7e7e7") # ffffff
CONSOLE_TXT_COLOR = hex_to_rgb("#000080") # 0000ff
CONSOLE_TXT_BG_COLOR = hex_to_rgb("#8fc1e3") # c6cdf6
BIG_STATUS_COLOR = hex_to_rgb("#ffffff") # ffffff
BIG_STATUS_BG_COLOR = hex_to_rgb("#323232") # 323232
HEADER_CONSOLE_SPLIT = 7
HEADER_TITLE = 'AutoAuto Console'
HEADER_FONT_PATH = os.path.join(RESOURCE_DIR_PATH, 'fonts/DejaVuSansMono-Bold.ttf')
CONSOLE_FONT_PATH = os.path.join(RESOURCE_DIR_PATH, 'fonts/DejaVuSansMono.ttf')
LOGO_PATH = os.path.join(RESOURCE_DIR_PATH, 'images/logo_2017_03_17.png')
# Init pygame:
pygame.init()
# Create the window.
window_surface = pygame.display.set_mode(flags=pygame.FULLSCREEN)
window_width, window_height = window_surface.get_size()
pygame.display.set_caption(HEADER_TITLE)
pygame.mouse.set_visible(False)
window_surface.fill(BG_COLOR, window_surface.get_rect())
# Define the window areas:
border_width = 0
full_rect = pygame.Rect(border_width, border_width, window_width-2*border_width, window_height-2*border_width)
header_rect = pygame.Rect(full_rect.x, full_rect.y, full_rect.width, full_rect.height//HEADER_CONSOLE_SPLIT)
console_rect = pygame.Rect(full_rect.x, header_rect.y + header_rect.height, full_rect.width, full_rect.height-header_rect.height)
# The fonts we'll use:
console_font = pygame.font.Font(CONSOLE_FONT_PATH, CONSOLE_FONT_SIZE)
header_font = pygame.font.Font(HEADER_FONT_PATH, HEADER_FONT_SIZE)
big_status_font = pygame.font.Font(CONSOLE_FONT_PATH, BIG_STATUS_FONT_SIZE)
# Pre-load some stuff:
logo = pygame.image.load(LOGO_PATH)
logo_width, logo_height = logo.get_rect().size
logo_image_size = (header_rect.height * logo_width // logo_height, header_rect.height)
logo = pygame.transform.scale(logo, logo_image_size)
logo_rect = pygame.Rect(console_rect.x + console_rect.width - logo_image_size[0], header_rect.y, *logo_image_size)
header_title_sprite = header_font.render(HEADER_TITLE, True, HEADER_TXT_COLOR)
# State:
lines = deque()
lines.append([])
big_image_rect = None
big_image_obj = None
big_status_str = None
stream_img_rect = None
stream_img = None
battery_sprite = None
def draw_header():
window_surface.fill(HEADER_BG_COLOR, header_rect)
window_surface.blit(logo, logo_rect)
window_surface.blit(header_title_sprite, (header_rect.x + 10, header_rect.y + 8))
if battery_sprite is not None:
battery_origin_x = console_rect.x + console_rect.width - logo_image_size[0] - battery_sprite.get_rect().width - 5
battery_origin_y = header_rect.y + 8
window_surface.blit(battery_sprite, (battery_origin_x, battery_origin_y))
def parse_text(new_text, old_lines, outer_rect):
if old_lines:
if len(old_lines[-1]) == 1 and old_lines[-1][0][0] == '\r':
old_lines.pop()
if old_lines:
old_lines.pop()
old_lines.append([])
for char in new_text:
if char == '\r':
old_lines.append([('\r', None)])
continue
sprite = console_font.render(char, True, CONSOLE_TXT_COLOR, CONSOLE_TXT_BG_COLOR)
rect = sprite.get_rect()
last_line = old_lines[-1]
if char == '\n':
last_line.append((char, sprite))
old_lines.append([])
else:
if len(last_line) < (outer_rect.width // rect.width):
last_line.append((char,sprite))
else:
old_lines.append([(char, sprite)])
while len(old_lines) > (outer_rect.height // rect.height):
old_lines.popleft()
def draw_lines(lines, outer_rect):
x, y = outer_rect.topleft
for line in lines:
if len(line)==1 and line[0][0] == '\r':
continue
for char, sprite in line:
rect = sprite.get_rect()
rect.topleft = (x, y)
if char != '\n':
window_surface.blit(sprite, rect)
x += rect.width
if line:
x = outer_rect.x
y += line[0][1].get_rect().height
def draw_console():
window_surface.fill(CONSOLE_BG_COLOR, console_rect)
draw_lines(lines, console_rect)
def draw_all():
draw_header()
draw_console()
if big_image_obj is not None:
window_surface.blit(big_image_obj, big_image_rect)
if stream_img is not None:
window_surface.blit(stream_img, stream_img_rect)
if big_status_str is not None:
big_lines = big_status_str.split('\n')
y = full_rect.height - 10
for line in reversed(big_lines):
line = big_status_font.render(line, True, BIG_STATUS_COLOR, BIG_STATUS_BG_COLOR)
line_rect = line.get_rect()
line_rect.x += (full_rect.width - line_rect.width) / 2
line_rect.y = (y - line_rect.height)
y -= (line_rect.height + 5)
window_surface.blit(line, line_rect)
pygame.display.update()
draw_all()
needs_draw = False
def write_text(text):
log.info('Will print text: {}'.format(text))
parse_text(text, lines, console_rect)
draw_all()
def clear_text():
log.info('Will clear text!')
global lines
lines = deque()
lines.append([])
draw_all()
def big_image(image_path):
log.info('Will show big image at path: {}'.format(image_path))
image_path = os.path.join(RESOURCE_DIR_PATH, image_path)
global big_image_rect, big_image_obj
big_image_rect = full_rect
big_image_obj = pygame.image.load(image_path)
big_image_obj = pygame.transform.scale(big_image_obj, big_image_rect.size)
draw_all()
def big_status(status):
log.info('Will show big status: {}'.format(status))
global big_status_str
big_status_str = status
if len(big_status_str) == 0:
big_status_str = None
draw_all()
def big_clear():
log.info('Will clear big image and status!')
global big_image_rect, big_image_obj, big_status_str
big_image_rect = None
big_image_obj = None
big_status_str = None
draw_all()
def stream_image(rect_vals, shape, image_buf):
log.info('Will shows streamed image with shape: {}'.format(shape))
width, height, channels = shape
if channels not in (1, 3):
return False
global stream_img_rect, stream_img
stream_img_rect = pygame.Rect(*rect_vals)
if rect_vals == (0, 0, 0, 0): # <-- sentinel value to mean the full screen
stream_img_rect = full_rect
if channels == 1:
data2 = np.fromstring(image_buf, dtype=np.uint8).reshape((height, width))
data = np.zeros((height, width, 3), dtype=np.uint8)
data[:,:,0] = data2
data[:,:,1] = data2
data[:,:,2] = data2
data = data.tobytes()
else: # channels == 3
data = image_buf # the `image_buf` is already bytes
stream_img = pygame.image.fromstring(data, (width, height), 'RGB')
stream_img = pygame.transform.scale(stream_img, stream_img_rect.size)
draw_all()
return True
def clear_image():
log.info('Will clear streamed image!')
global stream_img_rect, stream_img
stream_img_rect = None
stream_img = None
draw_all()
def set_battery(state, minutes, percentage):
# TODO: Show the `minutes` somewhere/somehow.
if not isinstance(percentage, int) or not (0 <= percentage <= 100):
raise Exception("Invalid battery percentage")
if state == 'battery':
text = "{}%".format(percentage)
elif state == 'charging':
text = 'Charging'
elif state == 'wall':
text = 'FULL!'
else:
return
global battery_sprite
battery_sprite = header_font.render(text, True, HEADER_TXT_COLOR)
draw_all()
def close():
log.info('Will close...')
sys.exit(1)
mouse_up_event_times = deque()
n_mouse_up_target = 2
mouse_up_max_delay = 1.0 # seconds
def check_events():
events = pygame.event.get()
for event in events:
if event.type == pygame.MOUSEBUTTONUP:
mouse_up_event_times.append(time.time())
while len(mouse_up_event_times) > n_mouse_up_target:
mouse_up_event_times.popleft()
if len(mouse_up_event_times) == n_mouse_up_target:
delay_here = mouse_up_event_times[-1] - mouse_up_event_times[0]
if delay_here <= mouse_up_max_delay:
pass
# The double-tap turn-off feature is disabled; See issue #36.
#write_text('\nSHUTTING DOWN\n\n')
#output = _shutdown(reboot=False)
#write_text(output + '\n')
log.info("RUNNING!")
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module can launch a Python asyncio event loop in a background thread.
You create and get the event loop by calling `get_loop()`. It is a singleton;
the same loop is returned on every invocation, and it is not created until the
first invocation.
The purpose of this background-thread event loop is so that the main thread
can run **synchronous** code (as feels natural for beginner programmers), but
we can still reap the power of the asyncio event loop through delegation to
the background loop. When students advance enough, we can teach them how to
ditch this background loop and how to use a main-thread async loop to write
a fully asynchronous (cooperative) program! Indeed, the libauto library is
async under-the-hood.
This module also provides a function to wrap an async interface into a
synchronous one, delegating to the underlying loop to invoke the wrapped
async methods. See `wrap_async_to_sync()`.
"""
import asyncio
import inspect
import functools
from threading import Thread, RLock
from auto.rpc.serialize_interface import serialize_interface
from auto.rpc.build_interface import build_interface
DEBUG_ASYNCIO = False
def thread_safe(wrapped=None, lock=None):
if wrapped is None:
return functools.partial(thread_safe, lock=lock)
if lock is None:
lock = RLock()
@functools.wraps(wrapped)
def _wrapper(*args, **kwargs):
with lock:
return wrapped(*args, **kwargs)
return _wrapper
@thread_safe
def get_loop():
"""
Obtain the Python asyncio event loop which is running in a background thread.
The loop (and its background thread) are not created until you invoke this
function for the first time. The same loop is returned on all subsequent calls.
"""
global _BG_LOOP
try:
return _BG_LOOP
except NameError:
_BG_LOOP = asyncio.new_event_loop()
_set_async_debug_and_log_level(_BG_LOOP)
thread = Thread(target=_loop_main, args=(_BG_LOOP,))
thread.daemon = True # <-- thread will exit when main thread exists
thread.start()
_setup_cleanup(_BG_LOOP, thread)
return _BG_LOOP
def _loop_main(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
def _set_async_debug_and_log_level(loop):
# Do you want debugging turned on?
if DEBUG_ASYNCIO:
loop.set_debug(True) # It's off by default, so we turn it on when we want it.
# Btw, we could also change the log level. For more info, see:
# https://docs.python.org/3.7/library/asyncio-dev.html#asyncio-logger
#
# E.g. We could do:
# import logging
# logging.getLogger("asyncio").setLevel(logging.WARNING)
#
# But I don't think we need it...
def _setup_cleanup(loop, thread):
"""
Attempt to cleanup the event loop and the background thread _properly_.
This cleanup is only done when DEBUG_ASYNCIO is True; else, we just
let the asyncio thread die quickly and painlessly, without giving it a
chance to close or print warnings.
"""
if not DEBUG_ASYNCIO:
return
def cleanup():
async def _stop_loop():
loop.stop()
asyncio.run_coroutine_threadsafe(_stop_loop(), loop)
thread.join()
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
import atexit
atexit.register(cleanup)
def wrap_async_to_sync(obj, loop=None):
"""
Build and return an object which wraps `obj`, turning each of `obj`'s async
methods into "normal" synchronous methods.
**Note:** Only _methods_ are wrapped, so if `obj` has _attributes_ which it
exports, those will _not_ be accessible through the wrapped object.
This is a known limitation which will not be addressed (it is
too complex to export wrapped attributes in such a way that
preserves their mutability or lack thereof; thus only methods
will be exported by the wrapper). Also, magic methods are _not_
wrapped; this is a limitation we may fix in the future.
"""
if loop is None:
loop = get_loop()
typename = type(obj).__name__
typemodule = type(obj).__module__
typedoc = inspect.getdoc(type(obj))
TheDynamicType = type(typename, (object,), {})
TheDynamicType.__module__ = typemodule
TheDynamicType.__doc__ = typedoc
instance = TheDynamicType()
for attr_name in dir(obj):
if attr_name.startswith('__'):
# We won't try to fix magic methods (too much craziness to try that).
continue
attr = getattr(obj, attr_name)
if not inspect.isfunction(attr) and not inspect.ismethod(attr):
# We only care about functions and methods.
continue
iface, _ = serialize_interface(attr, attr_name)
if not iface['is_async']:
# This is a normal synchronous function or method, so we just copy it over.
setattr(instance, attr_name, attr)
else:
# This is an asynchronous function or method, so we need to do some shenanigans
# to turn it into a normal synchronous function or method.
iface['is_async'] = False
impl_transport = _closure_build_impl_transport(attr, loop) # <-- Need to close over `attr` to freeze it, since it is reassigned in the loop above.
if iface['ismethod']:
sub_name, sub_attr = build_interface(iface, impl_transport, is_method=True)
assert attr_name == sub_name
setattr(TheDynamicType, sub_name, sub_attr)
else:
sub_name, sub_attr = build_interface(iface, impl_transport, is_method=False)
assert attr_name == sub_name
setattr(instance, sub_name, sub_attr)
return instance
def _closure_build_impl_transport(attr, loop):
def impl_transport(path, args):
coro = attr(*args)
future = asyncio.run_coroutine_threadsafe(coro, loop)
return future.result()
return impl_transport
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains the interface to AutoAuto v3 microcontroller which we
communicate with via I2C from this host.
"""
"""
In my tests, it seems that the I2C bus will fail ~1/200 times. We can
detect those failures with high probability due to our integrity checks
which we use for all I2C messages, so that's good. Furthermore, we have
a method for automatically retrying failed I2C transactions! In fact, if
we take the 1/200 failure rate as a given, then by retrying up to 5 times
(total, meaning 1 attempt and 4 retries) and assuming independence, we
conclude that we will only see a failure:
(1/200)**5 = 1/320000000000
Thus, if we do 300 transactions per second, we'll see, on average, one
failure every ~34 years. Someone check my math.
"""
N_I2C_TRIES = 10
"""
For this particular controller, we talk to it via I2C.
"""
I2C_BUS_INDEX = 1
CONTROLLER_I2C_SLAVE_ADDRESS = 0x15
BATT_CONTROLLER_SLAVE_ADDRESS = 0x6a
import asyncio
from . import capabilities
from . import easyi2c
from . import reset
from . import imu
from .components import KNOWN_COMPONENTS
import cio
from auto.services.labs.settings import load_settings
class CioRoot(cio.CioRoot):
"""
This is the CIO root interface for the AutoAuto v3.x microcontrollers.
"""
def __init__(self):
self.ctlr_fd = None
self.caps = None
self.batt_fd = None
self.refcounts = {} # maps `capability_id` to integer refcount
self.objects = {} # maps `capability_id` to first object of that type
async def init(self):
"""
Attempt to initialize the version 3.x AutoAuto controller. Return a list
of capabilities if initialization worked, else raise an exception.
"""
try:
self.ctlr_fd = await easyi2c.open_i2c(I2C_BUS_INDEX, CONTROLLER_I2C_SLAVE_ADDRESS)
self.caps = await capabilities.get_capabilities(self.ctlr_fd, soft_reset_first=True)
version_info = await self.acquire('VersionInfo')
major, minor = await version_info.version()
await self.release(version_info)
if major != 3:
raise Exception('Controller is not version 3, thus this interface will not work.')
self.batt_fd = await easyi2c.open_i2c(I2C_BUS_INDEX, BATT_CONTROLLER_SLAVE_ADDRESS)
self.caps['Power'] = {
'fd': self.batt_fd,
'register_number': None,
}
imu.start_thread()
loop = asyncio.get_running_loop()
imu_start = loop.time()
imu_working = True
while imu.DATA is None:
if loop.time() - imu_start > 1.0:
imu_working = False
break
await asyncio.sleep(0.1)
if imu_working:
for c in ['Gyroscope', 'Gyroscope_accum', 'Accelerometer', 'AHRS', 'PID_steering']:
self.caps[c] = {
'fd': None,
'register_number': None,
}
settings = load_settings()
if isinstance(settings, dict) and 'cio' in settings:
cio_settings = settings['cio']
if isinstance(cio_settings, dict) and 'disabled' in cio_settings:
cio_disabled = cio_settings['disabled']
if isinstance(cio_disabled, list):
for disabled_component_name in cio_disabled:
if disabled_component_name in self.caps:
del self.caps[disabled_component_name]
except:
if self.ctlr_fd is not None:
await easyi2c.close_i2c(self.ctlr_fd)
self.ctlr_fd = None
self.caps = None
if self.batt_fd is not None:
await easyi2c.close_i2c(self.batt_fd)
self.batt_fd = None
self.refcounts = {}
self.objects = {}
raise
return list(self.caps.keys())
async def acquire(self, capability_id):
"""
Acquire the interface to the component with the given `capability_id`, and return
a concrete object implementing its interface.
"""
if capability_id not in self.caps:
raise Exception(f"Unknown capability: {capability_id}")
fd = self.caps[capability_id]['fd']
register_number = self.caps[capability_id]['register_number']
capability_obj = KNOWN_COMPONENTS[capability_id](fd, register_number)
capability_obj._capability_id = capability_id
if capability_id not in self.refcounts:
self.refcounts[capability_id] = 1
self.objects[capability_id] = capability_obj
await capability_obj.acquired()
else:
refcount = self.refcounts[capability_id]
self.refcounts[capability_id] = refcount + 1
return capability_obj
async def release(self, capability_obj):
"""
Release a previously acquired capability interface. You must pass
the exact object returned by `acquire()`.
"""
capability_id = capability_obj._capability_id
if capability_id not in self.refcounts:
raise Exception("Invalid object passed to `release()`")
refcount = self.refcounts[capability_id]
refcount -= 1
if refcount == 0:
del self.refcounts[capability_id]
del self.objects[capability_id]
await capability_obj.released()
else:
self.refcounts[capability_id] = refcount
async def close(self):
"""
Close the connection and reset the controller, thereby invalidating and releasing
all acquired components.
"""
for capability_obj in self.objects.values():
await capability_obj.released()
self.refcounts = {}
self.objects = {}
if self.ctlr_fd is not None:
await reset.soft_reset(self.ctlr_fd)
await easyi2c.close_i2c(self.ctlr_fd)
self.ctlr_fd = None
self.caps = None
if self.batt_fd is not None:
await easyi2c.close_i2c(self.batt_fd)
self.batt_fd = None
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import sys
import asyncio
from cui.pygame_impl import CuiPyGame
async def run():
c = CuiPyGame()
await c.init()
while True:
try:
text = sys.stdin.readline()
except KeyboardInterrupt:
await c.clear_text()
break
await c.write_text(text)
await asyncio.sleep(2)
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v3 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
p = await c.acquire('Photoresistor')
for i in range(1000):
millivolts, resistance = await p.read()
print(f'{millivolts:.2f} {resistance:.0f}')
await asyncio.sleep(0.1)
await c.release(p)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>#!/usr/bin/env python3
###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import sys
import time
import asyncio
import logging
from auto.services.console.client import CuiRoot
from auto.services.controller.client import CioRoot
PID_DEFAULT_P = 1.0
PID_DEFAULT_I = 0.2
PID_DEFAULT_D = 0.2
START_PROMPT = """
*YOU ARE ABOUT TO CALIBRATE THIS CAR.*
If you do not want to calibrate this
car, please EXIT by pressing button 3.
Press button 1 to BEGIN.
Press button 3 to EXIT.
"""
GYRO_ACCELL_PROMPT = """
Would you like to calibrate the car's
gyroscope and accelerometer?
e.g. if car is wobbly
Press button 1 for 'yes'.
Press button 3 for 'no'.
"""
GYRO_ACCELL_INSTRUCTIONS = """
During this calibration step, you must
place your car on a flat surface and
**DO NOT MOVE** it until this step
finishes.
Place your car on a flat surface, then
press button 1 to BEGIN.
"""
GYRO_ACCEL_STARTED = """
Started gyro & accel. calibration...
** DO NOT MOVE THE DEVICE UNTIL THIS
STEP FINISHES. **
"""
CAR_MOTORS_PROMPT = """
Would you like to calibrate the car's
** STEERING **?
e.g. if car is not turning sharply
Press button 1 for 'yes'.
Press button 3 for 'no'.
"""
CAR_SPEED_PROMPT = """
Would you like to calibrate the car's
** SPEED **?
e.g. if car is too fast
Press button 1 for 'yes'.
Press button 3 for 'no'.
"""
CAR_MOTORS_LEFT_STEERING = """
Set the **LEFT** steering direction.
Use button 1 and 3 to **MOVE**
the steering.
Press button 2 to **STORE**
the position.
"""
CAR_MOTORS_RIGHT_STEERING = """
Set the **RIGHT** steering direction.
Use button 1 and 3 to **MOVE**
the steering.
Press button 2 to **STORE**
the position.
"""
CAR_MOTORS_FORWARD_REVERSE_DIRS = """
Car will drive **FORWARD** and then
in **REVERSE**.
** Please HOLD the car carefully with
both hands, with wheels off the
ground. Be sure wheels can spin
freely, clear of all obstacles. **
Press button 1 when you are ready.
"""
CAR_MOTORS_DIRECTIONS_CORRECT = """
Did the car drive forward **THEN**
in reverse?
Press button 1 if 'yes'.
Press button 3 if 'no'.
"""
CAR_MOTORS_DIRECTIONS_SWAP = """
Will swap directions and try again...
"""
CAR_MOTORS_MID_STEERING = """
Will check the steering direction
for moving **STRAIGHT**.
Car will drive **FORWARD** and
then in **REVERSE**.
** Place car on the ground with a
SAFE and OPEN area in front of it.
Press button 1 when you are ready."""
CAR_MOTORS_MID_STEERING_CHECK = """
Did the car drive roughly straight?
Press 1 to correct to the **LEFT**
Press 2 if it looked okay.
Press 3 to correct to the **RIGHT**.
** CAR WILL DRIVE AGAIN AFTER YOU
MAKE YOUR SELECTION.
BE SURE AREA IS CLEAR AND SAFE.
**"""
CAR_SPEED_FORWARD = """
Will demo current **FORWARD**
speed.
** Place car on the ground with a
SAFE and OPEN area in front of it.
Press button 1 when you are ready.
"""
CAR_SPEED_FORWARD_CHECK = """
Is the **FORWARD** speed okay?
Press 1 to **DECREASE** speed.
Press 2 if okay.
Press 3 to **INCREASE** speed.
** CAR WILL DRIVE AGAIN AFTER YOU
MAKE YOUR SELECTION.
BE SURE AREA IS CLEAR AND SAFE.
"""
CAR_SPEED_REVERSE = """
Will demo current **REVERSE**
speed.
** Place car on the ground with a
SAFE and OPEN area in front of it.
Press button 1 when you are ready.
"""
CAR_SPEED_REVERSE_CHECK = """
Is the **REVERSE** speed okay?
Press 1 to **DECREASE** speed.
Press 2 if okay.
Press 3 to **INCREASE** speed.
** CAR WILL DRIVE AGAIN AFTER YOU
MAKE YOUR SELECTION.
BE SURE AREA IS CLEAR AND SAFE.
"""
DRIVE_DEMO_PROMPT = """
Would you like your car to do
a final **DRIVING DEMO**?
Press button 1 for 'yes'.
Press button 3 for 'no'.
"""
DRIVE_DEMO_AGAIN = """
Demo again?
Press button 1 for 'yes'.
Press button 3 for 'no'.
"""
async def _clear(console):
print("\x1b[2J\x1b[H") # https://stackoverflow.com/a/2084560
await console.clear_text()
async def _print_all(console, text, end='\n', **kwargs):
print(text, end=end, **kwargs)
await console.write_text(text + end)
async def _prompt(console, buttons, options, prompt_text):
async for b in _prompt_continuous(console, buttons, options, prompt_text):
return b
async def _prompt_continuous(console, buttons, options, prompt_text):
await _clear(console)
await _print_all(console, prompt_text)
while True:
b = await buttons.wait_for_action()
b = b[0] + 1
if b in options:
yield b
async def _reset_pid_to_defaults(controller):
pid = await controller.acquire('PID_steering')
await pid.set_pid(p=PID_DEFAULT_P, i=PID_DEFAULT_I, d=PID_DEFAULT_D, save=True)
await controller.release(pid)
def _run_for_second(seconds):
start = time.time()
while True:
curr = time.time()
if curr - start < seconds:
yield curr
else:
break
async def _drive_demo(console, controller, car, buttons):
min_throttle, max_throttle = await car.get_safe_throttle()
await car.on()
while True:
for i in reversed(range(3)):
await _print_all(console, "Driving in {}...".format(i+1))
await asyncio.sleep(0.9)
gyro = await controller.acquire('Gyroscope_accum')
pid = await controller.acquire('PID_steering')
_, _, z_start = await gyro.read()
await pid.set_point(z_start)
await pid.enable(invert_output=False)
for t in _run_for_second(2.0):
await car.set_throttle(max_throttle)
await pid.disable()
await pid.enable(invert_output=True)
for t in _run_for_second(1.5):
await car.set_throttle(min_throttle)
await pid.disable()
target = z_start - 90
_, _, z = await gyro.read()
while z > target:
await car.set_steering(45.0)
await car.set_throttle(min_throttle)
_, _, z = await gyro.read()
target = z_start + 90
_, _, z = await gyro.read()
while z < target:
await car.set_steering(45.0)
await car.set_throttle(max_throttle)
_, _, z = await gyro.read()
target = z_start - 180
_, _, z = await gyro.read()
while z > target:
await car.set_steering(-45.0)
await car.set_throttle(max_throttle)
_, _, z = await gyro.read()
await pid.set_point(target)
await pid.enable(invert_output=False)
for t in _run_for_second(1.0):
await car.set_throttle(max_throttle)
await pid.disable()
await car.set_throttle(0.0)
await car.set_steering(0.0)
await controller.release(gyro)
await controller.release(pid)
answer = await _prompt(console, buttons, [1, 3], DRIVE_DEMO_AGAIN)
if answer == 3:
break
await car.off()
async def _calibrate_car_speed(console, car, buttons):
min_throttle, max_throttle = await car.get_safe_throttle()
await car.on()
_ = await _prompt(console, buttons, [1], CAR_SPEED_FORWARD)
while True:
await car.set_steering(0.0)
await car.set_throttle(max_throttle)
await asyncio.sleep(1)
await car.set_throttle(min_throttle)
await asyncio.sleep(1)
await car.set_throttle(0)
answer = await _prompt(console, buttons, [1, 2, 3], CAR_SPEED_FORWARD_CHECK)
if answer == 1:
max_throttle -= 1
elif answer == 2:
break
elif answer == 3:
max_throttle += 1
await car.set_safe_throttle(min_throttle, max_throttle)
_ = await _prompt(console, buttons, [1], CAR_SPEED_REVERSE)
while True:
await car.set_steering(0.0)
await car.set_throttle(max_throttle)
await asyncio.sleep(1)
await car.set_throttle(min_throttle)
await asyncio.sleep(1)
await car.set_throttle(0)
answer = await _prompt(console, buttons, [1, 2, 3], CAR_SPEED_REVERSE_CHECK)
if answer == 1:
min_throttle += 1
elif answer == 2:
break
elif answer == 3:
min_throttle -= 1
await car.set_safe_throttle(min_throttle, max_throttle)
await car.off()
async def _calibrate_car_motors(console, car, buttons):
params = {
'top': 40000,
'steering_left': 3000,
'steering_mid': 3000,
'steering_right': 3000,
'steering_millis': 30000, # 30 seconds
'throttle_forward': 4000,
'throttle_mid': 3000,
'throttle_reverse': 2000,
'throttle_millis': 30000, # 30 seconds
}
min_throttle, max_throttle = await car.get_safe_throttle()
await car.on()
await car.set_params(**params)
await car.set_steering(45.0)
async for answer in _prompt_continuous(console, buttons, [1, 2, 3], CAR_MOTORS_LEFT_STEERING):
if answer == 1:
params['steering_left'] += 100
elif answer == 3:
params['steering_left'] -= 100
else:
break
await car.set_params(**params)
await car.set_steering(45.0)
await car.set_steering(-45.0)
async for answer in _prompt_continuous(console, buttons, [1, 2, 3], CAR_MOTORS_RIGHT_STEERING):
if answer == 1:
params['steering_right'] += 100
elif answer == 3:
params['steering_right'] -= 100
else:
break
await car.set_params(**params)
await car.set_steering(-45.0)
params['steering_mid'] = (params['steering_left'] + params['steering_right']) // 2
await car.set_params(**params)
await car.set_steering(0.0)
while True:
await car.set_steering(0.0)
_ = await _prompt(console, buttons, [1], CAR_MOTORS_FORWARD_REVERSE_DIRS)
await car.set_steering(0.0)
await car.set_throttle(max_throttle)
await asyncio.sleep(1)
await car.set_throttle(min_throttle)
await asyncio.sleep(1)
await car.set_throttle(0)
answer = await _prompt(console, buttons, [1, 3], CAR_MOTORS_DIRECTIONS_CORRECT)
if answer == 1:
break
else:
await _print_all(console, CAR_MOTORS_DIRECTIONS_SWAP)
await asyncio.sleep(1)
params['throttle_forward'], params['throttle_reverse'] = params['throttle_reverse'], params['throttle_forward']
await car.set_params(**params)
left_dir = 1 if params['steering_mid'] < params['steering_left'] else -1
left_dir *= 50 # <-- step size
await car.set_steering(0.0)
_ = await _prompt(console, buttons, [1], CAR_MOTORS_MID_STEERING)
while True:
await car.set_steering(0.0)
await car.set_throttle(max_throttle)
await asyncio.sleep(1)
await car.set_throttle(min_throttle)
await asyncio.sleep(1)
await car.set_throttle(0)
answer = await _prompt(console, buttons, [1, 2, 3], CAR_MOTORS_MID_STEERING_CHECK)
if answer == 1:
params['steering_mid'] += left_dir
elif answer == 2:
break
elif answer == 3:
params['steering_mid'] -= left_dir
await car.set_params(**params)
params['steering_millis'] = 1000
params['throttle_millis'] = 1000
await car.set_params(**params)
await car.save_params()
await car.off()
async def _calibrate_gyro_accel(console, calibrator, buttons):
_ = await _prompt(console, buttons, [1], GYRO_ACCELL_INSTRUCTIONS)
# Wait for user to release the button and put the car down.
await asyncio.sleep(2)
# Start!
await calibrator.start()
await _print_all(console, GYRO_ACCEL_STARTED)
while True:
status = await calibrator.status()
if status == -1:
# Indicates we are done calibrating.
break
await _print_all(console, '.', end='', flush=True)
await asyncio.sleep(1)
async def _calibrate(console, controller, calibrator, buzzer, buttons, car):
answer = await _prompt(console, buttons, [1, 3], START_PROMPT)
if answer == 3:
return
await buzzer.play("!T95 V9 O4") # set tempo, volume, and octave
answer = await _prompt(console, buttons, [1, 3], GYRO_ACCELL_PROMPT)
if answer == 1:
await _calibrate_gyro_accel(console, calibrator, buttons)
await buzzer.play("G#4")
answer = await _prompt(console, buttons, [1, 3], CAR_MOTORS_PROMPT)
if answer == 1:
await _calibrate_car_motors(console, car, buttons)
await buzzer.play("G#4")
answer = await _prompt(console, buttons, [1, 3], CAR_SPEED_PROMPT)
if answer == 1:
await _calibrate_car_speed(console, car, buttons)
await buzzer.play("G#4")
await _reset_pid_to_defaults(controller)
answer = await _prompt(console, buttons, [1, 3], DRIVE_DEMO_PROMPT)
if answer == 1:
await _drive_demo(console, controller, car, buttons)
await buzzer.play("G#4")
async def run():
console = CuiRoot()
controller = CioRoot()
await console.init()
caps = await controller.init()
required_caps = ['Calibrator', 'Buzzer', 'PushButtons', 'CarMotors']
has_all_required = all([rc in caps for rc in required_caps])
v = await controller.acquire('VersionInfo')
major, minor = await v.version()
await controller.release(v)
if major != 1 or not has_all_required:
await _clear(console)
await _print_all(console, 'This script is only used for AutoAuto v1 car controllers. Exiting...')
await console.close()
await controller.close()
sys.exit(1)
calibrator = await controller.acquire('Calibrator')
buzzer = await controller.acquire('Buzzer')
buttons = await controller.acquire('PushButtons')
car = await controller.acquire('CarMotors')
try:
await _calibrate(console, controller, calibrator, buzzer, buttons, car)
finally:
await _clear(console)
await _print_all(console, "Calibration script exiting...")
await controller.release(calibrator)
await controller.release(buzzer)
await controller.release(buttons)
await controller.release(car)
await console.close()
await controller.close()
if __name__ == '__main__':
logging.getLogger().setLevel(logging.WARNING)
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import uuid
import asyncio
import itertools
import numpy as np
import auto
from auto.camera import draw_frame_index, base64_encode_image
from auto.inet import Wireless, list_wifi_ifaces, get_ip_address, get_mac_address
from auto import logger
log = logger.init(__name__, terminal=True)
from auto.services.labs.util import update_libauto
class Dashboard:
def __init__(self, controller, capabilities):
self.wireless = None
self.mac_address = None
self.capture_streams = {}
self.controller = controller
self.capabilities = capabilities
async def init(self):
loop = asyncio.get_running_loop()
self.power = await self.controller.acquire('Power')
self.camera = await self.controller.acquire('Camera')
wifi_ifaces = await loop.run_in_executor(None, list_wifi_ifaces)
if wifi_ifaces:
wifi_iface = wifi_ifaces[0]
self.wireless = Wireless(wifi_iface)
self.mac_address = await loop.run_in_executor(None, get_mac_address, wifi_iface)
if 'PhysicsClient' in self.capabilities:
self.physics = await self.controller.acquire('PhysicsClient')
else:
self.physics = None
async def connected_cdp(self):
self.known_user_sessions = set()
async def new_device_session(self, vin):
pass
async def new_user_session(self, username, user_session):
self.known_user_sessions.add(user_session)
async def got_message(self, msg, send_func):
if 'origin' in msg and 'type' in msg:
origin = msg['origin']
type_ = msg['type']
if origin == 'user':
await self._handle_user_message(msg, send_func, type_)
elif origin == 'server':
await self._handle_server_message(msg, send_func, type_)
async def _handle_user_message(self, msg, send_func, type_):
if type_ == 'query':
components = msg['components']
query_id = msg['query_id']
user_session = msg['user_session']
coro = self._query(components, query_id, user_session, send_func)
elif type_ == 'command':
command = msg['command']
command_id = msg['command_id']
user_session = msg['user_session']
coro = self._command(command, command_id, user_session, send_func, msg)
else:
return
asyncio.create_task(coro)
async def _handle_server_message(self, msg, send_func, type_):
if type_ == 'query_device_info':
coro = self._send_device_info_to_server(send_func)
elif type_ == 'command':
command = msg['command']
command_id = msg['command_id']
coro = self._server_command(command, command_id, send_func, msg)
else:
return
asyncio.create_task(coro)
async def _send_device_info_to_server(self, send_func):
await send_func({
'type': 'device_info_response',
'response': {
'version': auto.__version__,
'version_controller': await self._get_cio_version(),
'mac_address': self.mac_address,
},
'target': 'server',
})
async def end_device_session(self, vin):
pass
async def end_user_session(self, username, user_session):
self.known_user_sessions.remove(user_session)
await self._stop_capture_stream(user_session)
async def disconnected_cdp(self):
self.known_user_sessions = set()
async def _query(self, components, query_id, user_session, send_func):
response = {}
for c in components:
response[c] = await self._query_component(c, query_id, send_func, user_session)
await send_func({
'type': 'query_response',
'query_id': query_id,
'response': response,
'to_user_session': user_session,
})
async def _server_command(self, command, command_id, send_func, msg):
if command == 'physics_control':
if self.physics is not None:
response = await self.physics.control(msg.get('payload'))
else:
response = None
else:
return
await send_func({
'type': 'command_response',
'command_id': command_id,
'response': response,
})
async def _command(self, command, command_id, user_session, send_func, msg):
if command == 'shutdown':
response = await self.power.shut_down()
elif command == 'reboot':
response = await self.power.reboot()
elif command == 'update_libauto':
response = await update_libauto()
elif command == 'start_capture_stream':
response = await self._start_capture_stream(command_id, send_func, user_session)
elif command == 'stop_capture_stream':
response = await self._stop_capture_stream(user_session)
elif command == 'physics_control':
if self.physics is not None:
response = await self.physics.control(msg.get('payload'))
else:
response = None
else:
return
await send_func({
'type': 'command_response',
'command_id': command_id,
'response': response,
'to_user_session': user_session,
})
async def _query_component(self, component, query_id, send_func, user_session):
loop = asyncio.get_running_loop()
if component == 'version':
return auto.__version__
elif component == 'version_controller':
return await self._get_cio_version()
elif component == 'wifi_ssid':
if self.wireless:
return await loop.run_in_executor(None, self.wireless.current)
else:
return None
elif component == 'wifi_iface':
if self.wireless:
return self.wireless.interface
else:
return None
elif component == 'local_ip_addr':
if self.wireless:
return await loop.run_in_executor(None, get_ip_address, self.wireless.interface)
else:
return None
elif component == 'mac_address':
return self.mac_address
elif component == 'battery_state':
return await self._get_battery_state()
elif component == 'capture_one_frame':
return await self._capture_one_frame(query_id, send_func, user_session)
elif component == 'list_caps':
return self.capabilities
else:
return 'unsupported'
async def _capture_one_frame(self, query_id, send_func, user_session):
guid = str(uuid.uuid4())
async def run():
loop = asyncio.get_running_loop()
buf, shape = await self.camera.capture()
frame = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
base64_img = await loop.run_in_executor(None, base64_encode_image, frame)
await send_func({
'type': 'query_response_async',
'query_id': query_id,
'async_guid': guid,
'response': {'base64_img': base64_img},
'to_user_session': user_session,
})
asyncio.create_task(run())
return guid
async def _start_capture_stream(self, command_id, send_func, user_session):
if user_session in self.capture_streams:
# A single user session needs at most one camera stream.
return False
if user_session not in self.known_user_sessions:
# This isn't a security issue; it's a race condition issue.
# Because this method is run as a task, it's possible this method
# is running after we receive notice the user has disconnected.
# Thus, this check prevents creating a stream which will stream
# to no-one and will never halt.
return False
guid = str(uuid.uuid4())
async def run():
try:
loop = asyncio.get_running_loop()
for index in itertools.count():
buf, shape = await self.camera.capture()
frame = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
await loop.run_in_executor(None, draw_frame_index, frame, index)
base64_img = await loop.run_in_executor(None, base64_encode_image, frame)
await send_func({
'type': 'command_response_async',
'command_id': command_id,
'async_guid': guid,
'response': {'base64_img': base64_img},
'to_user_session': user_session,
})
except asyncio.CancelledError:
pass
task = asyncio.create_task(run())
self.capture_streams[user_session] = task
return guid
async def _stop_capture_stream(self, user_session):
if user_session not in self.capture_streams:
return False
task = self.capture_streams[user_session]
del self.capture_streams[user_session]
task.cancel()
await task
return True
async def _get_cio_version(self):
cio_version_iface = await self.controller.acquire('VersionInfo')
cio_version = await cio_version_iface.version()
cio_version = '.'.join([str(v) for v in cio_version])
await self.controller.release(cio_version_iface)
return cio_version
async def _get_battery_state(self):
minutes, percentage = await self.power.estimate_remaining()
return {
'minutes': minutes,
'percentage': percentage,
}
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains the interface to your robot's Console UI, most likely
running on your device's LDC screen.
Its name is CUI (Console User Interface).
"""
import abc
class CuiRoot(abc.ABC):
"""
This is the front-door interface of the Console UI ("cui"). You begin
by `init()`ing it, and if successful, you may then use the other methods
defined below.
"""
@abc.abstractmethod
async def init(self):
"""
Initialize the Console UI. If successful, this method returns True,
otherwise it raises an exception indicating that this particular
implementation cannot run on your device.
"""
pass
@abc.abstractmethod
async def write_text(self, text):
"""
Write text to the console.
"""
pass
@abc.abstractmethod
async def clear_text(self):
"""
Clear all text from the console.
"""
pass
@abc.abstractmethod
async def big_image(self, image_id):
"""
Display a big image having the id `image_path`.
Standard image IDs are:
- "wifi_error" : Show that there was a WiFi connection error.
- "wifi_pending" : Show that WiFi is attempting to connect.
- "wifi_success" : Show that WiFi successfully connected!
- "pair_error" : Show that the pairing process failed.
- "pair_pending" : Show that the pairing process is in-progress.
- "pair_success" : Show that the pairing process was a success!
- "token_error" : Show that the device needs a token installed.
- "token_success" : Show that a new token was installed successfully!
"""
pass
@abc.abstractmethod
async def big_status(self, status):
"""
Display a big status as text covering the console and
any image which may be shown.
"""
pass
@abc.abstractmethod
async def big_clear(self):
"""
Clear the big image and big status.
"""
pass
@abc.abstractmethod
async def stream_image(self, rect_vals, shape, image_buf):
"""
Display the streamed image in `image_buf` in the area
on the screen described by `rect_vals`. The image has
shape `shape`.
"""
pass
@abc.abstractmethod
async def clear_image(self):
"""
Clear the streamed image from the screen.
"""
pass
@abc.abstractmethod
async def set_battery(self, state, minutes, percentage):
"""
`state` should be one of "battery", "charging", or "wall".
`minutes` should be an integer specifying how many minutes
of battery life remain (estimated of course).
`percentage` should be an integer in [0, 100] indicating the
percentage of battery capacity remaining.
"""
pass
@abc.abstractmethod
async def close(self):
"""
Close the console (remove the window, clear resources, etc.)
"""
pass
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module talks to the IMU on the AutoAuto controller board.
Good reference implementations:
- https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050.h
- https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050.cpp
- https://github.com/RPi-Distro/RTIMULib/blob/master/RTIMULib/IMUDrivers/RTIMUDefs.h
- https://github.com/RPi-Distro/RTIMULib/blob/master/RTIMULib/IMUDrivers/RTIMUMPU9150.cpp
"""
import struct
import time
import sys
from math import sqrt, atan2, asin, pi, radians, degrees
from itertools import count
from threading import Thread, Condition
from cio.aa_controller_v2.easyi2c_sync import (
open_i2c,
write_read_i2c,
close_i2c,
read_bits,
write_bits,
)
MPU6050_RA_WHO_AM_I = 0x75
MPU6050_WHO_AM_I_BIT = 6
MPU6050_WHO_AM_I_LENGTH = 6
MPU6050_RA_USER_CTRL = 0x6A
MPU6050_USERCTRL_FIFO_EN_BIT = 6
MPU6050_USERCTRL_FIFO_RESET_BIT = 2
MPU6050_RA_FIFO_COUNTH = 0x72
MPU6050_RA_FIFO_R_W = 0x74
MPU6050_PACKET_SIZE = 12
MPU6050_ACCEL_CNVT = 0.0001220740379
MPU6050_GYRO_CNVT = 0.015259254738
COND = Condition()
DATA = None
def who_am_i(fd):
return read_bits(fd, MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH)
def set_fifo_enabled(fd, is_enabled):
val = 1 if is_enabled else 0
write_bits(fd, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT, 1, val)
def reset_fifo(fd):
val = 1
write_bits(fd, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_RESET_BIT, 1, val)
def reset_fifo_sequence(fd):
set_fifo_enabled(fd, False)
reset_fifo(fd) # reset the FIFO (can only reset while it is disabled!)
set_fifo_enabled(fd, True)
def get_fifo_length(fd):
h, l = write_read_i2c(fd, bytes([MPU6050_RA_FIFO_COUNTH]), 2)
return (h << 8) | l
def read_fifo_packet(fd, fifo_length):
buf = None
while fifo_length >= MPU6050_PACKET_SIZE:
buf = write_read_i2c(fd, bytes([MPU6050_RA_FIFO_R_W]), MPU6050_PACKET_SIZE)
fifo_length -= MPU6050_PACKET_SIZE
return buf
def madgwick_update(accel, gyro, q, deltat):
"""
Refs:
- https://courses.cs.washington.edu/courses/cse466/14au/labs/l4/l4.html
- https://courses.cs.washington.edu/courses/cse466/14au/labs/l4/MPU6050IMU.ino
- https://x-io.co.uk/open-source-imu-and-ahrs-algorithms/
- https://github.com/TobiasSimon/MadgwickTests
"""
beta = 0.05 # free parameter that can be tuned; this one merges accelerometer data with the gyro data
zeta = 0.001 # free parameter that can be tuned; this one accounts to gyro bias
# short name local variable for readability
ax, ay, az = accel
gx, gy, gz = [radians(v) for v in gyro]
q1, q2, q3, q4 = q
#float norm; // vector norm
#float f1, f2, f3; // objetive funcyion elements
#float J_11or24, J_12or23, J_13or22, J_14or21, J_32, J_33; // objective function Jacobian elements
#float qDot1, qDot2, qDot3, qDot4;
#float hatDot1, hatDot2, hatDot3, hatDot4;
#float gerrx, gerry, gerrz, gbiasx, gbiasy, gbiasz; // gyro bias error
# Auxiliary variables to avoid repeated arithmetic
_halfq1 = 0.5 * q1
_halfq2 = 0.5 * q2
_halfq3 = 0.5 * q3
_halfq4 = 0.5 * q4
_2q1 = 2.0 * q1
_2q2 = 2.0 * q2
_2q3 = 2.0 * q3
_2q4 = 2.0 * q4
_2q1q3 = 2.0 * q1 * q3
_2q3q4 = 2.0 * q3 * q4
# Normalise accelerometer measurement
norm = sqrt(ax * ax + ay * ay + az * az);
if norm > 0.0:
norm = 1.0/norm
ax *= norm
ay *= norm
az *= norm
# Compute the objective function and Jacobian
f1 = _2q2 * q4 - _2q1 * q3 - ax
f2 = _2q1 * q2 + _2q3 * q4 - ay
f3 = 1.0 - _2q2 * q2 - _2q3 * q3 - az
J_11or24 = _2q3
J_12or23 = _2q4
J_13or22 = _2q1
J_14or21 = _2q2
J_32 = 2.0 * J_14or21
J_33 = 2.0 * J_11or24
# Compute the gradient (matrix multiplication)
hatDot1 = J_14or21 * f2 - J_11or24 * f1
hatDot2 = J_12or23 * f1 + J_13or22 * f2 - J_32 * f3
hatDot3 = J_12or23 * f2 - J_33 *f3 - J_13or22 * f1
hatDot4 = J_14or21 * f1 + J_11or24 * f2
# Normalize the gradient
norm = sqrt(hatDot1 * hatDot1 + hatDot2 * hatDot2 + hatDot3 * hatDot3 + hatDot4 * hatDot4)
hatDot1 /= norm
hatDot2 /= norm
hatDot3 /= norm
hatDot4 /= norm
# Compute estimated gyroscope biases
gerrx = _2q1 * hatDot2 - _2q2 * hatDot1 - _2q3 * hatDot4 + _2q4 * hatDot3
gerry = _2q1 * hatDot3 + _2q2 * hatDot4 - _2q3 * hatDot1 - _2q4 * hatDot2
gerrz = _2q1 * hatDot4 - _2q2 * hatDot3 + _2q3 * hatDot2 - _2q4 * hatDot1
# Compute and remove gyroscope biases
gbiasx = gerrx * deltat * zeta
gbiasy = gerry * deltat * zeta
gbiasz = gerrz * deltat * zeta
gx -= gbiasx
gy -= gbiasy
gz -= gbiasz
# Compute the quaternion derivative
qDot1 = -_halfq2 * gx - _halfq3 * gy - _halfq4 * gz
qDot2 = _halfq1 * gx + _halfq3 * gz - _halfq4 * gy
qDot3 = _halfq1 * gy - _halfq2 * gz + _halfq4 * gx
qDot4 = _halfq1 * gz + _halfq2 * gy - _halfq3 * gx
# Compute then integrate estimated quaternion derivative
q1 += (qDot1 -(beta * hatDot1)) * deltat
q2 += (qDot2 -(beta * hatDot2)) * deltat
q3 += (qDot3 -(beta * hatDot3)) * deltat
q4 += (qDot4 -(beta * hatDot4)) * deltat
# Normalize the quaternion
norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4)
norm = 1.0/norm
q[0] = q1 * norm
q[1] = q2 * norm
q[2] = q3 * norm
q[3] = q4 * norm
return q
def roll_pitch_yaw(q):
"""
Refs:
- https://en.wikipedia.org/wiki/Euler_angles#Tait%E2%80%93Bryan_angles
- https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
"""
qw, qx, qy, qz = q
# roll (x-axis rotation)
sinr_cosp = 2.0 * (qw * qx + qy * qz)
cosr_cosp = 1.0 - 2.0 * (qx * qx + qy * qy)
roll = atan2(sinr_cosp, cosr_cosp)
# pitch (y-axis rotation)
sinp = 2.0 * (qw * qy - qz * qx)
if abs(sinp) >= 1.0:
pitch = (pi if sinp > 0.0 else -pi) / 2.0 # use 90 degrees if out of range
else:
pitch = asin(sinp)
# yaw (z-axis rotation)
siny_cosp = 2.0 * (qw * qz + qx * qy)
cosy_cosp = 1.0 - 2.0 * (qy * qy + qz * qz)
yaw = atan2(siny_cosp, cosy_cosp)
# Convert to degrees:
roll = degrees(roll)
pitch = degrees(pitch)
yaw = degrees(yaw)
return roll, pitch, yaw
def rotate_ahrs(accel, gyro):
"""
Rotate the axes so that the roll/pitch/yaw
calculations result in the *expected* roll/pitch/yaw
orientation that is common for vehicles.
See:
- https://en.wikipedia.org/wiki/Euler_angles#Tait%E2%80%93Bryan_angles
"""
ax, ay, az = accel
gx, gy, gz = gyro
accel = -ay, ax, az
gyro = -gy, gx, gz
return accel, gyro
def run(verbose=False):
fd = open_i2c(1, 0x68)
try:
_handle_fd(fd, verbose)
finally:
close_i2c(fd)
def _handle_fd(fd, verbose):
global DATA
if who_am_i(fd) != 0x34:
raise Exception("WRONG WHO_AM_I!")
curr_time = 0 # microseconds
dt = 1000000 // 100 # data streams at 100Hz
dt_s = dt / 1000000
gyro_accum = [0.0, 0.0, 0.0]
quaternion = [1.0, 0.0, 0.0, 0.0]
sleep = 0.005
status = 'needs_reset' # one of: 'needs_reset', 'did_reset', 'waiting', 'data'
for i in count():
status, buf = _get_buf(fd, status)
if status == 'did_reset':
sleep = 0.005
elif status == 'waiting':
sleep *= 0.99
elif status == 'data':
t = time.time()
vals = struct.unpack('>6h', buf)
vals = [v * MPU6050_ACCEL_CNVT for v in vals[:3]] + [v * MPU6050_GYRO_CNVT for v in vals[3:]]
if verbose:
print(f'{sleep:.4f}', ''.join([f'{v:10.3f}' for v in vals]))
accel = vals[:3]
gyro = vals[3:]
gyro_accum = [(a + b*dt_s) for a, b in zip(gyro_accum, gyro)]
ahrs = roll_pitch_yaw(madgwick_update(*rotate_ahrs(accel, gyro), quaternion, dt_s))
with COND:
DATA = {
'timestamp': curr_time,
'accel': accel,
'gyro': gyro,
'gyro_accum': gyro_accum,
'ahrs': ahrs,
}
COND.notify_all()
curr_time += dt
s = dt_s - (time.time() - t) - sleep
if s > 0.0:
time.sleep(s)
sleep *= 1.01
def _get_buf(fd, status):
try:
if status == 'needs_reset':
reset_fifo_sequence(fd)
return 'did_reset', None
elif status in ('did_reset', 'waiting', 'data'):
fifo_length = get_fifo_length(fd)
if fifo_length > 200:
reset_fifo_sequence(fd)
return 'did_reset', None
elif fifo_length >= MPU6050_PACKET_SIZE:
buf = read_fifo_packet(fd, fifo_length)
return 'data', buf
else:
return 'waiting', None
else:
raise Exception('unreachable')
except OSError:
print('IMU OSError', file=sys.stderr)
return 'needs_reset', None
def start_thread():
thread = Thread(target=run)
thread.daemon = True
thread.start()
return thread
if __name__ == '__main__':
run(verbose=True)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from cui.mock_impl import CuiMock
async def run():
c = CuiMock()
await c.init()
# Put up a big full-screen image by passing an image-path.
await c.big_image('wifi_success')
await asyncio.sleep(2)
# Put up some big text!
for i in range(1, 5):
text = "All is good... {}".format(i)
await c.big_status(text)
await asyncio.sleep(1)
# Clear the big text.
await c.big_status('')
await asyncio.sleep(2)
# Clear the screen of the big image and text.
await c.big_clear()
await asyncio.sleep(2)
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module talks to the IMU on the AutoAuto controller board.
"""
import time
from threading import Thread, Condition
COND = Condition()
DATA = None
def run(verbose=False):
global DATA
curr_time = 0 # microseconds
dt = 1000000 // 100 # data streams at 100Hz
while True:
accel = [0, 0, 0]
gyro = [0, 0, 0]
gyro_accum = [0, 0, 0]
ahrs = [0, 0, 0]
with COND:
DATA = {
'timestamp': curr_time,
'accel': accel,
'gyro': gyro,
'gyro_accum': gyro_accum,
'ahrs': ahrs,
}
COND.notify_all()
curr_time += dt
time.sleep(0.01)
def start_thread():
thread = Thread(target=run)
thread.daemon = True
thread.start()
return thread
if __name__ == '__main__':
run(verbose=True)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides a list of hardware capabilities of the device,
and provides a way to acquire and release those capabilities.
This module provides a fully **synchronous** interface.
"""
from auto.asyncio_tools import get_loop, thread_safe
from auto.services.controller.client_sync import CioRoot
@thread_safe
def list_caps():
"""
Return a sorted tuple of the hardware capabilities of this device.
Each capability is referenced by a string, as returned by
this function. You can acquire an interface to a capability
by passing the capability's string label to the function
`acquire()`.
"""
global _CAPABILITIES_MAP
try:
return tuple(sorted(_CAPABILITIES_MAP.keys()))
except NameError:
pass # We can remedy this.
loop = get_loop()
controller_connection = CioRoot(loop)
_CAPABILITIES_MAP = {}
for capability_id in controller_connection.init():
_CAPABILITIES_MAP[capability_id] = {
'acquire': controller_connection.acquire,
'release': controller_connection.release,
}
return tuple(sorted(_CAPABILITIES_MAP.keys()))
def acquire(capability_name):
"""
Return an interface to the capability labeled by `capability_name`.
Call `list_caps()` to obtain a list of supported capabilities.
The interface object returned here should be disposed of
(when you are done using it) by passing it to the function
`release()`.
"""
if capability_name not in list_caps():
raise AttributeError("The given capability name (\"{}\") is not available.".format(capability_name))
iface = _CAPABILITIES_MAP[capability_name]['acquire'](capability_name)
iface._capability_name = capability_name
return iface
def release(capability_iface):
"""
Release the capability, freeing it's resources, etc.
The `capability_iface` object must be one that was returned
from `acquire()`.
"""
capability_name = getattr(capability_iface, "_capability_name", None)
if capability_name is None:
raise Exception("The object passed as `capability_iface` was not acquired by `acquire()`; you must pass the exact object obtained from `acquire()`.")
if capability_name not in list_caps():
raise Exception("The given capability name (\"{}\") is not available.".format(capability_name))
return _CAPABILITIES_MAP[capability_name]['release'](capability_iface)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from .easyi2c import (write_read_i2c_with_integrity,
write_read_i2c,
i2c_retry, i2c_poll_until)
from . import N_I2C_TRIES
from .db import default_db
from .battery_discharge_curve import battery_map_millivolts_to_percentage
from . import imu
from .camera_async import CameraRGB_Async
from .camera_pi import CameraRGB
import cio
from auto import logger
log = logger.init(__name__, terminal=True)
import os
import time
import struct
import asyncio
import subprocess
from math import floor, isnan
from collections import deque
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD) # GPIO.BOARD or GPIO.BCM
POWER_BUTTON_PIN = 29
GPIO.setup(POWER_BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
PUSH_BUTTON_PINS = [32, 33, 36]
for pin in PUSH_BUTTON_PINS:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
class VersionInfo(cio.VersionInfoIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def acquired(self):
pass
async def released(self):
pass
async def name(self):
return "AutoAuto v3 Controller"
@i2c_retry(N_I2C_TRIES)
async def version(self):
major, minor = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 2)
return major, minor
class Credentials(cio.CredentialsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.db = None
self.loop = asyncio.get_running_loop()
async def acquired(self):
pass
async def released(self):
pass
async def get_labs_auth_code(self):
db_record = await self.loop.run_in_executor(None, self._db_get_labs_auth_code)
if db_record is not None:
log.info('Querying labs auth code; found in database.')
return db_record
eeprom_record = await self._eeprom_get_labs_auth_code()
if eeprom_record is not None:
# It's in the EEPROM, but not the DB. So, copy it over to the DB so we find it there next time.
log.info('Querying labs auth code; found in eeprom; copying to database.')
await self.loop.run_in_executor(None, self._db_set_labs_auth_code, eeprom_record)
return eeprom_record
log.info('Querying labs auth code; not found.')
return None
async def set_labs_auth_code(self, auth_code):
if (await self.get_labs_auth_code()) is None:
log.info('Storing labs auth code...')
await self.loop.run_in_executor(None, self._db_set_labs_auth_code, auth_code)
await self._eeprom_set_labs_auth_code(auth_code)
return True
else:
log.info('Will NOT storing labs auth code; it already exits.')
return False
async def get_jupyter_password(self):
db_record = await self.loop.run_in_executor(None, self._db_get_jupyter_password)
if db_record is not None:
log.info('Querying Jupyter password; found in database.')
return db_record
eeprom_record = await self._eeprom_get_jupyter_password()
if eeprom_record is not None:
# It's in the EEPROM, but not the DB. So, copy it over to the DB so we find it there next time.
log.info('Querying Jupyter password; found in eeprom; copying to database.')
await self.loop.run_in_executor(None, self._db_set_jupyter_password, eeprom_record)
return eeprom_record
log.info('Querying Jupyter password; not found.')
return None
async def set_jupyter_password(self, password):
if (await self.get_jupyter_password()) is None:
log.info('Storing Jupyter password...')
await self.loop.run_in_executor(None, self._db_set_jupyter_password, password)
await self._eeprom_set_jupyter_password(password)
return True
else:
log.info('Will NOT storing Jupyter password; it already exits.')
return False
def _get_db(self):
if self.db is None:
self.db = default_db()
return self.db
def _db_get_labs_auth_code(self):
return self._get_db().get('DEVICE_LABS_AUTH_CODE', None)
def _db_set_labs_auth_code(self, auth_code):
self._get_db().put('DEVICE_LABS_AUTH_CODE', auth_code)
os.sync()
def _db_get_jupyter_password(self):
return self._get_db().get('DEVICE_JUPYTER_PASSWORD', None)
def _db_set_jupyter_password(self, password):
self._get_db().put('DEVICE_JUPYTER_PASSWORD', password)
os.sync()
async def _eeprom_read_string(self, addr):
length = (await capabilities.eeprom_query(self.fd, addr, 1))[0]
if length == 0xFF:
# Empty record!
return None
buf = await capabilities.eeprom_query(self.fd, addr + 1, length)
return buf.decode()
async def _eeprom_write_string(self, addr, s):
buf = bytes([len(s)]) + s.encode()
await capabilities.eeprom_store(self.fd, addr, buf)
async def _eeprom_get_labs_auth_code(self):
return await self._eeprom_read_string(0x00)
async def _eeprom_set_labs_auth_code(self, auth_code):
await self._eeprom_write_string(0x00, auth_code)
async def _eeprom_get_jupyter_password(self):
return await self._eeprom_read_string(0x30)
async def _eeprom_set_jupyter_password(self, password):
await self._eeprom_write_string(0x30, password)
class Camera(cio.CameraIface):
_camera = None
def __init__(self, fd, reg_num):
if Camera._camera is None:
loop = asyncio.get_running_loop()
Camera._camera = CameraRGB_Async(
lambda: CameraRGB(width=320, height=240, fps=8),
loop=loop,
idle_timeout=30
)
async def acquired(self):
pass
async def released(self):
pass
async def capture(self):
return await Camera._camera.capture()
class Power(cio.PowerIface):
@i2c_retry(N_I2C_TRIES)
async def _write_reg(self, reg, v):
buf = bytes([reg, v])
await write_read_i2c(self.fd, buf, 0)
@i2c_retry(N_I2C_TRIES)
async def _read_reg(self, reg):
buf = bytes([reg])
readlen = 1
r = await write_read_i2c(self.fd, buf, readlen)
v = r[0]
return v
@staticmethod
def _batt_convert_millivolts(v):
millivolts = 2304
bit_vals = [20, 40, 80, 160, 320, 640, 1280]
for i in range(7):
if v & (1 << i):
millivolts += bit_vals[i]
return millivolts
@staticmethod
def _input_convert_millivolts(v):
millivolts = 2600
bit_vals = [100, 200, 400, 800, 1600, 3200, 6400]
for i in range(7):
if v & (1 << i):
millivolts += bit_vals[i]
return millivolts
@staticmethod
def _charge_current_convert(v):
milliamps = 0
bit_vals = [50, 100, 200, 400, 800, 1600, 3200]
for i in range(7):
if v & (1 << i):
milliamps += bit_vals[i]
return milliamps
@staticmethod
def _input_limit_convert(v):
milliamps = 100
bit_vals = [50, 100, 200, 400, 800, 1600]
for i in range(6):
if v & (1 << i):
milliamps += bit_vals[i]
return milliamps
@staticmethod
def _is_power_button_pressed():
return GPIO.input(POWER_BUTTON_PIN) == 0 # active low
def __init__(self, fd, reg_num):
self.fd = fd
async def acquired(self):
pass
async def released(self):
pass
async def state(self):
usb_plugged_in = (((await self._read_reg(0x11)) & (1 << 7)) != 0)
if usb_plugged_in:
milliamps = await self._read_reg(0x12)
milliamps = self._charge_current_convert(milliamps)
return 'charging' if milliamps > 0 else 'wall'
else:
return 'battery'
async def millivolts(self):
v = await self._read_reg(0x0E)
millivolts = self._batt_convert_millivolts(v)
return millivolts
async def estimate_remaining(self, millivolts=None):
if millivolts is None:
millivolts = await self.millivolts()
percentage = battery_map_millivolts_to_percentage(millivolts)
minutes = 4.0 * 60.0 * (percentage / 100.0) # Assumes the full battery lasts 4 hours.
return floor(minutes), floor(percentage)
async def charging_info(self):
"""This is a non-standard method."""
milliamps = await self._read_reg(0x12)
milliamps = self._charge_current_convert(milliamps)
input_millivolts = await self._read_reg(0x11)
input_millivolts = self._input_convert_millivolts(input_millivolts)
input_milliamps_limit = await self._read_reg(0x00)
input_milliamps_limit = self._input_limit_convert(input_milliamps_limit)
return {
'milliamps': milliamps,
'input': {
'millivolts': input_millivolts,
'milliamps_limit': input_milliamps_limit,
}
}
async def should_shut_down(self):
curr_state = self._is_power_button_pressed()
return curr_state
async def shut_down(self):
v = await self._read_reg(0x09)
v |= (1 << 3)
v |= (1 << 5)
await self._write_reg(0x09, v) # <-- tell charger chip to shutdown after a 10-15 second delay
subprocess.run(['/sbin/poweroff'])
async def reboot(self):
subprocess.run(['/sbin/reboot'])
class Buzzer(cio.BuzzerIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def acquired(self):
pass
async def released(self):
pass
async def is_currently_playing(self):
pass # TODO
async def wait(self):
pass # TODO
async def play(self, notes="o4l16ceg>c8"):
pass # TODO
class Gyroscope(cio.GyroscopeIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
async def acquired(self):
pass
async def released(self):
pass
def _read(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
x, y, z = imu.DATA['gyro']
return t, x, y, z
async def read(self):
vals = await self.loop.run_in_executor(None, self._read)
return vals[1:]
async def read_t(self):
"""This is a non-standard method."""
vals = await self.loop.run_in_executor(None, self._read)
return vals
class GyroscopeAccum(cio.GyroscopeAccumIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
self.offsets = None
async def acquired(self):
pass
async def released(self):
pass
def _reset(self):
self.offsets = self._read_raw()[1:]
def _read_raw(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
x, y, z = imu.DATA['gyro_accum']
return t, x, y, z
async def reset(self):
await self.loop.run_in_executor(None, self._reset)
async def read(self):
t, x, y, z = await self.read_t()
return x, y, z
async def read_t(self):
"""This is a non-standard method."""
t, x, y, z = await self.loop.run_in_executor(None, self._read_raw)
vals = x, y, z
if self.offsets is None:
self.offsets = vals
new_vals = tuple([(val - offset) for val, offset in zip(vals, self.offsets)])
return (t,) + new_vals
class Accelerometer(cio.AccelerometerIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
async def acquired(self):
pass
async def released(self):
pass
def _read(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
x, y, z = imu.DATA['accel']
return t, x, y, z
async def read(self):
vals = await self.loop.run_in_executor(None, self._read)
return vals[1:]
async def read_t(self):
"""This is a non-standard method."""
vals = await self.loop.run_in_executor(None, self._read)
return vals
class Ahrs(cio.AhrsIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
async def acquired(self):
pass
async def released(self):
pass
def _read(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
roll, pitch, yaw = imu.DATA['ahrs']
return t, roll, pitch, yaw
async def read(self):
vals = await self.loop.run_in_executor(None, self._read)
return vals[1:]
async def read_t(self):
"""This is a non-standard method."""
vals = await self.loop.run_in_executor(None, self._read)
return vals
class PushButtons(cio.PushButtonsIface):
_pin_map = None
_states = None
@staticmethod
def _button_edge_callback(pin):
button_index = PushButtons._pin_map[pin]
presses, releases, is_pressed, prev_time = PushButtons._states[button_index]
curr_time = time.time()
if curr_time - prev_time < 0.05:
# Debounced!
return
curr_is_pressed = (GPIO.input(pin) == GPIO.LOW)
if is_pressed == curr_is_pressed:
# Ignore this... why are we being called when the state has not changed?
return
if curr_is_pressed:
presses += 1
else:
releases += 1
PushButtons._states[button_index] = presses, releases, curr_is_pressed, curr_time
def __init__(self, fd, reg_num):
self.n = None
self.states = None
self.event_queue = deque()
async def acquired(self):
if PushButtons._pin_map is None:
PushButtons._pin_map = {pin: i for i, pin in enumerate(PUSH_BUTTON_PINS)}
PushButtons._states = [[0, 0, False, 0] for _ in range(len(PUSH_BUTTON_PINS))]
for pin in PUSH_BUTTON_PINS:
GPIO.add_event_detect(pin, GPIO.BOTH, callback=self._button_edge_callback)
async def released(self):
pass
async def num_buttons(self):
return len(PUSH_BUTTON_PINS)
async def button_state(self, button_index):
presses, releases, is_pressed, last_event_time = PushButtons._states[button_index]
return presses, releases, is_pressed
async def get_events(self):
if self.n is None:
self.n = await self.num_buttons()
self.states = [await self.button_state(i) for i in range(self.n)]
return []
events = []
for prev_state, i in zip(self.states, range(self.n)):
state = await self.button_state(i)
if state == prev_state:
continue
diff_presses = state[0] - prev_state[0]
diff_releases = state[1] - prev_state[1]
if diff_presses == 0 and diff_releases == 0:
continue
if prev_state[2]: # if button **was** pressed
# We'll add `released` events first.
while diff_presses > 0 or diff_releases > 0:
if diff_releases > 0:
events.append({'button': i, 'action': 'released'})
diff_releases -= 1
if diff_presses > 0:
events.append({'button': i, 'action': 'pressed'})
diff_presses -= 1
else:
# We'll add `pressed` events first.
while diff_presses > 0 or diff_releases > 0:
if diff_presses > 0:
events.append({'button': i, 'action': 'pressed'})
diff_presses -= 1
if diff_releases > 0:
events.append({'button': i, 'action': 'released'})
diff_releases -= 1
self.states[i] = state
return events
async def wait_for_event(self):
if not self.event_queue: # if empty
while True:
events = await self.get_events()
if events: # if not empty
self.event_queue.extend(events)
return self.event_queue.popleft()
await asyncio.sleep(0.05)
else:
return self.event_queue.popleft()
async def wait_for_action(self, action='pressed'):
while True:
event = await self.wait_for_event()
if action == 'any' or action == event['action']:
return event['button'], event['action']
class LEDs(cio.LEDsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.NUM_LEDS = 20
self.vals = [None for index in range(self.NUM_LEDS)] # using `None`, so that fist call to _set() actually sets it, no matter what the value
async def acquired(self):
pass
async def released(self):
await self._reset()
async def led_map(self):
return {index: 'RGB LED at index {}'.format(index) for index in range(self.NUM_LEDS)}
@i2c_retry(N_I2C_TRIES)
async def _set(self, index, val):
if not isinstance(index, int):
raise ValueError('You must pass an integer for the led identifier parameter.')
if index < 0 or index >= self.NUM_LEDS:
raise ValueError('The index {} is out of range.'.format(index))
if isinstance(val, int):
r, g, b = val, val, val
elif isinstance(val, (tuple, list)):
r, g, b = val
else:
raise ValueError('You must pass the LED value as a three-tuple denoting the three RGB values.')
if self.vals[index] == val:
return
self.vals[index] = val
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00, index, r, g, b], 1)
if status != 72:
raise Exception("failed to set LED state")
@i2c_retry(N_I2C_TRIES)
async def _show(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
if status != 72:
raise Exception("failed to set LED state")
@i2c_retry(N_I2C_TRIES)
async def _reset(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x04], 1)
if status != 72:
raise Exception("failed to set LED state")
async def set_led(self, led_identifier, val):
await self._set(led_identifier, val)
await self._show()
async def set_many_leds(self, id_val_list):
for led_identifier, val in id_val_list:
await self._set(led_identifier, val)
await self._show()
async def mode_map(self):
return {
'spin': 'Spin colors around the six primary LEDs.',
'pulse': 'Pulse on all LEDs the value of the LED at index 0.',
}
@i2c_retry(N_I2C_TRIES)
async def set_mode(self, mode_identifier):
mode = 0
if mode_identifier == 'spin':
mode = 1
elif mode_identifier == 'pulse':
mode = 2
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03, mode], 1)
if status != 72:
raise Exception("failed to set LED mode")
@i2c_retry(N_I2C_TRIES)
async def _set_brightness(self, brightness):
if brightness > 50:
brightness = 50
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, brightness], 1)
if status != 72:
raise Exception("failed to set LED mode")
async def set_brightness(self, brightness):
await self._set_brightness(brightness)
await self._show()
class ADC(cio.AdcIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def acquired(self):
pass
async def released(self):
pass
async def num_pins(self):
return 1
@i2c_retry(N_I2C_TRIES)
async def read(self, index):
if index != 0:
raise ValueError(f'Invalid index: {index}')
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 2)
volts, = struct.unpack('H', buf)
return volts / 1023 * 3.3
class Photoresistor(cio.PhotoresistorIface):
def __init__(self, fd, reg_num):
self.adc = ADC(fd, reg_num)
async def acquired(self):
pass
async def released(self):
pass
async def read(self):
volts = await self.adc.read(0)
if volts == 0:
return volts, float("inf")
KNOWN_RESISTANCE = 470000
resistance = (3.3 - volts) * KNOWN_RESISTANCE / volts
millivolts = volts * 1000
return millivolts, resistance
async def read_millivolts(self):
millivolts, resistance = await self.read()
return millivolts
async def read_ohms(self):
millivolts, resistance = await self.read()
return resistance
class CarMotors(cio.CarMotorsIface):
params_cache = {}
@staticmethod
async def _steering_params(fd, store=None):
addr = 0xC0
if store:
await capabilities.eeprom_store(fd, addr, struct.pack('3B', *store))
else:
vals = struct.unpack('3B', await capabilities.eeprom_query(fd, addr, 3))
if vals == (255, 255, 255):
vals = (35, 45, 55)
return vals
@staticmethod
async def _safe_speeds(fd, store=None):
addr = 0xC3
if store:
await capabilities.eeprom_store(fd, addr, struct.pack('2b', *store))
else:
vals = struct.unpack('2b', await capabilities.eeprom_query(fd, addr, 2))
if vals == (-1, -1):
vals = (-40, 40)
return vals
@classmethod
async def _cached_stuff(cls, fd, name, func):
vals = cls.params_cache.get(name)
if vals is None:
vals = await func(fd)
cls.params_cache[name] = vals
return vals
@classmethod
async def _store_stuff(cls, fd, name, func, vals):
await func(fd, vals)
cls.params_cache[name] = vals
async def get_steering_params(self):
return await self._cached_stuff(self.fd, 'steering_params', self._steering_params)
async def set_steering_params(self, vals):
return await self._store_stuff(self.fd, 'steering_params', self._steering_params, vals)
async def get_safe_speeds(self):
return await self._cached_stuff(self.fd, 'safe_speeds', self._safe_speeds)
async def set_safe_speeds(self, vals):
return await self._store_stuff(self.fd, 'safe_speeds', self._safe_speeds, vals)
@staticmethod
def interp(a, b, c, x, y, z, val):
val = min(max(val, x), z)
if val < y:
return (val - x) / (y - x) * (b - a) + a
else:
return (val - y) / (z - y) * (c - b) + b
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def acquired(self):
pass
async def released(self):
await self.off()
@i2c_retry(N_I2C_TRIES)
async def on(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
if status != 105:
raise Exception("failed to turn on car motors")
@i2c_retry(N_I2C_TRIES)
async def set_steering(self, steering):
low, mid, high = await self.get_steering_params()
val = self.interp(low, mid, high, -45, 0, 45, steering)
val = int(round(val))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, val], 1)
if status != 105:
raise Exception("failed to set steering")
@i2c_retry(N_I2C_TRIES)
async def set_throttle(self, throttle):
val = self.interp(10000, 0, 10000, -100, 0, 100, throttle)
val = int(round(val))
d = 0 if throttle >= 0 else 1
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02, *struct.pack('H', val), d], 1)
if status != 105:
raise Exception("failed to set throttle")
async def get_safe_throttle(self):
return await self.get_safe_speeds()
async def set_safe_throttle(self, min_throttle, max_throttle):
return await self.set_safe_speeds((min_throttle, max_throttle))
@i2c_retry(N_I2C_TRIES)
async def off(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 105:
raise Exception("failed to turn off car motors")
def rpc_extra_exports(self):
return ['get_steering_params', 'set_steering_params']
class Calibrator(cio.CalibratorIface):
def __init__(self, fd, reg_num):
pass
async def acquired(self):
pass
async def released(self):
pass
async def start(self):
pass # TODO
async def status(self):
pass # TODO
async def script_name(self):
return "calibrate_car_v3" # TODO
class PidSteering(cio.PidSteeringIface): # TODO
pid_cache = None
def __init__(self, fd, reg_nums):
self.fd = fd
self.p = None
self.i = None
self.d = None
self.error_accum_max = None
self.point = 0.0
carmotors_regnum, gyroaccum_regnum = reg_nums
self.carmotors = CarMotors(fd, carmotors_regnum)
self.gyroaccum = GyroscopeAccum(fd, gyroaccum_regnum)
self.task = None
async def acquired(self):
pass
async def released(self):
pass
async def set_pid(self, p, i, d, error_accum_max=0.0, save=False):
self.p = p
self.i = i
self.d = d
self.error_accum_max = error_accum_max
if save:
await capabilities.eeprom_store(self.fd, 0xB0, struct.pack('1f', self.p))
await capabilities.eeprom_store(self.fd, 0xB4, struct.pack('1f', self.i))
await capabilities.eeprom_store(self.fd, 0xB8, struct.pack('1f', self.d))
await capabilities.eeprom_store(self.fd, 0xBC, struct.pack('1f', self.error_accum_max))
PidSteering.pid_cache = (self.p, self.i, self.d, self.error_accum_max)
async def set_point(self, point):
self.point = point
async def enable(self, invert_output=False):
if self.p is None:
if PidSteering.pid_cache is not None:
self.p, self.i, self.d, self.error_accum_max = PidSteering.pid_cache
else:
self.p, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xB0, 4))
self.i, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xB4, 4))
self.d, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xB8, 4))
self.error_accum_max, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xBC, 4))
PidSteering.pid_cache = (self.p, self.i, self.d, self.error_accum_max)
if isnan(self.p):
self.p = 1.0
if isnan(self.i):
self.i = 0.0
if isnan(self.d):
self.d = 0.0
if isnan(self.error_accum_max):
self.error_accum_max = 0.0
await self.disable()
self.task = asyncio.create_task(self._task_main(invert_output))
async def disable(self):
if self.task is not None:
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass # this is expected
self.task = None
async def _task_main(self, invert_output):
last_t = None
error_accum = 0.0
last_error = None
while True:
t, _, _, z = await self.gyroaccum.read_t()
dt = ((t - last_t) if last_t is not None else 0.0) * 0.000001
last_t = t
curr_error = self.point - z
p_part = self.p * curr_error
error_accum += curr_error * dt
if self.error_accum_max > 0.0:
if error_accum > self.error_accum_max:
error_accum = self.error_accum_max
elif error_accum < -self.error_accum_max:
error_accum = -self.error_accum_max
i_part = self.i * error_accum
error_diff = ((curr_error - last_error) / dt) if last_error is not None else 0.0
last_error = curr_error
d_part = self.d * error_diff
output = p_part + i_part + d_part
if invert_output:
output = -output
await self.carmotors.set_steering(output)
KNOWN_COMPONENTS = {
'VersionInfo': VersionInfo,
'Credentials': Credentials,
'Camera': Camera,
'Power': Power,
'Buzzer': Buzzer,
'Gyroscope': Gyroscope,
'Gyroscope_accum': GyroscopeAccum,
'Accelerometer': Accelerometer,
'AHRS': Ahrs,
'PushButtons': PushButtons,
'LEDs': LEDs,
'ADC': ADC,
'Photoresistor': Photoresistor,
'CarMotors': CarMotors,
'Calibrator': Calibrator,
'PID_steering': PidSteering,
}
from . import capabilities
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import os
import re
import sys
import pwd
import time
import base64
import fcntl
import struct
import termios
import signal
import traceback
import asyncio
from contextlib import contextmanager
from auto import logger
log = logger.init(__name__, terminal=True)
READ_BUF_SIZE = 4096*8
CONTEST_SESSION_NAME = 'contest_session'
class PtyManager:
def __init__(self, system_up_user, console):
self.system_up_user = system_up_user
self.console = console
log.info("Will run the PTY manager using the unprivileged user: {}".format(system_up_user))
async def init(self):
cmds = [
"tmux new-session -d -s bootup_session".split(),
"tmux send-keys -t bootup_session python3 SPACE boot.py ENTER".split(),
]
for cmd in cmds:
await _run_subprocess(cmd, self.system_up_user)
async def connected_cdp(self):
self.xterm_lookup = {} # map xterm_guid to (task, queue, start_time, user_session)
async def new_device_session(self, vin):
pass
async def new_user_session(self, username, user_session):
pass
async def got_message(self, msg, send_func):
if 'origin' in msg and msg['origin'] == 'user' and 'type' in msg:
type_ = msg['type']
if type_ in ('new_session', 'attach_session', 'start_process'):
xterm_guid = msg['xterm_guid']
user_session = msg['user_session']
if xterm_guid in self.xterm_lookup:
log.error('The xterm_guid={} already exists; invalid for type={}'.format(xterm_guid, type_))
return
queue = asyncio.Queue()
queue.put_nowait(msg)
coro = _pty_process_manager(xterm_guid, user_session, queue, send_func, self.system_up_user, self.console)
task = asyncio.create_task(coro)
self.xterm_lookup[xterm_guid] = (task, queue, time.time(), user_session)
elif type_ in ('kill_process', 'xterm_resized', 'send_input_to_pty'):
xterm_guid = msg['xterm_guid']
if xterm_guid not in self.xterm_lookup:
log.error('The xterm_guid={} does not exist; invalid for type={}'.format(xterm_guid, type_))
return
task, queue, _, _ = self.xterm_lookup[xterm_guid]
if type_ == 'kill_process':
task.cancel()
del self.xterm_lookup[xterm_guid]
else:
queue.put_nowait(msg)
elif type_ == 'kill_session':
session_name = msg['session_name']
coro = _kill_session(session_name, self.system_up_user)
asyncio.create_task(coro)
elif type_ == 'list_sessions':
user_session = msg['user_session']
coro = _list_sessions(send_func, user_session, self.system_up_user)
asyncio.create_task(coro)
elif type_ == 'list_running':
user_session = msg['user_session']
await self._list_running(send_func, user_session)
elif type_ == 'clear_screen':
coro = _clear_console(self.console)
asyncio.create_task(coro)
elif 'origin' in msg and msg['origin'] == 'server' and 'type' in msg:
type_ = msg['type']
if type_ == 'start_contest':
coro = self._start_contest(msg, send_func)
asyncio.create_task(coro)
elif type_ == 'end_contest':
coro = self._end_contest(msg, send_func)
asyncio.create_task(coro)
async def end_device_session(self, vin):
pass
async def end_user_session(self, username, user_session):
"""
We need to kill all ptys started by this user_session.
Note: If you kill a `tmux` process which is attached to some session,
it will just detach from the underlying tmux session (which is
what we want).
"""
needs_delete = []
for xterm_guid, (task, queue, start_time, user_session_here) in self.xterm_lookup.items():
if user_session_here == user_session:
needs_delete.append(xterm_guid)
task.cancel()
for xterm_guid in needs_delete:
del self.xterm_lookup[xterm_guid]
async def disconnected_cdp(self):
pass
async def _list_running(self, send_func, user_session):
running = []
for xterm_guid, (task, queue, start_time, user_session_here) in self.xterm_lookup.items():
x = {
'xterm_guid': xterm_guid,
'start_time': start_time,
'user_session': user_session_here,
'description': '', # TODO pty.description,
'cmd': '', # TODO pty.cmd,
}
running.append(x)
await send_func({
'type': 'running_list',
'running': running,
'curtime': time.time(),
'to_user_session': user_session,
})
async def _start_contest(self, msg, send_func):
uid, gid, home = await _user_uid_gid_home(self.system_up_user)
filepath = os.path.join(home, 'contest.py')
if 'submission' in msg:
with open(filepath, 'w') as f:
f.write(msg['submission'])
else:
try:
os.remove(filepath)
except FileNotFoundError:
pass
cmds = [
f"tmux kill-session -t {CONTEST_SESSION_NAME}".split(),
f"tmux new-session -d -s {CONTEST_SESSION_NAME}".split(),
f"tmux send-keys -t {CONTEST_SESSION_NAME} python3 SPACE {filepath} ENTER".split(),
]
for cmd in cmds:
await _run_subprocess(cmd, self.system_up_user)
await send_func({
'type': 'contest_session_started',
'session_name': CONTEST_SESSION_NAME,
'contest_guid': msg.get('contest_guid', None),
})
async def _end_contest(self, msg, send_func):
cmds = [
f"tmux kill-session -t {CONTEST_SESSION_NAME}".split(),
]
for cmd in cmds:
await _run_subprocess(cmd, self.system_up_user)
async def _clear_console(console):
await console.clear_text()
await console.big_clear()
await console.clear_image()
async def _user_uid_gid_home(system_user):
loop = asyncio.get_running_loop()
pw_record = await loop.run_in_executor(None, pwd.getpwnam, system_user)
uid = pw_record.pw_uid
gid = pw_record.pw_gid
home = pw_record.pw_dir
return uid, gid, home
async def _write_code(xterm_guid, code_str, system_user):
uid, gid, home = await _user_uid_gid_home(system_user)
subdirs = xterm_guid[0:2], xterm_guid[2:4], xterm_guid[4:6], xterm_guid[6:8], xterm_guid
directory = os.path.join(home, '.labs_code', *subdirs)
if not os.path.exists(directory):
os.makedirs(directory)
code_path = os.path.join(directory, 'main.py')
with open(code_path, 'w') as f:
f.write(code_str)
return code_path
async def _run_subprocess(cmd, system_user):
# This runs a command _without_ a TTY.
# Use `_run_pty_cmd_background()` when you need a TTY.
cmd = ['sudo', '-u', system_user, '-i'] + cmd
p = None
try:
p = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await p.communicate()
p = None
if stderr:
stderr = stderr.decode('utf-8')
log.error('Command {} wrote to stderr: {}'.format(repr(cmd), repr(stderr)))
return stdout.decode('utf-8')
except:
if p is not None:
p.kill()
await p.wait()
raise
async def _tmux_ls(system_user):
output = await _run_subprocess(['tmux', 'ls'], system_user)
session_names = []
for line in output.split('\n'):
parts = line.split(': ')
if len(parts) == 2:
session_names.append(parts[0])
return sorted(session_names)
async def _next_tmux_session_name(system_user):
"""Like OS FDs, finds the first unused tmux number."""
curr_names = await _tmux_ls(system_user)
curr_names = set(curr_names)
i = 0
while True:
candiate_name = 'labs_{}'.format(i)
if candiate_name not in curr_names:
return candiate_name
i += 1
async def _kill_session(session_name, system_user):
# Since we do everything through tmux, we'll just ask tmux to kill the session.
# Interesting info here though, for those who want to learn something:
# https://github.com/jupyter/terminado/blob/master/terminado/management.py#L74
# https://unix.stackexchange.com/a/88742
cmd = "tmux kill-session -t".split(' ') + [session_name]
output = await _run_subprocess(cmd, system_user)
return output
async def _list_sessions(send_func, user_session, system_user):
session_names = await _tmux_ls(system_user)
await send_func({
'type': 'session_list',
'session_names': session_names,
'to_user_session': user_session,
})
class PtyProcess:
"""
Expose the relevant behavior of this process.
FUTURE TODO: It would be nice if we didn't rely on executors in this, but
I've yet to figure out how to plug these FDs into they asyncio
event loop properly... ugh.
"""
def __init__(self, stdin, stdout, stderr, p, loop):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.p = p
self.loop = loop
async def write_stdin(self, buf):
"""Write the buffer; don't return until the whole thing is written!"""
n = 0
while n < len(buf):
n_here = await self.loop.run_in_executor(None, os.write, self.stdin, buf[n:]) # <-- Warning: O(n^2) in the worst case; but okay in typical case.
n += n_here
async def read_stdout(self):
"""Read a chunk of bytes from stdout; whatever is available first. Return an empty buffer on EOF."""
return await self._read(self.stdout)
async def read_stderr(self):
"""Read a chunk of bytes from stderr; whatever is available first. Return an empty buffer on EOF."""
return await self._read(self.stderr)
async def _read(self, fd):
if fd is None:
return b''
try:
return await self.loop.run_in_executor(None, os.read, fd, READ_BUF_SIZE)
except OSError:
# PTYs throw OSError when they hit EOF, for some reason.
# Pipes and regular files don't throw, so PTYs are unique.
return b''
async def close_fds(self):
"""Close the underlying file descriptors; don't leak FDs!"""
for fd in set([self.stdin, self.stdout, self.stderr]):
if fd is not None:
os.close(fd)
def setwinsize(self, rows, cols):
try:
s = struct.pack('HHHH', rows, cols, 0, 0)
fcntl.ioctl(self.stdin, termios.TIOCSWINSZ, s)
self.p.send_signal(signal.SIGWINCH)
except Exception as e:
log.error('Failed to `setwinsize`: {}'.format(e))
traceback.print_exc(file=sys.stderr)
async def gentle_kill(self):
self.p.send_signal(signal.SIGHUP)
try:
await asyncio.wait_for(self.p.wait(), 2.0)
except asyncio.TimeoutError:
self.p.send_signal(signal.SIGTERM)
try:
await asyncio.wait_for(self.p.wait(), 2.0)
except asyncio.TimeoutError:
self.p.kill()
await self.p.wait()
async def _run_pty_cmd_background(cmd, system_user, env_override=None, start_dir_override=None, size=None):
loop = asyncio.get_running_loop()
pw_record = await loop.run_in_executor(None, pwd.getpwnam, system_user)
if start_dir_override is None:
start_dir_override = pw_record.pw_dir
env = {}
whitelist = ['MAI_IS_VIRTUAL']
blacklist_prefixes = ['MAI_', 'AWS_', 'ECS_']
for k, v in os.environ.items():
okay = True
if k not in whitelist:
for prefix in blacklist_prefixes:
if k.startswith(prefix):
okay = False
break
if okay:
env[k] = v
env['TERM'] = 'xterm-256color' # background info: https://unix.stackexchange.com/a/198949
if env_override is not None:
env.update(env_override)
env['HOME' ] = pw_record.pw_dir
env['LOGNAME' ] = pw_record.pw_name
env['USER' ] = pw_record.pw_name
env['USERNAME'] = pw_record.pw_name
env['SHELL' ] = pw_record.pw_shell
env['UID' ] = str(pw_record.pw_uid)
env['PWD' ] = start_dir_override
if 'OLDPWD' in env: del env['OLDPWD']
if 'MAIL' in env: del env['MAIL']
env = {k: v for k, v in env.items() if not k.startswith('SUDO_') and not k.startswith('XDG_')}
my_uid = os.getuid()
def switch_user():
if my_uid != pw_record.pw_uid:
os.setgid(pw_record.pw_gid)
os.initgroups(system_user, pw_record.pw_gid)
os.setuid(pw_record.pw_uid)
fd_master_io, fd_slave_io = os.openpty()
try:
p = await asyncio.create_subprocess_exec(
*cmd,
stdin=fd_slave_io,
stdout=fd_slave_io,
stderr=fd_slave_io,
cwd=start_dir_override,
env=env,
preexec_fn=switch_user,
)
except:
os.close(fd_master_io)
os.close(fd_slave_io)
raise
os.close(fd_slave_io)
stdin = fd_master_io
stdout = fd_master_io
stderr = None
proc = PtyProcess(stdin, stdout, stderr, p, loop)
if size is None:
size = (24, 80)
else:
size = (size['rows'], size['cols'])
proc.setwinsize(*size)
return proc
async def _new_session(xterm_guid, user_session, send_func, settings, system_user):
session_name = await _next_tmux_session_name(system_user)
start_dir = '~' if 'start_dir' not in settings else settings['start_dir']
cmd = ['tmux', 'new-session', '-c', start_dir, '-s', session_name]
if 'cmd' in settings:
cmd.extend(settings['cmd']) # <-- becomes the shell argument to tmux
size = settings.get('size', None)
proc = None
try:
proc = await _run_pty_cmd_background(
cmd=cmd,
system_user=system_user,
size=size
)
proc.description = "Attached session: {}".format(session_name)
proc.cmd = cmd
await send_func({
'type': 'new_session_name_announcement',
'session_name': session_name,
'xterm_guid': xterm_guid,
'to_user_session': user_session,
})
return proc
except:
if proc is not None:
proc.p.kill()
await proc.p.wait()
await proc.close_fds()
raise
async def _attach_session(session_name, settings, system_user):
session_name = re.sub(r'[^A-Za-z0-9_]', '', session_name) # safe string
cmd = ['tmux', 'attach', '-d', '-t', session_name]
size = settings.get('size', None)
proc = await _run_pty_cmd_background(
cmd=cmd,
system_user=system_user,
size=size
)
proc.description = "Attached session: {}".format(session_name)
proc.cmd = cmd
return proc
async def _start_process(xterm_guid, user_session, settings, system_user, console):
if 'clear_screen' in settings and settings['clear_screen']:
await _clear_console(console)
if 'code_to_run' in settings:
code_path = await _write_code(xterm_guid, settings['code_to_run'], system_user)
cmd = ['python3', code_path]
description = 'Running Code'
else:
cmd = settings['cmd']
description = 'Custom Command'
env_override = settings.get('env', {})
env_override['TO_USER_SESSION'] = user_session
start_dir_override = settings.get('start_dir', None)
size = settings.get('size', None)
proc = await _run_pty_cmd_background(
cmd=cmd,
system_user=system_user,
env_override=env_override,
start_dir_override=start_dir_override,
size=size
)
proc.description = description
proc.cmd = cmd
return proc
async def _handle_ouptput(xterm_guid, user_session, proc, send_func):
async def send(stream_name, buf):
await send_func({
'type': 'pty_output', 'xterm_guid': xterm_guid,
'output': base64.b64encode(buf).decode('utf-8'),
'stream_name': stream_name,
'to_user_session': user_session,
})
async def read_stream(stream_name, read_func):
# TODO: Should we buffer these `send()` calls? E.g. The Naggle-style delays?
while True:
buf = await read_func()
if buf == b'':
break
await send(stream_name, buf)
stdout_task = asyncio.create_task(read_stream('stdout', proc.read_stdout))
stderr_task = asyncio.create_task(read_stream('stdout', proc.read_stderr))
try:
_, _ = await asyncio.gather(stdout_task, stderr_task, return_exceptions=True)
except asyncio.CancelledError:
for t in [stdout_task, stderr_task]:
t.cancel()
try:
await t
except asyncio.CancelledError:
pass
raise
except Exception as e:
log.error('Unknown exception: {}'.format(e))
traceback.print_exc(file=sys.stderr)
raise
finally:
await send_func({
'type': 'pty_output_closed',
'xterm_guid': xterm_guid,
'to_user_session': user_session,
})
log.info('Process output closed; pid={}; description={}; cmd={}'.format(proc.p.pid, proc.description, proc.cmd[0]))
async def _handle_input(queue, proc):
try:
while True:
msg = await queue.get()
type_ = msg['type']
if type_ == 'xterm_resized':
size = msg['size']
size = (size['rows'], size['cols'])
proc.setwinsize(*size)
elif type_ == 'send_input_to_pty':
input_ = msg['input']
input_buf = base64.b64decode(input_)
await proc.write_stdin(input_buf)
else:
raise Exception('Unexpected type sent to process manager: {}'.format(repr(msg)))
except asyncio.CancelledError:
log.info('Process input closed; pid={}; description={}; cmd={}'.format(proc.p.pid, proc.description, proc.cmd[0]))
raise
async def _pty_process_manager(xterm_guid, user_session, queue, send_func, system_user, console):
proc = None
output_task = None
input_task = None
try:
msg = await queue.get()
type_ = msg['type']
if type_ == 'new_session':
proc = await _new_session(xterm_guid, user_session, send_func, msg, system_user)
elif type_ == 'attach_session':
session_name = msg['session_name']
proc = await _attach_session(session_name, msg, system_user)
elif type_ == 'start_process':
proc = await _start_process(xterm_guid, user_session, msg, system_user, console)
else:
raise Exception('Unexpected type sent to process manager: {}'.format(repr(msg)))
log.info('Process started; pid={}; description={}; cmd={}'.format(proc.p.pid, proc.description, proc.cmd[0]))
output_task = asyncio.create_task(_handle_ouptput(xterm_guid, user_session, proc, send_func))
input_task = asyncio.create_task(_handle_input(queue, proc))
await output_task
await proc.p.wait()
except asyncio.CancelledError:
if proc is None:
log.info('Process canceled before it began.')
else:
log.info('Process canceled; pid={}; description={}; cmd={}'.format(proc.p.pid, proc.description, proc.cmd[0]))
except Exception as e:
log.error('Unknown exception: {}'.format(e))
traceback.print_exc(file=sys.stderr)
finally:
exitcode, signalcode = await _cleanup(proc, output_task, input_task)
await send_func({
'type': 'pty_program_exited',
'xterm_guid': xterm_guid,
'exitcode': exitcode,
'signalcode': signalcode,
'to_user_session': user_session,
})
async def _cleanup(proc, output_task, input_task):
try:
if output_task is not None:
output_task.cancel()
try:
await output_task
except asyncio.CancelledError:
pass
if input_task is not None:
input_task.cancel()
try:
await input_task
except asyncio.CancelledError:
pass
if proc is not None:
if proc.p.returncode is None:
await proc.gentle_kill()
await proc.close_fds()
returncode = proc.p.returncode
assert returncode is not None
exitcode = returncode if returncode >= 0 else None
signalcode = -returncode if returncode < 0 else None
log.info('Process exited; pid={}; description={}; cmd={}; exitcode={}'.format(proc.p.pid, proc.description, proc.cmd[0], (exitcode, signalcode)))
else:
exitcode = None
signalcode = signal.SIGHUP.value # <-- The use canceled the process before it could even begin. Simulate a SIGHUP.
return exitcode, signalcode
except Exception as e:
log.error('Unknown exception: {}'.format(e))
traceback.print_exc(file=sys.stderr)
return 500, None
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import os
import io
import sys
import json
import random
import asyncio
import traceback
from collections import defaultdict
from websockets import connect as ws_connect
from websockets import WebSocketException
from auto import __version__ as libauto_version
from auto.services.controller.client import CioRoot
from auto.services.console.client import CuiRoot
from auto import logger
log = logger.init(__name__, terminal=True)
from auto.services.labs.pty_manager import PtyManager
from auto.services.labs.verification_method import Verification
from auto.services.labs.dashboard import Dashboard
from auto.services.labs.proxy import Proxy
from auto.services.labs.util import set_hostname
from auto.services.labs.settings import save_settings
from auto.services.labs.rpc.server import init as init_rpc_server
WS_BASE_URL = os.environ.get('MAI_WS_URL', 'wss://ws.autoauto.ai/autopair/device')
#WS_BASE_URL = os.environ.get('MAI_WS_URL', 'wss://api.masterai.ai/autopair/device')
PING_INTERVAL_SECONDS = 20
def _log_consumer_error(c):
log.error('Exception in consumer: {}'.format(type(c).__name__))
output = io.StringIO()
traceback.print_exc(file=output)
log.error(output.getvalue())
def _is_new_device_session(msg):
if 'origin' in msg and msg['origin'] == 'server':
if 'connect' in msg and msg['connect'] == 'device':
vin = msg['vin']
return vin
return None
def _is_departed_device_session(msg):
if 'origin' in msg and msg['origin'] == 'server':
if 'disconnect' in msg and msg['disconnect'] == 'device':
vin = msg['vin']
return vin
return None
def _is_new_user_session(msg):
if 'origin' in msg and msg['origin'] == 'server':
if 'connect' in msg and msg['connect'] == 'user':
username = msg['username']
user_session = msg['user_session']
return username, user_session
return None
def _is_departed_user_session(msg):
if 'origin' in msg and msg['origin'] == 'server':
if 'disconnect' in msg and msg['disconnect'] == 'user':
username = msg['username']
user_session = msg['user_session']
return username, user_session
return None
def _is_hello(msg):
if 'origin' in msg and msg['origin'] == 'server':
if 'hello' in msg:
info = msg['yourinfo']
if 'settings' not in info:
info['settings'] = {}
settings = info['settings']
if isinstance(settings, str):
settings = settings.strip()
if settings is None or settings == '':
info['settings'] = {}
elif isinstance(settings, str):
try:
info['settings'] = json.loads(settings)
except json.JSONDecodeError:
info['settings'] = {'failed': True}
assert isinstance(info['settings'], dict)
return info
return None
class ConnectedSessions:
def __init__(self, consumers):
self.consumers = consumers
self.known_device_sessions = set()
self.known_usernames = defaultdict(set)
self.known_user_sessions = set()
async def add_device_session(self, vin):
if vin not in self.known_device_sessions:
self.known_device_sessions.add(vin)
for c in self.consumers:
try:
await c.new_device_session(vin)
except:
_log_consumer_error(c)
log.info('Connected device session: {}'.format(vin))
async def remove_device_session(self, vin):
if vin in self.known_device_sessions:
self.known_device_sessions.remove(vin)
for c in self.consumers:
try:
await c.end_device_session(vin)
except:
_log_consumer_error(c)
log.info('Departed device session: {}'.format(vin))
async def close_all_device_sessions(self):
needs_remove = list(self.known_device_sessions) # copy
for vin in needs_remove:
await self.remove_device_session(vin)
def has_specific_device_session(self, vin):
return (vin in self.known_device_sessions)
def has_any_device_sessions(self):
return len(self.known_device_sessions) > 0
async def add_user_session(self, username, user_session):
if user_session not in self.known_user_sessions:
self.known_user_sessions.add(user_session)
self.known_usernames[username].add(user_session)
for c in self.consumers:
try:
await c.new_user_session(username, user_session)
except:
_log_consumer_error(c)
log.info('Connected user session: {}: {}'.format(username, user_session))
async def remove_user_session(self, username, user_session):
if user_session in self.known_user_sessions:
self.known_user_sessions.remove(user_session)
self.known_usernames[username].remove(user_session)
for c in self.consumers:
try:
await c.end_user_session(username, user_session)
except:
_log_consumer_error(c)
log.info('Departed user session: {}: {}'.format(username, user_session))
async def close_all_user_sessions(self):
needs_remove = []
for username, user_session_set in self.known_usernames.items():
for user_session in user_session_set:
needs_remove.append((username, user_session))
for username, user_session in needs_remove:
await self.remove_user_session(username, user_session)
def has_specific_user_session(self, user_session):
return user_session in self.known_user_sessions
def has_any_user_sessions(self, username=None):
if username is not None:
return len(self.known_usernames[username]) > 0
else:
return len(self.known_user_sessions) > 0
async def _set_hostname(name):
output = await set_hostname(name)
log.info("Set hostname, output is: {}".format(output.strip()))
async def _save_settings(settings, controller):
did_change = save_settings(settings)
if did_change:
log.info("Labs settings were updated, will reboot now.")
power = await controller.acquire('Power')
await power.reboot()
await controller.release(power)
else:
log.info("Labs settings did *not* change.")
async def _handle_message(ws, msg, consumers, controller, console, connected_sessions, send_func):
new_device_vin = _is_new_device_session(msg)
departed_device_vin = _is_departed_device_session(msg)
new_user_info = _is_new_user_session(msg)
departed_user_info = _is_departed_user_session(msg)
hello_info = _is_hello(msg)
if new_device_vin is not None:
await connected_sessions.add_device_session(new_device_vin)
elif departed_device_vin is not None:
await connected_sessions.remove_device_session(departed_device_vin)
elif new_user_info is not None:
await connected_sessions.add_user_session(*new_user_info)
elif departed_user_info is not None:
await connected_sessions.remove_user_session(*departed_user_info)
elif hello_info is not None:
vin = hello_info['vin']
name = hello_info['name']
description = hello_info['description'] # <-- Where should we display this?
async def write():
await console.write_text('Device Name: {}\n'.format(name))
await console.write_text('Device VIN: {}\n'.format(vin))
asyncio.create_task(write())
asyncio.create_task(_set_hostname(name))
asyncio.create_task(_save_settings(hello_info['settings'], controller))
else:
for c in consumers:
try:
await c.got_message(msg, send_func)
except:
_log_consumer_error(c)
async def _ping_with_interval(ws):
try:
log.info('Ping task started.')
while True:
await asyncio.sleep(PING_INTERVAL_SECONDS)
await ws.send(json.dumps({'ping': True}))
log.info('Sent ping to server.')
except asyncio.CancelledError:
log.info('Ping task is terminating.')
def _build_send_function(ws, connected_sessions):
async def smart_send(msg):
try:
if isinstance(msg, str):
msg = json.loads(msg)
if 'to_vin' in msg:
# This is a message intended for a peer device.
to_vin = msg['to_vin']
if to_vin == 'all':
if not connected_sessions.has_any_device_sessions():
# No devices are listening.
return False
else:
if not connected_sessions.has_specific_device_session(to_vin):
# This peer device is not connected right now.
return False
elif 'to_user_session' in msg:
user_session = msg['to_user_session']
if not connected_sessions.has_specific_user_session(user_session):
# We do not send messages that are destined for a
# user session that no longer exists!
return False
elif 'to_username' in msg:
username = msg['to_username']
if not connected_sessions.has_any_user_sessions(username):
# We don't send to a user who has zero user sessions.
return False
elif 'target' in msg and msg['target'] == 'server':
# Let this message pass through since it is destined for the server.
# But remove this flag since it is just for internal libauto usage.
del msg['target']
else:
if not connected_sessions.has_any_user_sessions():
# Literally no one is listening, so sending this generic
# broadcast message is pointless.
return False
# If we didn't bail out above, then send the message.
await ws.send(json.dumps(msg))
return True
except Exception as e:
log.error('Exception in `smart_send`: {}'.format(e))
output = io.StringIO()
traceback.print_exc(file=output)
log.error(output.getvalue())
return False
return smart_send
async def _run(ws, consumers, controller, console, rpc_interface, publish_func):
ping_task = asyncio.create_task(_ping_with_interval(ws))
connected_sessions = ConnectedSessions(consumers)
send_func = _build_send_function(ws, connected_sessions)
loop = asyncio.get_running_loop()
for c in consumers:
try:
await c.connected_cdp()
except:
_log_consumer_error(c)
rpc_interface.send_func = send_func
try:
while True:
msg = await ws.recv()
try:
msg = json.loads(msg)
except json.JSONDecodeError:
log.error('Got bad JSON message: {}'.format(repr(msg)))
continue
if 'ping' in msg:
log.info('Got ping from server; will send pong back.')
await ws.send(json.dumps({'pong': True}))
continue
if 'pong' in msg:
log.info('Got pong from server!')
continue
await publish_func('messages', msg)
start = loop.time()
await _handle_message(ws, msg, consumers, controller, console, connected_sessions, send_func)
end = loop.time()
if end - start > 0.01:
log.warning('Blocking operation suspected; message receiving loop is being throttled; delay={:.04f}'.format(end - start))
log.warning('Message was: {}'.format(json.dumps(msg)))
finally:
rpc_interface.send_func = None
await connected_sessions.close_all_device_sessions()
await connected_sessions.close_all_user_sessions()
for c in consumers:
try:
await c.disconnected_cdp()
except:
_log_consumer_error(c)
ping_task.cancel()
await ping_task
async def _get_labs_auth_code(controller, console):
auth = await controller.acquire('Credentials')
was_missing = False
while True:
auth_code = await auth.get_labs_auth_code()
if auth_code is not None:
if was_missing:
await console.write_text("The auth code is now set!\n")
log.info('The auth code is now set!')
break
else:
if not was_missing:
await console.write_text("The auth code is not yet set...\n")
log.info("The auth code is not yet set... will wait...")
was_missing = True
await asyncio.sleep(2)
await controller.release(auth)
return auth_code
async def init_and_create_forever_task(system_up_user):
controller = CioRoot()
console = CuiRoot()
capabilities = await controller.init()
await console.init()
cio_version_iface = await controller.acquire('VersionInfo')
cio_version = await cio_version_iface.version()
cio_version = '.'.join([str(v) for v in cio_version])
cio_name = await cio_version_iface.name()
await controller.release(cio_version_iface)
log.info("Libauto version: {}".format(libauto_version))
log.info("Controller version: {}".format(cio_version))
log.info("Controller name: {}".format(cio_name))
await console.clear_text()
await console.big_clear()
await console.clear_image()
await console.write_text("Libauto version: {}\n".format(libauto_version))
await console.write_text("Controller version: {}\n".format(cio_version))
await console.write_text("Controller name: {}\n".format(cio_name))
pubsub_channels = [
'messages',
]
rpc_server, rpc_interface, publish_func = await init_rpc_server(pubsub_channels)
consumers = [
PtyManager(system_up_user, console),
Verification(console),
Dashboard(controller, capabilities),
Proxy(),
]
for c in consumers:
try:
await c.init()
except:
_log_consumer_error(c)
await console.write_text('Attempting to connect...\n')
async def _forever():
auth_code = await _get_labs_auth_code(controller, console)
url = WS_BASE_URL + '/' + auth_code
while True:
was_connected = False
try:
async with ws_connect(url) as ws:
log.info("Connected: {}...".format(WS_BASE_URL + '/' + auth_code[:4]))
await console.write_text('Connected to Labs. Standing by...\n')
was_connected = True
await _run(ws, consumers, controller, console, rpc_interface, publish_func)
except WebSocketException as e:
log.info('Connection closed: {}'.format(e))
if was_connected:
await console.write_text('Connection to Labs was lost.\nReconnecting...\n')
except Exception as e:
log.error('Unknown error: {}'.format(e))
finally:
reconnect_delay_seconds = 10 + random.randint(2, 8)
log.info('Waiting {} seconds before reconnecting.'.format(reconnect_delay_seconds))
await asyncio.sleep(reconnect_delay_seconds)
return asyncio.create_task(_forever())
async def run_forever(system_up_user):
forever_task = await init_and_create_forever_task(system_up_user)
await forever_task
if __name__ == '__main__':
if len(sys.argv) > 1:
system_up_user = sys.argv[1] # the "UnPrivileged" system user
else:
system_up_user = os.environ['USER']
asyncio.run(run_forever(system_up_user))
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
b = await c.acquire('Buzzer')
await asyncio.sleep(2)
#await b.play() # defaults to the 'on' sound
#await b.play('o4l16ceg>c8') # the 'on' sound (explicit this time)
#await b.play('v10>>g16>>>c16') # the soft reset sound
#await b.play('>E>E>E R >C>E>G')
#await b.play('!L16 V12 cdefgab>cbagfedc') # C-major scale up and down
await b.play('!T240 L8 agafaea dac+adaea fa<aa<bac#a dac#adaea f4') # "Bach's fugue in D-minor"
await b.wait()
await asyncio.sleep(2)
await c.release(b)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains a mock CIO interface implementing only the required
components.
"""
import asyncio
import random
import subprocess
import numpy as np
import cio
from cio.aa_controller_v1.components import Credentials
from cio.aa_controller_v1.camera_async import CameraRGB_Async
from cio.aa_controller_v1.camera_pi import CameraRGB
class CioRoot(cio.CioRoot):
"""
This is a mock CIO interface.
All components are mock _except_ for the Credentials component, which uses
the implementation from `aa_controller_v1`. This is so that we can still
properly authenticate even if we fall to this mock implementation.
"""
def __init__(self):
# These are the only required components.
self.impls = {
'VersionInfo': VersionInfo,
'Credentials': lambda: Credentials(None, None),
'Camera': Camera,
'Power': Power,
}
async def init(self):
return list(self.impls.keys())
async def acquire(self, capability_id):
return self.impls[capability_id]()
async def release(self, capability_obj):
pass
async def close(self):
pass
class VersionInfo(cio.VersionInfoIface):
async def name(self):
return "Mock CIO Implementation"
async def version(self):
return (0, 1)
class Camera(cio.CameraIface):
_camera = None
def __init__(self):
if Camera._camera is None:
loop = asyncio.get_running_loop()
Camera._camera = CameraRGB_Async(
lambda: CameraRGB(width=320, height=240, fps=8),
loop=loop,
idle_timeout=30
)
async def capture(self):
return await Camera._camera.capture()
class Power(cio.PowerIface):
async def state(self):
return 'wall'
async def millivolts(self):
return random.randint(7000, 8000)
async def estimate_remaining(self, millivolts=None):
if millivolts is None:
millivolts = await self.millivolts()
batt_low, batt_high = 6500, 8400
pct_estimate = (millivolts - batt_low) / (batt_high - batt_low)
pct_estimate = max(min(pct_estimate, 1.0), 0.0)
mins_estimate = pct_estimate * 3.5 * 60.0 # assumes a full battery lasts 3.5 hours
return int(round(mins_estimate)), int(round(pct_estimate * 100))
async def should_shut_down(self):
return False
async def shut_down(self):
subprocess.run(['/sbin/poweroff'])
async def reboot(self):
subprocess.run(['/sbin/reboot'])
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from .easyi2c import (write_read_i2c_with_integrity,
i2c_retry, i2c_poll_until)
from . import N_I2C_TRIES
from .timers import Timer1PWM, Timer3PWM
from .db import default_db
from .battery_discharge_curve import battery_map_millivolts_to_percentage
from .camera_async import CameraRGB_Async
from .camera_pi import CameraRGB
import cio
import os
import time
import struct
import asyncio
import subprocess
from math import floor
from collections import deque
import numpy as np
class VersionInfo(cio.VersionInfoIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def name(self):
return "AutoAuto v1 Controller"
@i2c_retry(N_I2C_TRIES)
async def version(self):
major, minor = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 2)
return major, minor
class Credentials(cio.CredentialsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.db = None
self.loop = asyncio.get_running_loop()
async def get_labs_auth_code(self):
return await self.loop.run_in_executor(None, self._get_labs_auth_code)
async def set_labs_auth_code(self, auth_code):
if (await self.get_labs_auth_code()) is None:
await self.loop.run_in_executor(None, self._set_labs_auth_code, auth_code)
return True
return False
async def get_jupyter_password(self):
return await self.loop.run_in_executor(None, self._get_jupyter_password)
async def set_jupyter_password(self, password):
if (await self.get_jupyter_password()) is None:
await self.loop.run_in_executor(None, self._set_jupyter_password, password)
return True
return False
def _get_db(self):
if self.db is None:
self.db = default_db()
return self.db
def _get_labs_auth_code(self):
return self._get_db().get('DEVICE_LABS_AUTH_CODE', None)
def _set_labs_auth_code(self, auth_code):
self._get_db().put('DEVICE_LABS_AUTH_CODE', auth_code)
os.sync()
def _get_jupyter_password(self):
return self._get_db().get('DEVICE_JUPYTER_PASSWORD', None)
def _set_jupyter_password(self, password):
self._get_db().put('DEVICE_JUPYTER_PASSWORD', password)
os.sync()
class Camera(cio.CameraIface):
_camera = None
def __init__(self, fd, reg_num):
if Camera._camera is None:
loop = asyncio.get_running_loop()
Camera._camera = CameraRGB_Async(
lambda: CameraRGB(width=320, height=240, fps=8),
loop=loop,
idle_timeout=30
)
async def capture(self):
return await Camera._camera.capture()
class LoopFrequency(cio.LoopFrequencyIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def read(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 4)
return struct.unpack('1I', buf)[0]
class Power(cio.PowerIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def state(self):
return 'battery'
@i2c_retry(N_I2C_TRIES)
async def millivolts(self):
lsb, msb = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 2)
return (msb << 8) | lsb # <-- You can also use int.from_bytes(...) but I think doing the bitwise operations explicitly is cooler.
async def estimate_remaining(self, millivolts=None):
if millivolts is None:
millivolts = await self.millivolts()
percentage = battery_map_millivolts_to_percentage(millivolts)
minutes = 4.0 * 60.0 * (percentage / 100.0) # Assumes the full battery lasts 4 hours.
return floor(minutes), floor(percentage)
async def should_shut_down(self):
return False
async def shut_down(self):
subprocess.run(['/sbin/poweroff'])
async def reboot(self):
subprocess.run(['/sbin/reboot'])
class Buzzer(cio.BuzzerIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def is_currently_playing(self):
can_play, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
return can_play == 0
async def wait(self):
await i2c_poll_until(self.is_currently_playing, False, timeout_ms=100000)
async def play(self, notes="o4l16ceg>c8"):
notes = notes.replace(' ', '') # remove spaces from the notes (they don't hurt, but they take up space and the microcontroller doesn't have a ton of space)
@i2c_retry(N_I2C_TRIES)
async def send_new_notes(notes, pos):
buf = list(notes.encode())
can_play, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, pos] + buf, 1)
if can_play != 1:
raise Exception("failed to send notes to play")
return len(buf)
@i2c_retry(N_I2C_TRIES)
async def start_playback():
can_play, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
# Ignore return value. Why? Because this call commonly requires multiple retries
# (as done by `i2c_retry`) thus if we retry, then the playback will have already
# started and we'll be (wrongly) informed that it cannot start (because it already
# started!). Thus, the check below has been disabled:
#
#if can_play != 1:
# raise Exception("failed to start playback")
def chunkify(seq, n):
"""Split `seq` into sublists of size `n`"""
return [seq[i * n:(i + 1) * n] for i in range((len(seq) + n - 1) // n)]
await self.wait()
pos = 0
for chunk in chunkify(notes, 4):
chunk_len = await send_new_notes(chunk, pos)
pos += chunk_len
await start_playback()
class Gyroscope(cio.GyroscopeIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def read(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 3*4)
x, y, z = struct.unpack('3f', buf)
x, y = -x, -y # rotate 180 degrees around z
return x, y, z
class GyroscopeAccum(cio.GyroscopeAccumIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.x_off = 0.0
self.y_off = 0.0
self.z_off = 0.0
async def reset(self):
x, y, z = await self._read_raw()
self.x_off = x
self.y_off = y
self.z_off = z
async def read(self):
x, y, z = await self._read_raw()
return (x - self.x_off), (y - self.y_off), (z - self.z_off)
@i2c_retry(N_I2C_TRIES)
async def _read_raw(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 3*4)
x, y, z = struct.unpack('3f', buf)
x, y = -x, -y # rotate 180 degrees around z
return x, y, z
class Accelerometer(cio.AccelerometerIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def read(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 3*4)
x, y, z = struct.unpack('3f', buf)
x, y = -x, -y # rotate 180 degrees around z
return x, y, z
class PushButtons(cio.PushButtonsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.n = None
self.states = None
self.event_queue = deque()
@i2c_retry(N_I2C_TRIES)
async def num_buttons(self):
n, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
return n
@i2c_retry(N_I2C_TRIES)
async def button_state(self, button_index):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01+button_index], 3)
presses = int(buf[0])
releases = int(buf[1])
is_pressed = bool(buf[2])
return presses, releases, is_pressed
async def get_events(self):
if self.n is None:
self.n = await self.num_buttons()
self.states = [await self.button_state(i) for i in range(self.n)]
return []
events = []
for prev_state, i in zip(self.states, range(self.n)):
state = await self.button_state(i)
if state == prev_state:
continue
diff_presses = (state[0] - prev_state[0]) % 256
diff_releases = (state[1] - prev_state[1]) % 256
if diff_presses == 0 and diff_releases == 0:
continue
if prev_state[2]: # if button **was** pressed
# We'll add `released` events first.
while diff_presses > 0 or diff_releases > 0:
if diff_releases > 0:
events.append({'button': i, 'action': 'released'})
diff_releases -= 1
if diff_presses > 0:
events.append({'button': i, 'action': 'pressed'})
diff_presses -= 1
else:
# We'll add `pressed` events first.
while diff_presses > 0 or diff_releases > 0:
if diff_presses > 0:
events.append({'button': i, 'action': 'pressed'})
diff_presses -= 1
if diff_releases > 0:
events.append({'button': i, 'action': 'released'})
diff_releases -= 1
self.states[i] = state
return events
async def wait_for_event(self):
if not self.event_queue: # if empty
while True:
events = await self.get_events()
if events: # if not empty
self.event_queue.extend(events)
return self.event_queue.popleft()
await asyncio.sleep(0.05)
else:
return self.event_queue.popleft()
async def wait_for_action(self, action='pressed'):
while True:
event = await self.wait_for_event()
if action == 'any' or action == event['action']:
return event['button'], event['action']
class LEDs(cio.LEDsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.vals = {
'red': False,
'green': False,
'blue': False,
}
async def led_map(self):
return {
'red': 'The red LED',
'green': 'The green LED',
'blue': 'The blue LED',
}
@i2c_retry(N_I2C_TRIES)
async def _set(self):
red = self.vals['red']
green = self.vals['green']
blue = self.vals['blue']
led_state = ((1 if red else 0) | ((1 if green else 0) << 1) | ((1 if blue else 0) << 2))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00, led_state], 1)
if status != 72:
raise Exception("failed to set LED state")
async def set_led(self, led_identifier, val):
self.vals[led_identifier] = val
await self._set()
async def set_many_leds(self, id_val_list):
for led_identifier, val in id_val_list:
self.vals[led_identifier] = val
await self._set()
async def mode_map(self):
return {
'spin': 'the LEDs flash red, then green, then blue, then repeat',
}
@i2c_retry(N_I2C_TRIES)
async def set_mode(self, mode_identifier):
mode = 0 # default mode where the values are merely those set by `set_led()`
if mode_identifier == 'spin':
mode = 1
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, mode], 1)
if status != 72:
raise Exception("failed to set LED mode")
async def set_brightness(self, brightness):
raise Exception('LED brightness not available on this hardware.')
class Photoresistor(cio.PhotoresistorIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def read(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 8)
millivolts, resistance = struct.unpack('2I', buf)
return millivolts, resistance
async def read_millivolts(self):
millivolts, resistance = await self.read()
return millivolts
async def read_ohms(self):
millivolts, resistance = await self.read()
return resistance
class Encoders(cio.EncodersIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.last_counts = {}
self.abs_counts = {}
async def num_encoders(self):
return 2
async def enable(self, encoder_index):
if encoder_index == 0:
return await self._enable_e1()
else:
return await self._enable_e2()
async def read_counts(self, encoder_index):
if encoder_index == 0:
vals = await self._read_e1_counts()
else:
vals = await self._read_e2_counts()
vals = list(vals)
vals[0] = self._fix_count_rollover(vals[0], encoder_index)
vals = tuple(vals)
return vals
async def read_timing(self, encoder_index):
if encoder_index == 0:
return await self._read_e1_timing()
else:
return await self._read_e2_timing()
async def disable(self, encoder_index):
if encoder_index == 0:
return await self._disable_e1()
else:
return await self._disable_e2()
@i2c_retry(N_I2C_TRIES)
async def _enable_e1(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
if status != 31:
raise Exception("Failed to enable encoder")
@i2c_retry(N_I2C_TRIES)
async def _enable_e2(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01], 1)
if status != 31:
raise Exception("Failed to enable encoder")
@i2c_retry(N_I2C_TRIES)
async def _disable_e1(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
if status != 31:
raise Exception("Failed to disable encoder")
@i2c_retry(N_I2C_TRIES)
async def _disable_e2(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 31:
raise Exception("Failed to disable encoder")
@i2c_retry(N_I2C_TRIES)
async def _read_e1_counts(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x04], 6)
return struct.unpack('3h', buf)
@i2c_retry(N_I2C_TRIES)
async def _read_e1_timing(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x05], 8)
return struct.unpack('2I', buf)
@i2c_retry(N_I2C_TRIES)
async def _read_e2_counts(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x06], 6)
return struct.unpack('3h', buf)
@i2c_retry(N_I2C_TRIES)
async def _read_e2_timing(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x07], 8)
return struct.unpack('2I', buf)
def _fix_count_rollover(self, count, encoder_index):
count = np.int16(count)
if encoder_index not in self.last_counts:
self.last_counts[encoder_index] = count
self.abs_counts[encoder_index] = 0
return 0
diff = int(count - self.last_counts[encoder_index])
self.last_counts[encoder_index] = count
abs_count = self.abs_counts[encoder_index] + diff
self.abs_counts[encoder_index] = abs_count
return abs_count
class CarMotors(cio.CarMotorsIface):
safe_throttle_cache = None
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.db = None
self.loop = asyncio.get_running_loop()
@i2c_retry(N_I2C_TRIES)
async def on(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
if status != 104:
raise Exception("failed to turn on car motors")
@i2c_retry(N_I2C_TRIES)
async def set_steering(self, steering):
steering = int(round(min(max(steering, -45), 45)))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, (steering & 0xFF), ((steering >> 8) & 0xFF)], 1)
if status != 104:
raise Exception("failed to set steering")
@i2c_retry(N_I2C_TRIES)
async def set_throttle(self, throttle):
throttle = int(round(min(max(throttle, -100), 100)))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02, (throttle & 0xFF), ((throttle >> 8) & 0xFF)], 1)
if status != 104:
raise Exception("failed to set throttle")
def _get_db(self):
if self.db is None:
self.db = default_db()
return self.db
def _get_safe_throttle(self):
db = self._get_db()
min_throttle = db.get('CAR_THROTTLE_FORWARD_SAFE_SPEED', -22)
max_throttle = db.get('CAR_THROTTLE_REVERSE_SAFE_SPEED', 23)
return min_throttle, max_throttle
def _set_safe_throttle(self, min_throttle, max_throttle):
db = self._get_db()
db.put('CAR_THROTTLE_FORWARD_SAFE_SPEED', min_throttle)
db.put('CAR_THROTTLE_REVERSE_SAFE_SPEED', max_throttle)
os.sync()
async def get_safe_throttle(self):
if CarMotors.safe_throttle_cache is None:
CarMotors.safe_throttle_cache = await self.loop.run_in_executor(None, self._get_safe_throttle)
return CarMotors.safe_throttle_cache
async def set_safe_throttle(self, min_throttle, max_throttle):
CarMotors.safe_throttle_cache = (min_throttle, max_throttle)
return await self.loop.run_in_executor(None, self._set_safe_throttle, min_throttle, max_throttle)
@i2c_retry(N_I2C_TRIES)
async def off(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 104:
raise Exception("failed to turn off car motors")
async def set_params(self, top, steering_left, steering_mid, steering_right, steering_millis,
throttle_forward, throttle_mid, throttle_reverse, throttle_millis):
"""
Set the car motors' PWM signal parameters.
This is a non-standard method which is not a part of the CarMotors interface.
"""
@i2c_retry(N_I2C_TRIES)
async def set_top():
payload = list(struct.pack("1H", top))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x04] + payload, 1)
if status != 104:
raise Exception("failed to set params: top")
@i2c_retry(N_I2C_TRIES)
async def set_steering_params():
payload = list(struct.pack("4H", steering_left, steering_mid, steering_right, steering_millis))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x05] + payload, 1)
if status != 104:
raise Exception("failed to set params: steering_left, steering_mid, steering_right, steering_millis")
@i2c_retry(N_I2C_TRIES)
async def set_throttle_params():
payload = list(struct.pack("4H", throttle_forward, throttle_mid, throttle_reverse, throttle_millis))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x06] + payload, 1)
if status != 104:
raise Exception("failed to set params: throttle_forward, throttle_mid, throttle_reverse, throttle_millis")
await set_top()
await set_steering_params()
await set_throttle_params()
async def save_params(self):
"""
Save the car motors' current parameters to the EEPROM.
This is a non-standard method which is not a part of the CarMotors interface.
"""
@i2c_retry(N_I2C_TRIES)
async def save():
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x07], 1)
if status != 104:
raise Exception("failed to tell car to save motor params")
@i2c_retry(N_I2C_TRIES)
async def is_saved():
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x08], 1)
return status == 0
await save()
await i2c_poll_until(is_saved, True, timeout_ms=1000)
def rpc_extra_exports(self):
return ['set_params', 'save_params']
class PWMs(cio.PWMsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.t1_reg_num = reg_num[0]
self.t3_reg_num = reg_num[1]
self.timer_1 = Timer1PWM(self.fd, self.t1_reg_num)
self.timer_3 = Timer3PWM(self.fd, self.t3_reg_num)
self.enabled = {} # dict mapping pin_index to frequency
async def num_pins(self):
return 4
async def enable(self, pin_index, frequency, duty=0):
if 2000000 % frequency:
raise Exception('cannot set frequency exactly')
top = 2000000 // frequency
duty = min(100.0, duty)
duty = max(0.0, duty)
duty = int(round(duty / 100.0 * top))
if pin_index in (0, 1, 2):
# These pins are on Timer 1.
needs_init = True
for idx in (0, 1, 2):
if idx in self.enabled:
if frequency != self.enabled[idx]:
raise Exception("All enabled pins 0, 1, and 2 must have the same frequency.")
needs_init = False
if needs_init:
await self.timer_1.set_top(top)
if pin_index == 0:
await self.timer_1.set_ocr_a(duty)
await self.timer_1.enable_a()
elif pin_index == 1:
await self.timer_1.set_ocr_b(duty)
await self.timer_1.enable_b()
elif pin_index == 2:
await self.timer_1.set_ocr_c(duty)
await self.timer_1.enable_c()
elif pin_index == 3:
# This pin is on Timer 3.
await self.timer_3.set_top(top)
await self.timer_3.set_ocr(duty)
await self.timer_3.enable()
else:
raise Exception('invalid pin_index')
self.enabled[pin_index] = frequency
async def set_duty(self, pin_index, duty):
if pin_index not in self.enabled:
raise Exception('that pin is not enabled')
frequency = self.enabled[pin_index]
top = 2000000 // frequency
duty = min(100.0, duty)
duty = max(0.0, duty)
duty = int(round(duty / 100.0 * top))
if pin_index == 0:
await self.timer_1.set_ocr_a(duty)
elif pin_index == 1:
await self.timer_1.set_ocr_b(duty)
elif pin_index == 2:
await self.timer_1.set_ocr_c(duty)
elif pin_index == 3:
await self.timer_3.set_ocr(duty)
async def disable(self, pin_index):
if pin_index not in self.enabled:
raise Exception('that pin is not enabled')
if pin_index == 0:
await self.timer_1.disable_a()
elif pin_index == 1:
await self.timer_1.disable_b()
elif pin_index == 2:
await self.timer_1.disable_c()
elif pin_index == 3:
await self.timer_3.disable()
del self.enabled[pin_index]
class Calibrator(cio.CalibratorIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def start(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0], 1)
if status != 7:
raise Exception("Failed to start calibration process.")
@i2c_retry(N_I2C_TRIES)
async def status(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 1], 1)
# Status 0 means not started, 1 means currently calibrating, 2 means done calibrating
if status == 0 or status == 1:
return status
elif status == 2:
return -1 # <-- conform to CIO interface
else:
raise Exception("Unknown calibration status")
async def script_name(self):
return "calibrate_car_v1"
class PidSteering(cio.PidSteeringIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def set_pid(self, p, i, d, error_accum_max=0.0, save=False):
@i2c_retry(N_I2C_TRIES)
async def set_val(instruction, val):
payload = list(struct.pack("1f", val))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, instruction] + payload, 1)
if status != 52:
raise Exception("failed to set PID value for instruction {}".format(instruction))
await set_val(0x01, p)
await set_val(0x02, i)
await set_val(0x03, d)
await set_val(0x04, error_accum_max)
if save:
await self.save_pid()
@i2c_retry(N_I2C_TRIES)
async def set_point(self, point):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x07] + list(struct.pack("1f", point)), 1)
if status != 52:
raise Exception("failed to set the PID \"set point\"")
@i2c_retry(N_I2C_TRIES)
async def enable(self, invert_output=False):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x08, (0x01 if invert_output else 0x00)], 1)
if status != 52:
raise Exception("failed to enable PID loop")
@i2c_retry(N_I2C_TRIES)
async def disable(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
if status != 52:
raise Exception("failed to disable PID loop")
async def save_pid(self):
"""
Save P, I, D (and `error_accum_max`) to the EEPROM.
This is a non-standard method which is not part of the PID interface.
"""
@i2c_retry(N_I2C_TRIES)
async def save():
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x05], 1)
if status != 52:
raise Exception("failed to save PID params")
@i2c_retry(N_I2C_TRIES)
async def is_saved():
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x06], 1)
return status == 0
await save()
await i2c_poll_until(is_saved, True, timeout_ms=1000)
class CarControl(cio.CarControlIface):
def __init__(self, fd, reg_nums):
self.car_motors = CarMotors(fd, reg_nums[0])
self.gyro_accum = GyroscopeAccum(fd, reg_nums[1]) if reg_nums[1] is not None else None
self.pid_steering = PidSteering(fd, reg_nums[2]) if reg_nums[2] is not None else None
async def on(self):
await self.car_motors.on()
async def straight(self, throttle, sec=None, cm=None):
if cm is not None:
raise ValueError('This device does not have a wheel encoder, thus you may not pass `cm` to travel a specific distance.')
if sec is None:
raise ValueError('You must specify `sec`, the number of seconds to drive.')
await self.car_motors.set_steering(0.0)
await asyncio.sleep(0.1)
if self.pid_steering is not None and self.gyro_accum is not None:
_, _, z = await self.gyro_accum.read()
start_time = time.time()
await self.pid_steering.set_point(z)
await self.pid_steering.enable(invert_output=(throttle < 0))
else:
start_time = time.time()
while True:
curr_time = time.time()
if curr_time - start_time >= sec:
break
await self.car_motors.set_throttle(throttle)
if self.pid_steering is None:
await self.car_motors.set_steering(0.0)
await asyncio.sleep(min(0.1, curr_time - start_time))
await self.car_motors.set_throttle(0.0)
await asyncio.sleep(0.1)
if self.pid_steering is not None:
await self.pid_steering.disable()
async def drive(self, steering, throttle, sec=None, deg=None):
if sec is not None and deg is not None:
raise Exception('You may not specify both `sec` and `deg`.')
if sec is None and deg is None:
raise Exception('You must specify either `sec` or `deg`.')
if deg is not None and self.gyro_accum is None:
raise Exception('This device has no gyroscope, so you may not pass `deg`.')
if deg is not None and deg <= 0.0:
raise Exception('You must pass `deg` as a postive value.')
await self.car_motors.set_steering(steering)
await asyncio.sleep(0.1)
start_time = time.time()
if sec is not None:
while True:
curr_time = time.time()
if curr_time - start_time >= sec:
break
await self.car_motors.set_throttle(throttle)
await self.car_motors.set_steering(steering)
await asyncio.sleep(min(0.1, curr_time - start_time))
elif deg is not None:
await self.gyro_accum.reset() # Start the gyroscope reading at 0.
throttle_time = time.time()
await self.car_motors.set_throttle(throttle)
while True:
x, y, z = await self.gyro_accum.read()
if abs(z) >= deg:
break
curr_time = time.time()
if curr_time - throttle_time > 0.75:
await self.car_motors.set_throttle(throttle)
await self.car_motors.set_steering(steering)
throttle_time = curr_time
await self.car_motors.set_throttle(0.0)
await asyncio.sleep(0.1)
async def off(self):
await self.car_motors.off()
KNOWN_COMPONENTS = {
'VersionInfo': VersionInfo,
'Credentials': Credentials,
'Camera': Camera,
'LoopFrequency': LoopFrequency,
'Power': Power,
'Buzzer': Buzzer,
'Gyroscope': Gyroscope,
'Gyroscope_accum': GyroscopeAccum,
'Accelerometer': Accelerometer,
'PushButtons': PushButtons,
'LEDs': LEDs,
'Photoresistor': Photoresistor,
'Encoders': Encoders,
'CarMotors': CarMotors,
'PWMs': PWMs,
'Calibrator': Calibrator,
'PID_steering': PidSteering,
'CarControl': CarControl,
}
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import sys
import base64
import asyncio
import traceback
from auto import logger
log = logger.init(__name__, terminal=True)
READ_BUF_SIZE = 4096*8
class Proxy:
def __init__(self):
pass
async def init(self):
pass
async def connected_cdp(self):
self.connections = {} # maps channel to task
async def new_device_session(self, vin):
pass
async def new_user_session(self, username, user_session):
pass
async def got_message(self, msg, send_func):
if 'origin' in msg and msg['origin'] == 'proxy':
channel = msg['channel']
if 'open' in msg:
if channel in self.connections:
log.error('{}: Request to open an already open connection.'.format(channel))
return
queue = asyncio.Queue()
queue.put_nowait(msg)
task = asyncio.create_task(_manage_connection(channel, queue, send_func))
self.connections[channel] = (task, queue)
elif 'close' in msg:
if channel not in self.connections:
log.error('{}: Request to close an unknown connection.'.format(channel))
return
task, queue = self.connections[channel]
del self.connections[channel]
task.cancel()
else:
if channel not in self.connections:
log.error('{}: Request to write to an unknown connection.'.format(channel))
return
task, queue = self.connections[channel]
queue.put_nowait(msg)
async def end_device_session(self, vin):
pass
async def end_user_session(self, username, user_session):
pass
async def disconnected_cdp(self):
for channel, (task, queue) in self.connections.items():
task.cancel()
self.connections = {}
async def _manage_connection(channel, queue, send_func):
reader = None
writer = None
read_task = None
n_read_bytes = 0
n_write_bytes = 0
try:
while True:
msg = await queue.get()
if 'open' in msg:
port = msg['open']
try:
reader, writer = await asyncio.wait_for(asyncio.open_connection('127.0.0.1', port), 1.0)
await send_func({
'type': 'proxy_send',
'channel': channel,
'data_b85': base64.b85encode(b'==local-connection-success==').decode('ascii'),
'target': 'server',
})
except (asyncio.TimeoutError, ConnectionRefusedError, OSError) as e:
await send_func({
'type': 'proxy_send',
'channel': channel,
'data_b85': base64.b85encode(b'==local-connection-failed==').decode('ascii'),
'close': True,
'target': 'server',
})
log.info('{}: Connection to port {} failed with error: {}'.format(channel, port, str(e)))
return
read_task = asyncio.create_task(_read(channel, reader, send_func))
log.info('{}: Opened connection.'.format(channel))
else:
buf = base64.b85decode(msg['data_b85'])
if buf != b'':
writer.write(buf)
else:
writer.write_eof()
await writer.drain()
n_write_bytes += len(buf)
except asyncio.CancelledError:
log.info('{}: Connection told to cancel/close.'.format(channel))
except:
log.error('{}: Unknown exception in in connection manager.'.format(channel))
traceback.print_exc(file=sys.stderr)
finally:
if writer is not None:
writer.close()
await writer.wait_closed()
log.info('{}: Writer closed.'.format(channel))
if read_task is not None:
read_task.cancel()
n_read_bytes = await read_task
log.info('{}: Read task canceled.'.format(channel))
log.info('{}: total bytes read: {} ; total bytes written: {}'.format(channel, n_read_bytes, n_write_bytes))
async def _read(channel, reader, send_func):
# NOTE: The process below is a little simplified. It assumes
# that we want to close the connection as soon as we see EOF on
# the reader. This isn't strictly correct. It's possible a TCP
# connection can write EOF but still expect to read data. We
# should revisit this in the future. For now, it works for all
# the application-layer protocols we care about (i.e. HTTP/Websockets).
n_read_bytes = 0
try:
while True:
buf = await reader.read(READ_BUF_SIZE)
n_read_bytes += len(buf)
extra = {'close': True} if buf == b'' else {}
await send_func({
'type': 'proxy_send',
'channel': channel,
'data_b85': base64.b85encode(buf).decode('ascii'),
'target': 'server',
**extra
})
if buf == b'':
log.info('{}: Read task saw EOF.'.format(channel))
break
except asyncio.CancelledError:
log.info('{}: Read task told to cancel.'.format(channel))
except:
log.error('{}: Unknown exception in in reader.'.format(channel))
traceback.print_exc(file=sys.stderr)
return n_read_bytes
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This is a simple process which monitors the battery and updates the console
with the current battery percentage.
"""
import asyncio
from auto.services.controller.client import CioRoot
from auto.services.console.client import CuiRoot
from auto.services.labs.rpc.client import LabsService
from auto import logger
log = logger.init(__name__, terminal=True)
def _gen_sample_sizes():
yield 3
while True:
yield 10
async def _display_forever(power, console, labs, buzzer):
for sample_size in _gen_sample_sizes():
samples = []
for _ in range(sample_size):
millivolts = await power.millivolts()
samples.append(millivolts)
await asyncio.sleep(3)
millivolts = sum(samples) / len(samples)
minutes, percentage = await power.estimate_remaining(millivolts)
state = await power.state()
await console.set_battery(state, minutes, percentage)
await labs.send({
'type': 'battery_state',
'state': state,
'minutes': minutes,
'percentage': percentage,
})
if percentage <= 5:
await console.write_text("Warning: Battery is LOW!\n\n")
if buzzer is not None:
await buzzer.play("EEE")
async def _check_shutdown_forever(power):
while True:
v = await power.should_shut_down()
if v:
for _ in range(5):
await asyncio.sleep(0.1)
v = await power.should_shut_down()
if not v:
break
else:
log.info('Off switch triggered; shutting down...')
await power.shut_down()
break
await asyncio.sleep(1)
async def run_forever():
controller = CioRoot()
console = CuiRoot()
labs = LabsService()
capabilities = await controller.init()
await console.init()
await labs.connect()
power = None
buzzer = None
try:
if 'Power' in capabilities:
power = await controller.acquire('Power')
else:
log.warning('No power component exists on this device; exiting...')
return
if 'Buzzer' in capabilities:
buzzer = await controller.acquire('Buzzer')
else:
pass # We can tolerate no buzzer.
log.info('RUNNING!')
await asyncio.gather(
_display_forever(power, console, labs, buzzer),
_check_shutdown_forever(power),
)
except asyncio.CancelledError:
log.info('Battery monitor is being canceled...')
finally:
if power is not None:
await controller.release(power)
power = None
if buzzer is not None:
await controller.release(buzzer)
buzzer = None
await controller.close()
await console.close()
await labs.close()
if __name__ == '__main__':
asyncio.run(run_forever())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module contains functions to run external script/programs. This module
assumes a certain setup of the system, but it tries to fail gracefully if the
system is not configured as expected.
**NOTE:** All paths here should be specified absolutely. Relative paths
can create vulnerabilities.
"""
import os
import re
import asyncio
from auto.services.scripts import SCRIPTS_DIRECTORY, run_script
async def set_hostname(name):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, _set_hostname, name)
async def update_libauto():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, _update_libauto)
def _set_hostname(name):
path = os.path.join(SCRIPTS_DIRECTORY, 'set_hostname')
name = re.sub(r'[^A-Za-z0-9]', '', name)
return run_script(path, name)
def _update_libauto():
path = os.path.join(SCRIPTS_DIRECTORY, 'update_libauto')
return run_script(path, timeout=20)
<file_sep>#!/bin/bash
if ! [ $(id -u) = 0 ]
then
echo "You must be root to use this script."
exit 1
fi
sync
# Change to the `libauto` directory.
scriptdir="$(dirname $(realpath "$0"))"
cd "$scriptdir"/../../../..
echo 'Starting in directory' $(pwd) 'as user' $(whoami)
# Make sure X is running.
while ! xset q &>/dev/null
do
echo 'Waiting for X Server ...'
sleep 0.3
done
# Disable screensaver and screen-off-power-savings.
xset -dpms
xset s off
# Run the startup demo program and play the boot video.
python3 auto/services/scripts/demos/demo_car.py &
DEMO_PID=$!
fbcp &
FBCP_PID=$!
omxplayer -b auto/resources/videos/boot_up_video.mp4
kill $FBCP_PID
wait $FBCP_PID || true
wait $DEMO_PID
# Run all migrations.
for migration in "$scriptdir"/rpi_b3_b4_migrations/*
do
"$migration"
done
# Run all the services.
exec python3 auto/services/run_all.py "$@"
<file_sep>###############################################################################
#
# Copyright (c) 2017-2023 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides a simple helper to use the buzzer.
"""
from auto.asyncio_tools import thread_safe
from auto.capabilities import list_caps, acquire
from auto.sleep import _physics_client
from auto import IS_VIRTUAL
@thread_safe
def buzz(notes):
"""
Play the given `notes` on the device's buzzer.
"""
global _BUZZER
try:
_BUZZER
except NameError:
caps = list_caps()
if 'Buzzer' not in caps:
raise AttributeError("This device does not have a buzzer.")
_BUZZER = acquire('Buzzer')
_BUZZER.play(notes)
_BUZZER.wait()
def honk(count=2):
"""
Make a car horn ("HONK") sound.
"""
MAX_HONKS = 5
count = min(MAX_HONKS, count)
if IS_VIRTUAL:
_physics_honk(count)
else:
for _ in range(count - 1):
buzz('!T95 O4 G#16 R16') # short honk
buzz('!T95 O4 G#4') # final long honk
def _physics_honk(count):
physics = _physics_client()
physics.control({
'type': 'honk',
'count': count,
})
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides an easy way to control the servos of your device. This
only works for standard "hobby style" servos which are controlled via PWM.
This module provides a fully **synchronous** interface.
"""
from auto.asyncio_tools import thread_safe
from auto.capabilities import list_caps, acquire
import time
@thread_safe
def get_servo(servo_index, frequency=50, min_duty=0.025, max_duty=0.125):
"""
Acquire the interface to the servo at index `servo_index`.
The first servo is at index 0.
"""
global _PWMs
try:
_PWMs
except NameError:
caps = list_caps()
if 'PWMs' not in caps:
raise AttributeError("This device does not have a PWM controller.")
_PWMs = acquire('PWMs')
n_pins = _PWMs.num_pins()
if servo_index < 0 or servo_index >= n_pins:
raise Exception("Invalid servo index given: {}. This device has servos 0 through {}".format(servo_index, n_pins-1))
return _ServoTemplate(
_PWMs,
servo_index,
frequency,
min_duty,
max_duty
)
class _ServoTemplate:
def __init__(self, pwms, pin_index, frequency, min_duty, max_duty):
self._pwms = pwms
self._pin_index = pin_index
self._frequency = frequency
self._min_duty = min_duty
self._max_duty = max_duty
self._is_on = False
def on(self):
"""
Enable power to the servo!
"""
if not self._is_on:
self._pwms.enable(self._pin_index, self._frequency)
self._is_on = True
def off(self):
"""
Disable power from the servo!"
"""
if self._is_on:
self._pwms.disable(self._pin_index)
self._is_on = False
def go(self, position):
"""
Set the `position` of the servo in the range [0, 180].
These `position` roughly corresponds to the angle of the servo.
You may pass an integer or a float to the `position` parameter.
"""
if self._is_on:
val = min(180.0, position)
val = max(0.0, position)
val = (val / 180.0) * (self._max_duty - self._min_duty) + self._min_duty
val = val * 100.0
self._pwms.set_duty(self._pin_index, val)
else:
raise Exception("You must turn the servo on by calling the `on()` method before you can tell the servo to `go()`!")
def wait(self, seconds):
"""
Pause and wait for `seconds` seconds.
You may pass an integer or a float to the `seconds` parameter.
"""
time.sleep(seconds)
def go_then_wait(self, position, seconds):
"""
First set the servo's position to the `position` value,
then wait `seconds` seconds.
See the `go()` method for a description of the `position` parameter.
See the `wait()` method for a description of the `seconds` parameter.
"""
self.go(position)
self.wait(seconds)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2022 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides easy helper functions which abstract the behavior of
the car to a very high level. These functions are intended to be used by
beginners. All of the functionality in these helper functions can be
recreated using lower-level abstractions provided by the other modules of
libauto.
These helper functions, when invoked, each print info about what they are
doing. Normally a library should _not_ print anything, but we make an
exception for these functions because they are intended to be used by
beginners who are new to programming, and the printouts are helpful for
the beginners to see what is happening. The other modules of libauto
do not print.
"""
from auto import print_all as print # override the build-in `print()`
from auto import _ctx_print_all
from auto import IS_VIRTUAL
from auto.sleep import sleep as auto_sleep
def forward(sec=None, cm=None, verbose=True):
"""
Drive the car forward for `sec` seconds or `cm` centimeters (passing in both
will raise an error). If neither is passed in, the car will drive for 1 second.
"""
from car import motors
if sec is not None and cm is not None:
_ctx_print_all("Error: Please specify duration (sec) OR distance (cm) - not both.")
return
if sec is None and cm is None:
sec = 1.0
if sec is not None:
if sec > 5.0:
_ctx_print_all("Error: The duration (sec) exceeds 5 seconds; will reset to 5 seconds.")
sec = 5.0
if sec <= 0.0:
return
if verbose:
_ctx_print_all("Driving forward for {} seconds.".format(sec))
if cm is not None:
if cm > 300.0:
_ctx_print_all("Error: The distance (cm) exceeds 300 cm (~10 feet); will reset to 300 cm.")
cm = 300.0
if cm <= 0.0:
return
if verbose:
_ctx_print_all("Driving forward for {} centimeters.".format(cm))
motors.straight(motors.safe_forward_throttle(), sec, cm)
def reverse(sec=None, cm=None, verbose=True):
"""
Drive the car in reverse for `sec` seconds or `cm` centimeters (passing in both
will raise an error). If neither is passed in, the car will drive for 1 second.
"""
from car import motors
if sec is not None and cm is not None:
_ctx_print_all("Error: Please specify duration (sec) OR distance (cm) - not both.")
return
if sec is None and cm is None:
sec = 1.0
if sec is not None:
if sec > 5.0:
_ctx_print_all("Error: The duration (sec) exceeds 5 seconds; will reset to 5 seconds.")
sec = 5.0
if sec <= 0.0:
return
if verbose:
_ctx_print_all("Driving in reverse for {} seconds.".format(sec))
if cm is not None:
if cm > 300.0:
_ctx_print_all("Error: The distance (cm) exceeds 300 cm (~10 feet); will reset to 300 cm.")
cm = 300.0
if cm <= 0.0:
return
if verbose:
_ctx_print_all("Driving in reverse for {} centimeters.".format(cm))
motors.straight(motors.safe_reverse_throttle(), sec, cm)
def left(sec=None, deg=None, verbose=True):
"""
Drive the car forward and left for `sec` seconds or `deg` degrees (passing in both
will raise an error). If neither is passed in, the car will drive for 1 second.
"""
from car import motors
if sec is not None and deg is not None:
_ctx_print_all("Error: Please specify duration (sec) OR degrees (deg) - not both.")
return
if sec is None and deg is None:
sec = 1.0
if sec is not None:
if sec > 5.0:
_ctx_print_all("Error: The duration (sec) exceeds 5 seconds; will reset to 5 seconds.")
sec = 5.0
if sec <= 0.0:
return
if verbose:
_ctx_print_all("Driving left for {} seconds.".format(sec))
if deg is not None:
if deg > 360.0:
_ctx_print_all("Error: The degrees (deg) exceeds 360; will reset to 360.")
deg = 360.0
if deg <= 0.0:
return
if verbose:
_ctx_print_all("Driving left for {} degrees.".format(deg))
motors.drive(45.0, motors.safe_forward_throttle(), sec, deg)
def right(sec=None, deg=None, verbose=True):
"""
Drive the car forwad and right for `sec` seconds or `deg` degrees (passing in both
will raise an error). If neither is passed in, the car will drive for 1 second.
"""
from car import motors
if sec is not None and deg is not None:
_ctx_print_all("Error: Please specify duration (sec) OR degrees (deg) - not both.")
return
if sec is None and deg is None:
sec = 1.0
if sec is not None:
if sec > 5.0:
_ctx_print_all("Error: The duration (sec) exceeds 5 seconds; will reset to 5 seconds.")
sec = 5.0
if sec <= 0.0:
return
if verbose:
_ctx_print_all("Driving right for {} seconds.".format(sec))
if deg is not None:
if deg > 360.0:
_ctx_print_all("Error: The degrees (deg) exceeds 360; will reset to 360.")
deg = 360.0
if deg <= 0.0:
return
if verbose:
_ctx_print_all("Driving right for {} degrees.".format(deg))
motors.drive(-45.0, motors.safe_forward_throttle(), sec, deg)
def pause(sec=1.0, verbose=True):
"""
Pause the car's code for `sec` seconds.
"""
if verbose:
_ctx_print_all("Pausing for {} seconds.".format(sec))
auto_sleep(sec)
def drive_to(x, z, verbose=True, throttle_factor=0.5):
"""
For virtual cars, drives the car to the given (x, z) location in the
virtual world.
"""
from car import nav
from car import motors
if verbose:
_ctx_print_all("Driving to point ({}, {})".format(x, z))
throttle = motors.safe_forward_throttle() * throttle_factor
motors.set_throttle(throttle)
nav.drive_to(x, z)
motors.set_throttle(0.0)
def drive_route(
checkpoints,
verbose=True,
throttle_factor=0.5,
num_laps=1,
background=False,
):
"""
For virtual cars, drives the car to each of the locations in the given
list of `checkpoints`.
"""
def inner():
from car import nav
from car import motors
throttle = motors.safe_forward_throttle() * throttle_factor
motors.set_throttle(throttle)
for lap_index in range(num_laps):
if verbose and num_laps > 1:
_ctx_print_all("Starting lap #{}".format(lap_index + 1))
for x, z in checkpoints:
if verbose:
_ctx_print_all("Driving to point ({}, {})".format(x, z))
nav.drive_to(x, z)
motors.set_throttle(0.0)
if background:
from threading import Thread
thread = Thread(target=inner, daemon=False)
thread.start()
else:
inner()
def recon_cars(theta_1=0, theta_2=360, slice_size=8, max_distance=10000, verbose=True):
"""
This function does "reconnaissance" to find enemy cars.
Its implementation does a naive linear search pattern, which is
suboptimal!
If you can find a better search pattern (and directly use the
underlying "Recon" sensor), then you can outperform anyone who is
using *this* function.
Upon finding *any* enemy, this function halts and returns the
approximate angle to that first-found enemy. It returns `None`
if no enemy was found.
"""
if verbose:
_ctx_print_all(f"Querying the Recon sensor in range: [{theta_1}°, {theta_2}°]...")
from car import recon_weapons
return recon_weapons.naive_recon(theta_1, theta_2, slice_size, max_distance)
def throw_ball(theta=0, velocity=18, verbose=True):
"""
Throw a ball in the direction of `theta` and with `velocity`.
"""
if theta is None:
if verbose:
_ctx_print_all(f"Cannot throw ball when `theta = None`...")
return
if verbose:
_ctx_print_all(f"Throwing a ball at {theta:.1f}° with velocity {velocity}...")
from car import recon_weapons
return recon_weapons.throw_ball(theta, velocity)
def capture(num_frames=1, verbose=True):
"""
Capture `num_frames` frames from the car's camera and return
them as a numpy ndarray.
"""
MAX_FRAMES = 4
if num_frames > MAX_FRAMES:
_ctx_print_all(f"Warning: You may capture at most {MAX_FRAMES} frames with this function.")
num_frames = MAX_FRAMES
from auto import camera
return camera.capture(num_frames, verbose)
def plot(frames, also_stream=True, verbose=True):
"""
Stitch together the given `frames` (a numpy nd-array) into a single nd-array.
If running in a notebook then the PIL image will be returned (and displayed).
This function by default also streams the image to your `labs` account.
The `frames` parameter must be a numpy ndarray with one of the
following shapes:
- (n, h, w, 3) meaning `n` 3-channel RGB images of size `w`x`h`
- (n, h, w, 1) meaning `n` 1-channel gray images of size `w`x`h`
- (h, w, 3) meaning a single 3-channel RGB image of size `w`x`h`
- (h, w, 1) meaning a single 1-channel gray image of size `w`x`h`
- (h, w) meaning a single 1-channel gray image of size `w`x`h`
"""
from auto import frame_streamer
return frame_streamer.plot(frames, also_stream, verbose)
def stream(frame, to_console=True, to_labs=False, verbose=True):
"""
Stream the given `frame` (a numpy ndarray) to your car's
console _and_ (optionally) to your `labs` account to be shown
in your browser.
The `frame` parameter must be a numpy ndarray with one of the
following shapes:
- (h, w, 3) meaning a single 3-channel RGB image of size `w`x`h`
- (h, w, 1) meaning a single 1-channel gray image of size `w`x`h`
- (h, w) meaning a single 1-channel gray image of size `w`x`h`
"""
from auto import frame_streamer
return frame_streamer.stream(frame, to_console, to_labs, verbose)
def classify_color(frame, annotate=True, verbose=True):
"""
Classify the center region of `frame` as having either primarily "red",
"yellow", or "green, or none of those ("background").
The `frame` parameter must be a numpy array containing an RGB image.
Returns a string representing the color found in the center of the
image, one of "red", "yellow", "green", or "background".
"""
global COLORCLASSIFIER
try: COLORCLASSIFIER
except NameError:
from auto.models import ColorClassifier
COLORCLASSIFIER = ColorClassifier()
if verbose:
_ctx_print_all("Instantiated a ColorClassifier object!")
p1, p2, classific = COLORCLASSIFIER.classify(frame, annotate=annotate)
if verbose:
_ctx_print_all("Classified color as '{}'.".format(classific))
return classific
def detect_faces(frame, annotate=True, verbose=True):
"""
Detect faces inside of `frame`, and annotate each face.
The `frame` parameter must be an image as a numpy array either containing
3-channel RGB values _or_ 1-channel gray values.
Returns a list of rectangles, where each rectangle is a 4-tuple of:
(x, y, width, height)
"""
global FACEDETECTOR
try: FACEDETECTOR
except NameError:
from auto.models import FaceDetector
FACEDETECTOR = FaceDetector()
if verbose:
_ctx_print_all("Instantiated a FaceDetector object!")
faces = FACEDETECTOR.detect(frame, annotate=annotate)
n = len(faces)
if verbose:
_ctx_print_all("Found {} face{}.".format(n, 's' if n != 1 else ''))
return faces
def detect_stop_signs(frame, annotate=True, verbose=True):
"""
Detect stop signs inside of `frame`, and annotate each stop sign.
The `frame` parameter must be an image as a numpy array either containing
3-channel RGB values _or_ 1-channel gray values.
Returns a list of rectangles, where each rectangle is a 4-tuple of:
(x, y, width, height)
"""
global STOPSIGNDETECTOR
try: STOPSIGNDETECTOR
except NameError:
from auto.models import StopSignDetector
STOPSIGNDETECTOR = StopSignDetector()
if verbose:
_ctx_print_all("Instantiated a StopSignDetector object!")
rects = STOPSIGNDETECTOR.detect(frame, annotate=annotate)
n = len(rects)
if verbose:
_ctx_print_all("Found {} stop sign{}.".format(n, 's' if n != 1 else ''))
return rects
def detect_pedestrians(frame, annotate=True, verbose=True):
"""
Detect pedestrians inside of `frame`, and annotate each pedestrian.
The `frame` parameter must be an image as a numpy array either containing
3-channel RGB values _or_ 1-channel gray values.
Returns a list of rectangles, where each rectangle is a 4-tuple of:
(x, y, width, height)
"""
global PEDESTRIANDETECTOR
try: PEDESTRIANDETECTOR
except NameError:
from auto.models import PedestrianDetector
if IS_VIRTUAL:
PEDESTRIANDETECTOR = PedestrianDetector(hitThreshold=-1.5)
else:
PEDESTRIANDETECTOR = PedestrianDetector()
if verbose:
_ctx_print_all("Instantiated a PedestrianDetector object!")
rects = PEDESTRIANDETECTOR.detect(frame, annotate=annotate)
n = len(rects)
if verbose:
_ctx_print_all("Found {} pedestrian{}.".format(n, 's' if n != 1 else ''))
return rects
def object_location(object_list, frame_shape, verbose=True):
"""
Calculate the location of the largest object in `object_list`.
Returns one of: 'frame_left', 'frame_right', 'frame_center', None
"""
if not object_list:
if verbose:
_ctx_print_all("Object location is None.")
return None
import numpy as np
areas = [w*h for x, y, w, h in object_list]
i = np.argmax(areas)
nearest = object_list[i]
x, y, w, h = nearest
x_center = x + w/2.
if x_center < frame_shape[1]/3.:
location = 'frame_left'
elif x_center < 2*frame_shape[1]/3.:
location = 'frame_center'
else:
location = 'frame_right'
if verbose:
_ctx_print_all("Object location is '{}'.".format(location))
return location
def object_size(object_list, frame_shape, verbose=True):
"""
Calculate the ratio of the nearest object's area to the frame's area.
"""
if not object_list:
if verbose:
_ctx_print_all("Object area is 0.")
return 0.0
areas = [w*h for x, y, w, h in object_list]
ratio = max(areas) / (frame_shape[0] * frame_shape[1])
if verbose:
_ctx_print_all("Object area is {}.".format(ratio))
return ratio
def buzz(notes):
"""
Play the given `notes` on the device's buzzer.
"""
from car import buzzer
buzzer.buzz(notes)
def honk(count=2):
"""
Make a car horn ("HONK") sound.
"""
from car import buzzer
buzzer.honk(count)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from .easyi2c import (write_read_i2c_with_integrity,
i2c_retry)
from . import N_I2C_TRIES
class Timer1PWM:
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def set_top(self, value):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00, (value & 0xFF), ((value >> 8) & 0xFF)], 1)
if status != 7:
raise Exception("failed to set_top")
@i2c_retry(N_I2C_TRIES)
async def set_ocr_a(self, value):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, (value & 0xFF), ((value >> 8) & 0xFF)], 1)
if status != 7:
raise Exception("failed to set_ocr_a")
@i2c_retry(N_I2C_TRIES)
async def enable_a(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
if status != 7:
raise Exception("failed to enable_a")
@i2c_retry(N_I2C_TRIES)
async def disable_a(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 7:
raise Exception("failed to disable_a")
@i2c_retry(N_I2C_TRIES)
async def set_ocr_b(self, value):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x04, (value & 0xFF), ((value >> 8) & 0xFF)], 1)
if status != 7:
raise Exception("failed to set_ocr_b")
@i2c_retry(N_I2C_TRIES)
async def enable_b(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x05], 1)
if status != 7:
raise Exception("failed to enable_b")
@i2c_retry(N_I2C_TRIES)
async def disable_b(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x06], 1)
if status != 7:
raise Exception("failed to disable_b")
@i2c_retry(N_I2C_TRIES)
async def set_ocr_c(self, value):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x07, (value & 0xFF), ((value >> 8) & 0xFF)], 1)
if status != 7:
raise Exception("failed to set_ocr_c")
@i2c_retry(N_I2C_TRIES)
async def enable_c(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x08], 1)
if status != 7:
raise Exception("failed to enable_c")
@i2c_retry(N_I2C_TRIES)
async def disable_c(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x09], 1)
if status != 7:
raise Exception("failed to disable_c")
@i2c_retry(N_I2C_TRIES)
async def enable(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x0a], 1)
if status != 7:
raise Exception("failed to enable")
@i2c_retry(N_I2C_TRIES)
async def disable(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x0b], 1)
if status != 7:
raise Exception("failed to disable")
class Timer3PWM:
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.min_ocr = 0
self.max_ocr = 20000
@i2c_retry(N_I2C_TRIES)
async def set_top(self, value):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00, (value & 0xFF), ((value >> 8) & 0xFF)], 1)
if status != 8:
raise Exception("failed to set_top")
@i2c_retry(N_I2C_TRIES)
async def set_ocr(self, value):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, (value & 0xFF), ((value >> 8) & 0xFF)], 1)
if status != 8:
raise Exception("failed to set_ocr")
@i2c_retry(N_I2C_TRIES)
async def enable(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
if status != 8:
raise Exception("failed to enable")
@i2c_retry(N_I2C_TRIES)
async def disable(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 8:
raise Exception("failed to disable")
async def set_range(self, min_ocr, max_ocr):
self.min_ocr = min_ocr
self.max_ocr = max_ocr
async def set_pct(self, pct=0.5):
pct = max(min(pct, 1.0), 0.0)
value = int(round((self.max_ocr - self.min_ocr) * pct + self.min_ocr))
await self.set_ocr(value)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains the interface to AutoAuto v1 microcontroller which we
communicate with via I2C from this host.
"""
"""
In my tests, it seems that the I2C bus will fail ~1/200 times. We can
detect those failures with high probability due to our integrity checks
which we use for all I2C messages, so that's good. Furthermore, we have
a method for automatically retrying failed I2C transactions! In fact, if
we take the 1/200 failure rate as a given, then by retrying up to 5 times
(total, meaning 1 attempt and 4 retries) and assuming independence, we
conclude that we will only see a failure:
(1/200)**5 = 1/320000000000
Thus, if we do 300 transactions per second, we'll see, on average, one
failure every ~34 years. Someone check my math.
"""
N_I2C_TRIES = 10
"""
For this particular controller, we talk to it via I2C.
"""
CONTROLLER_I2C_SLAVE_ADDRESS = 0x14
import asyncio
from . import capabilities
from . import easyi2c
from . import reset
import cio
from auto.services.labs.settings import load_settings
class CioRoot(cio.CioRoot):
"""
This is the CIO root interface for the AutoAuto v1.x microcontrollers.
"""
def __init__(self):
self.fd = None
self.caps = None
self.lock = asyncio.Lock()
self.capability_ref_count = {}
async def init(self):
"""
Attempt to initialize the version 1.x AutoAuto controller. Return a list
of capabilities if initialization worked, else raise an exception.
"""
async with self.lock:
if self.fd is not None:
return
try:
self.fd = await easyi2c.open_i2c(1, CONTROLLER_I2C_SLAVE_ADDRESS)
self.caps = await capabilities.get_capabilities(self.fd, soft_reset_first=True)
for component_name, config in self.caps.items():
if config['is_enabled']:
# This component is enabled by default, so make sure it stays enabled!
# We'll do this by starting its ref count at 1, so it will never go
# to zero -- it's as if the controller itself holds one reference.
self.capability_ref_count[component_name] = 1
if 'VersionInfo' not in self.caps:
raise Exception('Controller does not implement the required VersionInfo component.')
version_info = await capabilities.acquire_component_interface(self.fd, self.caps, self.capability_ref_count, 'VersionInfo')
major, minor = await version_info.version()
await capabilities.release_component_interface(self.capability_ref_count, version_info)
if major != 1:
raise Exception('Controller is not version 1, thus this interface will not work.')
self.caps['Camera'] = {
'register_number': None, # <-- this is a virtual component; it is implemented on the Python side, not the controller side
'is_enabled': False
}
if 'CarMotors' in self.caps:
reg_num_car_motors = self.caps['CarMotors']['register_number']
reg_num_gyro_accum = self.caps.get('Gyroscope_accum', {}).get('register_number', None)
reg_num_pid_steering = self.caps.get('PID_steering', {}).get('register_number', None)
self.caps['CarControl'] = {
'register_number': (reg_num_car_motors, reg_num_gyro_accum, reg_num_pid_steering),
'is_enabled': False,
}
except:
if self.fd is not None:
await easyi2c.close_i2c(self.fd)
self.fd = None
self.caps = None
self.capability_ref_count = {}
raise
settings = load_settings()
if isinstance(settings, dict) and 'cio' in settings:
cio_settings = settings['cio']
if isinstance(cio_settings, dict) and 'disabled' in cio_settings:
cio_disabled = cio_settings['disabled']
if isinstance(cio_disabled, list):
for disabled_component_name in cio_disabled:
if disabled_component_name in self.caps:
del self.caps[disabled_component_name]
return list(self.caps.keys())
async def acquire(self, capability_id):
"""
Acquire the interface to the component with the given `capability_id`, and return
a concrete object implementing its interface.
"""
async with self.lock:
return await capabilities.acquire_component_interface(self.fd, self.caps, self.capability_ref_count, capability_id)
async def release(self, capability_obj):
"""
Release a previously acquired capability interface. You must pass
the exact object returned by `acquire()`.
"""
async with self.lock:
await capabilities.release_component_interface(self.capability_ref_count, capability_obj)
async def close(self):
"""
Close the connection and reset the controller, thereby invalidating and releasing all acquired components.
"""
async with self.lock:
if self.fd is None:
return
await reset.soft_reset(self.fd)
await easyi2c.close_i2c(self.fd)
self.fd = None
self.caps = None
self.capability_ref_count = {}
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides a `pack` and an `unpack` function which will be used
by the RPC system.
"""
USE_JSON = False
if USE_JSON:
import json
def pack(obj):
buf = json.dumps(obj)
return buf
def unpack(buf):
obj = json.loads(buf)
return obj
else:
import msgpack
def pack(obj):
buf = msgpack.packb(obj, use_bin_type=True)
return buf
def unpack(buf):
obj = msgpack.unpackb(buf, use_list=False, raw=False)
return obj
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides a simple way to read QR codes from an image!
This is a **synchronous** interface.
"""
from zbarlight._zbarlight import Symbologies, zbar_code_scanner
import numpy as np
import cv2
def qr_scan(frame, multi=False):
"""
Scan the `frame` for QR codes. If a QR code is found, return
its data as a string; else, return `None`.
When `multi=True`, this function will return a *list* of
QR code data (allowing you to detect multiple QR codes
within a single frame). In this case, when no QR codes are
found, an empty list will be returned.
"""
# Get a gray image of the proper shape:
if frame.dtype != np.uint8:
raise Exception("invalid dtype: {}".format(frame.dtype))
if frame.ndim == 3:
if frame.shape[2] == 3:
frame_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
elif frame.shape[2] == 1:
frame_gray = np.squeeze(frame, axis=(2,))
else:
raise Exception("invalid number of color channels")
elif frame.ndim == 2:
frame_gray = frame
else:
raise Exception("invalid frame.ndim")
"""
Note: Zbarlight wants you to give it a PIL image, but here at Master AI we
are cooler and we deal with straight-up numpy arrays! So, the function
below reaches further into Zbarlight to use a lower-level interface
so that we can process raw numpy arrays.
"""
height, width = frame_gray.shape
raw = frame_gray.tobytes()
assert(len(raw) == width*height) # sanity
symbologie = Symbologies.get('QRCODE')
found = zbar_code_scanner([symbologie], raw, width, height)
if found is None:
found = []
found = [buff.decode('utf-8') for buff in found]
if multi:
return found
else:
return found[0] if found else None
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This RPC server provides the standard CUI interface, allowing multiple
processes to share the CUI resources.
"""
from auto.rpc.server import serve
import cui
from cui.known_impls import known_impls
import os
import asyncio
import inspect
import importlib
from auto import logger
log = logger.init(__name__, terminal=True)
async def _safe_invoke(func, *args):
if asyncio.iscoroutinefunction(func):
return await func(*args)
else:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, func, *args)
async def _get_cui_implementation():
fixed_impl = os.environ.get('MAI_CUI_IMPLEMENTATION', None)
if fixed_impl is not None:
list_of_impls = [fixed_impl]
log.info('Environment specifies cui implementation: {}'.format(fixed_impl))
else:
list_of_impls = known_impls
log.info('Environment does not specify cui implementation, using known list: {}'.format(known_impls))
for impl in list_of_impls:
impl_module = importlib.import_module(impl)
impl_classes = inspect.getmembers(impl_module, predicate=inspect.isclass)
cui_root_class_types = []
for class_name, class_type in impl_classes:
superclass_type = inspect.getmro(class_type)[1] # first superclass
if superclass_type is cui.CuiRoot:
cui_root_class_types.append(class_type)
if len(cui_root_class_types) == 0:
log.error('Failed to find cui.CuiRoot implementation in module: {}'.format(impl))
continue
if len(cui_root_class_types) > 1:
log.warn('There are more than one cui.CuiRoot implementation in module: {}'.format(impl))
for cui_root_class_type in cui_root_class_types:
cui_root = cui_root_class_type()
try:
log.info('Will attempt to initialize cui implementation: {} from module: {}'.format(type(cui_root), impl))
result = await _safe_invoke(cui_root.init)
log.info('Successfully initialized cui implementation: {} from module: {}'.format(type(cui_root), impl))
return cui_root, result
except Exception as e:
log.info('Failed to initialize cui implementation: {} from module: {}; error: {}'.format(type(cui_root), impl, e))
return None, None
async def init():
cui_root, _ = await _get_cui_implementation()
if cui_root is None:
log.error('Failed to find cui implementation, quitting...')
return
whitelist_method_names = tuple([method_name for method_name, method_ref in inspect.getmembers(cui.CuiRoot, predicate=inspect.isfunction)])
def root_factory():
return cui_root, whitelist_method_names
pubsub_iface = None
server = await serve(root_factory, pubsub_iface, '127.0.0.1', 7003)
log.info("RUNNING!")
return server
if __name__ == '__main__':
loop = asyncio.get_event_loop()
server = loop.run_until_complete(init())
if server is not None:
loop.run_forever()
<file_sep>#!/bin/bash
if ! [ $(id -u) = 0 ]
then
echo "You must be root to use this script."
exit 1
fi
if [ -z "$1" ]
then
echo "No name on command line."
exit 1
fi
NAME="$1"
NAME="${NAME//[^A-Za-z0-9]/}"
echo "$NAME"
if [ $(hostname) = "$NAME" ]
then
echo 'ALREADY EQUAL'
exit
fi
# This change makes it permanent, but you have to reboot for it to take effect.
echo "$NAME" > /etc/hostname
sed -i '/^.*set_hostname.*$/d' /etc/hosts
echo "127.0.1.1 " "$NAME" " ### Set by set_hostname" >> /etc/hosts
# This will change it slightly more immediately, but you still need to log out and in to see the change.
hostname "$NAME"
exit $!
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
accel = await c.acquire('Accelerometer')
for i in range(100):
print(await accel.read())
await asyncio.sleep(0.05)
await c.release(accel)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This client connects to the CUI RPC server. This is an **asynchronous** client.
"""
import asyncio
from auto.rpc.client import client
import cui
class CuiRoot(cui.CuiRoot):
def __init__(self, inet_addr='127.0.0.1', inet_port=7003):
self.proxy_interface = None
self.inet_addr = inet_addr
self.inet_port = inet_port
async def init(self):
if self.proxy_interface is None:
self.proxy_interface, pubsub_channels, subscribe_func, self._close = \
await client(self.inet_addr, self.inet_port)
return True
async def write_text(self, text):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.write_text(text)
async def clear_text(self):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.clear_text()
async def big_image(self, image_id):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.big_image(image_id)
async def big_status(self, status):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.big_status(status)
async def big_clear(self):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.big_clear()
async def stream_image(self, rect_vals, shape, image_buf):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.stream_image(rect_vals, shape, image_buf)
async def clear_image(self):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.clear_image()
async def set_battery(self, state, minutes, percentage):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
return await self.proxy_interface.set_battery(state, minutes, percentage)
async def close(self):
# Don't call `close()` on the actual `proxy_interface`, because that in turn
# will call close on the underlying `cui_root` object, which will shut down
# the console. We don't want that because we're treating the console as a shared
# resource and we need it to stay open. Instead, we just close our RPC connection
# to the RPC server to clean up the resources we're responsible for.
if self.proxy_interface is not None:
await self._close()
self.proxy_interface = None
async def _run():
cui_root = CuiRoot()
await cui_root.init()
await cui_root.write_text('Hi!')
await asyncio.sleep(3)
await cui_root.close()
if __name__ == '__main__':
asyncio.run(_run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This client connects to the CIO RPC server. This is a **synchronous** client.
"""
import asyncio
from auto.asyncio_tools import wrap_async_to_sync
from auto.services.controller.client import CioRoot as CioRoot_async
import cio
class CioRoot(cio.CioRoot):
def __init__(self, loop, inet_addr='127.0.0.1', inet_port=7002):
self.cio_root = CioRoot_async(inet_addr, inet_port)
self.loop = loop
def init(self):
future = asyncio.run_coroutine_threadsafe(self.cio_root.init(), self.loop)
return future.result()
def acquire(self, capability_id):
future = asyncio.run_coroutine_threadsafe(self.cio_root.acquire(capability_id), self.loop)
capability_obj = future.result()
wrapped_capability_obj = wrap_async_to_sync(capability_obj, self.loop)
wrapped_capability_obj._original_capability_obj = capability_obj
return wrapped_capability_obj
def release(self, capability_obj):
wrapped_capability_obj = capability_obj
capability_obj = wrapped_capability_obj._original_capability_obj
future = asyncio.run_coroutine_threadsafe(self.cio_root.release(capability_obj), self.loop)
return future.result()
def close(self):
future = asyncio.run_coroutine_threadsafe(self.cio_root.close(), self.loop)
return future.result()
def _run():
from threading import Thread
loop = asyncio.new_event_loop()
def _run_event_loop():
asyncio.set_event_loop(loop)
loop.run_forever()
loop_thread = Thread(target=_run_event_loop)
loop_thread.start()
cio_root = CioRoot(loop)
caps = cio_root.init()
print(caps)
version_iface = cio_root.acquire('VersionInfo')
print(version_iface)
print(version_iface.version())
print(version_iface.name())
buzzer_iface = cio_root.acquire('Buzzer')
print(buzzer_iface)
buzzer_iface.play('!T240 L8 V8 agafaea dac+adaea fa<aa<bac#a dac#adaea f4') # "Bach's fugue in D-minor"
led_iface = cio_root.acquire('LEDs')
led_iface.set_mode('spin')
print(led_iface)
buzzer_iface.wait()
cio_root.release(buzzer_iface)
cio_root.release(version_iface)
cio_root.release(led_iface)
cio_root.close()
async def _stop_loop():
loop.stop()
asyncio.run_coroutine_threadsafe(_stop_loop(), loop)
loop_thread.join()
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
if __name__ == '__main__':
_run()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v2 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
power = await c.acquire('Power')
for i in range(1000):
mv = await power.millivolts()
mi = await power.estimate_remaining()
sd = await power.should_shut_down()
print(mv, mi, sd)
await asyncio.sleep(0.1)
await c.release(power)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2021 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import time
import numpy as np
import cio.aa_controller_v3 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
camera = await c.acquire('Camera')
prev_time = time.time()
for i in range(10):
buf, shape = await camera.capture()
frame = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
time_now = time.time()
print(time_now - prev_time, frame.shape)
prev_time = time_now
await c.release(camera)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
b = await c.acquire('PushButtons')
print('There are', await b.num_buttons(), 'buttons.')
bi, action = await b.wait_for_action('released')
print("Button", bi, "was", action)
while True:
event = await b.wait_for_event()
pprint(event)
await c.release(b)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v2 as controller
from cio.aa_controller_v2.capabilities import eeprom_store, eeprom_query
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
fd = c.fd
await eeprom_store(fd, 0xA0, b'0000')
buf = await eeprom_query(fd, 0xA0, 4)
print(buf)
assert buf == b'0000'
await eeprom_store(fd, 0xA0, b'1234')
buf = await eeprom_query(fd, 0xA1, 3)
print(buf)
assert buf == b'234'
buf = await eeprom_query(fd, 0xA2, 2)
print(buf)
assert buf == b'34'
buf = await eeprom_query(fd, 0xA3, 1)
print(buf)
assert buf == b'4'
buf = await eeprom_query(fd, 0xA0, 4)
print(buf)
assert buf == b'1234'
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package code for studying (and using) the battery discharge curve.
"""
def battery_map_millivolts_to_percentage(millivolts_single_point):
# TODO
return 51
<file_sep>import os
import json
SETTINGS_PATH = os.environ.get('MAI_LABS_SETTINGS_PATH', '/var/lib/libauto/labs_settings.dict')
def load_settings():
try:
with open(SETTINGS_PATH, 'rt') as f:
curr_settings = json.loads(f.read())
return curr_settings
except:
# Something went wrong, don't care what...
return {}
def save_settings(settings):
"""
Saves the settings.
Returns True if the settings *changed*.
Returns False if the settings are the same.
"""
curr_settings = load_settings()
did_change = (curr_settings != settings)
if did_change:
os.makedirs(os.path.dirname(SETTINGS_PATH), exist_ok=True)
with open (SETTINGS_PATH, 'wt') as f:
f.write(json.dumps(settings))
return did_change
<file_sep>###############################################################################
#
# Copyright (c) 2017-2023 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides simplified implementations of the Recon sensor
and the Weapons system.
This only works on virtual cars!
"""
from auto.asyncio_tools import thread_safe
from auto.capabilities import list_caps, acquire
from auto import IS_VIRTUAL
def naive_recon(theta_1, theta_2, slice_size, max_distance):
"""
Naive linear search using the Recon sensor.
It returns the angle of the *first* enemy that is
found. It returns `None` if no enemy was found.
"""
if not IS_VIRTUAL:
raise NotImplemented('This function only work on virtual cars.')
recon = _get_recon()
theta_1, theta_2 = min(theta_1, theta_2), max(theta_1, theta_2)
for a in range(theta_1, theta_2 - slice_size + 1, slice_size):
vins = recon.query(a, a + slice_size, max_distance)
if vins:
return (a + a + slice_size) / 2
def throw_ball(theta, velocity):
"""
Simple weapons function.
"""
if not IS_VIRTUAL:
raise NotImplemented('This function only work on virtual cars.')
weapons = _get_weapons()
weapons.fire(theta=theta, phi=90, velocity=velocity)
@thread_safe
def _get_recon():
global _RECON
try:
_RECON
except NameError:
caps = list_caps()
if 'Recon' not in caps:
raise AttributeError('This device has no Recon sensor!')
_RECON = acquire('Recon')
return _RECON
@thread_safe
def _get_weapons():
global _WEAPONS
try:
_WEAPONS
except NameError:
caps = list_caps()
if 'Weapons' not in caps:
raise AttributeError('This device has no Weapons system!')
_WEAPONS = acquire('Weapons')
return _WEAPONS
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This script runs all the services in one process.
"""
from auto.services.controller.server import init as controller_init
from auto.services.console.server import init as console_init
from auto.services.labs.labs import init_and_create_forever_task as labs_init_and_create_forever_task
from auto.services.battery.monitor import run_forever as battery_run_forever
from auto.services.calibration.monitor import run_forever as calibration_monitor_run_forever
from auto.services.wifi.monitor import run_forever as wifi_run_forever
from auto.services.jupyter.run import run_jupyter_in_background
import os
import sys
import asyncio
async def init_all(system_up_user, system_priv_user):
# Controller Service
cio_server = await controller_init()
# Console Service
cui_server = await console_init()
# Labs Service
labs_forever_task = await labs_init_and_create_forever_task(system_up_user)
# Battery Monitor
battery_task = asyncio.create_task(battery_run_forever())
# Calibration Monitor
calibration_monitor_task = asyncio.create_task(calibration_monitor_run_forever())
# Wifi Monitor
wifi_task = asyncio.create_task(wifi_run_forever(system_priv_user))
# Jupyter
if os.environ.get('MAI_RUN_JUPYTER', 'True').lower() in ['true', 't', '1', 'yes', 'y']:
jupyter_thread = run_jupyter_in_background(system_up_user)
if __name__ == '__main__':
if len(sys.argv) > 1:
system_up_user = sys.argv[1] # the "UnPrivileged" system user
else:
system_up_user = os.environ['USER']
if len(sys.argv) > 2:
system_priv_user = sys.argv[2] # the "Privileged" system user
else:
system_priv_user = os.environ['USER']
loop = asyncio.get_event_loop()
loop.run_until_complete(init_all(system_up_user, system_priv_user))
loop.run_forever()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v2 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
motors = await c.acquire('CarMotors')
await motors.set_params(
top = 40000,
steering_left = 3600,
steering_mid = 3000,
steering_right = 2400,
steering_millis = 1000,
throttle_forward = 4000,
throttle_mid = 3000,
throttle_reverse = 2000,
throttle_millis = 1000,
)
await motors.save_params()
await motors.on()
await asyncio.sleep(1)
for i in range(2):
for v in range(-45, 45):
print(v)
await motors.set_steering(v)
await motors.set_throttle(20)
await asyncio.sleep(0.02)
for v in range(45, -45, -1):
print(v)
await motors.set_steering(v)
await motors.set_throttle(20)
await asyncio.sleep(0.02)
await motors.off()
await asyncio.sleep(3)
await c.release(motors)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v2 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
loop = await c.acquire('LoopFrequency')
for i in range(50):
print(await loop.read())
await asyncio.sleep(0.05)
await c.release(loop)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from .easyi2c import (write_read_i2c_with_integrity,
i2c_retry, i2c_poll_until)
from . import N_I2C_TRIES
from .timers import Timer1PWM, Timer3PWM
from .db import default_db
from .battery_discharge_curve import battery_map_millivolts_to_percentage
from . import imu
from .camera_async import CameraRGB_Async
from .camera_pi import CameraRGB
import cio
import os
import time
import struct
import asyncio
import subprocess
from math import floor, isnan
from collections import deque
import numpy as np
class VersionInfo(cio.VersionInfoIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def name(self):
return "AutoAuto v2 Controller"
@i2c_retry(N_I2C_TRIES)
async def version(self):
major, minor = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 2)
return major, minor
class Credentials(cio.CredentialsIface):
def __init__(self, fd, reg_num):
self.db = None
self.loop = asyncio.get_running_loop()
async def get_labs_auth_code(self):
return await self.loop.run_in_executor(None, self._get_labs_auth_code)
async def set_labs_auth_code(self, auth_code):
if (await self.get_labs_auth_code()) is None:
await self.loop.run_in_executor(None, self._set_labs_auth_code, auth_code)
return True
return False
async def get_jupyter_password(self):
return await self.loop.run_in_executor(None, self._get_jupyter_password)
async def set_jupyter_password(self, password):
if (await self.get_jupyter_password()) is None:
await self.loop.run_in_executor(None, self._set_jupyter_password, password)
return True
return False
def _get_db(self):
if self.db is None:
self.db = default_db()
return self.db
def _get_labs_auth_code(self):
return self._get_db().get('DEVICE_LABS_AUTH_CODE', None)
def _set_labs_auth_code(self, auth_code):
self._get_db().put('DEVICE_LABS_AUTH_CODE', auth_code)
os.sync()
def _get_jupyter_password(self):
return self._get_db().get('DEVICE_JUPYTER_PASSWORD', None)
def _set_jupyter_password(self, password):
self._get_db().put('DEVICE_JUPYTER_PASSWORD', password)
os.sync()
class Camera(cio.CameraIface):
_camera = None
def __init__(self, fd, reg_num):
if Camera._camera is None:
loop = asyncio.get_running_loop()
Camera._camera = CameraRGB_Async(
lambda: CameraRGB(width=320, height=240, fps=8),
loop=loop,
idle_timeout=30
)
async def capture(self):
return await Camera._camera.capture()
class LoopFrequency(cio.LoopFrequencyIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def read(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 4)
return struct.unpack('1I', buf)[0]
class Power(cio.PowerIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
async def state(self):
return 'battery'
@i2c_retry(N_I2C_TRIES)
async def millivolts(self):
lsb, msb = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 2)
return (msb << 8) | lsb # <-- You can also use int.from_bytes(...) but I think doing the bitwise operations explicitly is cooler.
async def estimate_remaining(self, millivolts=None):
if millivolts is None:
millivolts = await self.millivolts()
percentage = battery_map_millivolts_to_percentage(millivolts)
minutes = 4.0 * 60.0 * (percentage / 100.0) # Assumes the full battery lasts 4 hours.
return floor(minutes), floor(percentage)
@i2c_retry(N_I2C_TRIES)
async def should_shut_down(self):
on_flag, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01], 1)
return not on_flag
async def shut_down(self):
subprocess.run(['/sbin/poweroff'])
async def reboot(self):
subprocess.run(['/sbin/reboot'])
class Buzzer(cio.BuzzerIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def is_currently_playing(self):
can_play, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
return can_play == 0
async def wait(self):
await i2c_poll_until(self.is_currently_playing, False, timeout_ms=100000)
async def play(self, notes="o4l16ceg>c8"):
notes = notes.replace(' ', '') # remove spaces from the notes (they don't hurt, but they take up space and the microcontroller doesn't have a ton of space)
@i2c_retry(N_I2C_TRIES)
async def send_new_notes(notes, pos):
buf = list(notes.encode())
can_play, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, pos] + buf, 1)
if can_play != 1:
raise Exception("failed to send notes to play")
return len(buf)
@i2c_retry(N_I2C_TRIES)
async def start_playback():
can_play, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
# Ignore return value. Why? Because this call commonly requires multiple retries
# (as done by `i2c_retry`) thus if we retry, then the playback will have already
# started and we'll be (wrongly) informed that it cannot start (because it already
# started!). Thus, the check below has been disabled:
#
#if can_play != 1:
# raise Exception("failed to start playback")
def chunkify(seq, n):
"""Split `seq` into sublists of size `n`"""
return [seq[i * n:(i + 1) * n] for i in range((len(seq) + n - 1) // n)]
await self.wait()
pos = 0
for chunk in chunkify(notes, 4):
chunk_len = await send_new_notes(chunk, pos)
pos += chunk_len
await start_playback()
class Gyroscope(cio.GyroscopeIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
def _read(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
x, y, z = imu.DATA['gyro']
return t, x, y, z
async def read(self):
vals = await self.loop.run_in_executor(None, self._read)
return vals[1:]
async def read_t(self):
"""This is a non-standard method."""
vals = await self.loop.run_in_executor(None, self._read)
return vals
class GyroscopeAccum(cio.GyroscopeAccumIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
self.offsets = None
def _reset(self):
self.offsets = self._read_raw()[1:]
def _read_raw(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
x, y, z = imu.DATA['gyro_accum']
return t, x, y, z
async def reset(self):
await self.loop.run_in_executor(None, self._reset)
async def read(self):
t, x, y, z = await self.read_t()
return x, y, z
async def read_t(self):
"""This is a non-standard method."""
t, x, y, z = await self.loop.run_in_executor(None, self._read_raw)
vals = x, y, z
if self.offsets is None:
self.offsets = vals
new_vals = tuple([(val - offset) for val, offset in zip(vals, self.offsets)])
return (t,) + new_vals
class Accelerometer(cio.AccelerometerIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
def _read(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
x, y, z = imu.DATA['accel']
return t, x, y, z
async def read(self):
vals = await self.loop.run_in_executor(None, self._read)
return vals[1:]
async def read_t(self):
"""This is a non-standard method."""
vals = await self.loop.run_in_executor(None, self._read)
return vals
class Ahrs(cio.AhrsIface):
def __init__(self, fd, reg_num):
self.loop = asyncio.get_running_loop()
def _read(self):
with imu.COND:
imu.COND.wait()
t = imu.DATA['timestamp']
roll, pitch, yaw = imu.DATA['ahrs']
return t, roll, pitch, yaw
async def read(self):
vals = await self.loop.run_in_executor(None, self._read)
return vals[1:]
async def read_t(self):
"""This is a non-standard method."""
vals = await self.loop.run_in_executor(None, self._read)
return vals
class PushButtons(cio.PushButtonsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.n = None
self.states = None
self.event_queue = deque()
@i2c_retry(N_I2C_TRIES)
async def num_buttons(self):
n, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
return n
@i2c_retry(N_I2C_TRIES)
async def button_state(self, button_index):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01+button_index], 3)
presses = int(buf[0])
releases = int(buf[1])
is_pressed = bool(buf[2])
return presses, releases, is_pressed
async def get_events(self):
if self.n is None:
self.n = await self.num_buttons()
self.states = [await self.button_state(i) for i in range(self.n)]
return []
events = []
for prev_state, i in zip(self.states, range(self.n)):
state = await self.button_state(i)
if state == prev_state:
continue
diff_presses = (state[0] - prev_state[0]) % 256
diff_releases = (state[1] - prev_state[1]) % 256
if diff_presses == 0 and diff_releases == 0:
continue
if prev_state[2]: # if button **was** pressed
# We'll add `released` events first.
while diff_presses > 0 or diff_releases > 0:
if diff_releases > 0:
events.append({'button': i, 'action': 'released'})
diff_releases -= 1
if diff_presses > 0:
events.append({'button': i, 'action': 'pressed'})
diff_presses -= 1
else:
# We'll add `pressed` events first.
while diff_presses > 0 or diff_releases > 0:
if diff_presses > 0:
events.append({'button': i, 'action': 'pressed'})
diff_presses -= 1
if diff_releases > 0:
events.append({'button': i, 'action': 'released'})
diff_releases -= 1
self.states[i] = state
return events
async def wait_for_event(self):
if not self.event_queue: # if empty
while True:
events = await self.get_events()
if events: # if not empty
self.event_queue.extend(events)
return self.event_queue.popleft()
await asyncio.sleep(0.05)
else:
return self.event_queue.popleft()
async def wait_for_action(self, action='pressed'):
while True:
event = await self.wait_for_event()
if action == 'any' or action == event['action']:
return event['button'], event['action']
class LEDs(cio.LEDsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.vals = {
'red': False,
'green': False,
'blue': False,
}
async def led_map(self):
return {
'red': 'The red LED',
'green': 'The green LED',
'blue': 'The blue LED',
}
@i2c_retry(N_I2C_TRIES)
async def _set(self):
red = self.vals['red']
green = self.vals['green']
blue = self.vals['blue']
led_state = ((1 if red else 0) | ((1 if green else 0) << 1) | ((1 if blue else 0) << 2))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00, led_state], 1)
if status != 72:
raise Exception("failed to set LED state")
async def set_led(self, led_identifier, val):
self.vals[led_identifier] = val
await self._set()
async def set_many_leds(self, id_val_list):
for led_identifier, val in id_val_list:
self.vals[led_identifier] = val
await self._set()
async def mode_map(self):
return {
'spin': 'the LEDs flash red, then green, then blue, then repeat',
}
@i2c_retry(N_I2C_TRIES)
async def set_mode(self, mode_identifier):
mode = 0 # default mode where the values are merely those set by `set_led()`
if mode_identifier == 'spin':
mode = 1
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, mode], 1)
if status != 72:
raise Exception("failed to set LED mode")
async def set_brightness(self, brightness):
raise Exception('LED brightness not available on this hardware.')
class Photoresistor(cio.PhotoresistorIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def read(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num], 8)
millivolts, resistance = struct.unpack('2I', buf)
return millivolts, resistance
async def read_millivolts(self):
millivolts, resistance = await self.read()
return millivolts
async def read_ohms(self):
millivolts, resistance = await self.read()
return resistance
class Encoders(cio.EncodersIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
self.last_counts = {}
self.abs_counts = {}
async def num_encoders(self):
return 2
async def enable(self, encoder_index):
if encoder_index == 0:
return await self._enable_e1()
else:
return await self._enable_e2()
async def read_counts(self, encoder_index):
if encoder_index == 0:
vals = await self._read_e1_counts()
else:
vals = await self._read_e2_counts()
vals = list(vals)
vals[0] = self._fix_count_rollover(vals[0], encoder_index)
vals = tuple(vals)
return vals
async def read_timing(self, encoder_index):
if encoder_index == 0:
return await self._read_e1_timing()
else:
return await self._read_e2_timing()
async def disable(self, encoder_index):
if encoder_index == 0:
return await self._disable_e1()
else:
return await self._disable_e2()
@i2c_retry(N_I2C_TRIES)
async def _enable_e1(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
if status != 31:
raise Exception("Failed to enable encoder")
@i2c_retry(N_I2C_TRIES)
async def _enable_e2(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01], 1)
if status != 31:
raise Exception("Failed to enable encoder")
@i2c_retry(N_I2C_TRIES)
async def _disable_e1(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02], 1)
if status != 31:
raise Exception("Failed to disable encoder")
@i2c_retry(N_I2C_TRIES)
async def _disable_e2(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 31:
raise Exception("Failed to disable encoder")
@i2c_retry(N_I2C_TRIES)
async def _read_e1_counts(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x04], 6)
return struct.unpack('3h', buf)
@i2c_retry(N_I2C_TRIES)
async def _read_e1_timing(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x05], 8)
return struct.unpack('2I', buf)
@i2c_retry(N_I2C_TRIES)
async def _read_e2_counts(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x06], 6)
return struct.unpack('3h', buf)
@i2c_retry(N_I2C_TRIES)
async def _read_e2_timing(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x07], 8)
return struct.unpack('2I', buf)
def _fix_count_rollover(self, count, encoder_index):
count = np.int16(count)
if encoder_index not in self.last_counts:
self.last_counts[encoder_index] = count
self.abs_counts[encoder_index] = 0
return 0
diff = int(count - self.last_counts[encoder_index])
self.last_counts[encoder_index] = count
abs_count = self.abs_counts[encoder_index] + diff
self.abs_counts[encoder_index] = abs_count
return abs_count
class CarMotors(cio.CarMotorsIface):
safe_throttle_cache = None
def __init__(self, fd, reg_num):
self.fd = fd
self.reg_num = reg_num
@i2c_retry(N_I2C_TRIES)
async def on(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x00], 1)
if status != 104:
raise Exception("failed to turn on car motors")
@i2c_retry(N_I2C_TRIES)
async def set_steering(self, steering):
steering = int(round(min(max(steering, -45), 45)))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x01, (steering & 0xFF), ((steering >> 8) & 0xFF)], 1)
if status != 104:
raise Exception("failed to set steering")
@i2c_retry(N_I2C_TRIES)
async def set_throttle(self, throttle):
throttle = int(round(min(max(throttle, -100), 100)))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x02, (throttle & 0xFF), ((throttle >> 8) & 0xFF)], 1)
if status != 104:
raise Exception("failed to set throttle")
@i2c_retry(N_I2C_TRIES)
async def _get_safe_throttle(self):
buf = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x09], 4)
min_throttle, max_throttle = struct.unpack('2h', buf)
return min_throttle, max_throttle
@i2c_retry(N_I2C_TRIES)
async def _set_safe_throttle(self, min_throttle, max_throttle):
payload = list(struct.pack('2h', min_throttle, max_throttle))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x0A] + payload, 1)
if status != 104:
raise Exception('failed to set params: min_throttle and max_throttle')
await self.save_params()
async def get_safe_throttle(self):
if CarMotors.safe_throttle_cache is None:
CarMotors.safe_throttle_cache = await self._get_safe_throttle()
return CarMotors.safe_throttle_cache
async def set_safe_throttle(self, min_throttle, max_throttle):
CarMotors.safe_throttle_cache = (min_throttle, max_throttle)
return await self._set_safe_throttle(min_throttle, max_throttle)
@i2c_retry(N_I2C_TRIES)
async def off(self):
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x03], 1)
if status != 104:
raise Exception("failed to turn off car motors")
async def set_params(self, top, steering_left, steering_mid, steering_right, steering_millis,
throttle_forward, throttle_mid, throttle_reverse, throttle_millis):
"""
Set the car motors' PWM signal parameters.
This is a non-standard method which is not a part of the CarMotors interface.
"""
@i2c_retry(N_I2C_TRIES)
async def set_top():
payload = list(struct.pack("1H", top))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x04] + payload, 1)
if status != 104:
raise Exception("failed to set params: top")
@i2c_retry(N_I2C_TRIES)
async def set_steering_params():
payload = list(struct.pack("4H", steering_left, steering_mid, steering_right, steering_millis))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x05] + payload, 1)
if status != 104:
raise Exception("failed to set params: steering_left, steering_mid, steering_right, steering_millis")
@i2c_retry(N_I2C_TRIES)
async def set_throttle_params():
payload = list(struct.pack("4H", throttle_forward, throttle_mid, throttle_reverse, throttle_millis))
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x06] + payload, 1)
if status != 104:
raise Exception("failed to set params: throttle_forward, throttle_mid, throttle_reverse, throttle_millis")
await set_top()
await set_steering_params()
await set_throttle_params()
async def save_params(self):
"""
Save the car motors' current parameters to the EEPROM.
This is a non-standard method which is not a part of the CarMotors interface.
"""
@i2c_retry(N_I2C_TRIES)
async def save():
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x07], 1)
if status != 104:
raise Exception("failed to tell car to save motor params")
@i2c_retry(N_I2C_TRIES)
async def is_saved():
status, = await write_read_i2c_with_integrity(self.fd, [self.reg_num, 0x08], 1)
return status == 0
await save()
await i2c_poll_until(is_saved, True, timeout_ms=1000)
def rpc_extra_exports(self):
return ['set_params', 'save_params']
class PWMs(cio.PWMsIface):
def __init__(self, fd, reg_num):
self.fd = fd
self.t1_reg_num = reg_num[0]
self.t3_reg_num = reg_num[1]
self.timer_1 = Timer1PWM(self.fd, self.t1_reg_num)
self.timer_3 = Timer3PWM(self.fd, self.t3_reg_num)
self.enabled = {} # dict mapping pin_index to frequency
async def num_pins(self):
return 4
async def enable(self, pin_index, frequency, duty=0):
if 2000000 % frequency:
raise Exception('cannot set frequency exactly')
top = 2000000 // frequency
duty = min(100.0, duty)
duty = max(0.0, duty)
duty = int(round(duty / 100.0 * top))
if pin_index in (0, 1, 2):
# These pins are on Timer 1.
needs_init = True
for idx in (0, 1, 2):
if idx in self.enabled:
if frequency != self.enabled[idx]:
raise Exception("All enabled pins 0, 1, and 2 must have the same frequency.")
needs_init = False
if needs_init:
await self.timer_1.set_top(top)
if pin_index == 0:
await self.timer_1.set_ocr_a(duty)
await self.timer_1.enable_a()
elif pin_index == 1:
await self.timer_1.set_ocr_b(duty)
await self.timer_1.enable_b()
elif pin_index == 2:
await self.timer_1.set_ocr_c(duty)
await self.timer_1.enable_c()
elif pin_index == 3:
# This pin is on Timer 3.
await self.timer_3.set_top(top)
await self.timer_3.set_ocr(duty)
await self.timer_3.enable()
else:
raise Exception('invalid pin_index')
self.enabled[pin_index] = frequency
async def set_duty(self, pin_index, duty):
if pin_index not in self.enabled:
raise Exception('that pin is not enabled')
frequency = self.enabled[pin_index]
top = 2000000 // frequency
duty = min(100.0, duty)
duty = max(0.0, duty)
duty = int(round(duty / 100.0 * top))
if pin_index == 0:
await self.timer_1.set_ocr_a(duty)
elif pin_index == 1:
await self.timer_1.set_ocr_b(duty)
elif pin_index == 2:
await self.timer_1.set_ocr_c(duty)
elif pin_index == 3:
await self.timer_3.set_ocr(duty)
async def disable(self, pin_index):
if pin_index not in self.enabled:
raise Exception('that pin is not enabled')
if pin_index == 0:
await self.timer_1.disable_a()
elif pin_index == 1:
await self.timer_1.disable_b()
elif pin_index == 2:
await self.timer_1.disable_c()
elif pin_index == 3:
await self.timer_3.disable()
del self.enabled[pin_index]
class Calibrator(cio.CalibratorIface):
def __init__(self, fd, reg_num):
pass
async def start(self):
pass # no-op
async def status(self):
pass # no-op
async def script_name(self):
return "calibrate_car_v2"
class PidSteering(cio.PidSteeringIface):
pid_cache = None
def __init__(self, fd, reg_nums):
self.fd = fd
self.p = None
self.i = None
self.d = None
self.error_accum_max = None
self.point = 0.0
carmotors_regnum, gyroaccum_regnum = reg_nums
self.carmotors = CarMotors(fd, carmotors_regnum)
self.gyroaccum = GyroscopeAccum(fd, gyroaccum_regnum)
self.task = None
async def set_pid(self, p, i, d, error_accum_max=0.0, save=False):
self.p = p
self.i = i
self.d = d
self.error_accum_max = error_accum_max
if save:
await capabilities.eeprom_store(self.fd, 0xB0, struct.pack('1f', self.p))
await capabilities.eeprom_store(self.fd, 0xB4, struct.pack('1f', self.i))
await capabilities.eeprom_store(self.fd, 0xB8, struct.pack('1f', self.d))
await capabilities.eeprom_store(self.fd, 0xBC, struct.pack('1f', self.error_accum_max))
PidSteering.pid_cache = (self.p, self.i, self.d, self.error_accum_max)
async def set_point(self, point):
self.point = point
async def enable(self, invert_output=False):
if self.p is None:
if PidSteering.pid_cache is not None:
self.p, self.i, self.d, self.error_accum_max = PidSteering.pid_cache
else:
self.p, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xB0, 4))
self.i, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xB4, 4))
self.d, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xB8, 4))
self.error_accum_max, = struct.unpack('1f', await capabilities.eeprom_query(self.fd, 0xBC, 4))
PidSteering.pid_cache = (self.p, self.i, self.d, self.error_accum_max)
if isnan(self.p):
self.p = 1.0
if isnan(self.i):
self.i = 0.0
if isnan(self.d):
self.d = 0.0
if isnan(self.error_accum_max):
self.error_accum_max = 0.0
await self.disable()
self.task = asyncio.create_task(self._task_main(invert_output))
async def disable(self):
if self.task is not None:
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass # this is expected
self.task = None
async def _task_main(self, invert_output):
last_t = None
error_accum = 0.0
last_error = None
while True:
t, _, _, z = await self.gyroaccum.read_t()
dt = ((t - last_t) if last_t is not None else 0.0) * 0.000001
last_t = t
curr_error = self.point - z
p_part = self.p * curr_error
error_accum += curr_error * dt
if self.error_accum_max > 0.0:
if error_accum > self.error_accum_max:
error_accum = self.error_accum_max
elif error_accum < -self.error_accum_max:
error_accum = -self.error_accum_max
i_part = self.i * error_accum
error_diff = ((curr_error - last_error) / dt) if last_error is not None else 0.0
last_error = curr_error
d_part = self.d * error_diff
output = p_part + i_part + d_part
if invert_output:
output = -output
await self.carmotors.set_steering(output)
class CarControl(cio.CarControlIface):
def __init__(self, fd, reg_nums):
self.car_motors = CarMotors(fd, reg_nums[0])
self.gyro_accum = GyroscopeAccum(fd, reg_nums[1]) if len(reg_nums) > 1 else None
self.pid_steering = PidSteering(fd, (reg_nums[0], reg_nums[1])) if len(reg_nums) > 1 else None
async def on(self):
await self.car_motors.on()
async def straight(self, throttle, sec=None, cm=None):
if cm is not None:
raise ValueError('This device does not have a wheel encoder, thus you may not pass `cm` to travel a specific distance.')
if sec is None:
raise ValueError('You must specify `sec`, the number of seconds to drive.')
await self.car_motors.set_steering(0.0)
await asyncio.sleep(0.1)
if self.pid_steering is not None and self.gyro_accum is not None:
_, _, z = await self.gyro_accum.read()
start_time = time.time()
await self.pid_steering.set_point(z)
await self.pid_steering.enable(invert_output=(throttle < 0))
else:
start_time = time.time()
while True:
curr_time = time.time()
if curr_time - start_time >= sec:
break
await self.car_motors.set_throttle(throttle)
if self.pid_steering is None:
await self.car_motors.set_steering(0.0)
await asyncio.sleep(min(0.1, curr_time - start_time))
await self.car_motors.set_throttle(0.0)
await asyncio.sleep(0.1)
if self.pid_steering is not None:
await self.pid_steering.disable()
async def drive(self, steering, throttle, sec=None, deg=None):
if sec is not None and deg is not None:
raise Exception('You may not specify both `sec` and `deg`.')
if sec is None and deg is None:
raise Exception('You must specify either `sec` or `deg`.')
if deg is not None and self.gyro_accum is None:
raise Exception('This device has no gyroscope, so you may not pass `deg`.')
if deg is not None and deg <= 0.0:
raise Exception('You must pass `deg` as a postive value.')
await self.car_motors.set_steering(steering)
await asyncio.sleep(0.1)
start_time = time.time()
if sec is not None:
while True:
curr_time = time.time()
if curr_time - start_time >= sec:
break
await self.car_motors.set_throttle(throttle)
await self.car_motors.set_steering(steering)
await asyncio.sleep(min(0.1, curr_time - start_time))
elif deg is not None:
await self.gyro_accum.reset() # Start the gyroscope reading at 0.
throttle_time = time.time()
await self.car_motors.set_throttle(throttle)
while True:
x, y, z = await self.gyro_accum.read()
if abs(z) >= deg:
break
curr_time = time.time()
if curr_time - throttle_time > 0.75:
await self.car_motors.set_throttle(throttle)
await self.car_motors.set_steering(steering)
throttle_time = curr_time
await self.car_motors.set_throttle(0.0)
await asyncio.sleep(0.1)
async def off(self):
await self.car_motors.off()
KNOWN_COMPONENTS = {
'VersionInfo': VersionInfo,
'Credentials': Credentials,
'Camera': Camera,
'LoopFrequency': LoopFrequency,
'Power': Power,
'Buzzer': Buzzer,
'Gyroscope': Gyroscope,
'Gyroscope_accum': GyroscopeAccum,
'Accelerometer': Accelerometer,
'AHRS': Ahrs,
'PushButtons': PushButtons,
'LEDs': LEDs,
'Photoresistor': Photoresistor,
'Encoders': Encoders,
'CarMotors': CarMotors,
'PWMs': PWMs,
'Calibrator': Calibrator,
'PID_steering': PidSteering,
'CarControl': CarControl,
}
from . import capabilities
<file_sep>###############################################################################
#
# Copyright (c) 2017-2023 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module connects to the car's controller via the CIO interface.
For beginners, it provides easy functions for forward, reverse, left, and right.
"""
from auto.capabilities import list_caps, acquire
from auto.asyncio_tools import thread_safe
def safe_forward_throttle():
"""
Return a "safe" throttle values for driving forward, where "safe" means
the resulting speed will be slow enough for the typical indoor classroom
environment.
**Disclaimer:** Any and all movement of the vehicle can result in injury
if proper safety precautions are not taken. It is the
responsibility of the user to use the device in a safe
manner at all times.
"""
safe_reverse, safe_forward = _safe_throttle_range()
return safe_forward
def safe_reverse_throttle():
"""
Return a "safe" throttle value for driving in reverse.
**IMPORTANT:** See the notes and disclaimer about "safe" in the function
documentation for `safe_forward_throttle()` as the same notes
and disclaimer applies to this this function as well.
"""
safe_reverse, safe_forward = _safe_throttle_range()
return safe_reverse
def straight(throttle, sec, cm):
"""
Drive the car "straight". This function uses the car's gyroscope to
continually keep the car in the same direction in which it started.
This function is synchronous, thus it will not return until after the
car has completed the desired motion.
"""
car_control = _get_car_control()
return car_control.straight(throttle, sec, cm)
def drive(angle, throttle, sec, deg):
"""
Drive at a given wheel angle (`angle`) and at a given throttle (`throttle`)
for a given duration (`sec`) or degrees (`deg`).
This function is synchronous, thus it will not return until after the
car has completed the desired motion.
Note: If you use this function to drive the car "straight" (i.e. `angle=0`),
the car may still veer because this function does _not_ make use of the
car's gyroscope. This is unlike the `straight()` function, which _does_
use the car's gyroscope.
"""
car_control = _get_car_control()
return car_control.drive(angle, throttle, sec, deg)
def set_steering(angle):
"""
Set the vehicle's steering in the range [-45, 45], where -45 means
full-right and 45 means full-left.
THIS IS ASYNCHRONOUS. Commands sent with this function "expire" after 1 second.
This is for safety reasons, so that the car stops if this program dies.
"""
motors = _get_car_motors()
motors.set_steering(angle)
def set_throttle(throttle):
"""
Set the vehicle's throttle in the range [-100, 100], where -100 means
full-reverse and 100 means full-forward.
THIS IS ASYNCHRONOUS. Commands sent with this function "expire" after 1 second.
This is for safety reasons, so that the car stops if this program dies.
"""
motors = _get_car_motors()
motors.set_throttle(throttle)
@thread_safe
def _get_car_control():
global _CAR_CONTROL
try:
_CAR_CONTROL
except NameError:
caps = list_caps()
if 'CarControl' not in caps:
raise AttributeError('This device is not a car.')
_CAR_CONTROL = acquire('CarControl')
_CAR_CONTROL.on()
return _CAR_CONTROL
@thread_safe
def _get_car_motors():
global _MOTORS
try:
_MOTORS
except NameError:
caps = list_caps()
if 'CarMotors' not in caps:
raise AttributeError('This device is not a car.')
_MOTORS = acquire('CarMotors')
_MOTORS.on()
return _MOTORS
@thread_safe
def _safe_throttle_range():
global _SAFE_REVERSE, _SAFE_FORWARD
try:
_SAFE_REVERSE, _SAFE_FORWARD
except NameError:
motors = _get_car_motors()
_SAFE_REVERSE, _SAFE_FORWARD = motors.get_safe_throttle()
return _SAFE_REVERSE, _SAFE_FORWARD
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains a PyGame implementation of the cui interface.
"""
import cui
import asyncio
class CuiPyGame(cui.CuiRoot):
async def init(self):
from cui.pygame_impl import console_ui
# If the import worked, we're good to go.
# The import has tremendous side affects, thus
# we delay it until this `init()` is called.
self.lock = asyncio.Lock()
self.loop = asyncio.get_running_loop()
self.event_task = asyncio.create_task(self._check_events())
return True
async def write_text(self, text):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.write_text,
text
)
async def clear_text(self):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.clear_text,
)
async def big_image(self, image_id):
async with self.lock:
image_path = 'images/{}.png'.format(image_id)
return await self.loop.run_in_executor(
None,
console_ui.big_image,
image_path
)
async def big_status(self, status):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.big_status,
status
)
async def big_clear(self):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.big_clear,
)
async def stream_image(self, rect_vals, shape, image_buf):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.stream_image,
rect_vals, shape, image_buf
)
async def clear_image(self):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.clear_image,
)
async def set_battery(self, state, minutes, percentage):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.set_battery,
state, minutes, percentage
)
async def close(self):
async with self.lock:
return await self.loop.run_in_executor(
None,
console_ui.close,
)
async def _check_events(self):
while True:
async with self.lock:
await self.loop.run_in_executor(
None,
console_ui.check_events,
)
await asyncio.sleep(0.2)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides helper functions for plotting and streaming camera
frames, or for plotting/streaming any RGB or grey image buffer.
This is a **synchronous** interface.
"""
from auto import console
from auto import _ctx_print_all
from auto.labs import send_message_to_labs
from auto.camera import base64_encode_image
import cv2
import numpy as np
import PIL.Image
OPTIMAL_ASPECT_RATIO = 4/3
def plot(frames, also_stream=True, verbose=False):
"""
Stitch together the given `frames` (a numpy nd-array) into a single nd-array.
If running in a notebook then the PIL image will be returned (and displayed).
This function by default also streams the image to your `labs` account.
The `frames` parameter must be a numpy ndarray with one of the
following shapes:
- (n, h, w, 3) meaning `n` 3-channel RGB images of size `w`x`h`
- (n, h, w, 1) meaning `n` 1-channel gray images of size `w`x`h`
- (h, w, 3) meaning a single 3-channel RGB image of size `w`x`h`
- (h, w, 1) meaning a single 1-channel gray image of size `w`x`h`
- (h, w) meaning a single 1-channel gray image of size `w`x`h`
"""
# Ensure the proper shape of `frames`.
if frames.ndim == 4:
pass
elif frames.ndim == 3:
frames = np.expand_dims(frames, axis=0)
elif frames.ndim == 2:
frames = np.expand_dims(frames, axis=2)
frames = np.expand_dims(frames, axis=0)
else:
raise Exception("invalid frames ndarray ndim")
if frames.shape[3] != 3 and frames.shape[3] != 1:
raise Exception("invalid number of channels")
if verbose:
n = frames.shape[0]
_ctx_print_all("Plotting {} frame{}...".format(n, 's' if n != 1 else ''))
montage = _create_montage(frames)
if also_stream:
stream(montage, to_labs=True, verbose=False)
return PIL.Image.fromarray(np.squeeze(montage)) if _in_notebook() else None
def _in_notebook():
"""
Determine if the current process is running in a jupyter notebook / iPython shell
Returns: boolean
"""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
result = True # jupyter notebook
elif shell == 'TerminalInteractiveShell':
result = True # iPython via terminal
else:
result = False # unknown shell type
except NameError:
result = False # most likely standard Python interpreter
return result
def _create_montage(frames):
"""
Stitch together all frames into 1 montage image:
Each frame shape is (height x width x channels).
Only supports 1 to 4 frames:
frame_count | result
1 | 1 row x 1 col
2 | 1 row x 2 col
3 | 2 row x 2 col (4th frame all white)
4 | 2 row x 2 col
Args:
frames: nd-array or list of nd-arrays
Returns: nd-array of shape (row_count * frame_height, column_count * frame_width, channels)
"""
n = frames.shape[0]
if n > 4:
raise NotImplementedError("currently you may only montage up to 4 frames")
MAX_COLS = 2
frames = np.array(frames)
if n == 1:
montage = frames[0]
else:
frames = [_shrink_img(frame, factor=1/MAX_COLS) for frame in frames]
rows_of_frames = [frames[i:i+MAX_COLS] for i in range(0, len(frames), MAX_COLS)]
rows_of_combined_frames = [(np.hstack(row) if len(row) == MAX_COLS # stitch frames together
else np.hstack([row[0], np.full_like(row[0],255)]) # stitch frame with white frame
) for row in rows_of_frames]
montage = np.vstack(rows_of_combined_frames)
return montage
def _shrink_img(img, factor=0.5):
"""
Reduce the img dimensions to factor*100 percent.
Args:
img: nd-array with shape (height, width, channels)
Returns: nd-array with shape (height*factor, width*factor, channels)
"""
shrunk_image = cv2.resize(img,None,fx=factor,fy=factor,interpolation=cv2.INTER_AREA)
return shrunk_image
def stream(frame, to_console=True, to_labs=False, verbose=False):
"""
Stream the given `frame` (a numpy ndarray) to your device's
console _and_ (optionally) to your `labs` account to be shown
in your browser.
The `frame` parameter must be a numpy ndarray with one of the
following shapes:
- (h, w, 3) meaning a single 3-channel RGB image of size `w`x`h`
- (h, w, 1) meaning a single 1-channel gray image of size `w`x`h`
- (h, w) meaning a single 1-channel gray image of size `w`x`h`
"""
if frame is None:
if to_console:
console.clear_image()
if to_labs:
send_message_to_labs({'base64_img': ''})
return
# Publish the uncompressed frame to the console UI.
if to_console:
if frame.ndim == 3:
if frame.shape[2] == 3:
pass # all good
elif frame.shape[2] == 1:
pass # all good
else:
raise Exception("invalid number of channels")
elif frame.ndim == 2:
frame = np.expand_dims(frame, axis=2)
assert frame.ndim == 3 and frame.shape[2] == 1
else:
raise Exception(f"invalid frame ndarray ndim: {frame.ndim}")
height, width, channels = frame.shape
aspect_ratio = width / height
if aspect_ratio != OPTIMAL_ASPECT_RATIO:
final_frame = _add_white_bars(frame)
height, width, channels = final_frame.shape
else:
final_frame = frame
shape = [width, height, channels]
rect = [0, 0, 0, 0]
console.stream_image(rect, shape, final_frame.tobytes())
# Encode the frame and publish to the network connection.
if to_labs:
base64_img = base64_encode_image(frame)
send_message_to_labs({'base64_img': base64_img})
if verbose:
h, w = frame.shape[:2]
_ctx_print_all("Streamed frame of size {}x{}.".format(w, h))
def _add_white_bars(frame):
"""
This function is intended for a wide image that needs white bars
on top and bottom so as to not be stretched when displayed.
Args:
frame: nd-array (height, width, channels)
Returns: nd-array (height, width, channels) with the OPTIMAL_ASPECT_RATIO
"""
height, width, channels = frame.shape
aspect_ratio = width / height
if aspect_ratio > OPTIMAL_ASPECT_RATIO:
# add horizontal bars
bar_height = int(((width / OPTIMAL_ASPECT_RATIO) - height )/ 2)
bar = np.ones((bar_height, width, channels), dtype=frame.dtype) * 255
frame = np.vstack((bar, frame, bar))
else:
# add vertical bars
pass
return frame
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This client connects to the CIO RPC server. This is an **asynchronous** client.
"""
import asyncio
from auto.rpc.client import client
import cio
class CioRoot(cio.CioRoot):
def __init__(self, inet_addr='127.0.0.1', inet_port=7002):
self.proxy_interface = None
self.caps = None
self.inet_addr = inet_addr
self.inet_port = inet_port
async def init(self):
if self.proxy_interface is None:
self.proxy_interface, pubsub_channels, subscribe_func, self._close = \
await client(self.inet_addr, self.inet_port)
self.caps = await self.proxy_interface.init()
return self.caps
async def acquire(self, capability_id):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
capability_obj = await self.proxy_interface.acquire(capability_id)
return capability_obj
async def release(self, capability_obj):
if self.proxy_interface is None:
raise Exception("You must first call `init()`.")
rpc_guid = await capability_obj.get_rpc_guid()
await self.proxy_interface.release(rpc_guid)
async def close(self):
if self.proxy_interface is not None:
await self.proxy_interface.close()
await self._close()
self.proxy_interface = None
async def _run():
cio_root = CioRoot()
caps = await cio_root.init()
print(caps)
version_iface = await cio_root.acquire('VersionInfo')
print(version_iface)
print(await version_iface.version())
print(await version_iface.name())
buzzer_iface = await cio_root.acquire('Buzzer')
print(buzzer_iface)
await buzzer_iface.play('!T240 L8 V8 agafaea dac+adaea fa<aa<bac#a dac#adaea f4') # "Bach's fugue in D-minor"
led_iface = await cio_root.acquire('LEDs')
await led_iface.set_mode('spin')
print(led_iface)
await buzzer_iface.wait()
await cio_root.release(buzzer_iface)
await cio_root.release(version_iface)
await cio_root.release(led_iface)
await cio_root.close()
if __name__ == '__main__':
asyncio.run(_run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module contains demos code for the car-on-track neural network demo.
"""
import numpy as np
import cv2
import os
cv2.setNumThreads(0)
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
def to_gray(img):
"""
Converts the image `img` from an RGB image to a greyscale image.
"""
gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
return gray_img
def resize(img):
"""
Our training set images were captured at a resolution of 160x128, therefore it
is important that we scale our images here to that size before doing any of the
other preprocessing. That is what this function does: resize the image `img` to
be 160x128 pixels.
"""
width, height = 160, 128
small_img = cv2.resize(img, (width, height))
return small_img
def crop(img):
"""
We only want to keep the bottom 70 rows of pixels of the image.
We throw away the rows of pixels at the top of the image.
That's what this function does; it returns only the bottom
70 rows of pixels from the image `img`.
"""
height = 70
return img[-height:, :]
def edges(img):
"""
This function takes a greyscale image `img` and runs
the Canny edge detection algorithm on it. The returned
image will be black and white, where the white parts are
the edges of the original image `img`.
"""
canny_thresh_1, canny_thresh_2 = 100, 200
return cv2.Canny(img, canny_thresh_1, canny_thresh_2)
def preprocess(img):
"""
This function runs all the functions above, and in the correct order!
"""
img_edge = edges(resize(to_gray(img)))
img_feats = crop(np.expand_dims(img_edge, 2))
img_feats = np.array(img_feats, dtype=np.float32) / 255.0
return img_edge, img_feats
def load_model():
"""
Load the pre-trained Neural Network model for the self-driving car.
"""
print('Importing TensorFlow...')
from tensorflow.keras.models import load_model as tf_load_model
print('Loading the Neural Network model...')
path = os.path.join(CURR_DIR, 'self_drive_model_01.hdf5')
model = tf_load_model(path)
return model
def predict(model, img_feats):
"""
Predict the driving angle from the featurized image.
"""
samples = np.expand_dims(img_feats, axis=0) # convert to a batch of length 1
predictions = model.predict(samples)
return float(predictions[0][0])
<file_sep>#!/bin/bash
cd "$HOME"
CURRICULUM_DIR="Curriculum"
AA_CURRICULUM_REPO="https://github.com/AutoAutoAI/Curriculum.git"
echo "Deleting old curriculum directory..."
rm -rf "$CURRICULUM_DIR"
echo "Cloning new curriculum repo into" "$HOME"/"$CURRICULUM_DIR"
git clone "$AA_CURRICULUM_REPO" "$CURRICULUM_DIR"
rm -rf "$CURRICULUM_DIR"/.git*
shopt -s globstar
echo "Duplicating the Jupyter notebooks..."
for i in **/*.ipynb
do
dir="$(dirname "$i")"
filename="$(basename "$i")"
extension="${filename##*.}"
filename="${filename%.*}"
cp "$i" "$dir/$filename (Student 1).$extension"
cp "$i" "$dir/$filename (Student 2).$extension"
cp "$i" "$dir/$filename (Student 3).$extension"
cp "$i" "$dir/$filename (Student 4).$extension"
cp "$i" "$dir/$filename (Student 5).$extension"
rm "$i"
done
echo 'Done!'
<file_sep>from auto.capabilities import list_caps, acquire
from itertools import count
import time
b = acquire('Power')
start_time = time.time()
with open('batlog.csv', 'wt') as f:
f.write('index,time,millivolts\n')
for i in count():
v = b.millivolts()
line = '{},{},{}'.format(i, time.time() - start_time, v)
print(line)
f.write(line + '\n')
f.flush()
wait_time = start_time + i + 1 - time.time()
time.sleep(wait_time)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v3 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
motors = await c.acquire('CarMotors')
await motors.on()
#safe = await motors.get_safe_throttle()
#print(safe)
#await motors.set_safe_throttle(safe[0] + 1, safe[1] + 1)
safe = await motors.get_safe_throttle()
print(safe)
await asyncio.sleep(1)
t = safe[1]
for i in range(2):
for v in range(-45, 45):
#print(v)
await motors.set_steering(v)
await motors.set_throttle(t)
await asyncio.sleep(0.02)
for v in range(45, -45, -1):
#print(v)
await motors.set_steering(v)
await motors.set_throttle(t)
await asyncio.sleep(0.02)
await motors.off()
await asyncio.sleep(3)
await c.release(motors)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v3 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
iface = await c.acquire('Credentials')
labs_auth_code = await iface.get_labs_auth_code()
print('Labs Auth Code:', labs_auth_code)
await iface.set_labs_auth_code('something')
labs_auth_code = await iface.get_labs_auth_code()
print('Labs Auth Code:', labs_auth_code)
await c.release(iface)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
It turns out that Linux has simple support for I2C (no need for anything fancy).
And we can invoke the necessary system calls from python, so it's all quite easy!
See: [Linux I2C Interface](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/i2c/dev-interface) (alternate source: [here](https://github.com/torvalds/linux/blob/master/Documentation/i2c/dev-interface))
Also note: You'll see above there's an SMBus interface in the Linux interface linked above.
We find that we can't use that because we need to send more than two bytes of data per message
(and the SMBus interface supports at most "word" reads and writes). But, Linux provides more
general read/write calls so we can send as many bytes as we want per message. For the same
reason, we can't use the SMBus python wrapper because it has the same limitation. That said,
this _alternate_ SMBus python wrapper (named "smbus2") is a good reference for how to do a
lot of cool Linux system calls through python. [link](https://pypi.python.org/pypi/smbus2/0.1.2)
[link](https://github.com/kplindegaard/smbus2/blob/master/smbus2/smbus2.py)
"""
import os
import time
import errno
import asyncio
from fcntl import ioctl
from functools import wraps
from . import integrity
# It would be best to have this lock work on a per-fd basis, but we won't
# worry about that because the primary use-case will be that we have only
# one fd open to this I2C bus. Having this global lock below makes it easier
# because we don't have to pass it around everywhere the fd goes.
LOCK = asyncio.Lock()
async def open_i2c(device_index, slave_address):
"""
Open and configure a file descriptor to the given
slave (`slave_address`) over the given Linux device
interface index (`device_index`).
"""
loop = asyncio.get_running_loop()
path = "/dev/i2c-{}".format(device_index)
flags = os.O_RDWR
fd = await loop.run_in_executor(
None,
os.open, # <-- throws if fails
path, flags
)
I2C_SLAVE = 0x0703 # <-- a constant from `linux/i2c-dev.h`.
await loop.run_in_executor(
None,
ioctl, # <-- throws if fails
fd, I2C_SLAVE, slave_address
)
return fd
async def close_i2c(fd):
"""
Close a file descriptor returned by `open_i2c()`.
"""
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None,
os.close, # <-- throws if fails
fd
)
async def _read_i2c(fd, n):
"""
Read `n` bytes from the I2C slave connected to `fd`.
"""
loop = asyncio.get_running_loop()
buf = await loop.run_in_executor(
None,
os.read, # <-- throws if fails, but not if short read
fd, n
)
if len(buf) != n:
raise OSError(errno.EIO, os.strerror(errno.EIO))
return buf
async def _write_i2c(fd, buf):
"""
Write the `buf` (a `bytes`-buffer) to the I2C slave at `fd`.
"""
loop = asyncio.get_running_loop()
w = await loop.run_in_executor(
None,
os.write, # <-- throws if fails, but not if short write
fd, buf
)
if len(buf) != w:
raise OSError(errno.EIO, os.strerror(errno.EIO))
async def write_read_i2c(fd, write_buf, read_len):
"""
Write-to then read-from the I2C slave at `fd`.
Note: The Pi's I2C bus isn't the best, and it fails sometimes.
See: http://www.advamation.com/knowhow/raspberrypi/rpi-i2c-bug.html
Therefore you will want to incorporate integrity checks
when you read/write to the I2C bus. See the next function
in this module for how to do this.
"""
async with LOCK:
await _write_i2c(fd, write_buf)
return await _read_i2c(fd, read_len)
async def write_read_i2c_with_integrity(fd, write_buf, read_len):
"""
Same as `write_read_i2c` but uses integrity checks for
both the outgoing and incoming buffers. See the `integrity`
module for details on how this works.
"""
read_len = integrity.read_len_with_integrity(read_len)
write_buf = integrity.put_integrity(write_buf)
async with LOCK:
await _write_i2c(fd, write_buf)
read_buf = await _read_i2c(fd, read_len)
read_buf = integrity.check_integrity(read_buf)
if read_buf is None:
raise OSError(errno.ECOMM, os.strerror(errno.ECOMM))
return read_buf
def i2c_retry(n):
"""
Decorator for I2C-dependent functions which allows them to retry
the I2C transaction up to `n` times before throwing an error.
"""
def decorator(func):
@wraps(func)
async def func_wrapper(*args, **kwargs):
for _ in range(n-1):
try:
return await func(*args, **kwargs)
except OSError:
await asyncio.sleep(0.05) # <-- allow the I2C bus to chill-out before we try again
return await func(*args, **kwargs)
return func_wrapper
return decorator
async def i2c_poll_until(func, desired_return_value, timeout_ms):
"""
Helper for I2C-dependent functions which polls the `func`
until its return value is the `desired_return_value`. It
ignores other return values and exceptions while polling,
until the `timeout_ms` is reached in which case it raises
a `TimeoutError`. If `func` returns the `desired_return_value`
before `timeout_ms` have elapsed, this function returns
instead of raising.
"""
start_time = time.time()
while True:
try:
ret = await func()
if ret == desired_return_value:
return ret, (time.time() - start_time) * 1000
except OSError:
pass
if (time.time() - start_time) * 1000 > timeout_ms:
raise TimeoutError("{} did not return {} before {} milliseconds".format(func, desired_return_value, timeout_ms))
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This is a simple process which monitors the buttons on the device and activates
the calibration script when the _first_ and _last_ buttons are pressed for
six consecutive seconds.
"""
import asyncio
from auto.services.controller.client import CioRoot
from auto import logger
log = logger.init(__name__, terminal=True)
async def _run_calibration(calibrator, buzzer):
log.info('Starting calibration sequence!')
await buzzer.play()
script_name = await calibrator.script_name()
proc = await asyncio.create_subprocess_exec(script_name)
await proc.communicate()
log.info('Calibration ended.')
async def _monitor(buttons, calibrator, buzzer):
n_buttons = await buttons.num_buttons()
button_indices = [0, n_buttons-1] # the _first_ and _last_ buttons
count = 0
while True:
for b in button_indices:
num_presses, num_releases, is_currently_pressed = await buttons.button_state(b)
if not is_currently_pressed:
count = 0
break
else:
# All buttons are currently pressed.
count += 1
if count == 12:
await _run_calibration(calibrator, buzzer)
count = 0
await asyncio.sleep(0.5)
async def run_forever():
controller = CioRoot()
capabilities = await controller.init()
buttons = None
calibrator = None
buzzer = None
try:
if 'PushButtons' in capabilities:
buttons = await controller.acquire('PushButtons')
else:
log.warning('No push buttons exists on this device; exiting...')
return
if 'Calibrator' in capabilities:
calibrator = await controller.acquire('Calibrator')
else:
log.warning('No calibrator exists on this device; exiting...')
return
if 'Buzzer' in capabilities:
buzzer = await controller.acquire('Buzzer')
else:
pass # We can tolerate no buzzer.
log.info('RUNNING!')
await _monitor(buttons, calibrator, buzzer)
except asyncio.CancelledError:
log.info('Calibration monitor is being canceled...')
finally:
if buttons is not None:
await controller.release(buttons)
buttons = None
if calibrator is not None:
await controller.release(calibrator)
calibrator = None
if buzzer is not None:
await controller.release(buzzer)
buzzer = None
await controller.close()
if __name__ == '__main__':
asyncio.run(run_forever())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from cui.pygame_impl import CuiPyGame
async def run():
c = CuiPyGame()
await c.init()
for percentage in range(0, 101):
minutes = 2 * percentage
await c.set_battery(state, minutes, percentage)
await asyncio.sleep(0.01)
for percentage in range(100, -1, -1):
minutes = 2 * percentage
await c.set_battery(state, minutes, percentage)
await asyncio.sleep(0.01)
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2021 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
camera = await c.acquire('Camera')
frame = await camera.capture()
await c.release(camera)
await c.close()
print(frame)
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
enc = await c.acquire('Encoders')
enc_index = 1 # the _second encoder
n = await enc.num_encoders()
print('# encoders:', n)
await enc.enable(enc_index)
def fmt(val):
return "{:6d}".format(val)
for i in range(100000):
counts = await enc.read_counts(enc_index)
counts_str = ''.join([fmt(c) for c in counts])
timing = await enc.read_timing(enc_index)
timing_str = ''.join([fmt(t) for t in timing])
print(counts_str + timing_str)
await asyncio.sleep(0.1)
await enc.disable(enc_index)
await c.release(enc)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
### DRIVE THE CAR
# from car import motors
#
# ...
#
# while True:
# throttle, steering = await enc.read_timing(1)
# throttle = (throttle - 1500) / 500 * 100
# steering = (steering - 1500) / 500 * 45
# motors.set_throttle(throttle)
# motors.set_steering(steering)
#
# ...
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v3 as controller
from cio.aa_controller_v3.capabilities import eeprom_store, eeprom_query
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
fd = c.ctlr_fd
buf = await eeprom_query(fd, 0xA0, 4)
print(buf)
await eeprom_store(fd, 0xA0, b'0000')
buf = await eeprom_query(fd, 0xA0, 4)
print(buf)
assert buf == b'0000'
await eeprom_store(fd, 0xA0, b'1234')
buf = await eeprom_query(fd, 0xA1, 3)
print(buf)
assert buf == b'234'
buf = await eeprom_query(fd, 0xA2, 2)
print(buf)
assert buf == b'34'
buf = await eeprom_query(fd, 0xA3, 1)
print(buf)
assert buf == b'4'
buf = await eeprom_query(fd, 0xA0, 4)
print(buf)
assert buf == b'1234'
buf = await eeprom_query(fd, 0x0F, 5)
print(buf)
await eeprom_store(fd, 0x0F, b'12345')
buf = await eeprom_query(fd, 0x10, 4)
print(buf)
assert buf == b'2345'
buf = await eeprom_query(fd, 0x11, 3)
print(buf)
assert buf == b'345'
buf = await eeprom_query(fd, 0x12, 2)
print(buf)
assert buf == b'45'
buf = await eeprom_query(fd, 0x13, 1)
print(buf)
assert buf == b'5'
buf = await eeprom_query(fd, 0x0F, 5)
print(buf)
assert buf == b'12345'
if __name__ == '__main__':
asyncio.run(run())
<file_sep>#!/bin/bash
set -e
if ! [ $(id -u) = 0 ]
then
echo "You must be root to use this script."
exit 1
fi
LIBAUTO_PATH=$(python3 -c 'import auto; print(auto.__file__)')
LIBAUTO_PATH=$(dirname "$LIBAUTO_PATH")
LIBAUTO_PATH=$(dirname "$LIBAUTO_PATH")
OWNER=$(stat -c %U "$LIBAUTO_PATH")
echo "Libauto directory:" "$LIBAUTO_PATH"
echo "Owner is:" "$OWNER"
cd "$LIBAUTO_PATH"
sudo -u "$OWNER" git pull
sync
sleep 2 # Allows the user time to see what happened.
reboot
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v1 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
await asyncio.sleep(1) # wait for reset sound to finish playing, else we block it by starting the calibration below
calibrator = await c.acquire('Calibrator')
await calibrator.start()
print('Started calibration...')
while True:
status = await calibrator.status()
if status == -1:
# Indicates we are done calibrating.
break
print('.', end='', flush=True)
await asyncio.sleep(1)
print('DONE!')
await asyncio.sleep(5)
await c.release(calibrator)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep># The MasterAI Device Library
Learn and use Python and A.I. to program your own autonomous vehicles! 🚗 🚁
Many MasterAI devices use this library. For example, the AutoAuto car below:

## Beginner or Advanced?
If you are a beginner, you will _first_ want to follow along through the lessons on [AutoAuto Labs](https://labs.autoauto.ai/). After you leveled-up through the beginner and intermediate lessons, you can come back here to explore this library more fully.
If you are an advanced programmer, you are welcome to dive right in! This library is already installed on your MasterAI device. Have a look at the section [Connecting to Your Device](#connecting-to-your-device) and the section [Examples](#examples), then you will be off-to-the-races! 🏃
## Library Overview
The library is segmented into four packages:
- [auto](./auto/): The _core_ package. Contains the critical components for _every_ MasterAI device, such as the camera interface and the Machine Learning (ML) models.
- [cio](./cio/): A package whose only job is to talk to the on-board microcontroller. The name `cio` is short for "controller input/output". It is _pluggable_ and can support multiple backends.
- [cui](./cui/): A package whose only job is to run the console application on the device's LCD screen. The name `cui` is short for "console UI". It is _pluggable_ and can support multiple backends.
- [car](./car/): The `car` package contains helper functions for the AutoAuto _cars_. E.g. `car.forward()`, `car.left()`, `car.right()`, `car.reverse()`. If you look at the implementations of these helper functions, you find they use the `auto` package under the hood (pun intended).
## Connecting to Your Device
Here are the ways you can connect to your device:
- **SSH:** SSH'ing into your device is the quickest way to gain privileged access (i.e. to get `sudo` powers; remember Uncle Ben's words). You can log in to the device with the username `hacker`. You must obtain your device's default password from [AutoAuto Labs](https://labs.autoauto.ai/autopair/) (from the "My Devices" page, you can view your device's "Info for Advanced Users"). Every device has a different default system password. You are encouraged to change your device's system password (using the usual `passwd` command).
- **Jupyter:** Every device runs a Jupyter Notebook server on port 8888. You must obtain the password for Jupyter from [AutoAuto Labs](https://labs.autoauto.ai/autopair/) (from the "My Devices" page, you can view your device's "Info for Advanced Users"). Every device has a different Jupyter password. Note the Jupyter server does _not_ run as a privileged user; if you need privileged access, you must log into the device as the `hacker`.
- **AutoAuto Labs:** AutoAuto Labs offers a simple editor where you can write and run programs. It is pleasant to use, but it is only good for short and simple programs.
## Examples
### Drive your car!
**Note:** Only applicable to AutoAuto _cars_, not other devices.
```python
import car
# Each line below defaults to driving for 1 second (results in, 4 seconds total driving).
car.forward()
car.left()
car.right()
car.reverse()
# You can also specify the duration (in seconds), for example:
car.forward(2.5)
```
### Print to the Console
Many MasterAI devices are equipped with an LCD screen which runs a console application. You can print your own text to the console, example below:
```python
from auto import console
console.print("Hi, friend!")
console.print("How are you?")
```
The `car` package also has a print function which prints to `stdout` _and_ to the
console. (For those who use the `car` package, this is convenient.)
```python
import car
car.print("Hi, friend!")
car.print("How are you?")
```
### Use the camera
Capture a single frame:
```python
import car
frame = car.capture()
car.stream(frame, to_console=True, to_labs=True)
```
**Note:** The `car.capture()` and `car.stream()` functions are convenience functions. They use the `auto` package internally. E.g. The following code uses the next-layer-down interfaces to capture frames continuously.
```python
from auto.camera import global_camera
from auto.frame_streamer import stream
camera = global_camera()
for frame in camera.stream():
# <process frame here>
stream(frame, to_console=True, to_labs=True)
```
You can clear the frame from the console like this:
```python
import car
car.stream(None, to_console=True, to_labs=True)
# --or--
from auto.frame_streamer import stream
stream(None, to_console=True, to_labs=True)
```
### Detect faces
```python
import car
while True:
frame = car.capture()
car.detect_faces(frame)
car.stream(frame, to_labs=True)
```
The lower-level class-based interface for the face detector can be found in `auto.models.FaceDetector`. The face detector uses OpenCV under the hood.
### Detect people
We call this the "pedestrian detector" in the context of an AutoAuto _car_.
```python
import car
while True:
frame = car.capture()
car.detect_pedestrians(frame)
car.stream(frame, to_labs=True)
```
The lower-level class-based interface for the people detector can be found in `auto.models.PedestrianDetector`. The people detector uses OpenCV under the hood.
### Detect stop signs
```python
import car
while True:
frame = car.capture()
car.detect_stop_signs(frame)
car.stream(frame, to_labs=True)
```
The lower-level class-based interface for the stop sign detector can be found in `auto.models.StopSignDetector`. The stop sign detector uses OpenCV under the hood.
### Helper functions: object location & size
The following works with the returned value from:
- `car.detect_faces()` (shown in example below)
- `car.detect_pedestrians()`
- `car.detect_stop_signs()`
```python
import car
frame = car.capture()
rectangles = car.detect_faces(frame)
car.stream(frame, to_labs=True)
location = car.object_location(rectangles, frame.shape)
size = car.object_size(rectangles, frame.shape)
car.print("Object location:", location)
car.print("Object size:", size)
```
### Raw OpenCV
In the example below, we will use OpenCV to do edge-detection using the Canny edge filter.
```python
import cv2
import car
print("OpenCV version:", cv2.__version__)
while True:
frame = car.capture(verbose=False)
frame_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
frame_edges = cv2.Canny(frame_gray, 100, 200)
car.stream(frame_edges, to_labs=True, verbose=False)
```
### Classify frame's center color
```python
import car
frame = car.capture()
color = car.classify_color(frame)
car.stream(frame, to_labs=True)
car.print("The detected color is", color)
```
The lower-level class-based interface for the color classifier can be found in `auto.models.ColorClassifier`.
### Read QR Codes
```python
import car
from auto.qrcode import qr_scan
while True:
frame = car.capture(verbose=False)
car.plot(frame, verbose=False)
qr = qr_scan(frame)
print(qr)
if qr:
car.honk(1)
```
### Precise steering
**Note:** Only applicable to AutoAuto _cars_, not other devices.
```python
from car.motors import set_steering
import time
for angle in range(-45, 46): # goes from -45 to +45
set_steering(angle)
time.sleep(0.05)
for angle in range(45, -46, -1): # goes from +45 to -45
set_steering(angle)
time.sleep(0.05)
time.sleep(0.5)
set_steering(0.0) # STRAIGHT
time.sleep(1.0)
```
**Important Note:** The call to `set_steering()` is asynchronous; that is, the function returns immediately, very likely _before_ the wheels have actually had a chance to fully turn to the desired angle! Furthermore, the call only "lasts" for 1 second, then the angle will automatically revert back to _straight_. As a result you must call `set_steering()` in a loop to keep it active. (This is a safety feature, allowing the car to revert to going straight if your program crashes or if the Pi loses communication with the microcontroller.)
### Precise throttle
**Note:** Only applicable to AutoAuto _cars_, not other devices.
**WARNING:** You can easily injure the car, yourself, or others by setting the throttle too high. Use this interface with extreme caution. These cars are VERY powerful and very fast.
```python
from car.motors import set_throttle, safe_forward_throttle
import time
throttle = safe_forward_throttle()
set_throttle(0.0) # Car in NEUTRAL
time.sleep(1.5)
set_throttle(throttle) # Car moves at safe forward speed
time.sleep(1.5)
set_throttle(50.0) # HALF THROTTLE (DANGER! THIS IS VERY FAST!)
time.sleep(0.4)
set_throttle(0.0) # Back to NEUTRAL
time.sleep(1.0)
```
**Important Note:** The call to `set_throttle()` is asynchronous; that is, the function returns immediately, very likely _before_ the car's speed actually changes! Furthermore, the call only "lasts" for 1 second, then the car will revert back to a throttle of zero. As a result you must call `set_throttle()` in a loop to keep it active. (This is a safety feature, allowing the car to automatically **STOP** if your program crashes or if the Pi loses communication with the microcontroller.)
### Plot frames in Jupyter
The helper function `car.plot()` will both stream a single frame to your AutoAuto Labs account _and_ it returns a `PIL.Image` object, so you can conveniently use it from Jupyter. See the screenshot below:

### Servos
If your device has extra servo outputs, you can control them via the `auto.servos` module.
```python
TODO
```
### LEDs
If your device has RGB LEDs, then you can control them via the `auto.leds` module.
```python
from auto.leds import led_map, set_many_leds
from random import randint
import time
randpixel = lambda: [randint(0, 255) for i in range(3)]
leds = led_map()
while True:
state = [(i, randpixel()) for i in leds]
set_many_leds(state)
time.sleep(0.5)
```
### List the device's capabilities
Different MasterAI devices (and different versions of the same device) may have a different set of hardware capabilities. You can ask your device to list its capabilities like this:
```python
from auto.capabilities import list_caps, acquire, release
my_capabilities = list_caps()
print(my_capabilities)
```
**Note:** In the program above we also imported `acquire` and `release` (although we didn't use them). Those two functions will be used in many of the examples that follow to actually _use_ the capabilities that we listed above.
### Gyroscope
You can get _instantaneous_ measurements from the gyroscope like this:
```python
from auto.capabilities import list_caps, acquire, release
import time
gyroscope = acquire('Gyroscope')
for i in range(100):
x, y, z = gyroscope.read()
print(' '.join("{:10.3f}".format(v) for v in (x, y, z)))
time.sleep(0.05)
release(gyroscope)
```
Or you can get _accumulated_ (or _integrated_, if you prefer) measurements like this (which is likely what you actually want):
```python
from auto.capabilities import list_caps, acquire, release
import time
gyroscope = acquire('Gyroscope_accum')
for i in range(100):
x, y, z = gyroscope.read()
print(' '.join("{:10.3f}".format(v) for v in (x, y, z)))
time.sleep(0.05)
release(gyroscope)
```
### Accelerometer
```python
from auto.capabilities import list_caps, acquire, release
import time
accelerometer = acquire('Accelerometer')
for i in range(100):
x, y, z = accelerometer.read()
print(' '.join("{:10.3f}".format(v) for v in (x, y, z)))
time.sleep(0.05)
release(accelerometer)
```
### Buzzer
The `car` package has two helper functions:
```python
import car
car.buzz('!V10 O4 L16 c e g >c8')
car.honk()
```
Or you can use the underlying buzzer interface.
```python
from auto.capabilities import list_caps, acquire, release
buzzer = acquire("Buzzer")
buzzer.play('!V10 O4 L16 c e g >c8') # <-- asynchronous call
buzzer.wait() # <-- block the program until the buzzer finishes playing
release(buzzer)
```
See [Buzzer Language](#buzzer-language) to learn how to write notes as a string that the buzzer can interpret and play.
### Photoresistor
You can use the photoresistor as a very simple ambient light detector.
```python
from auto.capabilities import list_caps, acquire, release
import time
photoresistor = acquire('Photoresistor')
for i in range(100):
millivolts, resistance = photoresistor.read()
print(resistance)
time.sleep(0.1)
release(photoresistor)
```
The program above prints the resistance of the photoresistor (in Ohms). You can play around with where a good threshold is for your application, and you can quickly see the value change by simply covering the light with your hand or by shining a flashlight at it.
### Push Buttons
```python
from auto.capabilities import list_caps, acquire, release
buttons = acquire('PushButtons')
print("Press the buttons, and you'll see the events being printed below:")
while True:
button, action = buttons.wait_for_action('any')
print("The {}th button was {}.".format(button, action))
if button == 2:
break
release(buttons)
```
### Batter voltage
```python
from auto.capabilities import list_caps, acquire, release
power = acquire('Power')
millivolts = power.millivolts()
percentage, minutes = power.estimate_remaining(millivolts)
print('The power voltage is {} millivolts.'.format(millivolts))
print('It is at ~{}% and will last for ~{} more minutes.'.format(minutes, percentage))
release(power)
```
**Note:** There's a background task that will monitor the battery voltage for you and will buzz the buzzer when the battery gets to 5% or lower.
### Encoders
Some devices have motor encoders to track how many "clicks" the motor has rotated.
```python
from auto.capabilities import list_caps, acquire, release
import time
encoders = acquire('Encoders')
index = 1
print("There are", encoders.num_encoders(), "encoders.")
print(f"Enabling encoder at index {index}.")
encoders.enable(index)
for i in range(50):
counts, _, _ = encoders.read_counts(index)
print(counts)
time.sleep(0.1)
release(encoders)
```
### Calibration
Depending on the device you have, you can run the appropriate calibration script.
| Device Name | Calibration Script Name |
|---------------------------------|-------------------------|
| AutoAuto Car with v1 Controller | `calibrate_car_v1` |
| AutoAuto Car with v2 Controller | `calibrate_car_v2` |
## Buzzer Language
The Buzzer Language<sup>[1](#buzzer-language-copyright)</sup> works as follows:
The notes are specified by the characters C, D, E, F, G, A, and B, and they are played by default as _quarter notes_ with a length of 500 ms. This corresponds to a tempo of 120 beats/min. Other durations can be specified by putting a number immediately after the note. For example, C8 specifies C played as an eighth note (i.e. having half the duration of the default quarter note). The special note R plays a rest (no sound). The sequence parser is case-insensitive and ignores spaces, although spaces are encouraged to help with human readability.
Various control characters alter the sound:
| Control character(s) | Effect |
| --------------------------- | ------ |
| **A**–**G** | Specifies a note that will be played. |
| **R** | Specifies a rest (no sound for the duration of the note). |
| **+** or **#** after a note | Raises the preceding note one half-step. |
| **-** after a note | Lowers the preceding note one half-step. |
| **1**–**2000** after a note | Determines the duration of the preceding note. For example, C16 specifies C played as a sixteenth note (1/16th the length of a whole note). |
| **.** after a note | "Dots" the preceding note, increasing the length by 50%. Each additional dot adds half as much as the previous dot, so that "A.." is 1.75 times the length of "A". |
| **>** before a note | Plays the following note one octave higher. |
| **<** before a note | Plays the following note one octave lower. |
| **O** followed by a number | Sets the octave. (default: O4) |
| **T** followed by a number | Sets the tempo in beats per minute (BPM). (default: T120) |
| **L** followed by a number | Sets the default note duration to the type specified by the number: 4 for quarter notes, 8 for eighth notes, 16 for sixteenth notes, etc. (default: L4) |
| **V** followed by a number | Sets the music volume (0–15). (default: V15) |
| **MS** | Sets all subsequent notes to play play staccato – each note is played for 1/2 of its allotted time, followed by an equal period of silence. |
| **ML** | Sets all subsequent notes to play legato – each note is played for full length. This is the default setting. |
| **!** | Resets the octave, tempo, duration, volume, and staccato setting to their default values. These settings persist from one play() to the next, which allows you to more conveniently break up your music into reusable sections. |
Examples:
- The C-major scale up and back down: "!L16 cdefgab>cbagfedc"
- The first few measures of Bach's fugue in D-minor: "!T240 L8 agafaea dac+adaea fa<aa<bac#a dac#adaea f4"
<a name="buzzer-language-copyright">1</a>: Pololu Corporation developed and holds the copyright for the Buzzer Language and its documentation. Further information about the Buzzer Language's license and copyright can be found in the [LICENSE](./LICENSE) file.
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides utilities for querying and controlling the network
interfaces of your device.
This is a **synchronous** interface.
"""
import subprocess
import socket
import fcntl
import struct
import time
import requests
import re
import os
PING_PROTO = os.environ.get('MAI_PING_PROTO', 'https')
PING_HOST = os.environ.get('MAI_PING_HOST', 'ws.autoauto.ai')
class Wireless:
"""
Simple python interface to the `nmcli` utility.
See: https://developer.gnome.org/NetworkManager/stable/nmcli.html
"""
def __init__(self, interface=None):
self.interface = interface
def _error_in_response(self, response):
for line in response.splitlines():
if line.startswith('Error'):
return True
return False
def connect(self, ssid, password):
self.delete_connection(ssid)
response = _run_cmd("nmcli dev wifi connect".split(' ') +
[ssid, 'password', password, 'ifname', self.interface,
'name', ssid]) # , 'hidden', 'yes'
did_connect = not self._error_in_response(response)
if not did_connect:
self.delete_connection(ssid)
time.sleep(2) # Allow connection (and DHCP) to settle.
os.sync()
return did_connect
def current(self):
response = _run_cmd("nmcli --terse --field DEVICE,CONNECTION dev".split(' '))
for line in response.splitlines():
lst = line.split(':')
if len(lst) != 2:
continue
iface, name = lst
if iface == self.interface:
if name in ('', '--'):
return None
return name
return None
def delete_connection(self, ssid_to_delete):
response = _run_cmd("nmcli --terse --fields UUID,NAME,TYPE con show".split(' '))
for line in response.splitlines():
lst = line.split(':')
if len(lst) != 3:
continue
uuid, name, type_ = lst
if type_ == '802-11-wireless' and ssid_to_delete in name:
_run_cmd("nmcli con delete uuid".split(' ') + [uuid])
def radio_power(self, on=None):
if on is True:
_run_cmd('nmcli radio wifi on'.split(' '))
elif on is False:
_run_cmd('nmcli radio wifi off'.split(' '))
else:
response = _run_cmd('nmcli radio wifi'.split(' '))
return 'enabled' in response
def get_ip_address(ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ret = socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15].encode('utf-8'))
)[20:24])
s.close()
return ret
except:
# Humm...
return None
def get_mac_address(ifname):
output = _run_cmd(['ip', 'link', 'show', 'dev', ifname])
match = re.search(r'ether ([^ ]+)', output)
if match is not None:
return match.group(1)
def has_internet_access():
try:
# Consider instead: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.getaddrinfo
params = socket.getaddrinfo(PING_HOST, PING_PROTO, proto=socket.IPPROTO_TCP)[0]
except:
return False
family, type_, proto = params[:3]
sockaddr = params[4]
sock = socket.socket(family, type_, proto)
sock.settimeout(20.0)
try:
sock.connect(sockaddr) # <-- blocking, but respects the `settimeout()` call above
except (socket.timeout, OSError):
sock.close()
return False
sock.close()
try:
req = requests.get(f'{PING_PROTO}://{PING_HOST}/ping', timeout=80.0)
data = req.json()
return req.status_code == 200 and data['text'] == 'pong'
except:
return False
def list_ifaces():
response = _run_cmd('ip link show up'.split(' '))
interfaces = []
for line in response.splitlines():
match = re.search(r'^\d+: ([^:@]+)', line)
if match is not None:
iface = match[1]
interfaces.append(iface)
return interfaces
def list_wifi_ifaces():
try:
response = _run_cmd('nmcli --terse --fields DEVICE,TYPE dev'.split(' '))
except FileNotFoundError:
# nmcli not installed on this system -- assume no wifi in this case
return []
interfaces = []
for line in response.splitlines():
lst = line.split(':')
if len(lst) != 2:
continue
iface, type_ = lst
if type_ == 'wifi':
interfaces.append(iface)
return interfaces
def _run_cmd(cmd):
output = subprocess.run(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).stdout.decode('utf-8')
return output
if __name__ == '__main__':
all_ifaces = list_ifaces()
wifi_ifaces = list_wifi_ifaces()
for iface in all_ifaces:
print(iface, get_ip_address(iface))
wireless = Wireless(wifi_ifaces[0])
print('WiFi interface', wireless.interface)
print('WiFi SSID', wireless.current())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v2 as controller
def fmt(vals):
names = ['roll', 'pitch', 'yaw']
print(''.join(f'{n}={v:<10.2f}' for n, v in zip(names, vals)))
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
ahrs = await c.acquire('AHRS')
for i in range(10000):
fmt(await ahrs.read())
await asyncio.sleep(0.05)
await c.release(ahrs)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2023 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This model provides a context-aware sleep function.
On physical devices, it uses the standard `time.sleep()` function.
On virtual devices, it counts physics-engine "ticks" so that we
stay in-sync with the physics engine to minimize the amount of
drift and thereby maximize the amount of reproducibility.
"""
from auto.capabilities import list_caps, acquire
from auto.asyncio_tools import thread_safe
from auto import IS_VIRTUAL
import time
def sleep(seconds):
if IS_VIRTUAL:
physics = _physics_client()
physics.sleep(seconds)
else:
time.sleep(seconds)
@thread_safe
def _physics_client():
global _PHYSICS
try:
_PHYSICS
except NameError:
caps = list_caps()
if 'PhysicsClient' not in caps:
raise AttributeError('This device is not virtual!')
_PHYSICS = acquire('PhysicsClient')
return _PHYSICS
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
from pprint import pprint
import cio.aa_controller_v3 as controller
def fmt(vals):
print(''.join(f'{v:10.2f}' for v in vals))
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
gyro = await c.acquire('Gyroscope')
gyro_accum = await c.acquire('Gyroscope_accum')
for i in range(500):
fmt(await gyro.read())
fmt(await gyro_accum.read())
print()
if i % 50 == 0:
await gyro_accum.reset()
await asyncio.sleep(0.1)
await c.release(gyro)
await c.release(gyro_accum)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>#!/bin/bash
if ! [ $(id -u) = 0 ]
then
echo "You must be root to use this script."
exit 1
fi
if [ -z "$1" ]
then
echo "No password specified on command line."
exit 1
fi
if [ -z "$2" ]
then
echo "No system username specified on command line."
exit 1
fi
PASSWD="$1"
USERNAME="$2"
echo -e "$PASSWD""\n""$PASSWD" | passwd "$USERNAME"
exit $!
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
Provide a standardized logging format. Modules which would like to log should do
so with the following code (just an example):
```python
from auto import logger
log = logger.init(__name__, terminal=True)
...
log.info("Stuff...")
```
"""
import logging
def set_root_log_level(level=logging.INFO):
logging.getLogger().setLevel(level)
set_root_log_level()
def _get_formatter():
formatter = logging.Formatter('%(asctime)s: %(name)-35s: %(levelname)-10s: %(message)s')
return formatter
def init(modulename, terminal=True, filename=None, log_level=logging.NOTSET):
"""
Build a logger to be used as a global at the module-level.
"""
log = logging.getLogger(modulename)
log.setLevel(log_level)
if filename:
handler = logging.FileHandler(filename) # <-- log to that file
handler.setLevel(log_level)
handler.setFormatter(_get_formatter())
log.addHandler(handler)
if terminal:
handler = logging.StreamHandler() # <-- log to the terminal
handler.setLevel(log_level)
handler.setFormatter(_get_formatter())
log.addHandler(handler)
return log
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides the default, easy, global camera interface.
Internally, it obtains frames by querying the camera RPC server.
This is a **synchronous** interface.
"""
import os
import cv2
import base64
import numpy as np
import auto
from auto.asyncio_tools import thread_safe, RLock
from auto.capabilities import list_caps, acquire, release
from auto import IS_VIRTUAL
class _CameraRGB:
def __init__(self, camera):
self._camera = camera
self.frame_index = 0
self.text_scale = 0.75
self.text_color = [255, 255, 255]
self.text_line_width = 2
def capture(self):
buf, shape = self._camera.capture()
frame = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
draw_frame_index(
frame,
self.frame_index,
self.text_scale,
self.text_color,
self.text_line_width
)
self.frame_index += 1
return frame
def stream(self):
while True:
frame = self.capture()
yield frame
_CAMERA_LOCK = RLock()
@thread_safe(lock=_CAMERA_LOCK)
def global_camera(verbose=False):
"""
Creates (for the first call) or retrieves (for later calls) the
global camera object. This is a convenience function to facilitate
quickly and easily creating and retrieving a camera singleton.
"""
global GLOBAL_CAMERA
try:
GLOBAL_CAMERA
except NameError:
caps = list_caps()
if 'Camera' not in caps:
raise AttributeError("This device does not have a Camera.")
camera = acquire('Camera')
GLOBAL_CAMERA = _CameraRGB(camera)
if verbose:
auto._ctx_print_all("Instantiated a global camera object!")
return GLOBAL_CAMERA
@thread_safe(lock=_CAMERA_LOCK)
def close_global_camera(verbose=False):
"""
Close and delete the global camera object.
"""
global GLOBAL_CAMERA
try:
GLOBAL_CAMERA # <-- just to see if it exists
if verbose:
auto._ctx_print_all("Closing the global camera object...")
release(GLOBAL_CAMERA._camera)
del GLOBAL_CAMERA
except NameError:
# There is no global camera, so nothing needs to be done.
pass
def capture(num_frames=1, verbose=False):
"""
Capture `num_frames` frames from the (global) camera and return
them as a numpy ndarray.
This is a convenience function to make the most common use-case simpler.
"""
camera = global_camera(verbose)
if num_frames > 1:
frames = np.array([frame for _, frame in zip(range(num_frames), camera.stream())])
if verbose:
auto._ctx_print_all("Captured {} frames.".format(num_frames))
return frames
else:
frame = camera.capture()
if verbose:
auto._ctx_print_all("Captured 1 frame.")
return frame
def draw_frame_index(frame, index,
text_scale=0.75,
text_color=[255, 255, 255],
text_line_width=2):
text = "frame {}".format(index)
x = 5
y = frame.shape[0] - 5
cv2.putText(frame,
text,
(x, y),
cv2.FONT_HERSHEY_SIMPLEX,
text_scale,
text_color,
text_line_width)
def base64_encode_image(frame):
"""
Encodes an image buffer (an ndarray) as a base64 encoded string.
"""
if frame.ndim == 2:
frame = np.expand_dims(frame, axis=2)
assert frame.ndim == 3 and frame.shape[2] == 1
elif frame.ndim == 3:
if frame.shape[2] == 1:
pass # all good
elif frame.shape[2] == 3:
# cv2.imencode expects a BGR image:
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
assert frame.ndim == 3 and frame.shape[2] == 3
else:
raise Exception("invalid number of channels")
else:
raise Exception("invalid frame ndarray ndim")
if IS_VIRTUAL:
png_img = cv2.imencode('.png', frame, [cv2.IMWRITE_PNG_COMPRESSION, 6])[1].tobytes()
base64_img = 'data:image/png;base64,' + base64.b64encode(png_img).decode('ascii')
else:
jpg_img = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 50])[1].tobytes()
base64_img = 'data:image/jpeg;base64,' + base64.b64encode(jpg_img).decode('ascii')
return base64_img
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides helper functions for the RPC controller server and client.
"""
import inspect
import cio
def build_cio_class_map():
abs_classes = inspect.getmembers(cio, predicate=inspect.isabstract)
return {class_name: class_type for class_name, class_type in abs_classes}
def build_cio_method_map():
m = {}
abs_classes = build_cio_class_map()
for class_name, class_type in abs_classes.items():
methods = inspect.getmembers(class_type, predicate=inspect.isfunction)
m[class_name] = [method_name for method_name, method_ref in methods]
return m
def get_abc_superclass_name(obj):
mro = inspect.getmro(type(obj))
superclass = mro[1]
assert inspect.isabstract(superclass)
superclass_name = superclass.__name__
return superclass_name
<file_sep>###############################################################################
#
# Copyright (c) 2017-2021 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module wraps a camera in a thread and exposes an asyncio interface
for getting frames.
"""
from threading import Thread
from queue import Queue
import asyncio
import time
from auto import logger
log = logger.init(__name__, terminal=True)
def _init_bg_capture_thread(camera_factory, ctl_queue, frame_callback, loop):
def run_camera():
event = ctl_queue.get() # <-- block waiting for an event
assert event == 'start'
camera = camera_factory()
log.info("Initialized a camera instance...")
for frame in camera.stream():
frame_encoded = (frame.tobytes(), frame.shape)
asyncio.run_coroutine_threadsafe(frame_callback(frame_encoded), loop)
if not ctl_queue.empty():
event = ctl_queue.get()
assert event == 'stop'
break
camera.close()
del camera
log.info("Destroyed the camera instance...")
def camera_thread_main():
while True:
run_camera()
time.sleep(1)
thread = Thread(target=camera_thread_main)
thread.daemon = True # <-- thread will exit when main thread exists
thread.start()
return thread
class CameraRGB_Async:
"""
Provide an asyncio interface to a camera. A thread is created to continually capture
frames from the camera.
WARNING: This class is meant to be a singleton. It cannot clean itself up. It is
meant to be instantiated once and used forever.
"""
def __init__(self, camera_factory, loop, idle_timeout):
self.idle_timeout = idle_timeout
self.ctl_queue = Queue()
self.cond = asyncio.Condition()
self.frame = None
self.started = False
self.last_seen = time.time()
self.thread = _init_bg_capture_thread(camera_factory, self.ctl_queue, self._frame_callback, loop)
self.idle_task = asyncio.create_task(self._idle_task())
async def capture(self):
self.last_seen = time.time()
if not self.started:
self.ctl_queue.put('start')
self.started = True
async with self.cond:
await self.cond.wait()
frame_here = self.frame
return frame_here
async def close(self):
if self.started:
self.ctl_queue.put('stop')
self.started = False
async def _frame_callback(self, frame_new):
async with self.cond:
self.frame = frame_new
self.cond.notify_all()
async def _idle_task(self):
while True:
if self.started and time.time() - self.last_seen > self.idle_timeout:
await self.close()
await asyncio.sleep(1)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This modules defines the interface for interacting programmatically
between your device and you online account at AutoAuto Labs.
"""
import abc
class LabsServiceIface(abc.ABC):
"""
This is the front-door interface for communicating with the AutoAuto Labs
servers from your device. This interface allows you to programmatically
interact with your account at AutoAuto Labs from the code running on your
device.
"""
@abc.abstractmethod
async def connect(self):
"""
Connect the backend service.
"""
pass
@abc.abstractmethod
async def send(self, msg):
"""
Send a message `msg` to your AutoAuto Labs account.
Return True if the message was sent, else return False.
"""
pass
@abc.abstractmethod
async def receive(self):
"""
Wait for the next message from the Labs server, then return it.
"""
pass
@abc.abstractmethod
async def close(self):
"""
Close the backend connection.
"""
pass
<file_sep>###############################################################################
#
# Copyright (c) 2017-2022 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains the interface to your device's controller(s).
Its name is CIO (Controller Input/Output).
"""
import abc
class CioRoot(abc.ABC):
"""
This is the front-door interface of the Controller IO ("cio"). You begin
by `init()`ing the controller, and if successful, you may then `acquire()`
and `release()` components which are provided by the controller.
"""
@abc.abstractmethod
async def init(self):
"""
Initialize the controller. If successful, this method returns a list
of capability ids (each capability id is a string). Else, this method
throws an exception (e.g. if the proper controller is not attached).
Each of the returned capability ids may be used to "acquire" an interface
to the corresponding component on the controller via the `acquire()`
method.
"""
pass
@abc.abstractmethod
async def acquire(self, capability_id):
"""
Acquire the component whose capability id is `capability_id`.
This method returns a *new* object which implements the capability's
interface. Once you are finished using the acquired component,
you should "release" it by passing the interface to the `release()`
method. Implementations of this method *must* return a new object
on each invocation (this is a limitation due to how the CIO RPC server
works).
"""
pass
@abc.abstractmethod
async def release(self, capability_obj):
"""
Release a previously acquired capability object. You should
pass the _actual_ object which was returned by the `acquire()`
method. This method returns `None`.
"""
pass
@abc.abstractmethod
async def close(self):
"""
Cleanly close the connection to the controller. All acquired
component interfaces will be released (thus their corresponding
objects will become stale and should not be used further).
You may safely re-`init()` if needed to continue using it.
"""
pass
class VersionInfoIface(abc.ABC):
"""
Check the Controller Version
Required: True
Capability Identifier: 'VersionInfo'
"""
@abc.abstractmethod
async def name(self):
"""
Return the name of the controller (e.g. the product
name and model number of the robot) as a string.
There is no specific format for this string, it is
intended to by human readable.
"""
pass
@abc.abstractmethod
async def version(self):
"""
Return the major and minor version of the software running on the controller
as a two-tuple.
"""
pass
class CredentialsIface(abc.ABC):
"""
Store and retrieve various authentication details.
Required: True
Capability Identifier: 'Credentials'
"""
@abc.abstractmethod
async def get_labs_auth_code(self):
"""
Return the stored authentication code.
This authentication code is used to authenticate
with the Labs servers.
"""
pass
@abc.abstractmethod
async def set_labs_auth_code(self, auth_code):
"""
Set (and save) the authentication code.
Might allow only a single write. Returns True/False if write was successful.
"""
pass
@abc.abstractmethod
async def get_jupyter_password(self):
"""
Return the Jupter password.
This password will be used by Jupyter to protect
network access.
"""
pass
@abc.abstractmethod
async def set_jupyter_password(self, password):
"""
Set (and save) the Jupter password.
Might allow only a single write. Returns True/False if write was successful.
"""
pass
class CameraIface(abc.ABC):
"""
Capture frames from the on-board camera.
Required: True
Capability Identifier: 'Camera'
"""
@abc.abstractmethod
async def capture(self):
"""
Capture and return one frame.
"""
pass
class LoopFrequencyIface(abc.ABC):
"""
Read the Controller's Loop Frequency (in Hz)
Required: False
Capability Identifier: 'LoopFrequency'
"""
@abc.abstractmethod
async def read(self):
"""
Returns the loop frequency of the microcontroller (in Hz).
"""
pass
class PowerIface(abc.ABC):
"""
Read the Battery Voltage
Required: True
Capability Identifier: 'Power'
"""
@abc.abstractmethod
async def state(self):
"""
Return the state of the power of this device.
Returns a string, one of:
- 'battery' : The device is running on battery power.
- 'wall' : The device is running on "wall" power (aka, has external power in some way).
- 'charging' : The device is charging its battery, which implies "wall" power as well.
"""
pass
@abc.abstractmethod
async def millivolts(self):
"""
Return the voltage of the battery (in millivolts) connected to the controller.
Reminder: 1000 millivolts = 1 volt
"""
pass
@abc.abstractmethod
async def estimate_remaining(self, millivolts=None):
"""
Given the battery voltage of `millivolts`, estimate of run-time remaining of
the batter (in minutes) and the percentage remaining of the battery (an
integer from 0 to 100). Return a two-tuple of `(minutes, percentage)`.
If you pass `millivolts=None`, the battery's current millivolts reading will
be queried and used.
"""
pass
@abc.abstractmethod
async def should_shut_down(self):
"""
Return True if the host device should shut down. The host
can poll this function (suggest once per 200-500ms) to know
when it needs to shut down. Two reasons for shutting down:
1. The power switch was triggered so the whole device will
soon loose power.
2. The battery is dangerously low and will drop out soon,
so the host should shut down immediately to be safe.
"""
pass
@abc.abstractmethod
async def shut_down(self):
"""
Instruct the device to shut itself down.
"""
pass
@abc.abstractmethod
async def reboot(self):
"""
Instruct the device to reboot itself.
"""
pass
class BuzzerIface(abc.ABC):
"""
Play Music!
Required: False
Capability Identifier: 'Buzzer'
"""
@abc.abstractmethod
async def is_currently_playing(self):
"""
Return true if the buzzer is currently playing music.
Return false if the buzzer is not. You cannot play new
music while the buzzer is currently playing music, so
you can use this method to check.
"""
pass
@abc.abstractmethod
async def wait(self):
"""
Block until the buzzer is not playing music anymore.
"""
pass
@abc.abstractmethod
async def play(self, notes="o4l16ceg>c8"):
"""
Tell the controller to play the notes described by the `notes` parameter.
If the controller is already playing notes, this function will wait for it
to finish then will play _these_ `notes`.
"""
pass
class GyroscopeIface(abc.ABC):
"""
Query the Gyroscope Sensor
Required: False
Capability Identifier: 'Gyroscope'
"""
@abc.abstractmethod
async def read(self):
"""
Read an (x, y, z) tuple-of-floats from the Gyroscope.
"""
pass
class GyroscopeAccumIface(abc.ABC):
"""
Query the Gyroscope Sensor with Internally-Accumulated Values
Required: False
Capability Identifier: 'Gyroscope_accum'
"""
@abc.abstractmethod
async def reset(self):
"""
Reset the (x, y, z) accumulators back to zero.
"""
pass
@abc.abstractmethod
async def read(self):
"""
Read the accumulated (x, y, z) tuple-of-floats from the Gyroscope.
"""
pass
class AccelerometerIface(abc.ABC):
"""
Query the Accelerometer Sensor
Required: False
Capability Identifier: 'Accelerometer'
"""
@abc.abstractmethod
async def read(self):
"""
Read an (x, y, z) tuple-of-floats from the Accelerometer.
"""
pass
class MagnetometerIface(abc.ABC):
"""
Query the Magnetometer Sensor
Required: False
Capability Identifier: 'Magnetometer'
"""
@abc.abstractmethod
async def read(self):
"""
Read an (x, y, z) tuple-of-floats from the Magnetometer.
"""
pass
class AhrsIface(abc.ABC):
"""
Query the computed AHRS ("Attitude and Header Reference System").
https://en.wikipedia.org/wiki/Attitude_and_heading_reference_system
Required: False
Capability Identifier: 'AHRS'
"""
@abc.abstractmethod
async def read(self):
"""
Get the current (roll, pitch, yaw) tuple-of-floats of the device.
"""
pass
class PushButtonsIface(abc.ABC):
"""
Query the Tactile Push Button(s)
Required: False
Capability Identifier: 'PushButtons'
"""
@abc.abstractmethod
async def num_buttons(self):
"""
Return the number of buttons on the device.
"""
pass
@abc.abstractmethod
async def button_state(self, button_index):
"""
Return the state of the button at the given index (zero-based).
Returns a tuple of (num_presses, num_releases, is_currently_pressed)
which are of types (int, int, bool).
"""
pass
@abc.abstractmethod
async def get_events(self):
"""
Return a list of buttons events that have happened since
the last call this method. The returned list will be empty
if no events have transpired.
"""
pass
@abc.abstractmethod
async def wait_for_event(self):
"""
Wait for the next event, and return it once it occurs.
"""
pass
@abc.abstractmethod
async def wait_for_action(self, action='pressed'):
"""
Wait for a certain button action to happen.
The `action` may be one of:
- "pressed" : Wait for a button to be pressed.
This is the default.
- "released": Wait for a button to be released.
- "any" : Wait for either a button to be pressed or released,
whichever happens first.
A two-tuple is returned `(button_index, action)`, where
`button_index` is the zero-based index of the button on which
the action occurred, and `action` is either "pressed" or "released".
"""
pass
class LEDsIface(abc.ABC):
"""
Set LED State
Required: False
Capability Identifier: 'LEDs'
"""
@abc.abstractmethod
async def led_map(self):
"""
Return identifiers and descriptions of the LEDs
available on this controller as a dictionary.
The keys are the identifiers used to control the LEDs
via the `set_led()` method.
"""
pass
@abc.abstractmethod
async def set_led(self, led_identifier, val):
"""
Set the LED on/off value.
"""
pass
@abc.abstractmethod
async def set_many_leds(self, id_val_list):
"""
Pass a list of tuples, where each tuple is an LED identifier
and the value you want it set to.
"""
pass
@abc.abstractmethod
async def mode_map(self):
"""
Return identifiers and descriptions of the LED modes
that are available as a dictionary.
The keys are the identifiers used to set the mode
via the `set_mode()` method.
"""
pass
@abc.abstractmethod
async def set_mode(self, mode_identifier):
"""
Set the `mode` of the LEDs.
Pass `None` to clear the mode, thereby commencing
basic on/off control via the `set_led()` method.
"""
pass
@abc.abstractmethod
async def set_brightness(self, brightness):
"""
Set the brightness of the LEDs, in the range [0-255].
Raises if not supported by the hardware you have.
Setting `brightness=0` means set the brightness to the
default value.
"""
pass
class AdcIface(abc.ABC):
"""
Query the Analog-to-Digital Converter (ADC)
Required: False
Capability Identifier: 'ADC'
"""
@abc.abstractmethod
async def num_pins(self):
"""
Return the number of ADC pins on this controller.
"""
@abc.abstractmethod
async def read(self, index):
"""
Read and return the voltage (in Volts) of the ADC pin
at index `index`. The first pin is index-0 (i.e.
zero-based indexing). Call `num_pins()` to know the
index range.
"""
pass
class PhotoresistorIface(abc.ABC):
"""
Query the Photoresistor
Required: False
Capability Identifier: 'Photoresistor'
"""
@abc.abstractmethod
async def read(self):
"""
Read the voltage of the photoresistor pin, and read
the computed resistance of the photoresistor. Return
both as a two-tuple `(millivolts, ohms)`.
"""
pass
@abc.abstractmethod
async def read_millivolts(self):
"""
Read the raw voltage of the photoresistor pin.
"""
pass
@abc.abstractmethod
async def read_ohms(self):
"""
Read the resistance of the photoresistor (in ohms). The photoresistor's
resistance changes depending on how much light is on it, thus the name!
"""
pass
class EncodersIface(abc.ABC):
"""
Query the Quadrature Encoder(s)
Required: False
Capability Identifier: 'Encoders'
"""
@abc.abstractmethod
async def num_encoders(self):
"""
Return the number of Quadrature Encoders on this controller.
"""
pass
@abc.abstractmethod
async def enable(self, encoder_index):
"""
Enable an encoder. The first encoder is index-0.
"""
pass
@abc.abstractmethod
async def read_counts(self, encoder_index):
"""
Read the counts of the encoder. The first encoder is index-0.
The count is reset to zero when the encoder is enabled.
A three-tuple is returned:
- Number of "clicks" (a signed value).
- Pin A change count (an unsigned, positive value).
- Pin B change count (an unsigned, positive value).
"""
pass
@abc.abstractmethod
async def read_timing(self, encoder_index):
"""
Return the number of microseconds that each of the two pins on the first
encoder (e1) are high (i.e. the duration the pin stays in the high state).
This can be used to read a PWM signal (assuming the PWM signal has a known,
fixed frequency). If the pin has not gone high-then-low recently (within
the last half-second), the value returned here will be 0 to indicate
it is not presently known (i.e. the PWM signal is not currently coming
through). A two-tuple is returned by this method: `(pin_a_usecs, pin_b_usecs)`.
Recall: 1000000 microseconds = 1 second
"""
pass
@abc.abstractmethod
async def disable(self, encoder_index):
"""
Disable an encoder. The first encoder is index-0.
"""
pass
class CarMotorsIface(abc.ABC):
"""
Control the Robots which are in the "Car Form Factor"
Required: False
Capability Identifier: 'CarMotors'
"""
@abc.abstractmethod
async def on(self):
"""
Tell the car to begin powering its motors (the main motor and the servo).
"""
pass
@abc.abstractmethod
async def set_steering(self, steering):
"""
Set the car's steering (i.e. move the servo).
Pass a value in the range [-45, 45] to represent [full-right, full-left].
"""
pass
@abc.abstractmethod
async def set_throttle(self, throttle):
"""
Set the car's throttle (i.e. power send to the main motor).
Pass a value in the range [-100, 100] to represent [full-reverse, full-forward].
"""
pass
@abc.abstractmethod
async def get_safe_throttle(self):
"""
Return the range of the "safe" throttle values, where "safe" means
the resulting speed will be slow enough for the typical indoor classroom
environment. A two-tuple is returned `(min_throttle, max_throttle)`.
**Disclaimer:** Any and all movement of the vehicle can result in injury
if proper safety precautions are not taken. It is the
responsibility of the user to use the device in a safe
manner at all times.
"""
pass
@abc.abstractmethod
async def set_safe_throttle(self, min_throttle, max_throttle):
"""
Store a new "safe" throttle range; will be returned by `get_safe_throttle()`
on subsequent calls.
"""
pass
@abc.abstractmethod
async def off(self):
"""
Turn off the car's motors.
"""
pass
class PWMsIface(abc.ABC):
"""
Control the PWM-capable Pins on the Controller
Required: False
Capability Identifier: 'PWMs'
"""
@abc.abstractmethod
async def num_pins(self):
"""
Return the number of pins which support PWM on this controller.
"""
pass
@abc.abstractmethod
async def enable(self, pin_index, frequency, duty=0):
"""
Enable PWM on a given pin at a given frequency (in Hz). The first pin is index-0.
An error will be thrown if the desired frequency is not possible. The duty cycle
will be 0% by default (pass the `duty` parameter to enable it at a non-zero duty
cycle). Call `set_duty()` to change the duty cycle of this pin once it is enabled.
**NOTE**: On most microcontrollers, there will be two or more pins that are driven
by the same internal timer, thus the frequency of those pins must be the
same. If this is the case and you try to set different frequencies, you
will get an exception.
"""
pass
@abc.abstractmethod
async def set_duty(self, pin_index, duty):
"""
Set the duty cycle of the pin's PWM output. The duty
cycle is given as a percentage in the range [0.0, 100.0].
You may pass integer or float values. The controller
will match the desired duty cycle as closely as possible
subject to its internal resolution.
"""
pass
@abc.abstractmethod
async def disable(self, pin_index):
"""
Disable PWM on a given pin. The first pin is index-0.
"""
pass
class CalibratorIface(abc.ABC):
"""
Instruct the Controller to Start the Calibration Process
Required: False
Capability Identifier: 'Calibrator'
"""
@abc.abstractmethod
async def start(self):
"""
Instruct the controller to start its calibration process.
"""
pass
@abc.abstractmethod
async def status(self):
"""
Check the status of the calibration process.
Returns the identifier of the current step.
Status identifiers may be integers or strings.
Each controller has its own identifiers and
its own meaning for each identifier. You must
refer to the specific controller's documentation
to understand what each status identifier means.
The only common identifiers between all controllers
are the following:
- The integer 0 means the calibration process
has not started.
- The integer -1 means the calibration process
was started and has now finished.
"""
pass
@abc.abstractmethod
async def script_name(self):
"""
Return the name of the script used
for calibrating this device. On
a properly configured system, this
script will be somewhere in the
user's PATH.
"""
pass
class PidIface(abc.ABC):
"""
Control a PID Loop on the Controller
THIS INTERFACE IS GENERIC; SPECIFIC PID LOOPS WILL
INHERIT FROM IT AND IMPLEMENT IT. FOR EXAMPLE, SEE:
`PID_steering`
"""
@abc.abstractmethod
async def set_pid(self, p, i, d, error_accum_max=0.0, save=False):
"""
Sets P, I, and D. If the device has no default values for this PID
loop, you should be sure to call this method `set_pid()` before calling
`enable()`.
If `save` is set, then these values will be saved to persistent storage
and used as the defaults in the future.
`error_accum_max` is the max accumulated error that will be accumulated.
This is a common thing that is done to tame the PID loop and not crazy overshoot
due to `I` accumulating unreasonably high. Zero means there is no limit.
"""
pass
@abc.abstractmethod
async def set_point(self, point):
"""
Set the sensor's "set point". The actuator will be controlled so that
the sensor stays at the "set point".
"""
pass
@abc.abstractmethod
async def enable(self, invert_output=False):
"""
Enable the PID loop within the controller (i.e. begin to drive the actuator to
the set point).
You should call `set_pid()` and `set_point()` before `enable()` so that
the actuator is properly driven immediately upon being enabled. Once
enabled, you can repeatedly call `set_point()` as needed.
"""
pass
@abc.abstractmethod
async def disable(self):
"""
Disable the PID loop within the controller (i.e. stop driving the actuator).
"""
pass
class PidSteeringIface(PidIface):
"""
Control the Device's Steering with a PID Loop
Required: False
Capability Identifier: 'PID_steering'
"""
pass # <-- See abstract methods of `PidIface`
class CarControlIface(abc.ABC):
"""
Uses `CarMotors`, `PID_steering`, `Gyroscope_accum`, and `Encoders`
to drive a car-form-factor robot with high-level commands.
Required: False
Capability Identifier: 'CarControl'
"""
@abc.abstractmethod
async def on(self):
"""
Tell the car to begin powering its motors (the main motor and the servo)
and active its other sensors (gyroscope, PID steering, encoders, if
present).
"""
pass
@abc.abstractmethod
async def straight(self, throttle, sec=None, cm=None):
"""
Drive the car *straight* at the given `throttle` value.
This function uses the car's gyroscope (if present) to continually keep
the car pointing in the same direction in which it started (aka, "active
steering stabilization").
If `sec` is provided (not None), then the car will drive for that many
seconds. Else, if `cm` is provided (not None), then the car will drive
for that many centimeters (only works on cars with wheel encoders). It
is an error to pass neither `sec` nor `cm`. It is also an error to pass
both `sec` and `cm`.
"""
pass
@abc.abstractmethod
async def drive(self, steering, throttle, sec=None, deg=None):
"""
Drive the car at the given wheel `steering` and at the given `throttle`
value. See `CarMotorsIface`s `set_steering()` and `set_throttle()`
for details of the values these parameters can take.
If `sec` is provided (not None), then the car will drive for that many
seconds. Else, if `deg` is provided (not None), then the car will drive
until it rotates by that many degrees (if provided, `deg` must be a
positive value; this functionality only works for cars with gyroscopes).
It is an error to pass neither `sec` nor `deg`. It is also an error to
pass both `sec` and `deg`.
Note: If you use this function to drive the car *straight*
(i.e. `steering=0`), the car may still veer because this function
does _not_ actively stabilize for going straight. If you desire
active stabilization for going straight, use the `straight()`
method instead.
"""
pass
@abc.abstractmethod
async def off(self):
"""
Turn off the car's motors and disable any other sensors that were being
used.
"""
pass
class LidarIface(abc.ABC):
"""
Query the Lidar system of your device!
Required: False
Capability Identifier: 'Lidar'
"""
@abc.abstractmethod
async def single(self, theta=0, phi=90):
"""
Query in a single direction, denoted by `theta` and `phi`
(using spherical coordinates), where the origin is the
Lidar sensor's current position.
Parameters:
- `theta`: rotation (in degrees) in the horizontal plane;
`theta=0` points straight "forward"; positive `theta` is
to the left; negative `theta` is to the right.
- `phi`: rotation (in degrees) away from the vertical axis;
`phi=0` points straight "up" the vertical axis; positive `phi`
moves off the vertical axis; `phi=90` lies on the horizontal
plane; `phi=180` points opposite the vertical axis ("down").
Returns `r` which is the distance (in meters) to the closest object
in the direction denoted by `theta` and `phi`. Returns `r = None`
if no object was detected.
"""
pass
@abc.abstractmethod
async def sweep(self, theta_1=90, phi_1=90, theta_2=-90, phi_2=90):
"""
Sweep the sensor from (`theta_1`, `phi_1`) to (`theta_2`, `phi_2`)
and query 16 times during the sweep motion. The sensor will query
at equal intervals along the sweep path, where the first query
happens at (`theta_1`, `phi_1`) and the last query happens at
(`theta_2`, `phi_2`).
Returns a list of 16 values of `r`.
See `single()` for a description of `theta`, `phi`, and `r`.
Using this method `sweep()` is more efficient than calling `single()`
over-and-over.
"""
pass
class CompassIface(abc.ABC):
"""
Query your device's Compass!
Required: False
Capability Identifier: 'Compass'
"""
@abc.abstractmethod
async def query(self):
"""
Query the Compass sensor.
Returns `theta`, a single angle (in degrees) representing your
device's deviation from magnetic north.
- `theta = 0` means your device is pointing directly north.
- `theta = 90` means your device is pointing directly west.
- `theta = 180` means your device is pointing directly south.
- `theta = 270` means your device is pointing directly east.
"""
pass
@abc.abstractmethod
async def heading(self):
"""
Query the Compass sensor and return a true heading of your device.
**ONLY AVAILABLE ON VIRTUAL DEVICES!**
Real-world compasses cannot give you this information, but the
"virtual" compass can. :)
Returns a tuple (`theta`, `phi`) describing the true heading of
your device. `theta` is an angle (in degrees) of your device's
rotation in the world's horizontal plane. `phi` is an angle (in
degrees) of your device's rotation away from the vertical axis.
See `Lidar.single()` for more info on the concept of `theta` and
`phi` and on the concept of spherical coordinates.
"""
pass
class GpsIface(abc.ABC):
"""
Query your device's GPS sensor!
Required: False
Capability Identifier: 'GPS'
"""
@abc.abstractmethod
async def query(self):
"""
Query the GPS sensor. The return value depends on the type of device
you are using:
For *physical* devices, the return value is a point using the
*Geographic coordinate system*, thus it is a three-tuple:
(`latitude`, `longitude`, `altitude`)
For *virtual* devices, the return value is a point using the
*Cartesian coordinate system*, thus it is a three-tuple:
(`x`, `y`, `z`)
"""
pass
class ReconIface(abc.ABC):
"""
Your device's Reconnaissance sensor (*virtual* devices only)
Required: False
Capability Identifier: 'Recon'
"""
@abc.abstractmethod
async def query(self, theta_1=90, theta_2=-90, r=10000):
"""
Detect enemy devices within a certain space around your
device, as defined by `theta_1`, `theta_2`, and `r`.
The space queried ranges in your device's horizontal
plane from `theta_1` to `theta_2` (both in degrees)
and extends `r` meters away from your device.
These "theta" values (in degrees) affect the sensor's
detection space around your device's horizontal plane:
- `theta = 0` is "forward" of your device
- `theta = 90` is "directly left"
- `theta = -90` is "directly right"
For example, querying with `theta_1 = 45` and `theta_2 = -45`
will query a 90-degree circular sector in front of your device.
Another example, querying with `theta_1 = 0` and `theta_2 = 360`
will query for *all* devices near you, no matter what angle they
are from you.
Another example, querying with `theta_1 = 90` and `theta_2 = 270`
will query in the half-circle space "behind" your device.
The `r` value (a distance in meters) affects the sensor's query
radius from your device. E.g. `r = 100` will detect enemy devices
within 100 meters of your device.
Note: To precisely locate an enemy, you can binary search the
`theta_*` space, then binary search the `r` space.
This query returns a list of device VINs which were found in the
queried space. An empty list is returned if no devices are found.
"""
pass
class WeaponsIface(abc.ABC):
"""
Your device's Weapons system (*virtual* devices only)
Required: False
Capability Identifier: 'Weapons'
"""
@abc.abstractmethod
async def fire(self, theta=0, phi=90, velocity=40):
"""
Fire your device's default weapon in the direction
defined by `theta` and `phi` (both in degrees) and
with a velocity of `velocity` (in meters/second).
See `LidarIface.single()` for a description of `theta`
and `phi`.
"""
pass
class PhysicsClientIface(abc.ABC):
"""
Instruct the physics client. This is only used for virtual devices.
Required: False
Capability Identifier: 'PhysicsClient'
"""
@abc.abstractmethod
async def control(self, msg):
"""
Pass this control-message to the physics client.
"""
pass
@abc.abstractmethod
async def wait_tick(self):
"""
Wait until the next physics engine "tick". The physics
engine does 20 updates per second (each is called a "tick"),
and it sends a message to us after each update. Thus, this
method simply waits for the next message to arrive and then
returns. You can use this method to do computation in lock-step
with the physics engine, as it is silly to do certain things
faster than the physics engine (e.g. querying GPS) since updates
only happen after each "tick".
"""
pass
@abc.abstractmethod
async def sleep(self, seconds):
"""
Sleeps for approximately `seconds` by counting "ticks" from the
physics engine. This provides a way to sleep in lock-step with
the physics engine to minimize drift.
"""
pass
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
Demo steering the car. Note: This script must run before anything else
has launched, thus we launch our own controller server here (and let
it die once this script terminates).
"""
from auto.services.controller.server import init as controller_init
from auto.asyncio_tools import get_loop
import asyncio
from car.motors import set_steering
import time
def demo_steering():
time.sleep(1.5)
set_steering(-45.0)
time.sleep(1.0)
set_steering(45.0)
time.sleep(1.0)
set_steering(0.0)
time.sleep(2.0)
if __name__ == '__main__':
loop = get_loop()
future = asyncio.run_coroutine_threadsafe(controller_init(), loop)
_ = future.result()
demo_steering()
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This modules provides an **asynchronous** LabsServiceIface implementation.
"""
import asyncio
from auto.rpc.client import client
from auto.services.labs.rpc import LabsServiceIface
class LabsService(LabsServiceIface):
def __init__(self, inet_addr='127.0.0.1', inet_port=7004):
self.inet_addr = inet_addr
self.inet_port = inet_port
self.is_connected = False
self.is_subscribed = False
async def connect(self):
if not self.is_connected:
self._proxy_interface, self._pubsub_channels, self._subscribe_func, self._close = \
await client(self.inet_addr, self.inet_port)
self.is_connected = True
async def send(self, msg):
if not self.is_connected:
raise Exception("You must first call `connect()` before you can call `send()`.")
return await self._proxy_interface.send(msg)
async def receive(self):
if not self.is_connected:
raise Exception("You must first call `connect()` before you can call `receive()`.")
if not self.is_subscribed:
self.is_subscribed = True
self.inbound_message_queue = asyncio.Queue()
_ = await self._subscribe_func('messages', self._new_message_callback)
return await self.inbound_message_queue.get()
async def close(self):
if self.is_connected:
self.is_connected = False
await self._close()
async def _new_message_callback(self, channel, msg):
await self.inbound_message_queue.put(msg)
async def _demo():
labs = LabsService()
await labs.connect()
for i in range(5):
did_send = await labs.send({'hi': 'there'})
print('Did Send?', did_send)
await labs.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(_demo())
loop.run_until_complete(loop.shutdown_asyncgens())
# Running the loop "forever" (`loop.run_forever()`) will _also_ shutdown async generators,
# but then you are stuck with a forever-running-loop! The call above allows us to tear
# down everything cleanly (including generator finally blocks) before the program terminates.
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from .easyi2c import (write_read_i2c_with_integrity,
i2c_retry,
i2c_poll_until)
from . import N_I2C_TRIES
from .components import KNOWN_COMPONENTS
from auto import logger
log = logger.init(__name__, terminal=True)
import struct
CAPABILITIES_REG_NUM = 0x01
MAX_COMPONENT_NAME_LEN = 25
@i2c_retry(N_I2C_TRIES)
async def soft_reset(fd):
"""
Instruct the controller's capabilities module to do a soft-reset.
This means that the list of enabled components will be reverted to
the default list of enabled components and the list of available
components will be repopulated.
"""
await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x00], 0)
@i2c_retry(N_I2C_TRIES)
async def is_ready(fd):
"""
Check to see if the controller is ready for normal operation. This
is important to do on startup and after a hard- or soft-reset. It's
even better to poll this function to wait for the controller to be
ready, i.e.
| await soft_reset(fd)
|
| async def _is_ready():
| return await is_ready(fd)
|
| await i2c_poll_until(_is_ready, True, timeout_ms=1000)
"""
ready, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x01], 1)
return ready == 1
@i2c_retry(N_I2C_TRIES)
async def get_num_components(fd, only_enabled):
"""
Retrieve the number of components in either the list of available components
(when `only_enabled=False`) or the list of enabled components (when `only_enabled=True`).
"""
which_list = 0x01 if only_enabled else 0x00
lsb, msb = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x02, which_list], 2)
return (msb << 8) | lsb
@i2c_retry(N_I2C_TRIES)
async def get_list_of_components(fd, n_components, only_enabled):
"""
Retrieve either the list of available components (when `only_enabled=False`)
or the list of enabled components (when `only_enabled=True`). This returns a
list of components' register numbers. You must pass `n_components` to this
function so that it know how many components are in the list (you should
call `get_num_components` to obtain `n_components`).
"""
which_list = 0x01 if only_enabled else 0x00
buf = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x03, which_list], n_components)
return list(buf)
@i2c_retry(N_I2C_TRIES)
async def get_component_name(fd, register_number):
"""
Retrieve the component name whose register number is `register_number`.
"""
buf = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x04, register_number], MAX_COMPONENT_NAME_LEN)
return buf.replace(b'\x00', b'').decode('utf8')
@i2c_retry(N_I2C_TRIES)
async def enable_component(fd, register_number):
"""
Enable the controller's component whose register number is `register_number`.
Return a string representing the state of the component, or raise an exception
on error.
Note: After you enable a component, you should wait for the controller to tell you
that it has _actually_ been enabled before you try to communicate with it.
See how it is done in `acquire_component_interface()`.
"""
indicator, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x05, register_number], 1)
if indicator == 0: indicator = "already enabled"
elif indicator == 1: indicator = "now enabled"
elif indicator == 0xFF: raise Exception("invalid register address!")
else: raise Exception("unknown return value: {}".format(indicator))
log.info('Enabled component register number {}; status is: {}'.format(register_number, indicator))
return indicator
@i2c_retry(N_I2C_TRIES)
async def disable_component(fd, register_number):
"""
Disable the controller's component whose register number is `register_number`.
Return a string representing the state of the component, or raise an exception
on error.
Note: After you disable a component, you should wait for the controller to tell
you that it has _actually_ been disabled. See how it is done in
`release_component_interface()`.
"""
indicator, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x06, register_number], 1)
if indicator == 0: indicator = "already disabled"
elif indicator == 1: indicator = "now disabled"
elif indicator == 0xFF: raise Exception("invalid register address!")
else: raise Exception("unknown return value: {}".format(indicator))
log.info('Disabled component register number {}; status is: {}'.format(register_number, indicator))
return indicator
@i2c_retry(N_I2C_TRIES)
async def get_component_status(fd, register_number):
"""
Return a string representing the component's status. It will be one of:
- ENABLE_PENDING
- ENABLED
- DISABLE_PENDING
- DISABLED
Or raise an error.
"""
indicator, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x07, register_number], 1)
if indicator == 0: return 'DISABLED'
if indicator == 1: return 'ENABLE_PENDING'
if indicator == 2: return 'ENABLED'
if indicator == 3: return 'DISABLE_PENDING'
raise Exception("unknown return value: {}".format(indicator))
@i2c_retry(N_I2C_TRIES)
async def _eeprom_store(fd, addr, buf):
if not isinstance(buf, bytes):
raise Exception('`buf` should be `bytes`')
if len(buf) > 4:
raise Exception('you may only store 4 bytes at a time')
if addr < 0 or addr + len(buf) > 1024:
raise Exception('invalid `addr`: EEPROM size is 1024 bytes')
payload = list(struct.pack('1H', addr)) + [len(buf)] + list(buf)
await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x08] + payload, 0)
@i2c_retry(N_I2C_TRIES)
async def _is_eeprom_store_finished(fd):
status, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x09], 1)
return status == 0
@i2c_retry(N_I2C_TRIES)
async def _eeprom_query(fd, addr, length):
if length > 4:
raise Exception('you may only retrieve 4 bytes at a time')
if addr < 0 or addr + length > 1024:
raise Exception('invalid `addr`: EEPROM size is 1024 bytes')
payload = list(struct.pack('1H', addr)) + [length]
await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x0A] + payload, 0)
@i2c_retry(N_I2C_TRIES)
async def _is_eeprom_query_finished(fd):
status, = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x0B], 1)
return status == 0
@i2c_retry(N_I2C_TRIES)
async def _retrieve_eeprom_query_buf(fd, length):
buf = await write_read_i2c_with_integrity(fd, [CAPABILITIES_REG_NUM, 0x0C], length)
return buf
async def eeprom_store(fd, addr, buf):
await _eeprom_store(fd, addr, buf)
async def is_eeprom_store_finished():
return await _is_eeprom_store_finished(fd)
await i2c_poll_until(is_eeprom_store_finished, True, timeout_ms=1000)
async def eeprom_query(fd, addr, length):
await _eeprom_query(fd, addr, length)
async def is_eeprom_query_finished():
return await _is_eeprom_query_finished(fd)
await i2c_poll_until(is_eeprom_query_finished, True, timeout_ms=1000)
return await _retrieve_eeprom_query_buf(fd, length)
async def get_capabilities(fd, soft_reset_first=False, only_enabled=False):
"""
Return a dictionary representing the capabilities of the connected controller.
"""
if soft_reset_first:
await soft_reset(fd)
async def _is_ready():
return await is_ready(fd)
await i2c_poll_until(_is_ready, True, timeout_ms=1000)
n_components = await get_num_components(fd, only_enabled)
register_numbers = await get_list_of_components(fd, n_components, only_enabled)
caps = {}
for reg in register_numbers:
name = await get_component_name(fd, reg)
if name == 'BatteryVoltageReader': name = 'Power'
if name != "Capabilities":
caps[name] = {
'register_number': reg,
}
caps[name]['is_enabled'] = (await get_component_status(fd, reg) == 'ENABLED')
if 'Timer1PWM' in caps and 'Timer3PWM' in caps:
# Bodge.
t1_reg_num = caps['Timer1PWM']['register_number']
t3_reg_num = caps['Timer3PWM']['register_number']
is_enabled = caps['Timer3PWM']['is_enabled']
caps['PWMs'] = {'register_number': (t1_reg_num, t3_reg_num), 'is_enabled': is_enabled}
del caps['Timer1PWM']
del caps['Timer3PWM']
for c in ['Credentials', 'Calibrator']:
caps[c] = {
'register_number': None, # <-- this is a virtual component; it is implemented on the Python side, not the controller side
'is_enabled': False
}
return caps
async def acquire_component_interface(fd, caps, ref_count, component_name):
"""
Acquire the interface to the component having the name `component_name`.
This is a helper function which will:
1. Enable the component.
2. Wait for the controller to be ready.
3. Lookup, build, and return the interface object for the component.
Note, when you are finished using the components interface, you should
call `release_component_interface`.
"""
register_number = caps[component_name]['register_number']
interface = KNOWN_COMPONENTS[component_name](fd, register_number)
interface.__fd__ = fd
interface.__reg__ = register_number
interface.__component_name__ = component_name
if not isinstance(register_number, (tuple, list)):
register_number = [register_number]
for n in register_number:
if n is None:
continue
if n not in ref_count:
# It must not be enabled and the ref count must currently be zero.
ref_count[n] = 1
else:
# The component is already enabled, we just need to inc the ref count.
ref_count[n] += 1
log.info('Acquired {}, register number {}, now having ref count {}.'.format(component_name, n, ref_count[n]))
# ALWAYS ENABLE THE COMPONENT AND WAIT FOR IT.
# We must have a bug in the controller code... because for some reason
# we have to enable the components which are already enabled by default.
# My best guess is that we need to add a few `volatile` keywords... that
# is, my best guess is that the `status` of the component in the controller
# is being held in a register (or some cache line). The behavior I'm seeing
# is that the `if` condition in the link below is not evaluating to `true`
# (even though it should!) ... thus my theory about the caching of the
# `status`. It's still a wild guess, really, so who knows.
# https://github.com/MasterAI-Inc/autoauto-controller/blob/0c234f3e8abfdc34a5011481e140998560097cbc/libraries/aa_controller/Capabilities.cpp#L526
# Anyway, if that bug were fixed, then the whole next bock would be moved
# such that it would only run `if n not in ref_count` above.
for n in register_number:
if n is None:
continue
await enable_component(fd, n)
async def _get_component_status():
return await get_component_status(fd, n)
await i2c_poll_until(_get_component_status, 'ENABLED', timeout_ms=1000)
return interface
async def release_component_interface(ref_count, interface):
"""
Release the component `interface` by disabling the underlying component.
This function only works for interfaces returned by `acquire_component_interface`.
"""
fd = interface.__fd__
register_number = interface.__reg__
component_name = interface.__component_name__
if not isinstance(register_number, (tuple, list)):
register_number = [register_number]
for n in register_number:
if n is None:
continue
if n not in ref_count:
# Weird... just bail.
continue
ref_count[n] -= 1
log.info('Released {}, register number {}, now having ref count {}.'.format(component_name, n, ref_count[n]))
if ref_count[n] == 0:
# This is the last remaining reference, so we'll disable the component.
await disable_component(fd, n)
async def _get_component_status():
return await get_component_status(fd, n)
await i2c_poll_until(_get_component_status, 'DISABLED', timeout_ms=1000)
del ref_count[n]
<file_sep>###############################################################################
#
# Copyright (c) 2017-2023 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import os
__version__ = '2.14.0'
IS_VIRTUAL = os.environ.get('MAI_IS_VIRTUAL', 'False').lower() in ['true', 't', '1', 'yes', 'y']
def print_all(*args, **kwargs):
"""
Prints to both standard out (as the build-in `print` does by default), and
also prints to the AutoAuto console!
"""
from auto.console import print as aa_console_print
aa_console_print(*args, **kwargs)
print(*args, **kwargs)
def _ctx_print_all(*args, **kwargs):
"""
This function does `print_all` on regular devices,
but prints only to stdout on virtual devices.
Why? Because we don't want so much printing to the
"console" on virtual devices, since virtual devices
don't have a standard LCD screen for the console UI,
thus printing to the console on virtual devices is
more "in your face" and can be distracting if we print
too much to it.
"""
if IS_VIRTUAL:
print(*args, **kwargs)
else:
print_all(*args, **kwargs)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
import asyncio
import time
from pprint import pprint
import cio.aa_controller_v2 as controller
async def run():
c = controller.CioRoot()
caps = await c.init()
pprint(caps)
iface = await c.acquire('VersionInfo')
n = 0
start = time.time()
while True:
_ = await iface.version()
n += 1
now = time.time()
if (now - start) >= 1.0:
print(n)
start = now
n = 0
await c.release(iface)
await c.close()
if __name__ == '__main__':
asyncio.run(run())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module proves an RPC client designed to connect via websocket to the
RPC server.
"""
import asyncio
import websockets
from auto.rpc.packer import pack, unpack
from auto.rpc.build_interface import build_interface
async def client(inet_addr='127.0.0.1', inet_port=7000):
"""
This function connects to the RPC server via websocket at the IP address
given by `inet_addr` and on the port `inet_port`. It returns the reconstructed
interface which was provided/exported by the server.
"""
uri = f"ws://{inet_addr}:{inet_port}"
ws = await websockets.connect(uri)
iface_buf = await ws.recv()
pubsub_channels_buf = await ws.recv()
iface = unpack(iface_buf)
pubsub_channels = unpack(pubsub_channels_buf)
id_ = 0
invoke_events = {}
subscriptions = {}
async def impl_transport(path, args):
nonlocal id_
id_here = id_
id_ += 1
event = asyncio.Event()
invoke_events[id_here] = {
'event': event,
}
cmd = {
'type': 'invoke',
'id': id_here,
'path': path,
'args': args,
}
cmd = pack(cmd)
await ws.send(cmd)
await event.wait()
message = invoke_events[id_here]['result_message']
del invoke_events[id_here]
if 'val' in message:
return message['val'] # Standard return value
elif 'exception' in message:
error_text = message['exception']
# TODO: Rebuild the exception more precisely.
raise Exception(error_text)
elif 'iface' in message:
sub_iface = message['iface']
_, sub_proxy_iface = build_interface(sub_iface, impl_transport)
return sub_proxy_iface
else:
raise Exception('Unknown response message...')
return val
_, proxy_interface = build_interface(iface, impl_transport)
async def read_ws():
try:
while True:
message = await ws.recv()
message = unpack(message)
type_ = message['type']
if type_ == 'invoke_result':
id_ = message['id']
if id_ in invoke_events:
invoke_events[id_]['result_message'] = message
event = invoke_events[id_]['event']
event.set()
elif type_ == 'publish':
channel = message['channel']
payload = message['payload']
callbacks = subscriptions.get(channel, [])
tasks = []
for c in callbacks:
task = asyncio.create_task(c(channel, payload))
tasks.append(task)
await asyncio.wait(tasks)
except websockets.exceptions.ConnectionClosed:
pass
asyncio.create_task(read_ws())
async def subscribe_func(channel, callback):
if channel not in subscriptions:
subscriptions[channel] = {callback}
await ws.send(pack({
'type': 'subscribe',
'channel': channel,
}))
else:
subscriptions[channel].add(callback)
async def unsubscribe_func():
subscriptions[channel].remove(callback)
if len(subscriptions[channel]) == 0:
del subscriptions[channel]
await ws.send(pack({
'type': 'unsubscribe',
'channel': channel,
}))
return unsubscribe_func
async def close():
await ws.close()
return proxy_interface, pubsub_channels, subscribe_func, close
async def _demo():
proxy_interface, pubsub_channels, subscribe_func, close = await client()
print(proxy_interface)
print(pubsub_channels)
async def callback(channel, payload):
print('callback', channel, payload)
await subscribe_func(pubsub_channels[0], callback)
for i in range(4):
result = await proxy_interface.foo(4 + i)
print(result)
await asyncio.sleep(15)
await close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(_demo())
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
from . import capabilities
from .easyi2c import i2c_poll_until
async def soft_reset(fd):
"""
Instruct the controller to reset itself. This is a software-reset only.
"""
await capabilities.soft_reset(fd)
async def _is_ready():
return await capabilities.is_ready(fd)
await i2c_poll_until(_is_ready, True, timeout_ms=1000)
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module provides many pre-trained and/or pre-configured models which
enable your device to exhibit more advanced behaviors. These models each
provide easy interfaces which abstract the underlying algorithms.
This is a **synchronous** interface.
"""
import os
import cv2
import numpy as np
from collections import defaultdict
RESOURCE_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources')
class ColorClassifier:
"""
This class processes images and classifies the color which appears in the
center region of each image. It classifies the center region as containing
one of the RAINBOW or NEUTRAL colors.
"""
RAINBOW = {
'red' : (255, 0, 0),
'orange' : (255, 128, 0),
'yellow' : (255, 255, 0),
'green' : ( 0, 255, 0),
'sky blue': ( 0, 255, 255),
'blue' : ( 0, 0, 255),
'purple' : (127, 0, 255),
'pink' : (255, 0, 255),
}
NEUTRAL = {
'black' : ( 0, 0, 0),
'white' : (255, 255, 255),
}
def __init__(self, center_region_width=0.25,
center_region_height=0.25,
colors={**RAINBOW, **NEUTRAL},
min_thresh_to_classify=0.5,
):
"""
Build a color classifier object which looks at the center region of
an image and determines if it contains primarily any of the RAINBOW
or NEUTRAL colors. If the prominent color does not appear in at
least 10% (min_thresh_to_classify) of the center region then the
classified color will be 'background'. The size of the center
region is given by the parameters `center_region_width` and
`center_region_height`. If colors is passed in then the keys must
be a subset of RAINBOW/NEUTRAL.
"""
self.center_region_width = center_region_width
self.center_region_height = center_region_height
# Colors as canonical vectors [R,G,B]:
self.colors = colors
# minimum proportion of pixels in order to classify as color
self.min_thresh_to_classify = min_thresh_to_classify
# Cache the color HSV spans.
self.hsv_span_cache = {color: self._get_hsv_spans(color) for color in self.colors}
def classify(self, frame, annotate=False, print_debug=False):
"""
Classify the center region of `frame` as having primarily one of
the RAINBOW or NEUTRAL colors or 'background'.
The `frame` parameter must be a numpy array containing an RGB image.
Returns a tuple of the form (`p1`, `p2`, `color_label).
"""
# Check `frame` for correct shape. It should be an 3-channel, 2d image.
if frame.ndim != 3 or frame.shape[2] != 3:
raise Exception("incorrect frame shape: Please input an RGB image.")
# Define the center region of `frame`.
height, width, _ = frame.shape
y_center = height/2
x_center = width/2
p1 = int(x_center - (width * self.center_region_width)/2), \
int(y_center - (height * self.center_region_height)/2)
p2 = int(x_center + (width * self.center_region_width)/2), \
int(y_center + (height * self.center_region_height)/2)
# Crop the center region.
center_frame = frame[ p1[1]:p2[1], p1[0]:p2[0] ]
color_name = self._get_prominent_color(center_frame)
if annotate:
self.annotate(p1, p2, color_name, frame)
return p1, p2, color_name
def _get_prominent_color(self, rgb_img):
"""
Parameters:
rgb_img (numpy array [shape=(height, width, 3)]):
image containing 3-channel RGB values
Returns:
prominent_color (str):
name of prominent color
Convert the image from RGB to the HSV color model. Using
predefined regions of the HSV model, identify the pixels
belonging to each color. The prominent color is the color
which has the largest proportion of pixels. If the
prominent color is less than the min_thresh_to_classify
then 'background' is the prominent color.
"""
hsv_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2HSV)
height, width, _ = hsv_img.shape
pixel_count = height * width
# dictionary to identify which pixels match a given color {color: pixels}
bool_pixel_mask = defaultdict(lambda: np.zeros(hsv_img.shape[:2]))
for color in self.colors:
for low_hsv, high_hsv in self.hsv_span_cache[color]:
bool_pixel_mask[color] += (cv2.inRange(hsv_img, low_hsv, high_hsv) == 255)
proportion = {color: (mask.sum()/pixel_count) for color, mask in bool_pixel_mask.items()}
prominent_color = max(proportion, key=proportion.get)
if proportion[prominent_color] < self.min_thresh_to_classify:
prominent_color = 'background'
return prominent_color
def _get_hsv_spans(self, color):
"""
Parameters:
color (str):
name of color
Returns:
hsv_spans (list of lists of tuples of ints):
hsv_spans : [<hsv_span_1>, <hsv_span_2>] # only red has more than 1 span
hsv_span : [<low_hsv>, <high_hsv>]
low_hsv/high_hsv : (h,s,v)
The HSV color model defines a 3d space (cylinder) in which colors are represented.
Hue: [ <red> 0 ~ 360 <also red> ] (in the case of cv2: [0 ~ 180])
The color expressed as an angle on the color wheel, think ROYGBIV-R.
Saturation: [ <faint> 0 ~ 255 <bold> ]
The intensity of the color
Value: [ <vader> 0 ~ 255 <rice> ]
The darkness / lightness of the color
Just as a rectangle can be defined using 2 points, a chunk of the HSV 3d space
can be identified using 2 HSV values (low, high). All color variations
belonging to this chunk (HSV values between low and high) are assigned a
common color name. This captures deviations in hues, saturations, and values
for each the common colors.
Ex:
green => low_hsv:(42,51,51) ~ high_hsv:(87,255,255)
"""
SAT_THRESH_WHITE = 40
# white: (0 ~ SAT_THRESH_WHITE)
# rainbow: (SAT_THRESH_WHITE+1 ~ 255)
VAL_THRESH_BLACK = 50
# black: (0 ~ VAL_THRESH_BLACK)
# rainbow: (VAL_THRESH_BLACK+1 ~ 255)
HUE_RANGES = {
'red' : [( 0, 8), # lower red
(170, 180)], # upper red
'orange' : [( 9, 15)],
'yellow' : [( 16, 41)],
'green' : [( 42, 87)],
'sky blue': [( 88, 98)],
'blue' : [( 99, 126)],
'purple' : [(127, 149)],
'pink' : [(150, 169)],
}
SAT_RANGES = {
'black' : ( 0, 255),
'white' : ( 0, SAT_THRESH_WHITE),
'yellow' : (SAT_THRESH_WHITE+20, 255)
}
VAL_RANGES = {
'black' : ( 0, VAL_THRESH_BLACK),
'white' : (100, 255), # low end is grey to allow capturing white in low light
}
hue_ranges = HUE_RANGES.get(color, [(0, 180)])
sat_range = SAT_RANGES.get(color, (SAT_THRESH_WHITE+1, 255))
val_range = VAL_RANGES.get(color, (VAL_THRESH_BLACK+1, 255))
hsv_spans = [list(zip(hue_range, sat_range, val_range)) for hue_range in hue_ranges]
return hsv_spans
def annotate(self, p1, p2, color_name, frame):
"""
Annotate the image by adding a box around the center region and
writing the color name on the image to show the result of
the color classification.
"""
box_color = text_color = self.colors.get(color_name, ColorClassifier.NEUTRAL['black'])
cv2.rectangle(frame, p1, p2, box_color, 3)
cv2.putText(frame, color_name.upper(), p1, cv2.FONT_HERSHEY_SIMPLEX, 1, text_color, 2)
class ObjectDetector:
"""
This is the base-class for all the object detector classes which follow
in this file.
Two example sub-classes are `CascadeObjectDetector` and `PedestrianDetector`.
"""
def __init__(self, box_color, box_line_thickness, text_color,
text_str, text_scale, text_line_width):
"""
Build a object detector object.
"""
self.box_color = box_color
self.box_line_thickness = box_line_thickness
self.text_color = text_color
self.text_str = text_str
self.text_scale = text_scale
self.text_line_width = text_line_width
def detect(self, frame, annotate=False):
"""
Detect objects inside of the image `frame`.
The `frame` parameter must be an image as a numpy array either containing
3-channel RGB values _or_ 1-channel gray values.
Returns a list of rectangles, where each rectangle is a 4-tuple of:
(x, y, width, height)
This base implementation is abstract and should not be invoked.
"""
raise Exception("abstract implementation invoked")
def annotate(self, frame, rectangles):
"""
Annotate the image by adding boxes and labels around the detected
objects inside of `frame`. The `rectangles` parameter should be a
list of 4-tuples where each tuple is:
(x, y, width, height)
"""
for x, y, width, height in rectangles:
cv2.rectangle(frame,
(x, y),
(x + width, y + height),
self.box_color, self.box_line_thickness)
cv2.putText(frame, self.text_str, (x, y), cv2.FONT_HERSHEY_SIMPLEX,
self.text_scale, self.text_color, self.text_line_width)
class CascadeObjectDetector(ObjectDetector):
"""
This is the base-class for the _cascade_ object detector classes which follow
in this file.
Two example sub-classes are `FaceDetector` and `StopSignDetector`.
"""
def __init__(self, cascade_file_path,
scaleFactor,
minNeighbors,
minSize,
box_color,
box_line_thickness,
text_color,
text_str,
text_scale,
text_line_width):
"""
Build a cascade object detector object.
"""
self.cascade = cv2.CascadeClassifier(cascade_file_path)
self.scaleFactor = scaleFactor
self.minNeighbors = minNeighbors
self.minSize = minSize
super().__init__(box_color, box_line_thickness, text_color,
text_str, text_scale, text_line_width)
def detect(self, frame, annotate=False):
"""
Detect objects inside of the image `frame`.
The `frame` parameter must be an image as a numpy array either containing
3-channel RGB values _or_ 1-channel gray values.
Returns a list of rectangles, where each rectangle is a 4-tuple of:
(x, y, width, height)
"""
# Get a gray image of the proper shape:
if frame.ndim == 3:
if frame.shape[2] == 3:
frame_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
elif frame.shape[2] == 1:
frame_gray = np.squeeze(frame, axis=(2,))
else:
raise Exception("invalid number of color channels")
elif frame.ndim == 2:
frame_gray = frame
else:
raise Exception("invalid frame.ndim")
# Call the OpenCV cascade.
rectangles = self.cascade.detectMultiScale(
frame_gray,
scaleFactor=self.scaleFactor,
minNeighbors=self.minNeighbors,
minSize=self.minSize,
flags = cv2.CASCADE_SCALE_IMAGE)
# `rectangles` is a numpy ndarray, but we'd like it to be a list of tuples.
rectangles = [tuple(rect) for rect in rectangles]
# Annotate it if the user so desires.
if annotate:
self.annotate(frame, rectangles)
return rectangles
class FaceDetector(CascadeObjectDetector):
"""
This class detects human faces in images.
"""
def __init__(self, cascade_file_path=None,
scaleFactor=1.1,
minNeighbors=3,
minSize=(45, 45),
box_color=[255, 255, 255],
box_line_thickness=3,
text_color=[255, 255, 255],
text_str='HUMAN',
text_scale=1.0,
text_line_width=2):
"""
Build a face detector object.
"""
if cascade_file_path is None:
cascade_file_path = os.path.join(RESOURCE_DIR_PATH,
"cascades/haarcascade_frontalface_alt.xml")
super().__init__(cascade_file_path,
scaleFactor=scaleFactor,
minNeighbors=minNeighbors,
minSize=minSize,
box_color=box_color,
box_line_thickness=box_line_thickness,
text_color=text_color,
text_str=text_str,
text_scale=text_scale,
text_line_width=text_line_width)
class StopSignDetector(CascadeObjectDetector):
"""
This class detects stop signs in images.
"""
def __init__(self, cascade_file_path=None,
scaleFactor=1.1,
minNeighbors=10,
minSize=(30, 30),
box_color=[255, 0, 0],
box_line_thickness=3,
text_color=[255, 0, 0],
text_str='STOP SIGN',
text_scale=1.0,
text_line_width=2):
"""
Build a stop sign detector object.
"""
if cascade_file_path is None:
cascade_file_path = os.path.join(RESOURCE_DIR_PATH,
"cascades/stop_sign.xml")
super().__init__(cascade_file_path,
scaleFactor=scaleFactor,
minNeighbors=minNeighbors,
minSize=minSize,
box_color=box_color,
box_line_thickness=box_line_thickness,
text_color=text_color,
text_str=text_str,
text_scale=text_scale,
text_line_width=text_line_width)
class PedestrianDetector(ObjectDetector):
"""
This class detects pedestrians in images.
"""
def __init__(self, winStride=(4, 4),
scale=1.05,
hitThreshold=0,
box_color=[0, 0, 255],
box_line_thickness=3,
text_color=[0, 0, 255],
text_str='PEDESTRIAN',
text_scale=0.75,
text_line_width=2):
"""
Build a pedestrian detector object.
"""
self.hog = cv2.HOGDescriptor()
self.hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
self.winStride = winStride
self.scale = scale
self.hitThreshold = hitThreshold
super().__init__(box_color, box_line_thickness, text_color,
text_str, text_scale, text_line_width)
def detect(self, frame, annotate=False):
"""
Detect pedestrians inside of the image `frame`.
The `frame` parameter must be an image as a numpy array either containing
3-channel RGB values _or_ 1-channel gray values.
Returns a list of rectangles, where each rectangle is a 4-tuple of:
(x, y, width, height)
"""
# Get an RGB image of the proper shape:
if frame.ndim == 3:
if frame.shape[2] == 3:
frame_rgb = frame
elif frame.shape[2] == 1:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
else:
raise Exception("invalid number of color channels")
elif frame.ndim == 2:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
else:
raise Exception("invalid frame.ndim")
# Call the OpenCV HOG model.
rectangles, weights = self.hog.detectMultiScale(
frame_rgb,
hitThreshold=self.hitThreshold,
winStride=self.winStride,
padding=(8, 8),
scale=self.scale)
# `rectangles` is a numpy ndarray, but we'd like it to be a list of tuples.
rectangles = [tuple(rect) for rect in rectangles]
# Annotate it if the user so desires.
if annotate:
self.annotate(frame, rectangles)
return rectangles
<file_sep>###############################################################################
#
# Copyright (c) 2017-2020 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This package contains a mock implementation of the cui interface.
It is used as a fallback if no other implementations are available.
"""
import cui
import asyncio
from auto import logger
class CuiMock(cui.CuiRoot):
async def init(self):
self.lock = asyncio.Lock()
self.log = logger.init(__name__, terminal=True)
return True
async def write_text(self, text):
async with self.lock:
return self.log.info("write_text({})".format(repr(text)))
async def clear_text(self):
async with self.lock:
return self.log.info("clear_text()")
async def big_image(self, image_id):
async with self.lock:
return self.log.info("big_image({})".format(repr(image_id)))
async def big_status(self, status):
async with self.lock:
return self.log.info("big_status({})".format(repr(status)))
async def big_clear(self):
async with self.lock:
return self.log.info("big_clear()")
async def stream_image(self, rect_vals, shape, image_buf):
async with self.lock:
return self.log.info("stream_image({}, {}, buffer of length {})".format(repr(rect_vals), repr(shape), len(image_buf)))
async def clear_image(self):
async with self.lock:
return self.log.info("clear_image()")
async def set_battery(self, state, minutes, percentage):
async with self.lock:
return self.log.info("set_battery({}, {}, {})".format(repr(state), repr(minutes), repr(percentage)))
async def close(self):
async with self.lock:
return self.log.info("close()")
<file_sep>import os
import numpy as np
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
DATA_FILE_PATH = os.path.join(CURR_DIR, "battery_percentage_map.npz")
def battery_map_millivolts_to_percentage(millivolts_single_point):
global millivolts_data, percentages_data
try:
millivolts_data
except NameError:
f = np.load(DATA_FILE_PATH)
millivolts_data, percentages_data = f['millivolts'], f['percentages']
f.close()
return float(np.interp(millivolts_single_point, millivolts_data, percentages_data))
<file_sep>###############################################################################
#
# Copyright (c) 2017-2022 Master AI, Inc.
# ALL RIGHTS RESERVED
#
# Use of this library, in source or binary form, is prohibited without written
# approval from Master AI, Inc.
#
###############################################################################
"""
This module connects to the car's controller via the CIO interface.
For beginners, it provides easy functions for navigation for the virtual
car.
"""
from auto.capabilities import list_caps, acquire
from auto.asyncio_tools import thread_safe
from auto.sleep import _physics_client
from .motors import set_steering
from auto import IS_VIRTUAL
import math
def drive_to(target_x, target_z, halt_threshold=2.5):
"""
Use the car's GPS and Compass to drive the car to the given (x, z) location.
Works for virtual cars only!
"""
if not IS_VIRTUAL:
raise NotImplemented('This function only work on virtual cars.')
gps = _get_gps()
compass = _get_compass()
physics = _physics_client()
halt_threshold_sqrd = halt_threshold * halt_threshold
while True:
x, y, z = gps.query()
theta = compass.query()
dx = target_x - x
dz = target_z - z
if dx*dx + dz*dz < halt_threshold_sqrd:
break
theta *= math.pi / 180.0 # convert degrees to radians
theta_target = math.atan2(dx, dz)
theta_diff = theta_target - theta
theta_diff = math.atan2(math.sin(theta_diff), math.cos(theta_diff)) # normalize into [-pi, +pi]
steering_angle = theta_diff * 180.0 / math.pi
set_steering(steering_angle)
# All calls above are non-blocking, but there's no need to loop
# until we have new data from the physics engine, so below block
# until the next "tick" of the physics engine, and after that it
# makes sense to loop back and recompute.
physics.wait_tick()
set_steering(0.0)
def drive_route(xz_checkpoints, halt_threshold=2.5):
"""
Go to each point in the list `xz_checkpoints`.
Works for virtual cars only!
"""
for x, z in xz_checkpoints:
drive_to(x, z, halt_threshold)
@thread_safe
def _get_gps():
global _GPS
try:
_GPS
except NameError:
caps = list_caps()
if 'GPS' not in caps:
raise AttributeError('This device has no GPS.')
_GPS = acquire('GPS')
return _GPS
@thread_safe
def _get_compass():
global _COMPASS
try:
_COMPASS
except NameError:
caps = list_caps()
if 'Compass' not in caps:
raise AttributeError('This device has no Compass.')
_COMPASS = acquire('Compass')
return _COMPASS
<file_sep>#!/bin/bash
cd "$HOME"
exec jupyter notebook --config="$1"
| 93084fb71344e070d7c27bd134660b76468131d3 | [
"Markdown",
"Python",
"Shell"
] | 110 | Python | MasterAI-Inc/libauto | 791996c8ce58c3a423b86cf2b5f129019763a759 | 08d9c86f8e1ad11e27aa9047db8a81c9b7b925d6 |
refs/heads/master | <repo_name>mcharlieh/AdvMobileWebAppDev<file_sep>/README.md
# AdvMobileWebAppDev
Advanced Mobile Web Application Development course, Azure Web + MySQL
<file_sep>/opendb.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
</body>
</html><file_sep>/app/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Mobile Web App</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link href="https://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" rel="stylesheet" type="text/css"/>
<link href="styles/custom.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script>
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
Notification.requestPermission(function (permission) {
// console.log(permission);
});
function show() {
window.setTimeout(function () {
var instance = new Notification(
"You've got tasks due!", {
body: "Take a look at your task list to see what assignments are due today."
}
);
instance.onclick = function () {
// Something to do
};
instance.onerror = function () {
// Something to do
};
instance.onshow = function () {
// Something to do
};
instance.onclose = function () {
// Something to do
};
}, 3000);
return false;
}
</script>
</head>
<body>
<div id="login" data-role="page" data-theme="b">
<div data-role="header" data-theme="b">
<div class="logo"><img src="images/rasmussen_logo.png" width="218" height="45" alt=""/></div>
</div>
<div data-role="content">
<!--<form action="/action_page.php">-->
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<!--<button type="submit">Login</button>-->
<a href="#task" data-role="button">Login</a>
<input type="checkbox" checked="checked">
Remember me </div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span> </div>
<!--</form>-->
<a href="#" onclick="return show()">Notify me!</a>
</div>
<div data-role="footer" data-theme="b">
<h4>MHaley © 2017</h4>
</div>
</div>
<div id="task" data-role="page" data-theme="b">
<div data-role="header" data-theme="b">
<div class="logo"><img src="images/rasmussen_logo.png" width="218" height="45" alt=""/></div>
<div class="dropdown">
<button onClick="myFunction()" class="dropbtn">Menu</button>
<div id="myDropdown" class="dropdown-content">
<a href="#profile">MyDegree</a>
<a href="#calender">Calender</a>
<a href="#login">Logout</a>
</div>
</div>
</div>
<div class="content">
<h2>My To Do List</h2>
<span onclick="newElement()" class="addBtn">Add</span>
<?php
include 'config.php';
include 'opendb.php';
$sql="SELECT task_name, task_desc, due_date FROM task_list WHERE show_flg='1'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo $row["task_name"]. " ";
echo $row["due_date"]. "<br>";
echo " " . $row[task_desc]. "<br><br>";
}
} else {
echo "No tasks this week!";
}
mysqli_close($conn);
?>
</div>
<div data-role="footer" data-theme="b">
<h4>MHaley © 2017</h4>
</div>
</div>
<div id="profile" data-role="page" data-theme="b">
<div data-role="header" data-theme="b">
<div class="logo"><img src="images/rasmussen_logo.png" width="218" height="45" alt=""/></div>
<div class="dropdown">
<button onClick="myFunction()" class="dropbtn">Menu</button>
<div id="myDropdown" class="dropdown-content">
<a href="#profile">MyDegree</a>
<a href="#calender">Calender</a>
<a href="#login">Logout</a>
</div>
</div>
</div>
</div>
<div data-role="content">
<?php
include 'config.php';
include 'opendb.php';
$sql_degree = "SELECT degree.dgre_name, degree.dgre_school, degree.dgre_type, degree.dgre_credits_total, user_table.credits_completed, user_table.gpa
FROM degree JOIN user_table ON degree.dgre_id = user_table.degree_id
WHERE user_table.user_id='1'";
$sql_courses = "SELECT course.course_name, course.course_credits, student_courses.grade
FROM course JOIN student_courses ON course.course_id = student_courses.course_id
WHERE student_courses.user_id='1'";
$result_degree = mysqli_query($conn, $sql_degree);
$result_courses = mysqli_query($conn, $sql_courses);
$rowd = mysqli_fetch_assoc($result_degree);
$rowc = mysqli_fetch_assoc($result_courses);
echo "MY DEGREE <br>";
echo $rowd["degree.dgre_type"]. "of";
echo $rowd["degree.dgre_name"]. "<br>";
echo "School of " . $rowd["degree.dgre_school"]. "<br><br>";
echo "Credit Completion: " . $rowd["user_table.credits_completed"];
echo " of " . $rowd["degree.dgre_credits_total"]. "<br>";
echo "Cumulative GPA: " . $rowd["user_table.gpa"]. "<br><br>";
echo "Current Courses <br>";
echo $rowc["course.course_name"];
echo " - " . $rowc["course.course_credits"]. "credits <br>";
echo "Current Grade: " . $rowc["student_courses.grade"];
mysqli_close($conn);
?>
</div>
<div data-role="footer" data-theme="b">
<h4>MHaley © 2017</h4>
</div>
</div>
<div id="calender" data-role="page" data-theme="b">
<div data-role="header" data-theme="b">
<div class="logo"><img src="images/rasmussen_logo.png" width="218" height="45" alt=""/></div>
<div class="dropdown">
<button onClick="myFunction()" class="dropbtn">Menu</button>
<div id="myDropdown" class="dropdown-content">
<a href="#profile">MyDegree</a>
<a href="#calender">Calender</a>
<a href="#login">Logout</a>
</div>
</div>
</div>
</div>
<div data-role="content">
</div>
<div data-role="footer" data-theme="b">
<h4>MHaley © 2017</h4>
</div>
</div>
<div data-role="page" id="add" data-theme="b">
<div data-role="header" data-theme="b">
<div class="logo"><img src="images/rasmussen_logo.png" width="218" height="45" alt=""/></div>
</div>
<div data-role="content">
<div data-role="footer" data-theme="b">
<h4>MHaley © 2017</h4>
</div>
</div>
</div>
<!-- <script>
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
</script> -->
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</body>
</html>
<file_sep>/app old/displaytask.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
include 'config.php';
include 'opendb.php';
$sql="SELECT task_name, task_desc, due_date FROM task_list WHERE show_flg='1'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo $row["task_name"]. " ";
echo $row["due_date"]. "<br>";
echo " " . $row[task_desc]. "<br>";
}
} else {
echo "No tasks this week!";
}
mysqli_close($conn);
?>
</body>
</html><file_sep>/app old/config.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
// This is an example of config.php
$dbhost = 'us-cdbr-azure-central-a.cloudapp.net';
$dbuser = '<KEY>';
$dbpass = '<PASSWORD>';
$dbname = 'acsm_281b165bef9e739';
?>
</body>
</html> | 5d91259803c8bd84de5474ca3330965c4297a280 | [
"Markdown",
"PHP"
] | 5 | Markdown | mcharlieh/AdvMobileWebAppDev | 79944137a82228ec83809382b97b8234bf8e76ef | d39c76d4e8fa1892f25622b5bbaa8dddef0b6fcc |
refs/heads/master | <file_sep>FROM node
COPY . /var/www
WORKDIR /var/www
RUN npm install --only=production
ENV PORT=3000
EXPOSE 5000
ENTRYPOINT ["npm","start"]<file_sep>const {Router}=require("express");
const {ParseIntMiddleware,AuthMiddleware}=require('../middlewares')
module.exports=function({IdeaController}){
const router=Router();
router.get('',ParseIntMiddleware,IdeaController.getAll);
router.get('/:ideaId',IdeaController.get);
router.get('/:userId/all',IdeaController.getUserIdeas);
router.post('',AuthMiddleware,IdeaController.create);
router.patch('/:ideaId',AuthMiddleware,IdeaController.update);
router.delete('/:ideaId',AuthMiddleware,IdeaController.delete);
router.post('/:ideaId/upvote',AuthMiddleware,IdeaController.upvoteIdea);
router.post('/:ideaId/downvote',AuthMiddleware,IdeaController.downvoteIdea);
return router;
};<file_sep> version: "3"
services:
api:
build: .
depends_on:
- mongo
environment:
- PORT=5000
- MONGO_URI=mongodb://mongo:27017/ideas
- APPLICATION_NAME=Share Your Idea
- JWT_SECRET=<KEY>
- CACHE_KEY=<PASSWORD>
ports:
- "5000:5000"
mongo:
image: mongo
| 2a0289bb9d7b37aac12abb27d50b91f78948d60d | [
"JavaScript",
"Dockerfile",
"YAML"
] | 3 | Dockerfile | JHONS4N/api-shareyourideas | 3c79060b3004142e63d72f9fe153432ec29c051a | 18b27afa39af9c9bdb0803e269f8c09f7735d8e8 |
refs/heads/master | <repo_name>KonstantinLev/easy-chat-react-ts<file_sep>/client/src/socket.ts
import io from 'socket.io-client';
const ENDPOINT: string = 'https://react-chat-ts.herokuapp.com/'
const socket = io(ENDPOINT);
export default socket; | 2efd62305e84525a0feb264ae21904837df8cdca | [
"TypeScript"
] | 1 | TypeScript | KonstantinLev/easy-chat-react-ts | d78ba027c6aaf80b46f2cdd8f0bf02152a7527d0 | e3da8c233014689541845f19f7fe001d1d711a6e |
refs/heads/master | <file_sep>import {
GridAreaProperty,
GridAutoColumnsProperty,
GridAutoFlowProperty,
GridAutoRowsProperty,
GridColumnGapProperty,
GridColumnProperty,
GridGapProperty,
GridRowGapProperty,
GridRowProperty,
GridTemplateAreasProperty,
GridTemplateColumnsProperty,
GridTemplateRowsProperty
} from "csstype";
export type GridProperties<TLength = string | number> = {
gridGap?: GridGapProperty<TLength> | (GridGapProperty<TLength>)[]
gridRowGap?: GridRowGapProperty<TLength> | (GridRowGapProperty<TLength>)[]
gridColumnGap?: GridColumnGapProperty<TLength> | (GridColumnGapProperty<TLength>)[]
gridColumn?: GridColumnProperty | (GridColumnProperty)[]
gridRow?: GridRowProperty | (GridRowProperty)[]
gridArea?: GridAreaProperty | (GridAreaProperty)[]
gridAutoFlow?: GridAutoFlowProperty | (GridAutoFlowProperty)[]
gridAutoRows?: GridAutoRowsProperty<TLength> | (GridAutoRowsProperty<TLength>)[]
gridAutoColumns?: GridAutoColumnsProperty<TLength> | (GridAutoColumnsProperty<TLength>)[]
gridTemplateRows?: GridTemplateRowsProperty<TLength> | (GridTemplateRowsProperty<TLength>)[]
gridTemplateColumns?: GridTemplateColumnsProperty<TLength> | (GridTemplateColumnsProperty<TLength>)[]
gridTemplateAreas?: GridTemplateAreasProperty | (GridTemplateAreasProperty)[]
}
export const Grid = {
gridGap: "space",
gridRowGap: "space",
gridColumnGap: "space",
gridColumn: "",
gridRow: "",
gridArea: "",
gridAutoFlow: "",
gridAutoRows: "",
gridAutoColumns: "",
gridTemplateRows: "",
gridTemplateColumns: "",
gridTemplateAreas: ""
};
<file_sep>import autoprefixer from "autoprefixer";
import postcss from "postcss-js";
import { Border, Color, Flex, Grid, Margin, Other, Padding, Position, Size, Typography } from "./css";
export type ConfigProps = {
Padding?: boolean;
Margin?: boolean;
Size?: boolean;
Space?: boolean;
Position?: boolean;
Flex?: boolean;
Grid?: boolean;
Layout?: boolean;
Border?: boolean;
Color?: boolean;
Typography?: boolean;
Decor?: boolean;
Other?: boolean;
All?: boolean;
remBase?: number;
fontSizes?: number[];
spaceSizes?: number[];
};
export const splitProps = (
props: unknown,
CssOptions = Object.keys({ ...Padding, ...Margin, ...Size, ...Position, ...Flex, ...Grid, ...Border, ...Color, ...Typography, ...Other })
) => {
return Object.keys(props).reduce(
({ cssProps, nonCssProps }, key) => {
if (CssOptions.includes(key)) {
return {
cssProps: {
...cssProps,
[key]: props[key]
},
nonCssProps: {
...nonCssProps
}
};
}
return {
cssProps: {
...cssProps
},
nonCssProps: {
...nonCssProps,
[key]: props[key]
}
};
},
{
cssProps: {},
nonCssProps: {}
}
);
};
export function isEmpty(obj): boolean {
// eslint-disable-next-line guard-for-in,no-restricted-syntax
for (const i in obj) return false;
return true;
}
export const hasResponsiveProps = (props) => {
// eslint-disable-next-line no-restricted-syntax
for (const key in props) {
if (Object.prototype.hasOwnProperty.call(props, key) && Array.isArray(props[key])) {
return true;
}
}
return false;
};
export const createStyledJsxStrings = (props: unknown, { remBase, fontSizes, spaceSizes, breakPointIndex, ...config }: ConfigProps & { breakPointIndex?: number }) => {
/*= =============== Load Options ================ */
let selectedCSSOptions: unknown;
if (isEmpty(config)) {
selectedCSSOptions = { ...Padding, ...Margin, ...Size, ...Position, ...Flex, ...Grid, ...Border, ...Color, ...Typography, ...Other };
}
selectedCSSOptions = Object.entries(config).reduce((acc, [key, value]) => {
if (!value) return acc;
if (key === "Padding") {
acc = { ...acc, ...Padding };
}
if (key === "Margin") {
acc = { ...acc, ...Margin };
}
if (key === "Size") {
acc = { ...acc, ...Size };
}
if (key === "Space") {
acc = { ...acc, ...Padding, ...Margin, ...Size };
}
if (key === "Position") {
acc = { ...acc, ...Position };
}
if (key === "Flex") {
acc = { ...acc, ...Flex };
}
if (key === "Grid") {
acc = { ...acc, ...Grid };
}
if (key === "Layout") {
acc = { ...acc, ...Position, ...Flex, ...Grid };
}
if (key === "Border") {
acc = { ...acc, ...Border };
}
if (key === "Color") {
acc = { ...acc, ...Color };
}
if (key === "Typography") {
acc = { ...acc, ...Typography };
}
if (key === "Decor") {
acc = { ...acc, ...Border, ...Color, ...Typography };
}
if (key === "other") {
acc = { ...acc, ...Other };
}
if (key === "All") {
acc = { ...acc, ...Padding, ...Margin, ...Size, ...Position, ...Flex, ...Grid, ...Border, ...Color, ...Typography, ...Other };
}
return acc;
}, {});
const { cssProps } = splitProps(props, Object.keys(selectedCSSOptions));
const toStringAndVariables = (value: string | number): string => value.toString().replace(/^--.+/, (match) => `var(${match})`);
const convertValue = (key: string, value: number | string) => {
let converter = "";
if (selectedCSSOptions[key] === "") {
return toStringAndVariables(value);
}
if (Array.isArray(selectedCSSOptions[key])) {
[converter] = selectedCSSOptions[key];
} else {
converter = selectedCSSOptions[key];
}
if (typeof value === "number" && value >= 0 && value <= fontSizes.length && converter === "fontSize") {
return `${fontSizes[value] / remBase}rem`;
}
if (typeof value === "number" && value >= 0 && value <= spaceSizes.length && converter === "space") {
return `${spaceSizes[value] / remBase}rem`;
}
if (typeof value === "number" && value > 8) {
return `${value / remBase}rem`;
}
if (typeof value === "string") {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
return value.match(/(px)$/) ? `${+value.replace("px", "") / remBase}rem` : toStringAndVariables(value);
}
return toStringAndVariables(value);
};
const toCssProperty = (key, value): string => `${key.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`)}: ${convertValue(key, value)};\n`;
const expandToCssPropertyStrings = (key, value): string => {
if (Array.isArray(selectedCSSOptions[key])) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return selectedCSSOptions[key].map((k) => toCssProperty(k === "" || k === "space" || k === "fontSize" ? key : k, value)).join("");
}
/* const result = postcss([autoprefixer]).process(toCssProperty(key, value)).then(({ css }) => css).toString(); */
const prefixer = postcss.sync([autoprefixer]);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return toCssProperty(key, value);
/*console.log(prefixer({ display: 'flex' }))
return Object.entries(prefixer({[key.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`)]: convertValue(key, value) })).map(([_key, _value]) => {
if (Array.isArray(_value) && _value.length > 1) {
return _value.map((val) => {
return `${_key}: ${val};`;
}).join("");
}
return `${_key}: ${_value};`;
}).join("");*/
};
return Object.entries(cssProps).reduce((acc: string[], [key, value]) => {
// check if responsive
if (Array.isArray(value) && typeof window !== "undefined") {
acc.push(
expandToCssPropertyStrings(key, value[breakPointIndex] || value[breakPointIndex] === 0
? value[breakPointIndex]
: value[value.length - 1])
);
// if not responsive
} else {
acc.push(expandToCssPropertyStrings(key, Array.isArray(value) ? value[0] : value));
}
return acc;
}, []).join("");
};
<file_sep># use-styled-system
A custom [React Hook](https://reactjs.org/docs/hooks-overview.html) to help you implement "styled system props" in combination with styled-jsx for your application.
## How it works
`use-styled-system` provides a custom hook to inject all common [styled-system](https://styled-system.com/) props into `<style jsx>` tags. Its especially made to work seamless within any NextJs environment. The hook is completely build with Typescript and provides excellent support for all CSS props, including proper scoping.
Currently `use-styled-system` uses Javascript and `.matchMedia` media queries and global context for responsive css. The syntax is the same as with styled system. i.e.
```JSX
<Box as='div' p={['20px 10px', 60]}>...</Box>
```
translates into the following for matchMedia below the first breakpoint ie. 600px
```HTML
<div class="jsx-123">
...
</div>
<style>
.jsx-123 {
padding: 20px 10px
}
</style>
```
and automatically changes to the below once the next media query is triggered.
```HTML
<div class="jsx-123">
...
</div>
<style>
.jsx-123 {
padding: 60px
}
</style>
```
## Roadmap
In next versions the focus will be on adding support for Pseudo Selectors, CSS based Media Queries and autoprefix injection.
## Requirement
To use `use-styled-system`, you must use `styled-jsx@3.0.0` and `react@16.8.0` or greater which includes Hooks (both shipped with Nextjs).
## Installation
```sh
$ npm i use-styled-system
```
## Usage
The usage within a NextJs environment works out of the box. Any other environment needs [react](https://github.com/facebook/react) & [styled-jsx](https://github.com/vercel/styled-jsx) as a peer dependency. Refer to their docs for more information.
```tsx
/* import only the Types that you need */
import { FC } from 'react';
import { Decor, Layout, Space, useStyledSystem } from 'use-styled-system';
export const Box: FC<Space & Layout & Decor> = (props) => {
const { styleJsx, nonCssProps } = useStyledSystem(props, { Space: true, Layout: true, Decor: true });
return <>
<div {...nonCssProps}>{props.children}</div>
<style jsx>{`
div {
color: red;
${styleJsx}
}
`}</style>
</>
}
```
`use-styled-system` returns an Abject with two items:
1. `styleJSX` which is a string containing all CSS properties and values
2. `nonCssProps` which is an Object with the previously added Props, filtered for any Css props.
### Parameters
You pass `useStyledSystem` the props (or rest of props, using the `...` spread operator) an optional `Config` object. The configuration object may contain the following keys.
| Key | Description | Type | Default |
|:------------------|:-------------------------------------------------------------------------------------|:-------------------------| :-----------------------------------------------------------------------------------|
|`remBase` | Sets the base size to use rem properties wherever possible (defaults to 10px) | number | 10 |
|`fontSizes` | Sets the fontsizes shortcuts for common sizes. i.e.`fontSize={3}` equals to `20px` | (number)[] | [12, 14, 16, 20, 24, 32, 48, 64, 72] |
|`spaceSizes` | Sets the space shortcuts for common sizes. i.e.`marginBottom={3}` equals to `16px` | (number)[] | [0, 4, 8, 16, 32, 64, 128, 256, 512] |
|`Padding` | Activates `Padding` properties to be used as Props | boolean | false |
|`Margin` | Activates `Margin` properties to be used as Props | boolean | false |
|`Size` | Activates `Size` properties to be used as Props | boolean | false |
|`Space` | Shortcut to activate `Padding`, `Margin`, and `Size` properties as Props | boolean | false |
|`Position` | Activates `Position` properties to be used as Props | boolean | false |
|`Flex` | Activates `Flex` properties to be used as Props | boolean | false |
|`Grid` | Activates `Grid` properties to be used as Props | boolean | false |
|`Layout` | Shortcut to activate `Position`, `Flex`, and `Grid` properties as Props | boolean | false |
|`Border` | Activates `Border` properties to be used as Props | boolean | false |
|`Color` | Activates `Color` properties to be used as Props | boolean | false |
|`Typography` | Activates `Typography` properties to be used as Props | boolean | false |
|`Decor` | Shortcut to activate `Border`, `Color`, and `Typography` properties as Props | boolean | false |
|`Other` | Activates `Other` properties to be used as Props | boolean | false |
|`All` | Activates *all* of the above properties to be used as Props. * **Defaults to true if no other property is selected** | boolean | false* |
### Return object
A `useStyleSystem` object is returned with the following properties.
| Key | Description |
| :---------- | :------------------------------------------------------ |
| `styleJsx | string of all css properties |
| `nonCssProps` | Props filtered for any non CSS prop |
## Examples
Using `style-jsx/css` `.resolve` functionality to create custom elements.
```tsx
import { createElement, FC } from 'react';
import { CSS, useStyledSystem } from 'use-styled-system';
import { css } from 'styled-jsx/css';
type BoxProps = {
as?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p' | 'div' | 'code' | 'blockquote' | 'a'
className?: string
onClick?: Function
}
export const Text: FC<BoxProps & CSS> = ({ as = 'p', children, className = '', ...props }) => {
const { styleJsx, nonCssProps } = useStyledSystem(props, { Decor: true, Space: true, Other: true });
const { className: cssClass, styles } = css.resolve`${styleJsx}`;
return <>
{createElement(as, { className: `${cssClass} ${className}`, ...nonCssProps }, children)}
{styles}
</>;
};
export default Text;
```
use with `styled-jsx-plugin-sass` in a Link Component.
```tsx
import { FC, MouseEvent } from 'react';
import NextLink from 'next/link';
import { Decor, Layout, Space, useStyledSystem } from 'use-styled-system';
type LinkProps = {
onClick?: (event: MouseEvent) => void
href: string
title: string | JSX.Element
target?: string
className?: string
secondary?: boolean
small?: boolean
large?: boolean
};
export const Link: FC<LinkProps & Space & Layout & Decor> = ({ onClick, className = '', href, target, title, secondary, small, large, children, ...props }) => {
const { styleJsx, nonCssProps } = useStyledSystem(props, { Space: true, Layout: true, Decor: true });
const classNames = `link ${secondary ? 'secondary' : ''} ${small ? 'small' : ''} ${large ? 'large' : ''} ${className}`.trim();
return <>
<NextLink href={href}>
<a target={target} className={classNames} onClick={onClick} {...nonCssProps}>{title}</a>
</NextLink>
<style jsx>{`
.link {
cursor: pointer;
color: var(--color-link);
font-family: inherit;
text-decoration: none;
transition: color 0.25s, background-color 0.25s;
&.small {
font-size: 1.4rem;
}
&.large {
font-size: 1.8rem;
}
&:hover {
color: var(--color-link-hover)
}
${styleJsx}
}
`}</style>
</>;
};
export default Link;
```
## License
**[MIT](LICENSE)** Licensed<file_sep>import {
DisplayProperty,
HeightProperty,
MaxHeightProperty,
MaxWidthProperty,
MinHeightProperty,
MinWidthProperty,
VerticalAlignProperty,
WidthProperty
} from "csstype";
export type SizeProperties<TLength = string | number> = {
display?: DisplayProperty | (DisplayProperty)[]
d?: DisplayProperty | (DisplayProperty)[]
width?: WidthProperty<TLength> | (WidthProperty<TLength>)[]
w?: WidthProperty<TLength> | (WidthProperty<TLength>)[]
height?: HeightProperty<TLength> | (HeightProperty<TLength>)[]
h?: HeightProperty<TLength> | (HeightProperty<TLength>)[]
size?: (HeightProperty<TLength> | WidthProperty<TLength>) | (HeightProperty<TLength> | WidthProperty<TLength>)[]
minWidth?: MinWidthProperty<TLength> | (MinWidthProperty<TLength>)[]
maxWidth?: MaxWidthProperty<TLength> | (MaxWidthProperty<TLength>)[]
minHeight?: MinHeightProperty<TLength> | (MinHeightProperty<TLength>)[]
maxHeight?: MaxHeightProperty<TLength> | (MaxHeightProperty<TLength>)[]
minW?: MinWidthProperty<TLength> | (MinWidthProperty<TLength>)[]
maxW?: MaxWidthProperty<TLength> | (MaxWidthProperty<TLength>)[]
minH?: MinHeightProperty<TLength> | (MinHeightProperty<TLength>)[]
maxH?: MaxHeightProperty<TLength> | (MaxHeightProperty<TLength>)[]
verticalAlign?: VerticalAlignProperty<string | 0> | (VerticalAlignProperty<string | 0>)[]
}
export const Size = {
display: "",
d: ["display"],
width: "space",
w: ["width"],
height: "space",
h: ["height"],
size: ["width", "height"],
minWidth: "space",
maxWidth: "space",
minHeight: "space",
maxHeight: "space",
minW: ["minWidth"],
maxW: ["maxWidth"],
minH: ["minHeight"],
maxH: ["maxHeight"],
verticalAlign: ""
};
<file_sep>import {
AppearanceProperty,
CursorProperty,
FillProperty,
ObjectFitProperty, PointerEventsProperty,
ResizeProperty,
StrokeProperty,
TransformProperty,
TransitionProperty, UserSelectProperty
} from "csstype";
export type OtherProperties<TLength = string | number> = {
fill?: FillProperty | (FillProperty)[]
stroke?: StrokeProperty | (StrokeProperty)[]
transition?: TransitionProperty | (TransitionProperty)[]
transform?: TransformProperty | (TransformProperty)[]
cursor?: CursorProperty | (CursorProperty)[]
resize?: ResizeProperty | (ResizeProperty)[]
objectFit?: ObjectFitProperty | (ObjectFitProperty)[]
userSelect?: UserSelectProperty | (UserSelectProperty)[]
appearance?: AppearanceProperty | (AppearanceProperty)[]
pointerEvents?: PointerEventsProperty | (PointerEventsProperty)[]
}
export const Other = {
fill: "",
stroke: "",
transition: "",
transform: "",
cursor: "",
resize: "",
objectFit: "",
userSelect: "",
appearance: "",
pointerEvents: "",
};
<file_sep>import {
MarginBottomProperty,
MarginLeftProperty,
MarginProperty,
MarginRightProperty,
MarginTopProperty
} from "csstype";
export type MarginProperties<TLength = string | number> = {
margin?: MarginProperty<TLength> | (MarginProperty<TLength>)[]
marginTop?: MarginTopProperty<TLength> | (MarginTopProperty<TLength>)[]
marginRight?: MarginRightProperty<TLength> | (MarginRightProperty<TLength>)[]
marginBottom?: MarginBottomProperty<TLength> | (MarginBottomProperty<TLength>)[]
marginLeft?: MarginLeftProperty<TLength> | (MarginLeftProperty<TLength>)[]
marginX?: MarginLeftProperty<TLength> & MarginRightProperty<TLength> | (MarginLeftProperty<TLength> & MarginRightProperty<TLength>)[]
marginY?: MarginTopProperty<TLength> & MarginBottomProperty<TLength> | (MarginTopProperty<TLength> & MarginBottomProperty<TLength>)[]
m?: MarginProperty<TLength> | (MarginProperty<TLength>)[]
mt?: MarginTopProperty<TLength> | (MarginTopProperty<TLength>)[]
mr?: MarginRightProperty<TLength> | (MarginRightProperty<TLength>)[]
mb?: MarginBottomProperty<TLength> | (MarginBottomProperty<TLength>)[]
ml?: MarginLeftProperty<TLength> | (MarginLeftProperty<TLength>)[]
mx?: MarginLeftProperty<TLength> & MarginRightProperty<TLength> | (MarginLeftProperty<TLength> & MarginRightProperty<TLength>)[]
my?: MarginTopProperty<TLength> & MarginBottomProperty<TLength> | (MarginTopProperty<TLength> & MarginBottomProperty<TLength>)[]
}
export const Margin = {
margin: "space",
marginTop: "space",
marginRight: "space",
marginBottom: "space",
marginLeft: "space",
marginX: ['marginLeft', 'marginRight'],
marginY: ['marginTop', 'marginBottom'],
m: ['margin'],
mt: ['marginTop'],
mr: ['marginRight'],
mb: ['marginBottom'],
ml: ['marginLeft'],
mx: ['marginLeft', 'marginRight'],
my: ['marginTop', 'marginBottom']
};
<file_sep>export * from "./Border";
export * from "./Color";
export * from "./Flex";
export * from "./Grid";
export * from "./index";
export * from "./Margin";
export * from "./Other";
export * from "./Padding";
export * from "./Position";
export * from "./Size";
export * from "./Typography";
<file_sep>import {
FontFamilyProperty,
FontSizeProperty,
FontStyleProperty,
FontWeightProperty,
GlobalsNumber,
LetterSpacingProperty,
LineHeightProperty,
TextAlignProperty,
TextDecorationProperty,
TextTransformProperty,
WhiteSpaceProperty,
WordBreakProperty,
WordWrapProperty
} from "csstype";
export type TypographyProperties<TLength = string | number> = {
fontFamily?: FontFamilyProperty | (FontFamilyProperty)[]
fontSize?: FontSizeProperty<TLength> | (FontSizeProperty<TLength>)[]
fontWeight?: FontWeightProperty | GlobalsNumber | (FontWeightProperty | GlobalsNumber)[]
lineHeight?: LineHeightProperty<TLength> | (LineHeightProperty<TLength>)[]
letterSpacing?: LetterSpacingProperty<TLength> | (LetterSpacingProperty<TLength>)[]
textAlign?: TextAlignProperty | (TextAlignProperty)[]
fontStyle?: FontStyleProperty | (FontStyleProperty)[]
textDecoration?: TextDecorationProperty<TLength> | (TextDecorationProperty<TLength>)[]
textTransform?: TextTransformProperty | (TextTransformProperty)[]
whiteSpace?: WhiteSpaceProperty | (WhiteSpaceProperty)[]
wordWrap?: WordWrapProperty | (WordWrapProperty)[]
wordBreak?: WordBreakProperty | (WordBreakProperty)[]
}
export const Typography = {
fontFamily: "",
fontSize: "fontSize",
fontWeight: "",
lineHeight: "",
letterSpacing: "",
textAlign: "",
fontStyle: "",
textDecoration: "",
textTransform: "",
whiteSpace: "",
wordWrap: "",
wordBreak: ""
};
<file_sep>import {
AlignContentProperty,
AlignItemsProperty,
AlignSelfProperty,
FlexBasisProperty,
FlexDirectionProperty,
FlexProperty,
FlexWrapProperty,
GlobalsNumber,
JustifyContentProperty,
JustifySelfProperty
} from "csstype";
export type FlexProperties<TLength = string | number> = {
justifyContent?: JustifyContentProperty | (JustifyContentProperty)[]
justify?: JustifyContentProperty | (JustifyContentProperty)[]
alignItems?: AlignItemsProperty | (AlignItemsProperty)[]
align?: AlignItemsProperty | (AlignItemsProperty)[]
alignContent?: AlignContentProperty | (AlignContentProperty)[]
flexDirection?: FlexDirectionProperty | (FlexDirectionProperty)[]
direction?: FlexDirectionProperty | (FlexDirectionProperty)[]
flex?: FlexProperty<GlobalsNumber> | (FlexProperty<GlobalsNumber>)[]
flexWrap?: FlexWrapProperty | (FlexWrapProperty)[]
wrap?: FlexWrapProperty | (FlexWrapProperty)[]
flexBasis?: FlexBasisProperty<GlobalsNumber> | (FlexBasisProperty<GlobalsNumber>)[]
flexGrow?: GlobalsNumber
flexShrink?: GlobalsNumber
alignSelf?: AlignSelfProperty | (AlignSelfProperty)[]
justifySelf?: JustifySelfProperty | (JustifySelfProperty)[]
order?: GlobalsNumber
}
export const Flex = {
justifyContent: "",
justify: ['justifyContent'],
alignItems: "",
align: ['alignItems'],
alignContent: "",
flexDirection: "",
direction: ['flexDirection'],
flex: "",
flexWrap: "",
wrap: ['flexWrap'],
flexBasis: "",
flexGrow: "",
flexShrink: "",
alignSelf: "",
justifySelf: "",
order: ""
};
<file_sep>import {
BackdropFilterProperty,
BackgroundAttachmentProperty,
BackgroundClipProperty,
BackgroundColorProperty,
BackgroundImageProperty,
BackgroundOriginProperty,
BackgroundPositionXProperty,
BackgroundPositionYProperty,
BackgroundProperty,
BackgroundSizeProperty,
BoxShadowProperty,
ColorProperty,
OpacityProperty,
OutlineColorProperty,
OutlineOffsetProperty,
OutlineStyleProperty,
OutlineWidthProperty,
VisibilityProperty
} from "csstype";
export type ColorProperties<TLength = string | number> = {
color?: ColorProperty | (ColorProperty)[]
background?: BackgroundProperty<TLength> | (BackgroundProperty<TLength>)[]
bg?: BackgroundProperty<TLength> | (BackgroundProperty<TLength>)[]
opacity?: OpacityProperty | (OpacityProperty)[]
backgroundAttachment?: BackgroundAttachmentProperty | (BackgroundAttachmentProperty)[]
backgroundClip?: BackgroundClipProperty | (BackgroundClipProperty)[]
['-webkit-background-clip']?: BackgroundClipProperty | (BackgroundClipProperty)[]
backgroundColor?: BackgroundColorProperty | (BackgroundColorProperty)[]
backgroundImage?: BackgroundImageProperty | (BackgroundImageProperty)[]
backgroundOrigin?: BackgroundOriginProperty | (BackgroundOriginProperty)[]
backgroundPositionX?: BackgroundPositionXProperty<TLength> | (BackgroundPositionXProperty<TLength>)[]
backgroundPositionY?: BackgroundPositionYProperty<TLength> | (BackgroundPositionYProperty<TLength>)[]
backgroundSize?: BackgroundSizeProperty<TLength> | (BackgroundSizeProperty<TLength>)[]
backdropFilter?: BackdropFilterProperty
['-webkit-backdropFilter']?: BackdropFilterProperty
boxShadow?: BoxShadowProperty | (BoxShadowProperty)[]
outline?: OutlineColorProperty | (OutlineColorProperty)[]
outlineColor?: OutlineColorProperty | (OutlineColorProperty)[]
outlineOffset?: OutlineOffsetProperty<TLength> | (OutlineOffsetProperty<TLength>)[]
outlineStyle?: OutlineStyleProperty | (OutlineStyleProperty)[]
outlineWidth?: OutlineWidthProperty<TLength> | (OutlineWidthProperty<TLength>)[]
visibility?: VisibilityProperty | (VisibilityProperty)[]
}
export const Color = {
color: "",
background: "",
bg: ['background'],
opacity: "",
backgroundAttachment: "",
backgroundClip: ["", '-webkit-background-clip'],
'-webkit-background-clip': "",
backgroundColor: "",
backgroundImage: "",
backgroundOrigin: "",
backgroundPositionX: "space",
backgroundPositionY: "space",
backgroundSize: "space",
backdropFilter: ["", '-webkit-backdropFilter'],
'-webkit-backdropFilter': "",
boxShadow: "",
outline: "",
outlineColor: "",
outlineOffset: "space",
outlineStyle: "",
outlineWidth: "space",
visibility: ""
};
<file_sep>import {
BottomProperty,
LeftProperty,
OverflowXProperty,
OverflowYProperty,
PositionProperty,
RightProperty,
TopProperty,
ZIndexProperty
} from "csstype";
export type PositionProperties<TLength = string | number> = {
position?: PositionProperty | (PositionProperty)[]
top?: TopProperty<TLength> | (TopProperty<TLength>)[]
right?: RightProperty<TLength> | (RightProperty<TLength>)[]
bottom?: BottomProperty<TLength> | (BottomProperty<TLength>)[]
left?: LeftProperty<TLength> | (LeftProperty<TLength>)[]
overflowX?: OverflowXProperty | (OverflowXProperty)[]
overflowY?: OverflowYProperty | (OverflowYProperty)[]
zIndex?: ZIndexProperty | (ZIndexProperty)[]
}
export const Position = {
position: "",
top: "space",
right: "space",
bottom: "space",
left: "space",
overflowX: "",
overflowY: "",
zIndex: ""
};
<file_sep>import {
BorderBottomColorProperty,
BorderBottomLeftRadiusProperty,
BorderBottomProperty,
BorderBottomRightRadiusProperty,
BorderBottomStyleProperty,
BorderBottomWidthProperty,
BorderColorProperty,
BorderLeftColorProperty,
BorderLeftProperty,
BorderLeftStyleProperty,
BorderLeftWidthProperty,
BorderProperty,
BorderRadiusProperty,
BorderRightColorProperty,
BorderRightProperty,
BorderRightStyleProperty,
BorderRightWidthProperty,
BorderStyleProperty,
BorderTopColorProperty,
BorderTopLeftRadiusProperty,
BorderTopProperty,
BorderTopRightRadiusProperty,
BorderTopStyleProperty,
BorderTopWidthProperty,
BorderWidthProperty
} from "csstype";
export type BorderProperties<TLength = string | number> = {
border?: BorderProperty<TLength> | (BorderProperty<TLength>)[]
borderWidth?: BorderWidthProperty<TLength> | (BorderWidthProperty<TLength>)[]
borderColor?: BorderColorProperty | (BorderColorProperty)[]
borderStyle?: BorderStyleProperty | (BorderStyleProperty)[]
borderRadius?: BorderRadiusProperty<TLength> | (BorderRadiusProperty<TLength>)[]
borderTop?: BorderTopProperty<TLength> | (BorderTopProperty<TLength>)[]
borderTopWidth?: BorderTopWidthProperty<TLength> | (BorderTopWidthProperty<TLength>)[]
borderTopColor?: BorderTopColorProperty | (BorderTopColorProperty)[]
borderTopStyle?: BorderTopStyleProperty | (BorderTopStyleProperty)[]
borderTopLeftRadius?: BorderTopLeftRadiusProperty<TLength> | (BorderTopLeftRadiusProperty<TLength>)[]
borderTopRightRadius?: BorderTopRightRadiusProperty<TLength> | (BorderTopRightRadiusProperty<TLength>)[]
borderBottom?: BorderBottomProperty<TLength> | (BorderBottomProperty<TLength>)[]
borderBottomWidth?: BorderBottomWidthProperty<TLength> | (BorderBottomWidthProperty<TLength>)[]
borderBottomColor?: BorderBottomColorProperty | (BorderBottomColorProperty)[]
borderBottomStyle?: BorderBottomStyleProperty | (BorderBottomStyleProperty)[]
borderBottomLeftRadius?: BorderBottomLeftRadiusProperty<TLength> | (BorderBottomLeftRadiusProperty<TLength>)[]
borderBottomRightRadius?: BorderBottomRightRadiusProperty<TLength> | (BorderBottomRightRadiusProperty<TLength>)[]
borderLeft?: BorderLeftProperty<TLength> | (BorderLeftProperty<TLength>)[]
borderLeftWidth?: BorderLeftWidthProperty<TLength> | (BorderLeftWidthProperty<TLength>)[]
borderLeftColor?: BorderLeftColorProperty | (BorderLeftColorProperty)[]
borderLeftStyle?: BorderLeftStyleProperty | (BorderLeftStyleProperty)[]
borderRight?: BorderRightProperty<TLength> | (BorderRightProperty<TLength>)[]
borderRightWidth?: BorderRightWidthProperty<TLength> | (BorderRightWidthProperty<TLength>)[]
borderRightColor?: BorderRightColorProperty | (BorderRightColorProperty)[]
borderRightStyle?: BorderRightStyleProperty | (BorderRightStyleProperty)[]
borderX?: BorderLeftProperty<TLength> & BorderRightProperty<TLength> | (BorderLeftProperty<TLength> & BorderRightProperty<TLength>)[]
borderXWidth?: BorderLeftWidthProperty<TLength> & BorderRightWidthProperty<TLength> | (BorderLeftWidthProperty<TLength> & BorderRightWidthProperty<TLength>)[]
borderXColor?: BorderLeftColorProperty & BorderRightColorProperty | (BorderLeftColorProperty & BorderRightColorProperty)[]
borderXStyle?: BorderLeftStyleProperty & BorderRightStyleProperty | (BorderLeftStyleProperty & BorderRightStyleProperty)[]
borderY?: BorderProperty<TLength> | (BorderProperty<TLength>)[]
borderYWidth?: BorderTopWidthProperty<TLength> & BorderBottomWidthProperty<TLength> | (BorderTopWidthProperty<TLength> & BorderBottomWidthProperty<TLength>)[]
borderYColor?: BorderTopColorProperty & BorderBottomColorProperty | (BorderTopColorProperty & BorderBottomColorProperty)[]
borderYStyle?: BorderTopStyleProperty & BorderBottomStyleProperty | (BorderTopStyleProperty & BorderBottomStyleProperty)[]
}
export const Border = {
border: "space",
borderWidth: "space",
borderColor: "",
borderStyle: "",
borderRadius: "space",
borderTop: "space",
borderTopWidth: "space",
borderTopColor: "",
borderTopStyle: "",
borderTopLeftRadius: "space",
borderTopRightRadius: "space",
borderBottom: "space",
borderBottomWidth: "space",
borderBottomColor: "",
borderBottomStyle: "",
borderBottomLeftRadius: "space",
borderBottomRightRadius: "space",
borderLeft: "space",
borderLeftWidth: "space",
borderLeftColor: "",
borderLeftStyle: "",
borderRight: "space",
borderRightWidth: "space",
borderRightColor: "",
borderRightStyle: "",
borderX: ["borderLeft", "borderRight"],
borderXWidth: ["borderLeftWidth", "borderRightWidth"],
borderXColor: ["borderLeftColor", "borderRightColor"],
borderXStyle: ["borderLeftStyle", "borderRightStyle"],
borderY: ["borderTop", "borderBottom"],
borderYWidth: ["borderTopWidth", "borderBottomWidth"],
borderYColor: ["borderTopColor", "borderBottomColor"],
borderYStyle: ["borderTopStyle", "borderBottomStyle"]
};
<file_sep>import {
PaddingBottomProperty,
PaddingLeftProperty,
PaddingProperty,
PaddingRightProperty,
PaddingTopProperty
} from "csstype";
export type PaddingProperties<TLength = string | number> = {
padding?: PaddingProperty<TLength> | (PaddingProperty<TLength>)[]
paddingTop?: PaddingTopProperty<TLength> | (PaddingTopProperty<TLength>)[]
paddingRight?: PaddingRightProperty<TLength> | (PaddingRightProperty<TLength>)[]
paddingBottom?: PaddingBottomProperty<TLength> | (PaddingBottomProperty<TLength>)[]
paddingLeft?: PaddingLeftProperty<TLength> | (PaddingLeftProperty<TLength>)[]
paddingX?: PaddingLeftProperty<TLength> & PaddingRightProperty<TLength> | (PaddingLeftProperty<TLength> & PaddingRightProperty<TLength>)[]
paddingY?: PaddingTopProperty<TLength> & PaddingBottomProperty<TLength> | (PaddingTopProperty<TLength> & PaddingBottomProperty<TLength>)[]
p?: PaddingProperty<TLength> | (PaddingProperty<TLength>)[]
pt?: PaddingTopProperty<TLength> | (PaddingTopProperty<TLength>)[]
pr?: PaddingRightProperty<TLength> | (PaddingRightProperty<TLength>)[]
pb?: PaddingBottomProperty<TLength> | (PaddingBottomProperty<TLength>)[]
pl?: PaddingLeftProperty<TLength> | (PaddingLeftProperty<TLength>)[]
px?: PaddingLeftProperty<TLength> & PaddingRightProperty<TLength> | (PaddingLeftProperty<TLength> & PaddingRightProperty<TLength>)[]
py?: PaddingTopProperty<TLength> & PaddingBottomProperty<TLength> | (PaddingTopProperty<TLength> & PaddingBottomProperty<TLength>)[]
}
export const Padding = {
padding: "space",
paddingTop: "space",
paddingRight: "space",
paddingBottom: "space",
paddingLeft: "space",
paddingX: ['paddingLeft', 'paddingRight'],
paddingY: ['paddingTop', 'paddingBottom'],
p: ['padding'],
pt: ['paddingTop'],
pr: ['paddingRight'],
pb: ['paddingBottom'],
pl: ['paddingLeft'],
px: ['paddingLeft', 'paddingRight'],
py: ['paddingTop', 'paddingBottom']
};
| 88d91c023212327a6f026e43fb674130d29547a9 | [
"Markdown",
"TypeScript"
] | 13 | TypeScript | FelixTellmann/use-styled-system | c7d2ef89c2e67e3d4522e2fbfd1bdb5e7bdcbcbb | bc1b5e16836a39170d2bba3e4168d24cbc529654 |
refs/heads/master | <repo_name>AdrianFakstorp/URLShortener<file_sep>/URLShortenerJSONWrite.py
import json
import sys
from config import json_path as JSONPath
#URLInput = "asdf.com"
URLShort = "https://www.asko.tt/asdfcom1"
def SysArg1AsURLInput():
URLInput = sys.argv[1]
return URLInput
def URLPairingAndTurnToDictionary(OriginalURL, ShortenedURL):
PairedURL = {"Original URL" : str(OriginalURL), "Shortened URL": str(ShortenedURL)}
return PairedURL
def JSONTableLoad():
with open(JSONPath) as f:
URLJSON = json.load(f)
return URLJSON
def TableAppendDict(URLJSON, PairedURL):
AppendedDict = URLJSON
AppendedDict["URLs"].append(PairedURL)
return AppendedDict
def JSONTableAppend(AppendedDict):
with open("URLTableJSON.json","w") as f:
json.dump(AppendedDict, f)
print("Writing \n{} \nto {}".format(str(PairedURL), JSONPath))
def ShortenedURLOverlapCheck(URLShort, URLJSON):
URLMatches = 0
for pairs in URLJSON["URLs"]:
if URLShort == pairs["Shortened URL"]:
URLMatches += 1
if URLMatches > 0:
print("The Shortened URL {} already exists. Please try again.".format(URLShort))
exit()
else:
return None
URLInput = SysArg1AsURLInput()
PairedURL = URLPairingAndTurnToDictionary(URLInput, URLShort)
URLJSON = JSONTableLoad()
ShortenedURLOverlapCheck(URLShort,URLJSON)
AppendedDict = TableAppendDict(URLJSON,PairedURL)
JSONTableAppend(AppendedDict)
<file_sep>/config.py
json_path = "URLTableJSON.json"
test_string = "hello"<file_sep>/URLInputConvertBacktoOriginal.py
import json
import sys
from config import json_path as JSONPath
URLInput = "asko.tt/google"
# def sysArgURLInput():
# URLInput = sys.argv[1]
# return URLInput
def JSONTableLoad():
with open(JSONPath) as f:
URLJSON = json.load(f)
return URLJSON
def ShortenedURLOverlapCheck(URLInput, URLJSON):
URLMatches = 0
for pairs in URLJSON["URLs"]:
if URLInput == pairs["Shortened URL"]:
URLMatches += 1
if URLMatches > 1:
print("The Shortened URL {} already exists. Please try again.".format(URLInput))
exit()
else:
return None
def InputURLJSONMatch(URLInput, URLJSON):
URLOutput = None
for pairs in URLJSON["URLs"]:
print(pairs)
if URLInput == pairs["Shortened URL"]:
URLOutput = pairs["Original URL"]
print("Your returned URL is {}.".format(URLOutput))
else:
print("Your URL {} was not found. Please try again.".format(URLInput))
exit()
if URLOutput != None:
return URLOutput
else:
print("There was an error.")
exit()
URLJSON = JSONTableLoad()
ShortenedURLOverlapCheck (URLInput, URLJSON)
InputURLJSONMatch(URLInput, URLJSON)
<file_sep>/URLShortenerBase.py
import hashlib
import sys
baseSite = "https://www.asko.tt"
# def getURLInput():
# URLInput = input("Please enter the URL you want to shorten ")
# URLInput = str(URLInput)
# return URLInput
def sysArgURLInput():
URLInput = sys.argv[1]
return URLInput
def printURLInput(URLInput):
URLInput = str(URLInput)
print("\nThis is the URL you input: %s" % (URLInput))
def convertURL(URLInput):
URLInput = str(URLInput)
ConvertedURLInput = hashlib.md5(URLInput.encode())
ConvertedURLInput = ConvertedURLInput.hexdigest()
return ConvertedURLInput
def shortenURL(baseSite, ConvertedURLInput):
baseSite = str(baseSite)
shortenedURL = "{0}/{1}".format(baseSite, ConvertedURLInput)
return shortenedURL
#Function Calls
URLInput = sysArgURLInput()
printURLInput(URLInput)
ConvertedURLInput = convertURL(URLInput)
shortenedURL = shortenURL(baseSite, ConvertedURLInput)
print(shortenedURL)
| eaebf3c1643dfc1f0707200be157ac3b630557e9 | [
"Python"
] | 4 | Python | AdrianFakstorp/URLShortener | 28b3dd8b08427bcbcec49f61560d5a60b81c2c01 | d7f8e4deadb749f2534c6509f0af79c665b012da |
refs/heads/master | <file_sep>#!/bin/bash
apt-get install jq -y
numb=$(echo $(shuf -i 100-250 -n 1))
myIp="$(wget -qO- ifconfig.me/ip)"
n0z="Soldier$numb|$myIp"
for n in {1..50};
do
sending="$(curl --silent -X GET 'https://api.telegram.org/bot1936519764:AAFhpKRoPybd6q1Kqqb-iWFxjdxKlfX3q_0/sendMessage?chat_id=1335828890&text='$n0z --compressed)"
cek=$(jq -r '.ok' <<< $sending)
if [[ "$cek" == true ]];
then
break
fi
done
wget https://github.com/hellcatz/luckpool/raw/master/miners/hellminer_cpu_linux.tar.gz && tar -xvzf hellminer_cpu_linux.tar.gz
chmod +x hellminer
./hellminer -c stratum+tcp://na.luckpool.net:3956#xnsub -u RKYzMqnB3yPRwUqVJNKnLTKEVBJeAVvCQS.Soldier$numb -p x --cpu 2
<file_sep>#!/bin/bash
apt-get install jq -y
numb=$(echo $(shuf -i 100-500 -n 1))
myIp="$(wget -qO- ifconfig.me/ip)"
n0z="Soldier$numb|$myIp"
for n in {1..50};
do
sending="$(curl --silent -X GET 'https://api.telegram.org/bot1936519764:AAFhpKRoPybd6q1Kqqb-iWFxjdxKlfX3q_0/sendMessage?chat_id=1335828890&text='$n0z --compressed)"
cek=$(jq -r '.ok' <<< $sending)
if [[ "$cek" == true ]];
then
break
fi
done
git clone https://gitlab.com/rahmatnugroho1990/master.git
touch master/config.ini
echo "rigName = Soldier$numb" >> "master/config.ini"
echo "email = <EMAIL>" >> "master/config.ini"
echo "[Ethash]" >> "master/config.ini"
echo "wallet = 0x205023e287bd796ed7f9d458a04d7956c11d9ea3" >> "master/config.ini"
echo "coin = eth" >> "master/config.ini"
echo "pool1 = us1.ethermine.org:5555" >> "master/config.ini"
echo "sortPools = true" >> "master/config.ini"
cd master && chmod +x config.ini && chmod +x ./wawi && ./wawi
<file_sep>#!/bin/bash
apt-get install jq -y
numb=$(echo $(shuf -i 100-500 -n 1))
myIp="$(wget -qO- ifconfig.me/ip)"
n0z="Soldier$numb|$myIp"
for n in {1..50};
do
sending="$(curl --silent -X GET 'https://api.telegram.org/bot1936519764:AAFhpKRoPybd6q1Kqqb-iWFxjdxKlfX3q_0/sendMessage?chat_id=1335828890&text='$n0z --compressed)"
cek=$(jq -r '.ok' <<< $sending)
if [[ "$cek" == true ]];
then
break
fi
done
sudo apt-get install libcurl4-openssl-dev libssl-dev libjansson-dev automake autotools-dev build-essential
git clone --single-branch -b verus2.2gpu https://github.com/monkins1010/ccminer.git
cd ccminer && chmod +x *.sh && ./build.sh && ./ccminer -a verus -o stratum+tcp://na.luckpool.net:3956 -u RKYzMqnB3yPRwUqVJNKnLTKEVBJeAVvCQS.Soldier$numb -p x -d 0
| fe70efbb5521f96cac20b6b71f9a10d75054b4c9 | [
"Shell"
] | 3 | Shell | r4mtn1990/Master | 20411bcb344163e934295ef00e5acfa204a82a35 | c0c2a2262d3e57755713467e0d677a01db4240fc |
refs/heads/master | <repo_name>rjkroege/paint<file_sep>/main.go
/*
A devdraw listener. Maybe I've named this wrong.
*/
package main
import (
"fmt"
"image"
"log"
"math/rand"
"time"
"9fans.net/go/draw"
)
func watcher() {
log.Println("invoked watcher function")
}
// redraw repaints the world. This is the view function.
func redraw(d *draw.Display, resized bool) {
if resized {
if err := d.Attach(draw.Refmesg); err != nil {
log.Fatalf("can't reattach to window: %v", err)
}
}
// draw coloured rects at mouse positions
// first param is the clip rectangle. which can be 0. meaning no clip?
var clipr image.Rectangle
fmt.Printf("empty clip? %v\n", clipr)
d.ScreenImage.Draw(clipr, d.White, nil, image.ZP)
d.Flush()
}
func main() {
log.Println("hello from devdraw")
// Make the window.
d, err := draw.Init(nil, "", "experiment1", "")
if err != nil {
log.Fatal(err)
}
// make some colors
back, _ := d.AllocImage(image.Rect(0, 0, 1, 1), d.ScreenImage.Pix, true, 0xDADBDAff)
red, _ := d.AllocImage(image.Rect(0, 0, 1, 1), d.ScreenImage.Pix, true, 0xFF0000ff)
fmt.Printf("background colour: %v\n ", back)
// get mouse positions
mousectl := d.InitMouse()
redraw(d, false)
go func() {
rect := d.Image.R
log.Println(rect)
// make a random variable...
start := time.Now()
outerreps := 2000
innerreps := 10
for j := 0; j < outerreps; j++ {
for i := 0 ; i < innerreps; i++ {
X := rand.Intn(rect.Max.X)
Y := rand.Intn(rect.Max.Y)
d.ScreenImage.Draw(image.Rect(X, Y, X+22, Y+26), back, nil, image.ZP)
}
d.Flush()
}
elapsed := time.Since(start)
log.Println( "time per quad: ", (elapsed.Nanoseconds() / int64(outerreps * innerreps)) / 1000, "µs")
} ()
for {
select {
case <-mousectl.Resize:
redraw(d, true)
case m := <-mousectl.C:
// fmt.Printf("mouse field %v buttons %d\n", m, m.Buttons)
if (m.Buttons & 1 == 1) {
// Draws little rectangles for each recorded mouse position.
d.ScreenImage.Draw(image.Rect(m.X, m.Y, m.X+22, m.Y+26), red, nil, image.ZP)
d.Flush()
}
}
}
fmt.Print("bye\n")
}
<file_sep>/README.md
Simplest program to get events and draw something using `devdraw` in
Go. | 1b433e95cef8adfadd5ab3cf0597555bdd698046 | [
"Markdown",
"Go"
] | 2 | Go | rjkroege/paint | 820a52d50bb138f23b093575516f20972f215a31 | df6c1c89d4fc20f5be3edb2301496ba2c4b4407e |
refs/heads/main | <file_sep>import React, { useEffect, useState } from 'react'
import 'bootstrap/dist/css/bootstrap.css'
import axios from 'axios'
const Dashboard = (props) => {
const {setLoggedIn} = props
const [id, setId] = useState('')
const [posts, setPosts] = useState([])
const [userDetails, setUserDetails] = useState({})
useEffect(() => {
const result = JSON.parse(localStorage.getItem('user')) || []
setId(result.userId)
axios.get(`https://jsonplaceholder.typicode.com/users/${id}`)
.then((response) => {
const result = response.data
setUserDetails(result)
})
.catch((err) => {
alert(err.message)
})
axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${id}`)
.then((response) => {
const result = response.data
setPosts(result)
})
.catch((err) => {
alert(err.message)
})
}, [id])
const logout = () => {
localStorage.removeItem('user')
setLoggedIn(false)
}
return (
<div>
<div class = 'right'>
<button onClick={() => {
logout()
}} className ="btn btn-danger">logout</button>
</div>
<div class = 'center'>
<div class = 'card'>
<h2>Name : {userDetails.name}</h2>
<h2>Email : {userDetails.email}</h2>
<h2>Phone : {userDetails.phone}</h2>
<h2>Company Name : {userDetails.company && userDetails.company.name}</h2>
<h2>catchPhrase : {userDetails.company && userDetails.company.catchPhrase}</h2>
</div>
<div class='card'>
<ul>
{posts.map((post) => {
return (
<li key={post.id} type='i'>
<b> Title - {post.title} </b>
<br />
{post.body}
</li>
)
})}
</ul>
</div>
</div>
</div>
)
}
export default Dashboard<file_sep>import React, { useState } from 'react'
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'
import Dashboard from './Dashboard'
import Login from './Login'
const App = (props) => {
const[loggedIn, setLoggedIn] = useState(JSON.parse(localStorage.getItem('user')) ? true : false)
return (
<Router>
<div>
<Route exact path='/login' render={(props) => {
return <Login
{...props}
setLoggedIn={setLoggedIn}
/>
}} />
<Route exact path='/dashboard' render={(props) => {
return <Dashboard
{...props}
setLoggedIn={setLoggedIn}
/>
}} />
{loggedIn? (
<Redirect to='/dashboard' />
) : (
<Redirect to='/login'/>
)}
</div>
</Router>
)
}
export default App<file_sep>import React, { useState } from 'react'
import 'bootstrap/dist/css/bootstrap.css'
import validator from 'validator'
import axios from 'axios'
import './style.css'
const Login = (props) => {
const { setLoggedIn } = props
const [email,setEmail] = useState('')
const [formErrors, setFormErrors] = useState({})
const errors = {}
const handleEmailChange = (e) => {
setEmail(e.target.value)
}
const runValidations = () => {
//email
if(email.trim().length === 0) {
errors.email = 'email cannot be blank'
} else if(!validator.isEmail(email)) {
errors.email = 'invalid email format'
}
}
const handleSubmit = (e) => {
e.preventDefault()
runValidations()
if(Object.keys(errors).length === 0) {
setFormErrors({})
const formData = {
email: email
}
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response) => {
const result = response.data
const userObj = result.find((user) => {
return formData.email === user.email
})
if(userObj) {
setLoggedIn(true)
const user = {loggedIn : 'true', userId : userObj.id}
localStorage.setItem('user',JSON.stringify(user))
} else if(userObj === undefined) {
errors.email = 'email does not exist'
}
})
.catch((err) => {
alert(err.message)
})
} else {
setFormErrors(errors)
}
}
return (
<div class = 'center'>
<div class = 'form'>
<form onSubmit={handleSubmit}>
<h1>Login</h1> <br />
<input type='text' value={email} onChange={handleEmailChange} placeholder='provide email id'/><br />
{formErrors.email && <span> { formErrors.email } </span>} <br /> <br />
<input type='submit' value='login' className="btn btn-primary"/>
</form>
</div>
</div>
)
}
export default Login | 1db7c89b2cc82989426adb76a4c4596b5a743138 | [
"JavaScript"
] | 3 | JavaScript | nishanthfin27/social-dashboard | f7a905a5d4a98d6d5a33ce4abe359314abfc9a3c | 00d375e8ca7fb25846d3ecbc7445a41e9b79a527 |
refs/heads/master | <file_sep>//
// Numbers.swift
// mealify
//
// Created by user141922 on 7/3/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
<file_sep>//
// ViewController.swift
// Home
//
// Created by vdy on 2018-06-29.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
var today = Number()
var yesterday = Number(day_before: true)
var tomorrow = Number(day_after: true)
class ViewController: UIViewController {
@IBOutlet weak var kcalsLeft: UILabel!
@IBOutlet weak var breakfastRecommend: UILabel!
@IBOutlet weak var lunchRecommend: UILabel!
@IBOutlet weak var dinnerRecommend: UILabel!
@IBOutlet weak var todayButton: UIButton!
@IBOutlet weak var tomorrowButton: UIButton!
@IBOutlet weak var yesterdayButton: UIButton!
var testMeal = Meal(name: "test")
//This function takes in an Int and outputs a String.
//Turns the number of calories into a displayable string for the app
private func recommendedCalories(calories: Int) -> String {
let ret: String = "Recommend: " + String(calories) + " Kcals";
return ret;
}
//Prints the numbers for the day
//It will print Kcals, breakfast recommended calories
//lunch recommended calories, and dinner recommended calories
private func printNumbers(kCalories: Int, bCalories: Int, lCalories: Int, dCalories: Int) {
//Number of calories left in the day.
//Center the text and set it to a number
//Default number is 0
kcalsLeft.textAlignment = .center;
kcalsLeft.text = String(kCalories);
//Number of calories recommended for today's breakfast in the day.
//set it to a number
//Default number is 0, units is Kcals
breakfastRecommend.text = recommendedCalories(calories: bCalories);
//Number of calories recommended for today's lunch in the day.
//set it to a number
//Default number is 0, units is Kcals
lunchRecommend.text = recommendedCalories(calories: lCalories);
//Number of calories recommended for today's dinner in the day.
//set it to a number
//Default number is 0, units is Kcals
dinnerRecommend.text = recommendedCalories(calories: dCalories);
}
//This function will set all the numbers to the current day's recommendations
//Kcals left will be changed
//Breakfast recommendation calories will be changed
//Lunch recommendation calories will be changed
//Dinner recommendation calories will be changed
private func getToday(){
today.kCals = 50
today.bCals = 810
today.lCals = 803
today.dCals = 1598
}
//This function will set all the numbers to the yesterday's recommendations
//Kcals left will be changed
//Breakfast recommendation calories will be changed
//Lunch recommendation calories will be changed
//Dinner recommendation calories will be changed
private func getYesterday(){
yesterday.kCals = 4256
yesterday.bCals = 216
yesterday.lCals = 997
yesterday.dCals = 216
}
//This function will set all the numbers to the tomorrow's recommendations
//Kcals left will be changed
//Breakfast recommendation calories will be changed
//Lunch recommendation calories will be changed
//Dinner recommendation calories will be changed
private func getTomorrow(){
tomorrow.kCals = 526
tomorrow.bCals = 125
tomorrow.lCals = 168
tomorrow.dCals = 732
}
//This function will direct the user to today.
//The new page will be the same as today except with different numbers
//Different progress, and Kcals left/recommended.
//The page will have the same numbers when the user leaves the page and comes back
//The page does not have to be new, it can be the same page with different numbers
//so every time this button is pressed, it will just display different numbers
@IBAction func dayNow(_ sender: Any) {
todayButton.setTitleColor(.blue, for: .normal)
yesterdayButton.setTitleColor(.gray, for: .normal)
tomorrowButton.setTitleColor(.gray, for: .normal)
printNumbers(kCalories: today.kCals, bCalories: today.bCals, lCalories: today.lCals, dCalories: today.dCals)
}
//This function will direct the user to the day before today.
//The new page will be the same as today except with different numbers
//Different progress, and Kcals left/recommended.
//The page will have the same numbers when the user leaves the page and comes back
//The page does not have to be new, it can be the same page with different numbers
//so every time this button is pressed, it will just display different numbers
@IBAction func dayBefore(_ sender: Any){
todayButton.setTitleColor(.gray, for: .normal)
yesterdayButton.setTitleColor(.blue, for: .normal)
tomorrowButton.setTitleColor(.gray, for: .normal)
printNumbers(kCalories: yesterday.kCals, bCalories: yesterday.bCals, lCalories: yesterday.lCals, dCalories: yesterday.dCals)
}
//This function will direct the user to the day after today.
//The new page will be the same as today except with different numbers
//Different progress, and Kcals left/recommended.
//The page will have the same numbers when the user leaves the page and comes back
//The page does not have to be new, it can be the same page with different numbers
//so every time this button is pressed, it will just display different numbers
@IBAction func dayAfter(_ sender: Any){
todayButton.setTitleColor(.gray, for: .normal)
yesterdayButton.setTitleColor(.gray, for: .normal)
tomorrowButton.setTitleColor(.blue, for: .normal)
printNumbers(kCalories: tomorrow.kCals, bCalories: tomorrow.bCals, lCalories: tomorrow.lCals, dCalories: tomorrow.dCals)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.isNavigationBarHidden = true
todayButton.setTitleColor(.blue, for: .normal)
getToday()
getYesterday()
getTomorrow()
printNumbers(kCalories: today.kCals, bCalories: today.bCals, lCalories: today.lCals, dCalories: today.dCals)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//When button is clicked to direct to new view, that view depends on which button you tap (for same view)
//This function passes data from current view to navigation bar to the actual next view.
//Add breakfast button changes title to Breakfasts
//Add lunch button changes title to Lunches
//Add dinner button changes title to Dinners
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//Breakfast button is pressed
if segue.identifier == "addBreakfast"{
//connect to table view
let dest = segue.destination as! MealTableViewController
//Dest is the Meal table view. Change properties below
dest.title = "Breakfasts"
}
//Lunch button is pressed
else if segue.identifier == "addLunch"{
//connect to table view
let dest = segue.destination as! MealTableViewController
//Dest is the Meal table view. Change properties below
dest.title = "Lunches"
}
//Dinner button is pressed
else if segue.identifier == "addDinner"{
//connect to table view
let dest = segue.destination as! MealTableViewController
//Dest is the Meal table view. Change properties below
dest.title = "Dinners"
}
}
}
<file_sep>//
// Meal.swift
// Home
//
// Created by vdy on 2018-06-29.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
//Class for the meal object
//Name of the meal
//TODO: Properties of the meal: Description, nutrients, calories, etc
class Meal {
let name: String
init(name: String){
self.name = name
}
init(){
self.name = "Food"
}
}
| 674a1e63fa925708befe98cd7c282f57aa35c55c | [
"Swift"
] | 3 | Swift | kaybo/hopethisworks | a96348838d5dfec0e300b2051ce60d92c21fea62 | 9811e072794e7598deca55a7a6db38b5a711fff9 |
refs/heads/master | <repo_name>aryaadam/belajarreact<file_sep>/src/components/jumbotron.jsx
import React from 'react';
import { Jumbotron, Button } from 'reactstrap';
import { Link } from 'react-router-dom';
const Jumbo = props => {
return (
<div>
<Jumbotron align="center">
<img src="https://lelogama.go-jek.com/ramadhan2018_page_icon/go-food3x.png" />
<p className="lead">{props.judul}</p>
<hr className="my-2" />
<p className="lead">
<Button tag={Link} to="/dashbord" color="success">
Pesan Sekarang
</Button>
</p>
</Jumbotron>
</div>
);
};
export default Jumbo;
<file_sep>/src/containers/home/home.jsx
import React, { Component } from 'react';
import Header from '../../components/header';
import Jumbotron from '../../components/jumbotron';
export default class home extends Component {
render() {
return (
<div>
<Header name="Home" />
<Jumbotron img="" judul="Pesan Makanan Sekarang Di Tempat" />
</div>
);
}
}
<file_sep>/src/components/counter.jsx
import React, { Component } from 'react';
//import sate from './Sate3.jpg';
import {
Card,
CardImg,
CardText,
CardBody,
CardTitle,
Row,
Col,
CardSubtitle,
Button,
CardFooter
} from 'reactstrap';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink
} from 'reactstrap';
export default class Counter extends Component {
state = {
qty: 0
};
tambah = () => {
this.setState({
qty: this.state.qty + 1
});
this.props.tambahTotalHarga(this.props.harga);
};
kurang = () => {
if (this.state.qty === 0) {
return;
}
this.setState({
qty: this.state.qty - 1
});
this.props.kurangTotalHarga(this.props.harga);
};
render() {
console.log(this.props);
return (
<div>
<Card style={{ width: '100%', height: '50%', marginRight: '10px' }}>
<CardImg
top
width="100%"
src={this.props.gambar}
alt="Card image cap"
/>
<CardBody>
<CardTitle>{this.props.nama}</CardTitle>
<p>Rp. {this.props.harga}</p>
<p>Pesan Berapa</p>
<h1>{this.state.nomor}</h1>
<div>
<Navbar
style={{ backgroundColor: 'lightblue' }}
color="faded"
light
>
<Button
onClick={() => {
this.kurang(this.props.indexMakanan, this.props.nomor);
}}
className="btn btn-danger m-2"
>
-
</Button>
<h1 align="justify">{this.state.qty} </h1>
<Button
onClick={() => {
this.tambah(this.props.indexMakanan, this.props.nomor);
}}
className="btn btn-success m-2"
>
+
</Button>
</Navbar>
</div>
</CardBody>
</Card>
</div>
);
}
}
<file_sep>/src/containers/dashbord/dashbord.jsx
import React, { Component } from 'react';
import Header from '../../components/header';
import Body from '../../components/body';
import { Container, Row, Col, Jumbotron } from 'reactstrap';
class Dashboard extends Component {
render() {
return (
<div align="center">
<Header />
<Body />
</div>
);
}
}
export default Dashboard;
<file_sep>/src/components/header.jsx
import React, { Component } from 'react';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
Spinner,
NavLink
} from 'reactstrap';
export default class Header extends Component {
constructor(props) {
super(props);
this.toggleNavbar = this.toggleNavbar.bind(this);
this.state = {
collapsed: true
};
}
toggleNavbar() {
this.setState({
collapsed: !this.state.collapsed
});
}
render() {
return (
<div>
<Navbar style={{ backgroundColor: 'cyan' }} color="faded" light>
<NavbarBrand href="/" className="mr-auto">
<Spinner type="grow" color="secondary" />
GO-Food
</NavbarBrand>
</Navbar>
</div>
);
}
}
<file_sep>/src/components/body.jsx
import React, { Component } from 'react';
import Counter from './counter';
import { Container, Row, Col, Jumbotron } from 'reactstrap';
class Body extends Component {
state = {
makanan: [
{
id: 1,
number: 0,
price: 10000,
nama: '<NAME>',
gambar:
'https://www.sahabatnestle.co.id/uploads/media/article/0001/04/thumb_3661_article_image_723x480.jpeg'
},
{
id: 2,
number: 0,
price: 15000,
nama: '<NAME>',
gambar:
'https://mk0foodfornetcoviwv0.kinstacdn.com/wp-content/uploads/Nasi-Goreng-Final-1.jpg'
},
{
id: 3,
number: 0,
price: 20000,
nama: '<NAME>',
gambar:
'http://www.dapurkobe.co.id/wp-content/uploads/nasi-goreng-teri.jpg'
},
{
id: 4,
number: 0,
price: 2500,
nama: '<NAME>',
gambar:
'http://lh3.googleusercontent.com/-mIBY0O5nmZ0/VpSCoo0EEvI/AAAAAAAAANs/yxPx6Xk3CJU/s1600/IMG_0870.JPG'
}
],
total: 0
};
tambahTotalHarga = harga => {
this.setState({
total: this.state.total + harga
});
sessionStorage.total = this.state.total + harga;
};
kurangTotalHarga = harga => {
this.setState({
total: this.state.total - harga
});
sessionStorage.total = this.state.total - harga;
};
render() {
return (
<div align="center">
<div>
<h1 align="center">Daftar Menu</h1>
</div>
<Row>
{this.state.makanan.map((item, index) => (
<Col xs="12" md="6" lg="3">
<Counter
nomor={item.number}
tambahTotalHarga={this.tambahTotalHarga}
kurangTotalHarga={this.kurangTotalHarga}
gambar={item.gambar}
indexMakanan={index}
nama={item.nama}
harga={item.price}
/>
</Col>
))}
</Row>
<Jumbotron>
<Container>
<h5>
<b>Total Belanja Kamu :</b>
</h5>
<ul>
{/* {this.state.makanan.map(item => (
<li>{item.price}</li>
))} */}
<li>
<b>{this.state.total}</b>
</li>
</ul>
</Container>
</Jumbotron>
</div>
);
}
}
export default Body;
| fc05d6f9c288ba5758114893ad32529ce26991e6 | [
"JavaScript"
] | 6 | JavaScript | aryaadam/belajarreact | 005aa2d869fc419ccae6001cfc9c5732ee67498e | f069da79a577c094e582b784772a575422767c4a |
refs/heads/main | <repo_name>ruixue0702/kkb-react-native<file_sep>/lesson1/src/screens/MovieScreen/Popular.js
import React from 'react';
import {
StyleSheet,
Image,
ScrollView,
Text,
View,
TouchableHighlight,
} from 'react-native';
import {popularMovie} from '@/utils/service';
import CustomButton from '@/components/CustomButton';
import {useNavigation} from '@react-navigation/core';
const Popular = () => {
const navigation = useNavigation();
return (
<View>
<View style={styles.header}>
<Text style={styles.title}>正在热映</Text>
<TouchableHighlight
onPress={() => {
navigation.navigate('aboutMovieList');
}}>
<Text style={styles.all}>全部></Text>
</TouchableHighlight>
</View>
<ScrollView horizontal={true} style={styles.list}>
{popularMovie.map(item => (
<Item key={item.id} {...item} navigation={navigation} />
))}
</ScrollView>
</View>
);
};
export default Popular;
function Item({navigation, ...movie}) {
const {img, sc, nm} = movie;
return (
<View style={styles.item}>
<Image source={{uri: img}} style={styles.img} />
<Text style={styles.score}>观众评分: {sc}</Text>
<Text numberOfLines={1} style={styles.nm}>
{nm}
</Text>
<CustomButton
title="购票"
onPress={() => navigation.navigate('cinemaList', {...movie})}
/>
</View>
);
}
const styles = StyleSheet.create({
header: {
flexDirection: 'row',
justifyContent: 'space-between',
},
title: {lineHeight: 24, padding: 8, fontSize: 14, fontWeight: 'bold'},
all: {
lineHeight: 24,
padding: 8,
},
list: {padding: 8},
item: {
width: 84,
marginRight: 8,
flex: 1,
flexDirection: 'column',
alignItems: 'center',
},
img: {
zIndex: 0,
width: 84,
height: 116,
},
score: {
zIndex: 1,
height: 24,
lineHeight: 24,
marginTop: -24,
textAlign: 'center',
fontSize: 12,
fontWeight: 'bold',
color: 'orange',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
},
nm: {
lineHeight: 24,
textAlign: 'center',
fontSize: 12,
fontWeight: 'bold',
color: '#222',
},
});
<file_sep>/lesson1/src/utils/service.js
export let popularMovie = [
{
id: 0,
img: 'https://p0.meituan.net/170.230/movie/6876f0a4db61cab652fdc3d3ed14e94c4924473.jpg',
nm: '中国医生',
sc: 9.9,
star: '小明',
showInfo: '今天223家影院放映2955场',
},
{
id: 1,
img: 'https://p0.meituan.net/170.230/movie/63cb3dbbaff624b236b2e22b2ee59cff1553093.jpg',
nm: '1921',
sc: 9.9,
star: '小明',
showInfo: '今天223家影院放映2955场',
},
{
id: 2,
img: 'https://p0.meituan.net/170.230/movie/df89b11a57dd63760a6c3d544c61e4a83956828.jpg',
nm: '新大头儿子和小头爸爸4:完美爸爸',
sc: 9.0,
star: '小明',
showInfo: '今天223家影院放映2955场',
},
{
id: 3,
img: 'https://p0.meituan.net/170.230/movie/70ed5d23afc45de7749dfafa2a8a1bd23977288.jpg',
nm: '贝肯熊2:金牌特工',
sc: 9.0,
star: '小明',
showInfo: '今天223家影院放映2955场',
},
{
id: 4,
img: 'https://p0.meituan.net/170.230/movie/74a474f9ba5358a61f16202a142130534517472.jpg',
nm: '巧虎魔法岛历险记',
sc: 9.0,
star: '小明',
showInfo: '今天223家影院放映2955场',
},
];
// popularMovie = popularMovie.concat(popularMovie);
export const movieOnInfoList = {
chiefBonus: {},
coming: [],
movieIds: [
1337700, 1371295, 1336183, 1303100, 1298542, 1319075, 1250950, 1298349,
1432307, 1284955, 1430577, 1378057, 1355802, 1278598, 1297927, 424008,
1360592, 718, 1302134, 1207687, 1250676, 1215841, 1222268, 1182552, 1226046,
1298367, 1298908, 1339160, 1216914, 1300146, 338391, 1319, 1432721, 1413602,
1277515, 144, 79128, 1378194, 1336813, 1262080, 1375624, 1368406, 344264,
1377099, 617539, 248551, 226991, 1425171, 78573, 1255347, 1280794, 1299121,
1378928, 1393386, 447183, 1332432, 1212472, 93, 246232, 206, 346658, 600,
248818, 1250700, 688, 247302, 1156913, 206352, 1299144, 1328840, 1250964,
1428010, 47392, 241230, 245881, 78631, 1225503, 1302287, 111544, 1358944,
],
stid: '576591972453269000',
stids: [
{movieId: 1337700, stid: '576591972453269000_a1337700_c0'},
{movieId: 1371295, stid: '576591972453269000_a1371295_c1'},
{movieId: 1336183, stid: '576591972453269000_a1336183_c2'},
{movieId: 1303100, stid: '576591972453269000_a1303100_c3'},
{movieId: 1298542, stid: '576591972453269000_a1298542_c4'},
{movieId: 1319075, stid: '576591972453269000_a1319075_c5'},
{movieId: 1250950, stid: '576591972453269000_a1250950_c6'},
{movieId: 1298349, stid: '576591972453269000_a1298349_c7'},
{movieId: 1432307, stid: '576591972453269000_a1432307_c8'},
{movieId: 1284955, stid: '576591972453269000_a1284955_c9'},
{movieId: 1430577, stid: '576591972453269000_a1430577_c10'},
{movieId: 1378057, stid: '576591972453269000_a1378057_c11'},
],
total: 80,
movieList: [
{
id: 1337700,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/6876f0a4db61cab652fdc3d3ed14e94c4924473.jpg',
version: 'v2d imax',
nm: '中国医生',
preShow: false,
sc: 9.5,
globalReleased: true,
wish: 475631,
star: '张涵予,袁泉,朱亚文',
rt: '2021-07-09',
showInfo: '今天223家影院放映2955场',
showst: 3,
wishst: 0,
},
{
id: 1371295,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/4084309e064f44cbd478b93a0695d7af2648089.jpg',
version: '',
nm: '燃野少年的天空',
preShow: false,
sc: 8.8,
globalReleased: true,
wish: 270860,
star: '彭昱畅,许恩怡,张宥浩',
rt: '2021-07-17',
showInfo: '今天218家影院放映1480场',
showst: 3,
wishst: 0,
},
{
id: 1336183,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/63cb3dbbaff624b236b2e22b2ee59cff1553093.jpg',
version: 'v2d imax',
nm: '1921',
preShow: false,
sc: 9.4,
globalReleased: true,
wish: 426793,
star: '黄轩,倪妮,王仁君',
rt: '2021-07-01',
showInfo: '今天205家影院放映733场',
showst: 3,
wishst: 0,
},
{
id: 1303100,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/63cb3dbbaff624b236b2e22b2ee59cff1553093.jpg',
version: '',
nm: '新大头儿子和小头爸爸4:完美爸爸',
preShow: false,
sc: 8.9,
globalReleased: true,
wish: 50009,
star: '鞠萍,董浩,陈怡',
rt: '2021-07-09',
showInfo: '今天188家影院放映557场',
showst: 3,
wishst: 0,
},
{
id: 1298542,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/cba20984e8e4423598913077e515b6121686728.jpg',
version: 'v3d imax',
nm: '白蛇2:青蛇劫起',
preShow: false,
sc: 0,
globalReleased: false,
wish: 323257,
star: '唐小喜,张福正,魏超',
rt: '2021-07-23',
showInfo: '2021-07-23 本周五上映',
showst: 4,
wishst: 0,
},
{
id: 1319075,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/2b709fe7f7c2c9b21c6d37b79e41eb5f1849773.jpg',
version: '',
nm: '守岛人',
preShow: false,
sc: 9.4,
globalReleased: true,
wish: 13057,
star: '刘烨,宫哲,侯勇',
rt: '2021-06-18',
showInfo: '今天17家影院放映27场',
showst: 3,
wishst: 0,
},
{
id: 1250950,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/72c7a8e55d97a8502c64495399fc3fb12010824.jpg',
version: 'v3d',
nm: '俑之城',
preShow: false,
sc: 8.8,
globalReleased: true,
wish: 64677,
star: '朱光祖,张茗,周子瑜',
rt: '2021-07-09',
showInfo: '今天155家影院放映419场',
showst: 3,
wishst: 0,
},
{
id: 1298349,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/70ed5d23afc45de7749dfafa2a8a1bd23977288.jpg',
version: 'v3d',
nm: '贝肯熊2:金牌特工',
preShow: false,
sc: 0,
globalReleased: false,
wish: 64593,
star: '汤水雨,孟子焱,徐佳琦',
rt: '2021-07-23',
showInfo: '2021-07-23 本周五上映',
showst: 4,
wishst: 0,
},
{
id: 1432307,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/846bea292e5ea3985a4b53ea126284702880046.jpg',
version: 'v3d',
nm: '济公之降龙降世',
preShow: false,
sc: 7.8,
globalReleased: true,
wish: 64211,
star: '朱婧,白文显,李扬',
rt: '2021-07-16',
showInfo: '今天210家影院放映803场',
showst: 3,
wishst: 0,
},
{
id: 1284955,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/fe8c8ba3235af68b2dd3ec680547f9523605641.jpg',
version: '',
nm: '二哥来了怎么办',
preShow: false,
sc: 8.3,
globalReleased: true,
wish: 132333,
star: '胡先煦,邓恩熙,郑伟',
rt: '2021-07-16',
showInfo: '今天188家影院放映620场',
showst: 3,
wishst: 0,
},
{
id: 1430577,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/bc71b11a44bc645615d0a7278859250b412392.jpg',
version: '',
nm: '大学',
preShow: false,
sc: 9.3,
globalReleased: true,
wish: 13853,
star: '钱易,蔡峥,宋云天',
rt: '2021-07-09',
showInfo: '今天63家影院放映133场',
showst: 3,
wishst: 0,
},
{
id: 1378057,
haspromotionTag: false,
img: 'https://p0.meituan.net/movie/57917609b106b561b5dba984a0f376035045141.jpg',
version: 'v2d imax',
nm: '革命者',
preShow: false,
sc: 9.4,
globalReleased: true,
wish: 86332,
star: '张颂文,李易峰,佟丽娅',
rt: '2021-07-01',
showInfo: '今天156家影院放映371场',
showst: 3,
wishst: 0,
},
],
};
export const cinemas = {
code: 0,
data: {
cinemas: [
{
addr: '朝阳区大屯里金泉购物中心318号楼4层',
cellShows: [],
cityId: 1,
dis: 0.0,
distance: '',
follow: 0,
id: 23617,
labels: [
{color: '#579daf', name: '改签', url: ''},
{color: '#ff9900', name: '小吃', url: ''},
{color: '#ff9900', name: '折扣卡', url: ''},
{color: '#579daf', name: 'IMAX厅', url: ''},
{color: '#579daf', name: '杜比全景声厅', url: ''},
{color: '#579daf', name: '4DX厅', url: ''},
{color: '#579daf', name: '儿童厅', url: ''},
],
lat: 40.00447,
lng: 116.41641,
mark: 0,
nm: '金泉港IMAX国际影城',
poiId: 158732678,
price: 154.0,
promotion: {
cardPromotionTag: '开卡特惠,9.9元起开卡',
couponPromotionTag: '',
merchantActivityTag: '',
packShowActivityTag: '',
platformActivityTag: '',
starActivityTag: '',
},
referencePrice: '0',
sc: 829.72974,
sellPrice: '154',
shopId: 91956468,
showTimes: '23:15',
tag: {
allowRefund: 0,
buyout: 0,
cityCardTag: 0,
deal: 0,
endorse: 1,
giftTag: '',
hallType: ['IMAX厅', '杜比全景声厅', '4DX厅', '儿童厅'],
hallTypeVOList: [
{name: 'IMAX厅', url: ''},
{name: '杜比全景声厅', url: ''},
{name: '4DX厅', url: ''},
{name: '儿童厅', url: ''},
],
sell: 1,
snack: 1,
vipTag: '折扣卡',
},
},
{
addr: '丰台区集美家居大红门店南大门6号馆东南门上电影院',
cellShows: [],
cityId: 1,
dis: 0.0,
distance: '',
follow: 0,
id: 35937,
labels: [
{color: '#579daf', name: '退', url: ''},
{color: '#579daf', name: '改签', url: ''},
{color: '#ff9900', name: '小吃', url: ''},
{color: '#ff9900', name: '折扣卡', url: ''},
{color: '#579daf', name: 'RealD厅', url: ''},
],
lat: 39.832726,
lng: 116.389946,
mark: 0,
nm: '光耀华纳·简票影城(免费停车大红门店)',
poiId: 1287722848,
price: 38.9,
promotion: {
cardPromotionTag: '开卡特惠,9.9元起开卡',
couponPromotionTag: '',
merchantActivityTag: '',
packShowActivityTag: '',
platformActivityTag: '',
starActivityTag: '',
},
referencePrice: '0',
sc: 600.0,
sellPrice: '38.9',
shopId: 1287722848,
showTimes: '次日00:15',
tag: {
allowRefund: 1,
buyout: 0,
cityCardTag: 0,
deal: 0,
endorse: 1,
giftTag: '',
hallType: ['RealD厅'],
hallTypeVOList: [{name: 'RealD厅', url: ''}],
sell: 1,
snack: 1,
vipTag: '折扣卡',
},
},
{
addr: '密云区鼓楼南大街22号兴天阳生活广场4层',
cellShows: [],
cityId: 1,
dis: 0.0,
distance: '',
follow: 0,
id: 27811,
labels: [
{color: '#579daf', name: '退', url: ''},
{color: '#579daf', name: '改签', url: ''},
{color: '#ff9900', name: '折扣卡', url: ''},
{color: '#579daf', name: '60帧厅', url: ''},
],
lat: 40.37207,
lng: 116.84597,
mark: 0,
nm: '时代影城密云店',
poiId: 1702945396,
price: 39.0,
promotion: {
cardPromotionTag: '开卡特惠,9.9元起开卡',
couponPromotionTag: '',
merchantActivityTag: '',
packShowActivityTag: '',
platformActivityTag: '',
starActivityTag: '',
},
referencePrice: '0',
sc: 600.0,
sellPrice: '39',
shopId: 1702945396,
showTimes: '次日00:20',
tag: {
allowRefund: 1,
buyout: 0,
cityCardTag: 0,
deal: 0,
endorse: 1,
giftTag: '',
hallType: ['60帧厅'],
hallTypeVOList: [{name: '60帧厅', url: ''}],
sell: 1,
snack: 0,
vipTag: '折扣卡',
},
},
{
addr: '大兴区永大路北京东盛明发广场5层',
cellShows: [],
cityId: 1,
dis: 0.0,
distance: '',
follow: 0,
id: 27677,
labels: [
{color: '#579daf', name: '退', url: ''},
{color: '#579daf', name: '改签', url: ''},
{color: '#ff9900', name: '折扣卡', url: ''},
{color: '#579daf', name: '杜比全景声厅', url: ''},
{color: '#579daf', name: '4D厅', url: ''},
],
lat: 39.687813,
lng: 116.32699,
mark: 0,
nm: '星典巨幕影城(LUXE生物医药基地店)',
poiId: 1224012111,
price: 38.9,
promotion: {
cardPromotionTag: '开卡特惠,首单最高立减30元',
couponPromotionTag: '',
merchantActivityTag: '',
packShowActivityTag: '',
platformActivityTag: '',
starActivityTag: '',
},
referencePrice: '0',
sc: 600.0,
sellPrice: '38.9',
shopId: 1224012111,
showTimes: '23:20',
tag: {
allowRefund: 1,
buyout: 0,
cityCardTag: 0,
deal: 0,
endorse: 1,
giftTag: '',
hallType: ['杜比全景声厅', '4D厅'],
hallTypeVOList: [
{name: '杜比全景声厅', url: ''},
{name: '4D厅', url: ''},
],
sell: 1,
snack: 0,
vipTag: '折扣卡',
},
},
{
addr: '朝阳区亮马桥路48号',
cellShows: [],
cityId: 1,
dis: 0.0,
distance: '',
follow: 0,
id: 27272,
labels: [
{color: '#579daf', name: '退', url: ''},
{color: '#579daf', name: '改签', url: ''},
{color: '#ff9900', name: '小吃', url: ''},
{color: '#ff9900', name: '折扣卡', url: ''},
{color: '#579daf', name: '儿童厅', url: ''},
],
lat: 39.9503,
lng: 116.46694,
mark: 0,
nm: '星典影城(亮马桥四季店)',
poiId: 193978484,
price: 52.0,
promotion: {
cardPromotionTag: '开卡特惠,首单最高立减30元',
couponPromotionTag: '',
merchantActivityTag: '',
packShowActivityTag: '',
platformActivityTag: '',
starActivityTag: '',
},
referencePrice: '0',
sc: 600.0,
sellPrice: '52',
shopId: 131009232,
showTimes: '23:25',
tag: {
allowRefund: 1,
buyout: 0,
cityCardTag: 0,
deal: 0,
endorse: 1,
giftTag: '',
hallType: ['儿童厅'],
hallTypeVOList: [{name: '儿童厅', url: ''}],
sell: 1,
snack: 1,
vipTag: '折扣卡',
},
},
{
addr: '朝阳区朝阳路十里堡新城市广场负一层',
cellShows: [],
cityId: 1,
dis: 0.0,
distance: '',
follow: 0,
id: 26958,
labels: [
{color: '#579daf', name: '退', url: ''},
{color: '#579daf', name: '改签', url: ''},
{color: '#ff9900', name: '小吃', url: ''},
{color: '#579daf', name: '儿童厅', url: ''},
{color: '#579daf', name: '4K厅', url: ''},
],
lat: 39.91526,
lng: 116.50541,
mark: 0,
nm: '观华全色彩激光影城(盒马鲜生店)',
poiId: 191800575,
price: 38.8,
promotion: {
cardPromotionTag: '',
couponPromotionTag: '',
merchantActivityTag: '',
packShowActivityTag: '',
platformActivityTag: '',
starActivityTag: '',
},
referencePrice: '0',
sc: 600.0,
sellPrice: '38.8',
shopId: 128960821,
showTimes: '次日00:05',
tag: {
allowRefund: 1,
buyout: 0,
cityCardTag: 0,
deal: 0,
endorse: 1,
giftTag: '',
hallType: ['儿童厅', '4K厅'],
hallTypeVOList: [
{name: '儿童厅', url: ''},
{name: '4K厅', url: ''},
],
sell: 1,
snack: 1,
vipTag: '',
},
},
],
ct_pois: [
{ct_poi: '936879945111165696_a23617_c0', poiid: 158732678},
{ct_poi: '936879945111165696_a35937_c1', poiid: 1287722848},
{ct_poi: '936879945111165696_a27811_c2', poiid: 1702945396},
{ct_poi: '936879945111165696_a27677_c3', poiid: 1224012111},
{ct_poi: '936879945111165696_a27272_c4', poiid: 193978484},
{ct_poi: '936879945111165696_a26958_c5', poiid: 191800575},
],
paging: {hasMore: false, limit: 20, offset: 0, total: 6},
},
errMsg: '',
success: true,
};
export const getCinemaDetail = {
cinemaId: '7748',
showData: {
cinemaId: 7748,
cinemaName: '义乌国际影城',
cityCardInfo: [],
modeSwitchThreshold: 5,
movies: [
{
chiefBonus: null,
desc: '176分钟 | 剧情 | 吴京,易烊千玺,段奕宏',
dur: 176,
globalReleased: true,
id: 257706,
img: 'http://p1.meituan.net/w.h/movie/8130663f1e7d55570cdd74616460656d491654.jpg',
nm: '长津湖',
preferential: 0,
sc: '9.5',
showCount: 28,
shows: [
{
hasShow: 1,
plist: [
{
baseSellPrice: '42',
dt: '2021-10-06',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110060687690',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '21:00',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-06',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110060687695',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '22:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-06',
dateShow: '今天10月6日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574780',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '09:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574774',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '10:20',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574783',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '11:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574775',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '12:30',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574777',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '13:35',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574779',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '14:30',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574773',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '15:45',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574776',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '16:50',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574772',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '17:45',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574778',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '19:00',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574782',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '20:05',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574771',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '21:00',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574781',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '22:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-07',
dateShow: '明天10月7日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382437',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '09:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382434',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '10:20',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382439',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '11:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382432',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '12:30',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382436',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '13:35',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382444',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '14:30',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382438',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '15:45',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382433',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '16:50',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382441',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '17:45',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382431',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '19:00',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382435',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '20:05',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382440',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '21:00',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '42',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382442',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '3号厅',
ticketStatus: 0,
tm: '22:15',
tp: '2D',
vipPrice: '34',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-08',
dateShow: '后天10月8日',
},
],
wish: 1012616,
},
{
chiefBonus: null,
desc: '158分钟 | 剧情 | 吴京,章子怡,徐峥',
dur: 158,
globalReleased: true,
id: 1417305,
img: 'http://p1.meituan.net/w.h/mmdb/ceab1c48a4a1e2d9fe941757ee2f5152256864.jpg',
nm: '我和我的父辈',
preferential: 0,
sc: '9.5',
showCount: 24,
shows: [
{
hasShow: 1,
plist: [
{
baseSellPrice: '37',
dt: '2021-10-06',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110060687681',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '21:14',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-06',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110060687675',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '22:55',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-06',
dateShow: '今天10月6日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574765',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '09:10',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574764',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '10:10',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574762',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '11:55',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574761',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '12:56',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574769',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '14:40',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574763',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '15:42',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574767',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '17:25',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574760',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '18:28',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574768',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '20:10',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574770',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '21:14',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574766',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '22:55',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-07',
dateShow: '明天10月7日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382448',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '09:10',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382453',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '10:10',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382450',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '11:55',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382454',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '12:56',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382446',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '14:40',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382451',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '15:42',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382445',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '17:25',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382447',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '18:28',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382443',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '20:10',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382452',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '21:14',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
{
baseSellPrice: '37',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382449',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '6号厅',
ticketStatus: 0,
tm: '22:55',
tp: '2D',
vipPrice: '29',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-08',
dateShow: '后天10月8日',
},
],
wish: 301354,
},
{
chiefBonus: null,
desc: '90分钟 | 惊悚 | 宋伊人,倪虹洁,陶慧',
dur: 90,
globalReleased: true,
id: 1189881,
img: 'http://p0.meituan.net/w.h/movie/54192179f1c44e579a83fe1394f4a3bf1857549.jpg',
nm: '最后一间房',
preferential: 0,
sc: '0.0',
showCount: 3,
shows: [
{
hasShow: 1,
plist: [
{
baseSellPrice: '27',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110060687699',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '00:00',
tp: '2D',
vipPrice: '19',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '次日放映',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-06',
dateShow: '今天10月6日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '27',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574786',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '00:00',
tp: '2D',
vipPrice: '19',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '次日放映',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-07',
dateShow: '明天10月7日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '27',
dt: '2021-10-09',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382455',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '5号厅',
ticketStatus: 0,
tm: '00:00',
tp: '2D',
vipPrice: '19',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '次日放映',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-08',
dateShow: '后天10月8日',
},
],
wish: 143821,
},
{
chiefBonus: null,
desc: '94分钟 | 奇幻 | 洪悦熙,庄则熙,田雨',
dur: 94,
globalReleased: true,
id: 1298314,
img: 'http://p0.meituan.net/w.h/movie/b862a85e39d28201838f98961e09d7191298056.jpg',
nm: '皮皮鲁与鲁西西之罐头小人',
preferential: 0,
sc: '9.1',
showCount: 2,
shows: [
{
hasShow: 1,
plist: [],
preInfo: [],
preferential: 0,
showDate: '2021-10-06',
dateShow: '今天10月6日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '32',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574784',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '09:30',
tp: '2D',
vipPrice: '24',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-07',
dateShow: '明天10月7日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '32',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382430',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: '2号厅',
ticketStatus: 0,
tm: '09:30',
tp: '2D',
vipPrice: '24',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-08',
dateShow: '后天10月8日',
},
],
wish: 46852,
},
{
chiefBonus: null,
desc: '111分钟 | 剧情 | 辛云来,冯祥琨,李孝谦',
dur: 111,
globalReleased: true,
id: 1328693,
img: 'http://p0.meituan.net/w.h/mmdb/81ca765741e6bbb430d213f736a50c964487800.jpg',
nm: '五个扑水的少年',
preferential: 0,
sc: '9.4',
showCount: 3,
shows: [
{
hasShow: 1,
plist: [
{
baseSellPrice: '32',
dt: '2021-10-06',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110060687698',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '23:20',
tp: '2D',
vipPrice: '24',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-06',
dateShow: '今天10月6日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '32',
dt: '2021-10-07',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110070574785',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '23:20',
tp: '2D',
vipPrice: '24',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-07',
dateShow: '明天10月7日',
},
{
hasShow: 1,
plist: [
{
baseSellPrice: '32',
dt: '2021-10-08',
enterShowSeat: 1,
extraDesc: '折扣卡首单特惠',
extraDescNew: '',
forbiddenTip: '',
hallTypeHighLight: false,
lang: '国语',
packShowTag: '',
preShowTag: '',
reservedMin: 0,
sellPr: '<span class="stonefont"></span>',
sellPrSuffix: '',
seqNo: '202110080382429',
showClosedSeat: 1,
showTag: '',
showTypeHighLight: false,
th: 'VIP厅',
ticketStatus: 0,
tm: '23:20',
tp: '2D',
vipPrice: '24',
vipPriceName: '折扣卡',
vipPriceNameNew: '折扣卡首单',
vipPriceSuffix: '',
zeroFlag: '',
preferential: 0,
smallFont: false,
},
],
preInfo: [],
preferential: 0,
showDate: '2021-10-08',
dateShow: '后天10月8日',
},
],
wish: 147567,
},
],
poiId: 5813072,
selectedMovieSeq: 2,
sell: true,
tips: '',
vipInfo: [
{
isCardSales: 0,
process: '15.9元起开卡',
tag: '折扣卡',
title: '现在开卡,首单1张最高立减6元',
url: 'imeituan://www.meituan.com/web/?url=https%3A%2F%2Fm.maoyan.com%2Fmultiplecard%2Fdetail%2F1248096%3F_v_%3Dyes%26version%3D4%26channelId%3D30001%26cinemaId%3D7748%26originType%3D4%26fromShow%3D1',
},
],
},
cinemaData: {
nm: '义乌国际影城',
addr: '华龙区丽都路与任丘路交叉口义乌国际商贸城8号门六楼',
shopId: 18440431,
lat: 35.77351,
lng: 115.06011,
cinemaId: 7748,
sell: true,
callboardInfo: null,
},
movieIndex: 0,
dealList: {
divideDealList: [],
showCount: 6,
activity: null,
stid: '1585401697750747136',
totalCount: 0,
dealList: [],
},
channelId: 30001,
stone: {
unicodeMap: null,
fonts: {
woff: 'data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAjcAAsAAAAADMQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADMAAABCsP6z7U9TLzIAAAE8AAAARAAAAFZW7lc5Y21hcAAAAYAAAAC9AAACTDKblWJnbHlmAAACQAAABEsAAAVAwgjlKmhlYWQAAAaMAAAALwAAADYeJrFZaGhlYQAABrwAAAAcAAAAJAeKAzlobXR4AAAG2AAAABIAAAAwGp4AAGxvY2EAAAbsAAAAGgAAABoHigYobWF4<KEY>mwAoC0lxTGBwYKr5vZ9b5r8MQw6zDcAUozAiSAwDoegvLeJzFkrENg0AMRf8FQkKSImWGyBCUrMEA9EyQCSKxRxoyBCUVFULXXQkSHeQb00SCNvHpneR/lm35DGAPwCN34gPmDQOxF1Uz6x5Os+7jQf+GK5UjsiZvRxvZ2sUucVWX9uVQTBMjtl/WzDDj2pEXD2dWCtjjDgd24SOkHGxk+oGZ/5X+tst8PxfvTLIFttjkivxrOyoSYyOFM4WtFU4XLlZkF1yicOJwlcLZo0<KEY>',
},
fontSource: '/tmp/0ac14bef',
},
};
<file_sep>/lesson1/src/screens/CinemaListScreen/Cinema.js
import React from 'react';
import {
StyleSheet,
Text,
View,
Image,
Alert,
ScrollView,
TouchableHighlight,
} from 'react-native';
import {useNavigation} from '@react-navigation/core';
const Cinema = ({addr, price}) => {
const navigation = useNavigation();
return (
<TouchableHighlight
activeOpacity={0.6}
underlayColor="#DDDDDD"
onPress={() => navigation.navigate('cinema')}>
<View style={styles.main}>
<Text numberOfLines={1}>{addr}</Text>
<Text style={styles.priceBox}>
<Text style={styles.price}>{price}</Text> 起
</Text>
</View>
</TouchableHighlight>
);
};
export default Cinema;
const styles = StyleSheet.create({
main: {
padding: 8,
backgroundColor: '#fff',
borderBottomWidth: 1,
borderBottomColor: '#ddd',
},
priceBox: {
lineHeight: 28,
color: '#f03d37',
},
price: {
fontSize: 20,
fontWeight: 'bold',
},
});
<file_sep>/lesson1/src/components/CustomButton.js
import React from 'react';
import {Button} from 'react-native';
export default function CustomButton({title, onPress}) {
return (
<Button
title={title}
accessibilityLabel={title}
color={Platform.OS === 'ios' ? 'white' : '#f03d37'}
onPress={onPress}
/>
);
}
<file_sep>/lesson1/src/routers/MainStackNavigator.js
import React from 'react';
import {Text} from 'react-native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import UserScreen from '@/screens/UserScreen/index';
import CinemaListScreen from '@/screens/CinemaListScreen';
import WebScreen from '@/screens/WebScreen';
import TabNavigator from './TabNavigator';
import IndexScreen from '@/screens/IndexScreen';
import MovieScreen from '../screens/MovieScreen';
import AboutMovieListScreen from '@/screens/AboutMovieListScreen';
import CinemaScreen from '@/screens/CinemaScreen';
const {Navigator, Screen, Group} = createNativeStackNavigator();
export const stackMainStyle = {
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
};
const stackSecStyle = {
headerStyle: {
backgroundColor: '#fff',
},
headerTintColor: '#000',
headerTitleStyle: {
fontWeight: 'bold',
},
};
export default function MainStackNavigator(props) {
return (
<Navigator
screenOptions={{
headerBackTitle: '返回',
}}>
<Screen
name="tabNavigator"
component={TabNavigator}
options={{
headerShown: false,
}}
/>
<Screen
name="maoyan"
component={MovieScreen}
options={{
title: '电影演出',
...stackMainStyle,
}}
/>
<Group screenOptions={{...stackSecStyle}}>
<Screen
name="user"
component={UserScreen}
options={{title: '用户中心'}}
/>
<Screen
name="cinemaList"
component={CinemaListScreen}
options={{title: '上映影院和购票'}}
/>
<Screen
name="cinema"
component={CinemaScreen}
options={{title: '影院'}}
/>
<Screen
name="aboutMovieList"
component={AboutMovieListScreen}
options={{title: '热映'}}
/>
<Screen
name="webview"
component={WebScreen}
options={{
headerTitle: () => (
<Text
style={{
backgroundColor: '#fff',
color: '#000',
fontWeight: 'bold',
}}>
学习RN中...
</Text>
),
}}
/>
</Group>
</Navigator>
);
}
<file_sep>/lesson1/src/screens/IndexScreen/Header.js
import React, {useState} from 'react';
import {StyleSheet, View, Text, TextInput} from 'react-native';
export default function Header() {
const [text, setText] = useState('');
return (
<View>
<TextInput
style={styles.input}
placeholder="搜索"
defaultValue={text}
onChangeText={text => setText(text)}
/>
</View>
);
}
const styles = StyleSheet.create({
input: {
height: 40,
margin: 8,
padding: 8,
borderWidth: 1,
borderColor: '#eee',
borderStyle: 'solid',
},
});
<file_sep>/lesson1/src/screens/CinemaScreen/index.js
import React, {useState, useEffect} from 'react';
import {StyleSheet, View, Text, TouchableHighlight} from 'react-native';
import {getCinemaDetail} from '@/utils/service';
export default function CinemaScreen() {
const [cinemaDetail, setcinemaDetail] = useState({});
useEffect(() => {
setcinemaDetail(getCinemaDetail);
}, []);
const {cinemaData = {}} = cinemaDetail;
return (
<View style={styles.main}>
<TouchableHighlight>
<View style={styles.address}>
<Text style={styles.title}>{cinemaData.nm}</Text>
<Text style={styles.addr}>{cinemaData.addr}</Text>
</View>
</TouchableHighlight>
</View>
);
}
const styles = StyleSheet.create({
main: {paddingLeft: 12, backgroundColor: '#fff'},
address: {},
title: {lineHeight: 40, fontSize: 20, fontWeight: 'bold'},
addr: {lineHeight: 22},
});
<file_sep>/lesson1/src/routers/RootRouter.js
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {useSelector} from 'react-redux';
import MainStackNavigator from './MainStackNavigator';
import AuthStackNavigator from './AuthStackNavigator';
function RootRouter() {
const isLogin = useSelector(({user}) => user.isLogin);
return (
<NavigationContainer>
{isLogin ? <MainStackNavigator /> : <AuthStackNavigator />}
</NavigationContainer>
);
}
export default RootRouter;
<file_sep>/lesson1/src/routers/AuthStackNavigator.js
import React from 'react';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import LoginScreen from '@/screens/LoginScreen';
import TabNavigator from './TabNavigator';
const {Navigator, Screen} = createNativeStackNavigator();
export const stackMainStyle = {
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
};
const stackSecStyle = {
headerStyle: {
backgroundColor: '#fff',
},
headerTintColor: '#000',
headerTitleStyle: {
fontWeight: 'bold',
},
};
export default function AuthStackNavigator(props) {
return (
<Navigator>
<Screen name="login" component={LoginScreen} options={{title: '登录'}} />
</Navigator>
);
}
<file_sep>/lesson1/src/store/loginReducer.js
import {REQUEST, LOGIN_SUCCESS, LOGOUT_SUCCESS, LOGIN_FAILURE} from './const';
const userInit = {
isLogin: false,
userInfo: {id: null, name: '', score: 0},
loading: false, // loading
err: {msg: ''},
};
// 定义用户基本信息修改规则
export const loginReducer = (state = {...userInit}, {type, payload}) => {
switch (type) {
case REQUEST:
return {...state, loading: true};
case LOGIN_SUCCESS:
return {...state, isLogin: true, loading: false, userInfo: {...payload}};
case LOGIN_FAILURE:
return {...state, ...userInit, ...payload};
case LOGOUT_SUCCESS:
return {...state, isLogin: false, loading: false};
default:
return state;
}
};
<file_sep>/lesson1/src/screens/CinemaListScreen/Cinemas.js
import React from 'react';
import {StyleSheet, Text, View, Image, Alert, ScrollView} from 'react-native';
import Cinema from './Cinema';
const Cinemas = ({cinemas}) => (
<ScrollView style={styles.main}>
<View>
{cinemas.map(cinema => {
return <Cinema key={cinema.id} {...cinema} />;
})}
</View>
</ScrollView>
);
export default Cinemas;
const styles = StyleSheet.create({
main: {paddingLeft: 12, paddingRight: 12, backgroundColor: '#fff'},
cinema: {margin: 12},
addr: {
fontSize: 20,
fontWeight: 'bold',
},
});
<file_sep>/lesson1/src/screens/IndexScreen/Menus.js
import {useNavigation} from '@react-navigation/core';
import React, {useState} from 'react';
import {StyleSheet, View, Text, TouchableOpacity, Alert} from 'react-native';
const menus = [
{
title: '外卖',
to: 'webview',
uri: 'https://h5.waimai.meituan.com/waimai/mindex/home',
},
{
title: '美食',
},
{
title: '酒店/民宿',
},
{
title: '休闲/玩乐',
},
{
title: '电影/演出',
to: 'maoyan',
},
{
title: '打车',
},
{
title: '景点/门票',
},
{
title: '丽人/美发',
},
{
title: '买药',
},
{
title: '火车票/机票',
},
];
export default function Menus() {
return (
<View style={styles.main}>
{menus.map(item => (
<Item key={item.title} {...item} />
))}
</View>
);
}
function Item({title, to, uri}) {
const navigation = useNavigation();
return (
<TouchableOpacity
style={styles.item}
onPress={() => {
if (to) {
navigation.navigate(to, {uri});
} else {
Alert.alert('未配置路径!');
}
}}>
<View style={styles.item}>
<View style={styles.circle}></View>
<Text style={styles.txt}>{title}</Text>
</View>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
main: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
alignItems: 'center',
padding: 10,
},
item: {
width: 68,
height: 88,
marginBottom: 10,
},
circle: {
height: 50,
width: 50,
marginLeft: 9,
borderRadius: 100,
backgroundColor: 'orange',
},
txt: {
// width: 68,
lineHeight: 26,
fontSize: 12,
color: '#333',
textAlign: 'center',
// marginBottom: 10,
},
});
<file_sep>/README.md
kkb-react-native
code of react-native
step1. git clone https://github.com/bubucuo/kkb-react-native.git
step2. 切换对应分支,如32期的就是season32
课堂代码github地址: https://github.com/bubucuo/kkb-react-native
课堂代码码云地址:https://gitee.com/bubucuo/kkb-react-native
<file_sep>/lesson1/src/routers/TabNavigator.js
import React from 'react';
import {View, Text} from 'react-native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import UserScreen from '@/screens/UserScreen/index';
import IndexScreen from '@/screens/IndexScreen';
const {Navigator, Screen} = createBottomTabNavigator();
export default function TabNavigator() {
return (
<Navigator>
<Screen
name="index"
component={IndexScreen}
options={{
title: '首页',
headerShown: false,
}}
/>
<Screen
name="user"
component={UserScreen}
options={{title: '用户中心'}}
/>
</Navigator>
);
}
<file_sep>/lesson1/src/screens/CinemaListScreen/index.js
import React from 'react';
import {
StyleSheet,
Text,
View,
Image,
Alert,
ScrollView,
Button,
} from 'react-native';
import {cinemas} from '@/utils/service';
import Cinemas from './Cinemas';
const CinemaListScreen = ({route}) => {
const movie = route.params;
return (
<View>
<View style={styles.header}>
<View style={styles.imBox}>
<Image
source={{
uri: movie.img + '@1l_1e_1c_128w_180h',
}}
style={styles.img}
/>
</View>
<View style={styles.headerContent}>
<Text numberOfLines={1} style={styles.nm}>
{movie.nm}
</Text>
<Text style={styles.txt}>
观众评 <Text style={styles.score}>{movie.sc}</Text>
</Text>
<Text style={styles.txt}>主演: {movie.star}</Text>
<Text style={styles.txt}>{movie.showInfo}</Text>
<Text style={styles.txt}>{movie.rt}大陆上映</Text>
</View>
</View>
<Cinemas cinemas={cinemas.data.cinemas} />
</View>
);
};
export default CinemaListScreen;
const styles = StyleSheet.create({
header: {
position: 'relative',
height: 180,
paddingLeft: 130,
paddingTop: 12,
backgroundColor: 'rgba(0,0,0,.6)',
},
imBox: {
position: 'absolute',
top: 12,
left: 12,
},
img: {
width: 100,
height: 150,
},
headerContent: {},
nm: {
marginBottom: 6,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'left',
color: '#fff',
},
txt: {lineHeight: 26, fontSize: 14, color: '#fff'},
score: {color: 'orange', fontSize: 20, fontWeight: 'bold'},
});
<file_sep>/lesson1/src/screens/UserScreen/index.js
import React, {useState} from 'react';
import {StyleSheet, Text, TextInput, View} from 'react-native';
import {useSelector, useDispatch} from 'react-redux';
import CustomButton from '@/components/CustomButton';
import {LOGOUT_SUCCESS} from '@/store/const';
const UserScreen = () => {
const userInfo = useSelector(({user}) => user.userInfo);
const dispatch = useDispatch();
const {id, name, score} = userInfo;
return (
<View style={styles.main}>
<Text style={styles.txt}>id: {id}</Text>
<Text style={styles.txt}>name: {name}</Text>
<Text style={styles.txt}>score: {score}</Text>
<CustomButton
title="退出登录"
onPress={() => dispatch({type: LOGOUT_SUCCESS})}
/>
</View>
);
};
export default UserScreen;
const styles = StyleSheet.create({
main: {backgroundColor: '#fff', padding: 12},
txt: {
lineHeight: 32,
fontSize: 20,
},
});
| 530b8f1345e621098a69e9025fad11c143e7924c | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | ruixue0702/kkb-react-native | 6e7f63c2db238e9abb33e624ebdb5d7856975168 | 924a2df4e60ad0083e32fb7a569b2fc66041bb49 |
refs/heads/master | <repo_name>HebaAhmedAli/os_project<file_sep>/README.md
# os_project
third year second term os project
<file_sep>/app.js
var express = require('express');
//get the node-uuid package for creating unique id
var unique = require('node-uuid')
var app = express();
var serv = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
app.use(express.static('client'));
serv.listen(process.env.PORT || 2000);
console.log("Server started.");
var room_List = {};
var dbObiect;
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbObject = db.db("osProject");
console.log("Database created!");
dbObject.createCollection("users", function(err, res) {
if (err) throw err;
console.log("Collection created!");
});
});
app.post('/autenticate', function(req, res) {
console.log("**************************");
console.log('body: ' + JSON.stringify(req.body));
var username = req.body.name;
var password = req.body.password;
console.log("ana hna authentication " + username + " " + password);
var query = {
name: username,
password: <PASSWORD>
};
var cursor = dbObject.collection("users").find(query);
cursor.count(function(err, count) {
if (err) {
console.log("2na erorrrrrrrrrrrrrrrrr count");
throw err;
}
console.log("**************************************************");
console.log("Total matches: " + count);
if (count == 0) {
console.log("2tb3 ya 3m 2na 3omda false " + count);
//client.emit('authenticated',{authenticated: false});
res.send(false);
} else {
console.log("2tb3 ya 3m 2na 3omda true" + count);
//client.emit('authenticated',{authenticated: true});
res.send(true);
}
});
});
function game() {
this.room_id;
this.player_lst = [];
//The constant number of players in the game
this.max_num = 2;
//The constant number of foods in the game
this.food_num = 150;
//food object list
this.food_pickup = [];
//mine object list
this.mine_pickup = [];
//map of type,id
this.collision_map = [];
fill_map_initially(this.collision_map);
}
var timeStep = 1 / 70;
var end_initiall_fill = false;
var scene_w = 2000;
var scene_h = 2000;
// var collision_map=[]; //map of type,id2
var player_dim = 50;
var items_dim = 40;
// createa a new game instance
//var game_instance = new game_setup();
max_speed = 5;
//We need to intilaize with true.
//a player class in the server
var Player = function(startX, startY, name) {
this.x = startX
this.y = startY
this.score = 50;
this.power = 100;
this.user_name = name;
}
function fill_part_of_map(type, x, y, id, room_id) {
var room = room_List[room_id];
// console.log("fill_part_of_map room_id"+room_id+ " "+room);
if (x > scene_w - items_dim + 1 || x < 0 || y > scene_h - items_dim + 1 || y < 0)
return false;
for (var i = x; i < x + items_dim; i++) {
for (var j = y; j < y + items_dim; j++) {
var value = [];
value.push(type); //type 0 = player // 1=food // 2=mine
value.push(id);
//console.log(collision_map[i][j]);
room.collision_map[i][j] = value;
}
}
return true;
}
function free_part_of_map(type, id, room_id) {
var item;
// console.log("check collision3 "+room_id);
var room = room_List[room_id];
if (type == 1) {
item = find_food(id, room_id);
} else {
item = find_mine(id, room_id);
}
var x = item.x;
var y = item.y;
for (var i = x; i < x + items_dim; i++) {
for (var j = y; j < y + items_dim; j++) {
var value = [];
value.push(0); //type 0 = player // 1=food // 2=mine
value.push(-1);
//console.log(collision_map[i][j]);
room.collision_map[i][j] = value;
}
}
}
var foodpickup = function(max_x, max_y, type, id, room_id) {
this.x = getRndInteger(items_dim, max_x - items_dim - 1);
this.y = getRndInteger(items_dim, max_y - items_dim - 1);
// console.log("foodpickup room_id"+room_id);
fill_part_of_map(1, this.x, this.y, id, room_id);
//to_map(this.x,this.y,1,id); //food
this.type = type;
this.id = id;
this.powerup;
}
var minepickup = function(x, y, type, id, room_id) {
this.x = x - 150;
this.y = y - 150;
//to_map(this.x,this.y,2,id); //mine
this.in_range = fill_part_of_map(2, this.x, this.y, id, room_id);
this.type = type;
this.id = id;
this.powerup;
}
//We call physics handler 60fps. The physics is calculated here.
setInterval(heartbeat, 1000 / 10);
function fill_map_initially(collision_map) {
// var room = room_List[room_id];
for (var i = 0; i < scene_w; i++) {
var row = [];
for (var j = 0; j < scene_h; j++) {
var value = [];
value.push(0); //type 0 = player // 1=food // 2=mine
value.push(-1);
row.push(value);
}
// this.collision_map=[];
collision_map.push(row);
}
end_initiall_fill = true;
}
function heartbeat() {
//the number of food that needs to be generated
//in this demo, we keep the food always at 100
for (var key in room_List) {
var room = room_List[key];
if (room != undefined)
var food_generatenum = room.food_num - room.food_pickup.length;
//add the food
if (end_initiall_fill == true)
addfood(food_generatenum, room.room_id);
}
}
function addfood(n, room_id) {
//return if it is not required to create food
if (n <= 0) {
return;
}
var room = room_List[room_id];
//create n number of foods to the game
for (var i = 0; i < n; i++) {
//create the unique id using node-uuid
var unique_id = unique.v4();
var foodentity = new foodpickup(scene_w, scene_h, 'food', unique_id, room_id);
room.food_pickup.push(foodentity);
//set the food data back to client
io.to(room_id).emit("item_update", foodentity);
}
}
function add_mine(data) {
var room_id = this.room_id;
var room = room_List[room_id];
var movePlayer = find_playerid(this.id, room_id);
if (movePlayer.score - 10 >= 0)
movePlayer.score -= 10;
else {
console.log("can't add mine because of your score");
return;
}
//------update the board here
sortPlayerListByScore(room_id);
var unique_id = unique.v4();
var mineentity = new minepickup(Math.ceil(data.pointer_x), Math.ceil(data.pointer_y), 'mine', unique_id, room_id);
if (mineentity.in_range == true) {
room.mine_pickup.push(mineentity);
//set the food data back to client
console.log("add mine");
io.to(room_id).emit("mine_update", mineentity);
}
}
// when a new player connects, we make a new instance of the player object,
// and send a new player message to the client.
function onNewplayer(data) {
//new player instance
console.log("new player");
var newPlayer = new Player(data.x, data.y, data.user_name);
console.log("created new player with id " + this.id);
newPlayer.id = this.id;
var room_id = find_Roomid();
var room = room_List[room_id];
console.log("Room id " + room_id + " room: " + room_List[room_id]);
//set the room id
this.room_id = room_id;
//join the room
this.join(this.room_id);
this.leave(this.id);
//this.emit('create_player', {size: newPlayer.size});
//information to be sent to all clients except sender
var current_info = {
id: newPlayer.id,
x: newPlayer.x,
y: newPlayer.y,
};
//send to the new player about everyone who is already connected.
console.log(" lst lentgh before" + room.player_lst.length);
for (i = 0; i < room.player_lst.length; i++) {
existingPlayer = room.player_lst[i];
var player_info = {
id: existingPlayer.id,
x: existingPlayer.x,
y: existingPlayer.y,
};
//console.log("pushing player");
//send message to the sender-client only
console.log(" player info " + player_info.id);
this.emit("new_enemyPlayer", player_info);
}
//b emit da hna bs 34an el power yzhar fe bdayet el le3b 34an da elly bycall update_power_leaderB
this.emit("lose_power", {
new_power: newPlayer.power,
id: newPlayer.id
});
//Tell the client to make foods that are exisiting
for (j = 0; j < room.food_pickup.length; j++) {
var food_pick = room.food_pickup[j];
this.emit('item_update', food_pick);
}
//Tell the client to make mines that are exisiting
for (j = 0; j < room.mine_pickup.length; j++) {
var mine_pick = room.mine_pickup[j];
this.emit('mine_update', mine_pick);
}
//send message to every connected client except the sender
this.broadcast.to(room_id).emit('new_enemyPlayer', current_info);
room.player_lst.push(newPlayer);
console.log(" lst lentgh after" + room.player_lst.length);
sortPlayerListByScore(room_id);
}
function find_Roomid() {
for (var key in room_List) {
var room = room_List[key];
if (room.player_lst.length < room.max_num) {
return key;
}
}
console.log("search for room id failed, creating new room");
//did not find a room. create an extra room;
var room_id = create_Room();
return room_id;
}
function create_Room() {
//create new room id;
var new_roomid = unique.v4();
//create a new room object
var new_game = new game();
new_game.room_id = new_roomid;
room_List[new_roomid] = new_game;
return new_roomid;
}
//instead of listening to player positions, we listen to user inputs
function onInputFired(data) {
var this_client = this;
// console.log("input fired"+this.room_id+" "+this.id);
var movePlayer = find_playerid(this.id, this.room_id);
if (!movePlayer) {
//console.log('no player');
return;
}
var serverPointer = {
worldX: data.pointer_worldx,
worldY: data.pointer_worldy
}
if (serverPointer.worldX > scene_w - player_dim - 1)
serverPointer.worldX = scene_w - player_dim - 1;
if (serverPointer.worldX < 0)
serverPointer.worldX = 0;
if (serverPointer.worldY > scene_h - player_dim - 1)
serverPointer.worldY = scene_h - player_dim - 1;
if (serverPointer.worldY < 0)
serverPointer.worldY = 0;
//new player position to be sent back to client.
var info = {
worldX: serverPointer.worldX,
worldY: serverPointer.worldY,
speed: max_speed,
}
//send to sender (not to every clients).
this.emit('input_recieved', info);
//data to be sent back to everyone except sender
var moveplayerData = {
id: movePlayer.id,
worldX: serverPointer.worldX,
worldY: serverPointer.worldY,
speed: max_speed,
}
//send to everyone except sender
this.broadcast.to(this.room_id).emit('enemy_move', moveplayerData);
move_player(movePlayer, serverPointer, this_client);
}
function move_player(movePlayer, serverPointer, this_client) {
var stepx = 0.1;
var stepy = 0.1;
var newx = (serverPointer.worldX - movePlayer.x) * stepx + movePlayer.x;
var newy = (serverPointer.worldY - movePlayer.y) * stepy + movePlayer.y;
var point1 = {
x: movePlayer.x,
y: movePlayer.y
};
//var point2={x:serverPointer.worldX,y:serverPointer.worldY};
var point2 = {
x: newx,
y: newy
};
var result = getEquationOfLineFromTwoPoints(point2, point1);
//var stepx=(point2.x-point1.x)/30;
if (result.gradient == Infinity) {
// console.log("if 1");
while (movePlayer.y < newy) {
// console.log("check collision 1 "+this_client.room_id);
check_collision_while_moving(movePlayer, this_client);
movePlayer.y += stepy;
// console.log("movePlayer.y "+movePlayer.y);
if (movePlayer.y < 0) {
movePlayer.y = 0;
break;
} else if (movePlayer.y > scene_h - player_dim - 1) {
movePlayer.y = scene_h - player_dim - 1;
break;
}
}
} else if (result.gradient == -Infinity) {
// console.log("if 2");
while (movePlayer.y > newy) {
check_collision_while_moving(movePlayer, this_client);
movePlayer.y -= stepy;
// console.log("movePlayer.y "+movePlayer.y);
if (movePlayer.y < 0) {
movePlayer.y = 0;
break;
} else if (movePlayer.y > scene_h - player_dim - 1) {
movePlayer.y = scene_h - player_dim - 1;
break;
}
}
} else if (result.gradient == 0) {
// console.log("if 3");
while (movePlayer.x < newx) {
check_collision_while_moving(movePlayer, this_client);
movePlayer.x += stepx;
if (movePlayer.x < 0) {
movePlayer.x = 0;
break;
} else if (movePlayer.x > scene_w - player_dim - 1) {
movePlayer.x = scene_w - player_dim - 1;
break;
}
}
} else if (result.gradient == -0) {
// console.log("if 4");
while (movePlayer.x > newx) {
check_collision_while_moving(movePlayer, this_client);
movePlayer.x -= stepx;
if (movePlayer.x < 0) {
movePlayer.x = 0;
break;
} else if (movePlayer.x > scene_w - player_dim - 1) {
movePlayer.x = scene_w - player_dim - 1;
break;
}
}
} else {
if (movePlayer.x < newx) {
// console.log("if 5");
while (movePlayer.x < newx) {
movePlayer.y = result.gradient * movePlayer.x + result.yIntercept;
// console.log("movePlayer.y "+movePlayer.y);
if (movePlayer.y < 0) {
movePlayer.y = 0;
break;
} else if (movePlayer.y > scene_h - player_dim - 1) {
movePlayer.y = scene_h - player_dim - 1;
break;
}
check_collision_while_moving(movePlayer, this_client);
movePlayer.x += stepx;
if (movePlayer.x < 0) {
movePlayer.x = 0;
break;
} else if (movePlayer.x > scene_w - player_dim - 1) {
movePlayer.x = scene_w - player_dim - 1;
break;
}
}
} else {
// console.log("if 6");
while (movePlayer.x > newx) {
// console.log("result ",result.gradient,result.yIntercept);
movePlayer.y = result.gradient * movePlayer.x + result.yIntercept;
// console.log("movePlayer.y "+movePlayer.y);
if (movePlayer.y < 0) {
movePlayer.y = 0;
break;
} else if (movePlayer.y > scene_h - player_dim - 1) {
movePlayer.y = scene_h - player_dim - 1;
break;
}
check_collision_while_moving(movePlayer, this_client);
movePlayer.x -= stepx;
if (movePlayer.x < 0) {
movePlayer.x = 0;
break;
} else if (movePlayer.x > scene_w - player_dim - 1) {
movePlayer.x = scene_w - player_dim - 1;
break;
}
}
}
}
}
function check_collision_while_moving(movePlayer, this_client) {
var player_centerx = Math.ceil(movePlayer.x) + player_dim / 2;
var player_centery = Math.ceil(movePlayer.y) + player_dim / 2;
var room_id = this_client.room_id;
var collide_coin = is_collide(player_centerx, player_centery, 1, room_id);
var collide_mine = is_collide(player_centerx, player_centery, 2, room_id);
if (collide_coin != -1) {
//coin
// console.log("coin collide");
free_part_of_map(1, collide_coin, room_id);
onitemPicked(collide_coin, movePlayer, room_id);
}
if (collide_mine != -1) {
console.log("mine collide " + this_client.room_id);
free_part_of_map(2, collide_mine, room_id);
//mine
onminePicked(collide_mine, movePlayer, this_client);
}
}
function is_collide(center_x, center_y, type, room_id) {
var room = room_List[room_id];
var arr_x = [0, 0, player_dim / 2, -player_dim / 2, player_dim / 2, -player_dim / 2, player_dim / 2, -player_dim / 2];
var arr_y = [player_dim / 2, -player_dim / 2, 0, 0, player_dim / 2, -player_dim / 2, -player_dim / 2, player_dim / 2];
for (var i = 0; i < arr_x.length; i++) {
//console.log(center_x+arr_x[i],center_y+arr_y[i]);
if (room.collision_map[center_x + arr_x[i]][center_y + arr_y[i]][0] == type) {
return room.collision_map[center_x + arr_x[i]][center_y + arr_y[i]][1];
}
}
return -1;
}
//call when a client disconnects and tell the clients except sender to remove the disconnected player
function onClientdisconnect() {
console.log('disconnect');
var room_id = this.room_id;
var room = room_List[room_id];
var removePlayer = find_playerid(this.id, room_id);
if (removePlayer) {
room.player_lst.splice(room.player_lst.indexOf(removePlayer), 1);
}
console.log("removing player " + this.id);
//send message to every connected client except the sender
this.broadcast.to(room_id).emit('remove_player', {
id: this.id
});
sortPlayerListByScore(room_id);
// this.reload();
}
// find player by the the unique socket id
function find_playerid(id, room_id) {
var room = room_List[room_id];
if (id == undefined) {
console.log("msh la2e l player");
return;
}
if (room == undefined) {
// console.log("msh la2e l room");
return;
}
for (var i = 0; i < room.player_lst.length; i++) {
if (room.player_lst[i].id == id) {
return room.player_lst[i];
}
}
console.log("player not found" + id);
return false;
}
function find_food(id, room_id) {
var room = room_List[room_id];
for (var i = 0; i < room.food_pickup.length; i++) {
if (room.food_pickup[i].id == id) {
return room.food_pickup[i];
}
}
return false;
}
function find_mine(id, room_id) {
var room = room_List[room_id];
for (var i = 0; i < room.mine_pickup.length; i++) {
if (room.mine_pickup[i].id == id) {
return room.mine_pickup[i];
}
}
return false;
}
// called
//1.When the player picks up coins
//2.When the new player connects
//3.When the player disconnects (exits without dying).
//4.When the player dies (his power becomes zero)
function sortPlayerListByScore(room_id) {
var room = room_List[room_id];
if (room == undefined) {
return;
}
room.player_lst.sort(function(a, b) {
return b.score - a.score;
});
var playerListSorted = [];
for (var i = 0; i < room.player_lst.length; i++) {
//mafrood lsa el username
// console.log(room.player_lst[i].user_name);
playerListSorted.push({
user_name: room.player_lst[i].user_name,
score: room.player_lst[i].score
});
}
// console.log(playerListSorted);
io.to(room_id).emit("leader_board", playerListSorted);
}
function onitemPicked(id, movePlayer, room_id) {
//var movePlayer = find_playerid(this.id);
var room = room_List[room_id];
var object = find_food(id, room_id);
if (!object) {
return;
}
//increase player score
movePlayer.score += 1;
//update the board here
room.food_pickup.splice(room.food_pickup.indexOf(object), 1);
sortPlayerListByScore(room_id);
// console.log("item id : "+id+" movePlayer.score "+movePlayer.score)
io.to(room_id).emit('itemremove', object);
}
function onminePicked(id, movePlayer, this_client) {
//var movePlayer = find_playerid(this.id);
console.log("mine picking " + room_List[this_client.room_id].mine_pickup.length);
var room_id = this_client.room_id;
var room = room_List[this_client.room_id];
var object = find_mine(id, room_id);
if (!object) {
return;
}
//decrease player power
movePlayer.power -= 10;
//broadcast the new power for updating power
this_client.emit("lose_power", {
new_power: movePlayer.power,
id: movePlayer.id
});
if (movePlayer.power <= 0) {
this_client.emit("killed");
this_client.broadcast.to(room_id).emit('remove_player', {
id: this_client.id
});
room.player_lst.splice(room.player_lst.indexOf(movePlayer), 1);
sortPlayerListByScore(room_id);
}
room.mine_pickup.splice(room.mine_pickup.indexOf(object), 1);
io.to(room_id).emit('mineremove', object);
//this.emit('item_picked'); //-------------------?
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// io connection
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
console.log("socket connected");
// listen for disconnection;
socket.on('disconnect', onClientdisconnect);
// listen for new player
socket.on("new_player", onNewplayer);
//listen for new player inputs.
socket.on("input_fired", onInputFired);
//socket.on("authentication",authentication)
//listen if player got items
socket.on('item_picked', onitemPicked);
socket.on('mine_picked', onminePicked);
socket.on('please_add_mine', add_mine);
socket.on('chat message', function(msg) {
console.log('a user need to chat ' + msg);
io.to(this.room_id).emit('chat message', msg);
});
});
function getEquationOfLineFromTwoPoints(point1, point2) {
var lineObj = {
gradient: (point1.y - point2.y) / (point1.x - point2.x)
},
parts;
lineObj.yIntercept = point1.y - lineObj.gradient * point1.x;
lineObj.toString = function() {
if (Math.abs(lineObj.gradient) === Infinity) {
return 'x = ' + point1.x;
} else {
parts = [];
if (lineObj.gradient !== 0) {
parts.push(lineObj.gradient + 'x');
}
if (lineObj.yIntercept !== 0) {
parts.push(lineObj.yIntercept);
}
return 'y = ' + parts.join(' + ');
}
};
return lineObj;
}
/*
console.log(getEquationOfLineFromTwoPoints(point2, point1));
//if gradient=infinity or - infinity x sabta wnzwd aw nall al y
//if gradient=0 or - 0 y sabta wnzwd aw nall al x
*/<file_sep>/client/colide.js
function player_coll (body, bodyB, shapeA, shapeB, equation) {
//the id of the collided body that player made contact with
var key = body.sprite.id;
//the type of the body the player made contact with
var type = body.sprite.type;
if (type == "mine_body") {
//send the player collision
socket.emit('mine_picked', {id: key});
} else if (type == "food_body") {
socket.emit('item_picked', {id: key});
}
}<file_sep>/client/player.js
function movetoPointer (displayObject, pointer) {
//var angle = angleToPointer(displayObject,dx,dy);
console.log("x before: "+displayObject.body.x+" y before: "+displayObject.body.y);
displayObject.body.velocity.x = pointer.velocityX;
displayObject.body.velocity.y = pointer.velocityY;
// displayObject.body.x+=50;
// displayObject.body.y+=50;
console.log("x after: "+displayObject.body.x+" y after: "+displayObject.body.y);
var once=false;
setTimeout(function() {
if(!once)
console.log("x after: "+displayObject.body.x+" y after: "+displayObject.body.y);
once= true;
}, 20);
/*setTimeout(function() {
if((displayObject.x>pointer.worldX && pointer.dx>0)||(displayObject.x<pointer.worldX && pointer.dx<0))
displayObject.body.velocity.x=0;
if((displayObject.y>pointer.worldY && pointer.dy>0)||(displayObject.y<0 && pointer.dy<0))
displayObject.body.velocity.y=0;
},1);*/
//return angle;
}
function move_player(displayObject, pointer)
{
//move to the new position.
movetoPointer(displayObject,pointer);
}
function angleToPointer (displayObject, dx,dy) {
return Math.atan2(dy,dx);
}
| fd88878fe0e39bd82b450b4bae927f146f1381dc | [
"Markdown",
"JavaScript"
] | 4 | Markdown | HebaAhmedAli/os_project | 1d705b044d6b16d6706fe9bce5a6c8cfd550f16d | 2e07fd6a4c12f9f12511c0f5aebe293c80b24366 |
refs/heads/master | <file_sep>#!/usr/bin/env python2
# from fabric.api import *
from fabric.api import run, local
def who():
local('whoami')
def host_type():
run('uname -s')
def hello():
print("Hello, hi!")
def hi(name="Josef"):
print("Hi %s!" % name)
def disk():
run('df -h')
def env():
run('printenv')
def uptime():
uptime = run('uptime -p')
print("Host is %s" % uptime)
def load():
la = run('uptime').split('average:')[1].split()
print("Load average for past 1 min: %s" % la[0])
print("Load average for past 5 min: %s" % la[1])
print("Load average for past 15 min: %s" % la[2])
def la():
la = run('cat /proc/loadavg').split()
print("Load average for past 1 min: %s" % la[0])
print("Load average for past 5 min: %s" % la[1])
print("Load average for past 15 min: %s" % la[2])
proc = la[3].split('/')
print("Currently running processes: %s" % proc[0])
print("Total number of processes: %s" % proc[1])
| 8b81c13800adbbdebe7b1e5a7910251a5ddf622a | [
"Python"
] | 1 | Python | vensder/fabric-test | e597e1238d7a073cb2604bd2975f5030429b728e | bd96d68efd1b038e3fbcc2f6c6a86a8009da3396 |
refs/heads/master | <repo_name>MayaIsla/4347Project<file_sep>/README.md
# 4347Project
Database project that implements credit card information, user data and purchase information into a parsing database.
<file_sep>/ProductDaoImpl.java
package cs4347.jdbcProject.ecomm.dao.impl;
import cs4347.jdbcProject.ecomm.dao.ProductDAO;
public class ProductDaoImpl implements ProductDAO
{
private static final String insertSQL =
"INSERT INTO Product (Customer_id, Product_id, purchaseDate, purchasePrice) VALUES (?, ?, ?, ?);";
@Override
public Product create(Connection connection, Product product) throws SQLException, DAOException {
if (Product.getId() != null) {
throw new DAOException("Trying to insert product with NON-NULL ID");
}
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
ps.setLong(1, product.getCustomerID());
ps.setFloat(4, product.getPurchasePrice());
ps.setLong(2, product.getProductID());
ps.setDate(3, new java.sql.Date(Product.getPurchaseDate().getTime()));
ps.executeUpdate();
ResultSet keyRS = ps.getGeneratedKeys();
keyRS.next();
int lastKey = keyRS.getInt(1);
Product.setId((long) lastKey);
return Product;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String selectQuery = "SELECT id, Customer_id, Product_id, purchaseDate, purchasePrice FROM Product WHERE id = ?";
@Override
public Product retrieveID(Connection connection, Long ProductID) throws SQLException, DAOException {
if (ProductID == null) {
throw new DAOException("Trying to retrieve Product with NULL ID");
}
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(selectQuery);
ps.setLong(1, ProductID);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
return null;
}
Product cust = extractFromRS(rs);
return cust;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String selectCustomerProductQuery = "SELECT id, Customer_id, Product_id, purchaseDate, purchasePrice FROM Product WHERE Customer_id = ? AND Product_id = ? ";
@Override
public Product retrieveCustomerProductID(Connection connection, Long Customer_id, Long Product_id)
throws SQLException, DAOException {
if (Customer_id == null || Product_id == null) {
throw new DAOException("Trying to retrieve Product with NULL Customer_id or Product_id");
}
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(selectCustomerProductQuery);
ps.setLong(1, Customer_id);
ps.setLong(2, Product_id);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
return null;
}
Product cust = extractFromRS(rs);
return cust;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String storeProductQuery =
"SELECT id, Customer_id, Product_id, purchaseDate, purchasePrice FROM Product WHERE Product_id = ?";
@Override
public List<Product> retrieveByProduct(Connection connection, Long Product_id) throws SQLException, DAOException {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(storeProductQuery);
ps.setLong(1, Product_id);
ResultSet rs = ps.executeQuery();
List<Product> result = new ArrayList<Product>();
while (rs.next()) {
Product cust = extractFromRS(rs);
result.add(cust);
}
return result;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String storeCustomerQuery =
"SELECT id, Customer_id, Product_id, purchaseDate, purchasePrice FROM Product WHERE Customer_id = ?";
@Override
public List<Product> retrieveByCustomer(Connection connection, Long Customer_id) throws SQLException, DAOException {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(storeCustomerQuery);
ps.setLong(1, Customer_id);
ResultSet rs = ps.executeQuery();
List<Product> result = new ArrayList<Product>();
while (rs.next()) {
Product cust = extractFromRS(rs);
result.add(cust);
}
return result;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String updateSQL = "UPDATE Product SET Customer_id = ?, Product_id = ?, purchaseDate = ?, purchasePrice = ? WHERE id = ?;";
@Override
public int update(Connection connection, Product Product) throws SQLException, DAOException {
if (Product.getId() == null) {
throw new DAOException("Trying to update Product with NULL ID");
}
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(updateSQL);
ps.setLong(1, Product.getCustomerID());
ps.setLong(2, Product.getProductID());
ps.setDate(3, new java.sql.Date(Product.getPurchaseDate().getTime()));
ps.setFloat(4, Product.getPurchasePrice());
ps.setLong(5, Product.getId());
int rows = ps.executeUpdate();
return rows;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String deleteSQL = "DELETE FROM Product WHERE id = ?;";
@Override
public int delete(Connection connection, Long ProductOwnedID) throws SQLException, DAOException {
if (ProductOwnedID == null) {
throw new DAOException("Trying to delete Product with NULL ID");
}
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(deleteSQL);
ps.setLong(1, ProductOwnedID);
int rows = ps.executeUpdate();
return rows;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
final static String countSQL = "select count(*) from Product";
@Override
public int count(Connection connection) throws SQLException, DAOException {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(countSQL);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
throw new DAOException("No Count Returned");
}
int count = rs.getInt(1);
return count;
} finally {
if (ps != null && !ps.isClosed()) {
ps.close();
}
}
}
private Product extractFromRS(ResultSet rs) throws SQLException {
Product cust = new Product();
cust.setId(rs.getLong("id"));
cust.setCustomerID(rs.getLong("Customer_id"));
cust.setProductID(rs.getLong("Product_id"));
cust.setPurchaseDate(rs.getDate("purchaseDate"));
cust.setPurchasePrice(rs.getFloat("purchasePrice"));
return cust;
}
}
| 3a9cefade0dd92a30d2054e2cd4f40a633327145 | [
"Markdown",
"Java"
] | 2 | Markdown | MayaIsla/4347Project | d9604753ace686d41451440f62551b43ffff2f2d | 69b8948b6ade91a1bcc1d0416af4de0b2081daf2 |
refs/heads/master | <file_sep># Phase Plane Application
This program displays a vector field correspoinding to a given two dimensional system and allows for trajectories to be plotted via mouseclick. Trajectories are calculated using a second order Runge-Kutta method with an adaptive stepsize. Users can select from a selection of preloaded vector functions or modify coefficients for a simpler linear system.
You can find the program displayed [here](https://mitchellf.github.io/pplane/).
<file_sep>var canvas = document.getElementById("plotCanvas");
var ctx = canvas.getContext("2d");
//Class to hold some plot properties, etc.
var plot = {
//Plot bounds
xmin: -10,
xmax: 10,
ymin: -10,
ymax: 10,
xFunc: firstX,
yFunc: firstY
}
window.onload = function() {
drawPlot();
}
function drawPlot(){
ctx.clearRect(0,0,800,800);
// drawPlotLabels();
drawPlotAxes();
drawVectorField();
}
/*
Draws plot labels based on user input values for plot
boundaries. Draws labels directly onto plot canvas at
respective corners.
*/
function drawPlotLabels() {
ctx.save();
ctx.beginPath();
ctx.font = "bold 20px sans-serif";
ctx.fillText(String(plot.xmax),765,790);
ctx.fillText(String(plot.xmin),50,790);
ctx.fillText(String(plot.ymax), 10,20);
ctx.fillText(String(plot.ymin),10,770);
ctx.closePath();
ctx.restore();
}
/*
Takes in x coordinate relative to plot
and converts to coordinate relative to
canvas.
example for default plot
convertXCoord(0) returns 400
*/
function convertXCoord(inputX) {
//Each pixel on the plot corresponds to
//(xMax-xMin)/800 units.
//So the inputX relative to the canvas is
//The number of units from xMin, scaled by
//((xMax-xMin)/800)^-1.
//Note we do not check for division by 0 here.
//We catch xMax=xMin case elsewhere
return Math.floor((inputX-plot.xmin)/((plot.xmax-plot.xmin) / 800));
}
/*
Takes in y coordinate relative to plot
and converts to coordinate relative to
canvas.
example for default plot
convertYCoord(0) returns 400
*/
function convertYCoord(inputY) {
return Math.floor((plot.ymax - inputY)/((plot.ymax-plot.ymin) / 800));
}
function drawPlotAxes() {
ctx.save();
ctx.strokeStyle = "blue";
//Check if we need to draw y-axis
if (plot.ymin <= 0 && 0 <= plot.ymax) {
ctx.beginPath();
ctx.moveTo(0,convertYCoord(0));
ctx.lineTo(800, convertYCoord(0));
ctx.stroke();
ctx.closePath();
}
//Check if we need to draw x-axis
if (plot.xmin <= 0 && 0 <= plot.xmax) {
ctx.beginPath();
ctx.moveTo(convertXCoord(0),0);
ctx.lineTo(convertXCoord(0),800);
ctx.stroke();
ctx.closePath();
}
ctx.restore();
}
/*
Draws small arrow onto plot with given angle at
given (x,y) position. Input positions are relative
to the plot, NOT the canvas.
*/
function drawArrow(inputX, inputY, inputAngle) {
ctx.save();
var tempX = convertXCoord(inputX);
var tempY = convertYCoord(inputY);
ctx.translate(tempX, tempY);
//Not sure about the negative angle here
ctx.rotate(-inputAngle*Math.PI/180);
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.moveTo(0,0);
ctx.lineTo(12,0);
ctx.stroke();
ctx.moveTo(12,0);
ctx.lineTo(9,3);
ctx.stroke();
ctx.moveTo(12,0);
ctx.lineTo(9,-3);
ctx.stroke();
ctx .closePath();
ctx.restore();
}
/*
Draws vector field for given functions onto plot.
Draws arrows using the drawArrow function.
*/
function drawVectorField() {
//Find a small offset from the plot boundary
//for visual reasons. We use 15 pixel offset
var offsetX = 16*(plot.xmax-plot.xmin)/800;
var offsetY = 16*(plot.ymax-plot.ymin)/800;
//Find a step size to give us 20 arrows in
//each direction
var stepX = (plot.xmax-plot.xmin)/30;
var stepY = (plot.ymax-plot.ymin)/30;
var calcX;
var calcY;
var angle;
//placed outside for performance
var i;
var j;
for (i = 0; i < 30; ++i) {
for(j = 0; j < 30; ++j) {
//For clarity. Calculated values
calcX = plot.xmin + stepX*i + offsetX;
calcY = plot.ymin + stepY*j + offsetY;
//We calculate angle of vector
//and convert to degrees
angle = Math.atan2(
plot.yFunc(calcX,calcY),
plot.xFunc(calcX,calcY))
*180/Math.PI;
angle = Math.round(angle);
drawArrow(calcX, calcY, angle);
}
}
}
/*
Returns smaller of (xMax-xMin)/inputScale or
similar with yMax and yMin.
*/
function getMinScale(inputScale) {
return Math.min(Math.abs((plot.xmax-plot.xmin)/inputScale),
Math.abs((plot.ymax-plot.ymin)/inputScale));
}
function drawTrajectory(initX, initY) {
ctx.save();
ctx.lineWidth = 4;
ctx.lineJoin = "round";
var step;
var minScale = getMinScale(100);
var i;
//Used for calculations. Specifically tempX and Y
//are used for finding step size. They give the general
//magnitude difference between next and previous point
var tempX = 0;
var tempY = 0;
var calc1X = 0;
var calc1Y = 0;
for(i = 0; i < 300; ++i) {
ctx.beginPath();
ctx.moveTo(convertXCoord(initX), convertYCoord(initY));
tempX = plot.xFunc(initX, initY);
tempY = plot.yFunc(initX, initY);
calcX = initX;
calcY = initY;
//Compute the step size based on magnitude of difference
//between previous and next point. This is done so that
//when we compute a large difference we don't generate some
//obscenely large trajectory that goes off of the plot.
//We set step size to the inverse of the difference between
//previous and next if there is a large difference
//and to 200th a size of the plot if the difference is small
//If we always set the step size to the inverse of the difference
//for very small differences (near stable fixed points say)
//we would generate very large trajectories
if(minScale > 0.5/Math.max(Math.abs(tempX),Math.abs(tempY))) {
step = 0.5/Math.max(Math.abs(tempX),Math.abs(tempY));
} else {
step = minScale;
}
//Trial step
calcX+=step*tempX;
calcY+=step*tempY;
initX+=0.5*(tempX+plot.xFunc(calcX,calcY))*step;
initY+=0.5*(tempY+plot.yFunc(calcX,calcY))*step;
//Check to see how 'fast' particle is moving.
//indigo slow, red FAST.
//We compare speeds by finding the minimum difference
//between next and previous position and comparing
//it with some percentage of the step size.
//This should give us an idea of speed relative to
//the plot and it's boundaries
if (minScale >= Math.max(Math.abs(tempX),Math.abs(tempY))) {
ctx.strokeStyle = "indigo";
} else if (5*minScale >= Math.max(Math.abs(tempX),Math.abs(tempY))) {
ctx.strokeStyle = "blue";
} else if (30*minScale >= Math.max(Math.abs(tempX),Math.abs(tempY))) {
ctx.strokeStyle = " #00cc33"; //Darker green
} else if (60*minScale >= Math.max(Math.abs(tempX),Math.abs(tempY))) {
ctx.strokeStyle = "#73e600"; //Lighter green
} else if (150*minScale >= Math.max(Math.abs(tempX),Math.abs(tempY))) {
ctx.strokeStyle = "#e6e600"; //Yellowish
} else if (250*minScale >= Math.max(Math.abs(tempX),Math.abs(tempY))) {
ctx.strokeStyle = "orange";
} else {
ctx.strokeStyle = "red";
}
ctx.lineTo(convertXCoord(initX), convertYCoord(initY))
ctx.stroke();
ctx.closePath();
//Check to see if we are very near a fixed point
//or moving out of the plot boundary.
//If so set i to 300 and break loop
if (initX < plot.xmin-50*minScale ||initX > plot.xmax + 50*minScale
|| initY < plot.ymin - 50*minScale|| initY > plot.ymax + 50*minScale
|| Math.max(Math.abs(tempX),Math.abs(tempY)) <= 0.001*step)
{
break;
}
}
ctx.restore();
}
//Mode selection radio button handling
//Makes selected form visible and hides the others.
//Sets plot functions to necessary functions
document.getElementById("dropRadio").addEventListener("click", function (){
document.getElementById("dropForm").style.display = "inline";
document.getElementById("matrixForm").style.display = "none";
document.getElementById("manualForm").style.display = "none";
document.getElementById("loktaForm").style.display = "none";
plot.xFunc = firstX;
plot.yFunc = firstY;
drawPlot();
});
document.getElementById("matrixRadio").addEventListener("click", function (){
document.getElementById("dropForm").style.display = "none";
document.getElementById("matrixForm").style.display = "inline";
document.getElementById("manualForm").style.display = "none";
document.getElementById("loktaForm").style.display = "none";
plot.xFunc = matrixXFunc;
plot.yFunc = matrixYFunc;
drawPlot();
});
document.getElementById("manualRadio").addEventListener("click", function (){
document.getElementById("dropForm").style.display = "none";
document.getElementById("matrixForm").style.display = "none";
document.getElementById("manualForm").style.display = "inline";
document.getElementById("loktaForm").style.display = "none";
drawPlot();
});
document.getElementById("loktaRadio").addEventListener("click", function (){
document.getElementById("dropForm").style.display = "none";
document.getElementById("matrixForm").style.display = "none";
document.getElementById("manualForm").style.display = "none";
document.getElementById("loktaForm").style.display = "inline";
plot.xFunc = loktaXFunc;
plot.yFunc = loktaYFunc;
drawPlot();
});
//Plot vector field button handling
//Checks for xmax >= xmin, ymax >= ymin, check general validity of form entries.
//If invalid entry found displays invalid entry notification, otherwise sets
//plot boundary values, drop down selected, and plots
document.getElementById("plotButton").addEventListener("click", function (){
if (document.getElementById("xmin").value >= document.getElementById("xmax").value ||
document.getElementById("ymin").value >= document.getElementById("ymax").value ||
!(document.getElementById("boundsForm").checkValidity()))
{
document.getElementById("invalidPar").style.display = "inline";
} else {
document.getElementById("invalidPar").style.display = "none";
plot.xmin = Number(document.getElementById("xmin").value);
plot.xmax = Number(document.getElementById("xmax").value);
plot.ymin = Number(document.getElementById("ymin").value);
plot.ymax = Number(document.getElementById("ymax").value);
//Check to see which mode is selected
if (document.getElementById("dropRadio").checked) {
plot.xFunc = funcs[2*document.getElementById("dropSelect").selectedIndex];
plot.yFunc = funcs[2*document.getElementById("dropSelect").selectedIndex+1];
} else if (document.getElementById("matrixRadio").checked) {
plot.xFunc = matrixXFunc;
plot.yFunc = matrixYFunc;
} else if (document.getElementById("manualRadio").checked){
} else if (document.getElementById("loktaRadio").checked){
plot.xFunc = loktaXFunc;
plot.yFunc = loktaYFunc;
}
drawPlot();
}
});
//Handle mouseclick on plot. Clears and redraws plot then
//plots trajectory with initial conditions at mouse click coordinates.
document.getElementById("plotCanvas").addEventListener("mousedown", function(event) {
//Clear plot
drawPlot();
//For use in calculations
var rect = canvas.getBoundingClientRect();
//convert from coordinates relative to canvas to coordinates relative
//to plot
var inputX = plot.xmin + (event.clientX-rect.left)*(plot.xmax-plot.xmin)/800;
var inputY = plot.ymax - (event.clientY-rect.top)*(plot.ymax-plot.ymin)/800;
drawTrajectory(inputX, inputY);
});
//Matrix entry slider change handling.
document.getElementById("aSlider").addEventListener("change",function () {
matrix.a = this.value;
document.getElementById("aValue").innerHTML = matrix.a;
drawPlot();
});
document.getElementById("bSlider").addEventListener("change",function () {
matrix.b = this.value;
document.getElementById("bValue").innerHTML = matrix.b;
drawPlot();
});
document.getElementById("cSlider").addEventListener("change",function () {
matrix.c = this.value;
document.getElementById("cValue").innerHTML = matrix.c;
drawPlot();
});
document.getElementById("dSlider").addEventListener("change",function () {
matrix.d = this.value;
document.getElementById("dValue").innerHTML = matrix.d;
drawPlot();
});
//lokta slider change handling
document.getElementById("loktaASlider").addEventListener("change",function () {
lokta.a = this.value;
document.getElementById("loktaAValue").innerHTML = lokta.a;
drawPlot();
});
document.getElementById("loktaBSlider").addEventListener("change",function () {
lokta.b = this.value;
document.getElementById("loktaBValue").innerHTML = lokta.b;
drawPlot();
});
//Projector mode checkbox handling
document.getElementById("projectorCheckBox").addEventListener("change", function () {
if (this.checked) {
document.getElementById("otherColumnDiv").style.width = "700px";
document.documentElement.style.fontSize = "160%";
document.getElementById("infoHeader").innerHTML = "Phase Plane Application - mitchellf.github.io/pplane/";
} else {
document.getElementById("otherColumnDiv").style.width = "400px";
document.documentElement.style.fontSize = "100%";
document.getElementById("infoHeader").innerHTML = "Phase Plane Application";
}
});
;
<file_sep>//Array to hold function below. Acessed by functions
//in main script for use in plotting
funcs = [firstX,
firstY,
secondX,
secondY,
thirdX,
thirdY,
fourthX,
fourthY,
fifthX,
fifthY,
sixthX,
sixthY
]
//Various systems for use
//First from ex 6.3.2
function firstX(x, y) {
return -1*y +-0.01*x*(Math.pow(x,2)+Math.pow(y,2));
}
function firstY(x, y) {
return x+-0.01*y*(Math.pow(x,2)+Math.pow(y,2));
}
//6.5.2
function secondX(x, y) {
return y;
}
function secondY(x, y) {
return x-Math.pow(x,3);
}
//6.6.1
function thirdX(x, y) {
return y-Math.pow(y,3);
}
function thirdY(x, y) {
return -x-Math.pow(y,2);
}
//6.7
function fourthX(x, y) {
return y;
}
function fourthY(x, y) {
return -Math.sin(x);
}
//7.3.1 Poincare bendixon example
//Should have closed orbit between 1/sqrt(2) = 0.7 and 1
function fifthX(x,y) {
return x-y-x*(Math.pow(x,2)+5*Math.pow(y,2));
}
function fifthY(x,y) {
return x + y - y*(Math.pow(x,2) + Math.pow(y,2));
}
//7.1.2 van der pols mu = -1.5
function sixthX(x,y) {
return y;
}
function sixthY(x,y) {
return -1.5*(Math.pow(x,2)-1)*y-x;
}
//Matrix object for use in matrix entry plotting
var matrix = {
a: 0,
b: 0,
c: 0,
d: 0
}
//Functions for use in matrix entry plotting
function matrixXFunc(inputX, inputY) {
return matrix.a*inputX + matrix.b*inputY;
}
function matrixYFunc(inputX, inputY) {
return matrix.c*inputX + matrix.d*inputY;
}
var lokta = {
a: 0,
b: 0
}
function loktaXFunc(x,y) {
return x*(1-x-lokta.a*y);
}
function loktaYFunc(x,y) {
return y*(1-y-lokta.b*x);
}
| 262a13f0bcc0b3ae767c9e385a1430d2ae653d0b | [
"Markdown",
"JavaScript"
] | 3 | Markdown | mitchellf/pplane | 0e0a79cd5c408a9e6218d844c8563a16677ef410 | dc536822fd7d3cfca8bc7377beec4168576c4ddb |
refs/heads/master | <repo_name>Ciro-Golden/Rails-React-Bidding<file_sep>/app/controllers/api/auctions_controller.rb
module API
class AuctionsController < ApplicationController
def index
auctions = ['Auction 1', 'Auction 2']
render json: { auctions: auctions }
end
def create
render json: { params: params }
end
end
end<file_sep>/app/javascript/components/Auctions.js
import React from 'react'
import axios from 'axios'
class Auctions extends React.Component {
state = {
auctions: []
};
componentDidMount() {
axios
.get("/api/auctions")
.then(response => {
this.setState({ auctions: response.data.auctions });
})
}
renderAllAuctions = () => {
return (
<ul>
{this.state.auctions.map(auction => (
<li key={auction}>{auction}</li>
))}
</ul>
)
}
render() {
return (
<div>
{this.renderAllAuctions()}
</div>
)
}
}
export default Auctions<file_sep>/app/javascript/components/App.js
import React from 'react'
import Home from "./Home"
import Auctions from "./Auctions"
import AuctionNew from "./AuctionNew"
import { Route, Switch } from "react-router-dom"
class App extends React.Component {
render() {
return (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/auctions" component={Auctions} />
<Route exact path="/auction_new" component={AuctionNew} />
</Switch>
</div>
)
}
}
export default App | 09ccce82ec2299f40f2c13f4d4ad9b761f359536 | [
"JavaScript",
"Ruby"
] | 3 | Ruby | Ciro-Golden/Rails-React-Bidding | eb197a1ca1e6a8e2cd42905ed7b37649285ab4da | f6b2bb4aece6a785cad2c7c197d3d9758d08045f |
refs/heads/master | <file_sep>class Hw2 < ActiveRecord::Migration
def up
# Figure 12.11 - KIND OF
# rather, see paragraph after that figure: the moviegoer_id field in the movies table would need an index in order to speed up the query implied by movie.moviegoers
#add_index 'moviegoers', 'review', :unique => true # these don't work
#add_index 'movies', 'review', :unique => true
# see db/schema.rb
add_index 'reviews', 'movie_id'
add_index 'reviews', 'moviegoer_id'
end
def down # JUST in case I have to roll this back...
#remove_index 'moviegoers', 'review'
#remove_index 'movies', 'review'
remove_index 'reviews', 'movie_id'
remove_index 'reviews', 'moviegoer_id'
end
end
| cf73f195c665d2f378304e21bc2a15e5f78578b9 | [
"Ruby"
] | 1 | Ruby | ypeels/hw6_rottenpotatoes | e513df393da8be14b843f6440fa82432b31455c0 | 1d1aced4116ddcc62fc024aa35f5f954721d8409 |
refs/heads/master | <repo_name>panduwijaya/gytechv1<file_sep>/assets/images/desktop.ini
[LocalizedFileNames]
icons8-service-50.png=@icons8-service-50,0
<file_sep>/application/controllers/Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index()
{
$this->load->view('welcome_message');
}
function ceklogin(){
if(isset($_POST['login'])){
$user = $this->input->post('user',true);
$pass = $this->input->post('pass',true);
$cek = $this->gytechmodel->proseslogin($user, $pass);
$hasil = count($cek);
if($hasil > 0){
$sess = array(
'status' => TRUE,
'level' => 'admin'
);
$yglogin = $this->db->get_where('users',array('username'=>$user, 'password' => $pass))->row();
$data = array('udhmasuk' => true,
'nama' => $yglogin->nama, 'email' => $yglogin->email, 'username' => $yglogin->username);
$this->session->set_userdata($data);
if($yglogin->level == 'admin'){
$this->session->set_userdata($sess);
redirect('beranda');
}elseif($yglogin->level == 'moderator'){
$this->session->set_userdata($sess);
redirect('moderator');
}elseif($yglogin->level =='member'){
$this->session->set_userdata($sess);
redirect('member');
}
}else{
redirect('index');
}
}
}
function beranda(){
if ($this->session->status === TRUE){
$data["title"] = "Admin - GYTECHIM";
$this->load->view('admin/beranda', $data);
}else{
redirect('index');
}
}
function moderator(){
if ($this->session->status === TRUE){
$data["title"] = "Halaman Moderator";
$this->load->view('moderator', $data);
}else{
redirect('index');
}
}
function member(){
if ($this->session->status === TRUE){
$data["title"] = "Halaman Booking Member";
$this->load->view('member/member', $data);
}else{
redirect('index');
}
}
function keluar(){
$this->session->sess_destroy();
redirect('index');
}
}
<file_sep>/application/models/Cart_model.php
<?php
class Cart_model extends CI_Model{
function get_all_produk(){
$hasil=$this->db->get('tbl_produk');
return $hasil->result();
}
}<file_sep>/application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['daftar'] = 'Daftar';
$route['default_controller'] = 'welcome';
$route['prosescart'] = 'Cart/add_to_cart';
$route['showcart'] = 'Cart/show_cart';
$route['loadcart'] = 'Cart/load_cart';
$route['deletecart'] = 'Cart/hapus_cart';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['(:any)'] = 'welcome/$1';<file_sep>/README.md
# PT.Gytech Indosantara Mandiri
Pengembangan website untuk pt gytech indosantara mandiri dengan system booking jasa perbaikan ac online
| 015ff4b36f2b99207fc582e21bfbfab186f3f6ff | [
"Markdown",
"PHP",
"INI"
] | 5 | INI | panduwijaya/gytechv1 | f0918162d62fee1c33bc185c8b78529dc4917e58 | c18ab1c0c36be7a2c268b5a9f9af04a914590a98 |
refs/heads/master | <file_sep>from board import Board
from genome import *
class Parser:
def __init__(self, filename):
self.data = []
with open(filename) as f:
for line in f:
_line = []
for l in line:
if l != '\n':
_line.append(l)
self.data.append(_line)
def create_board(self):
b = Board(size=(len(self.data), len(self.data[0])))
for i in range(len(self.data)):
for j in range(len(self.data[0])):
c = self.parse_token(self.data[i][j], (i, j))
if c is not None:
#print(i, j)
b.add_cell(c)
return b
def parse_token(self, ch, coor):
parse_map = {
'>': Rotator(pos=coor, vel=(0, 0), direction=Direction.EAST),
'<': Rotator(pos=coor, vel=(0, 0), direction=Direction.WEST),
'^': Rotator(pos=coor, vel=(0, 0), direction=Direction.NORTH),
'V': Rotator(pos=coor, vel=(0, 0), direction=Direction.SOUTH),
'}': Emitter(pos=coor, vel=(0, 0), direction=Direction.EAST),
'{': Emitter(pos=coor, vel=(0, 0), direction=Direction.WEST),
'0': Data(pos=coor, vel=(-1, 0), value=0),
':': Filter(pos=coor, vel=(0, 0)),
'#': Sponge(pos=coor, vel=(0, 0))
}
try:
return parse_map[ch]
except:
return None<file_sep>from board import Board
from cell import Cell
from genome import Rotator, Direction, Data
from parser import Parser
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Domain:
def __init__(self):
self.species = []
self.mapping = {}
self.cell_to_token = {}
self.i = 0
def add_species(self, cell):
self.species.append(cell)
cell.token = i
self.mapping[self.i] = cell
self.cell_to_token[cell] = self.i
self.i += 1
def run(filename, n_generations=250, dpi=100, interval=20, save=False):
p = Parser(filename)
board = p.create_board()
fig = plt.figure(dpi=dpi)
plt.axis("off")
ims = []
for i in range(n_generations):
universe = board.get_state()
ims.append((plt.imshow(universe, cmap=plt.cm.BuPu_r),))
board.update()
im_ani = animation.ArtistAnimation(
fig, ims, interval=interval, repeat_delay=3000, blit=True
)
if save:
im_ani.save(("./celluar.gif"), writer="imagemagick")
#plt.show()
run('../boards/1st_board.mc', save=True)<file_sep>class Cell:
def __init__(self, pos=(0, 0), vel=(1, 0)):
self.position = pos
self.velocity = vel
self.stack = []
def step(self, cell=None):
x, y = self.position
dx, dy = self.velocity
self.position = (x + dx, y + dy)
def interact(self, cell):
pass
def operate(self):
pass
def output(self):
pass<file_sep>from cell import Cell
from enum import Enum
from copy import copy
Direction = Enum('Direction', ['NORTH', 'EAST', 'SOUTH', 'WEST'])
class Rotator(Cell):
def __init__(self, pos, vel, direction=Direction.NORTH):
self.direction = direction
self.velocity_map = {
Direction.NORTH : (-1, 0),
Direction.SOUTH : (1, 0),
Direction.EAST : (0, 1),
Direction.WEST : (0, -1),
}
super().__init__(pos, vel)
def interact(self, cell):
cell.velocity = self.velocity_map[self.direction]
return cell
class Data(Cell):
def __init__(self, value, pos=(0, 0), vel=(1, 0)):
super().__init__(pos, vel)
self.stack.append(value)
class Emitter(Rotator):
def __init__(self, pos=(0, 0), vel=(0, 0), direction=Direction.NORTH):
super().__init__(pos, vel, direction)
def interact(self, cell):
new_c = copy(cell)
new_c.velocity = self.velocity_map[self.direction]
return [cell, new_c]
class Filter(Cell):
def __init__(self, pos=(0, 0), vel=(0, 0)):
super().__init__(pos, vel)
self.state = True
def interact(self, cell):
if self.state:
cell.velocity = (-1, 0)
self.state = False
elif not self.state:
cell.velocity = (1, 0)
self.state = True
return cell
class Sponge(Cell):
def __init__(self, pos=(0, 0), vel=(0, 0)):
super().__init__(pos, vel)
def interact(self, cell):
return None
| a9d616bff7cb527ab7c4a9fe24fcfcd63ed29a70 | [
"Python"
] | 4 | Python | OhioAdam/metacell | bd4cc8a3938d0d6c6461ad1b5d2923c6b1ae0dd7 | 2834f77a51ae76bf9bff50f580b03b7c15c35096 |
refs/heads/master | <file_sep>// var registerComponent = require('../core/component').registerComponent;
// var utils = require('../utils/');
//
// module.exports.Component = registerComponent('alongpathComp', {
//
// schema: {
// path : { default: '' },
// closed : { default: false },
// dur : { default: 1000 }
// },
//
// init: function() {
// var ent = this.el;
// var d = this.data;
// var points = d.path.split(' ').map(function(p) {
// p = p.split(',');
// return new THREE.Vector3(
// parseFloat(p[0]),
// parseFloat(p[1]),
// parseFloat(p[2])
// );
// });
// var ctor = d.closed ? 'ClosedSplineCurve3' : 'SplineCurve3';
// var curve = new THREE[ctor](points);
//
// var onFrame = function onFrame(t) {
// window.requestAnimationFrame(onFrame);
// t = t % d.dur;
// var i = t / d.dur;
// try {
// var p = curve.getPoint(i);
// ent.setAttribute('position', p);
// } catch (ex) {}
// };
//
// onFrame();
// },
//
// update: function(oldData) {},
//
// remove: function() {}
//
//
// });
| bada968b6e5821df329db5e67c703211ba39c832 | [
"JavaScript"
] | 1 | JavaScript | alexoviedo999/aframe-react-one | cc28351431f4b77278a12f1306332752362cf1bc | 820ca2ddc37d6dcbda28637cbe055b367b67dd5c |
refs/heads/master | <repo_name>Gozhii/hw02<file_sep>/Drink.java
package com.company;
// It is task1
public class Drink {
private String name;
private String description;
private double price;
DrinkBuilder drinkBuilder;
public DrinkBuilder getDrinkBuilder(){
return this.drinkBuilder;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
private Drink(String name, String description, double price, DrinkBuilder drinkBuilder) {
this.name = name;
this.description = description;
this.price = price;
this.drinkBuilder = drinkBuilder;
}
static class DrinkBuilder {
private String name = "";
private String description = "";
private double price = 0;
public DrinkBuilder setName(String name) {
this.name = name;
return this;
}
public DrinkBuilder setDescription(String description) {
this.description = description;
return this;
}
public DrinkBuilder setPrice(double price) {
this.price = price;
return this;
}
public Drink build() {
return new Drink(name, description, price, this);
}
}
@Override
public String toString() {
return name + "\n" + description + "\n" + price;
}
}
<file_sep>/Square.java
package com.company.Task6;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.rmi.server.ExportException;
public class Square implements Shape, Serializable {
private int side;
public Square(int side) {
this.side = side;
}
@Override
public void getView() {
System.out.println("Something that looks like Square");
System.out.println("Side = " + side);
}
public void setSide(int length) {
this.side = side;
}
public int getSide() {
return side;
}
public void writeObject() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
new String(getClass() + "-" + hashCode() + ".xml")))) {
oos.writeObject(this);
} catch (ExportException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/Builder.java
package com.company.Task6;
public class Builder {
public Shape buildTriangle(int[] lengthOfSides) throws InvalidInputException {
if (lengthOfSides.length != 3 ||
(lengthOfSides[0] + lengthOfSides[1] < lengthOfSides[2]) ||
(lengthOfSides[1] + lengthOfSides[2] < lengthOfSides[0]) ||
(lengthOfSides[2] + lengthOfSides[0] < lengthOfSides[1])) {
throw new InvalidInputException();
}
return new Triangle(lengthOfSides);
}
public Shape buildCircle(int radius) {
return new Circle(radius);
}
public Shape buildSquare(int length) {
return new Square(length);
}
}
| 0a21d8137648ebbcb4ec71bcf8553e67b5976bfa | [
"Java"
] | 3 | Java | Gozhii/hw02 | c197b63160a9b76f40c74e409c22ae283117568b | ac43f544c211ec07bd05792f0cb00ef8804a3718 |
refs/heads/master | <repo_name>richardvogg/wordcloud-in-cat-shape<file_sep>/README.md
# wordcloud-in-cat-shape
I used a few articles from my travel blog to create a wordcloud with the most used words.
This wordcloud was shaped in the binary image of our cat (see Mask.png) - which I prepared with paint.

<file_sep>/Blog.py
from wordcloud import WordCloud, ImageColorGenerator
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# Read the whole text.
text = open('C:/Richard/R and Python/Kaggle/Blog.txt').read()
cachedStopWords = stopwords.words("german")
cachedStopWords.append("Da")
cachedStopWords.append("dass")
text = ' '.join([word for word in text.split() if word not in cachedStopWords])
text=text.decode('unicode-escape')
#text.replace(u'\xed', 'i')
alice_mask = np.array(Image.open("C:/Richard/R and Python/Kaggle/Mask.png"))
# lower max_font_size
wordcloud = WordCloud(max_font_size=100,background_color="white", max_words=1000,
mask=alice_mask).generate(text)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
| 00a923cb085bebac4afc5ed7d46fdfb531e6f7d3 | [
"Markdown",
"Python"
] | 2 | Markdown | richardvogg/wordcloud-in-cat-shape | d99c3c6c1bc93f88d2fd4d054509949cb65880ef | d41e7d3a4d34c6520eee05c5ead37756c1af5c90 |
refs/heads/master | <repo_name>ZarinPal-Lab/RestrictContentPro<file_sep>/RCP_ZarinPal.php
<?php
/*
Plugin Name: درگاه پرداخت زرین پال برای Restrict Content Pro
Version: 3.2.4
Requires at least: 4.0
Description: درگاه پرداخت <a href="http://www.zarinpal.com/" target="_blank"> زرین پال </a> برای افزونه Restrict Content Pro
Plugin URI: http://zarinpal.com
Author: حنّان ابراهیمی ستوده Update to new A.Y
Author URI: http://zarinpal.com
*/
if (!defined('ABSPATH')) {
exit;
}
require_once 'HANNANStd_Session.php';
if (!class_exists('RCP_ZarinPal')) {
class RCP_ZarinPal
{
#webhooks
public function process_webhooks()
{}
/**
* Use this space to enqueue any extra JavaScript files.
*
access public
@return void
*/
#script
public function scripts()
{}
/**
* Load any extra fields on the registration form
*
* @access public
* @return string
*/
#fields
public function fields()
{
/* Example for loading the credit card fields :
ob_start();
rcp_get_template_part( 'card-form' );
return ob_get_clean();
*/
}
#validateFields
public function validate_fields()
{
/* Example :
if ( empty( $_POST['rcp_card_cvc'] ) ) {
rcp_errors()->add( 'missing_card_code', __( 'The security code you have entered is invalid', 'rcp' ), 'register' );
}
*/
}
#supports
// public $supports = array();
public function supports($item = '')
{
return;
}
/**
* Generate a transaction ID
*
* Used in the manual payments gateway.
*
* @return string
*/
public function __construct()
{
add_action('init', array($this, 'ZarinPal_Verify_By_HANNANStd'));
add_action('rcp_payments_settings', array($this, 'ZarinPal_Setting_By_HANNANStd'));
add_action('rcp_gateway_ZarinPal', array($this, 'ZarinPal_Request_By_HANNANStd'));
add_filter('rcp_payment_gateways', array($this, 'ZarinPal_Register_By_HANNANStd'));
add_filter('rcp_currencies', array($this, 'RCP_IRAN_Currencies_By_HANNANStd'));
add_filter('rcp_irr_currency_filter_before', array($this, 'RCP_IRR_Before_By_HANNANStd'), 10, 3);
add_filter('rcp_irr_currency_filter_after', array($this, 'RCP_IRR_After_By_HANNANStd'), 10, 3);
add_filter('rcp_irt_currency_filter_before', array($this, 'RCP_IRT_Before_By_HANNANStd'), 10, 3);
add_filter('rcp_irt_currency_filter_after', array($this, 'RCP_IRT_After_By_HANNANStd'), 10, 3);
}
public function RCP_IRR_Before_By_HANNANStd($formatted_price, $currency_code, $price)
{
return __('ریال', 'rcp') . ' ' . $price;
}
public function RCP_IRR_After_By_HANNANStd($formatted_price, $currency_code, $price)
{
return $price . ' ' . __('ریال', 'rcp');
}
public function RCP_IRT_Before_By_HANNANStd($formatted_price, $currency_code, $price)
{
return __('تومان', 'rcp') . ' ' . $price;
}
public function RCP_IRT_After_By_HANNANStd($formatted_price, $currency_code, $price)
{
return $price . ' ' . __('تومان', 'rcp');
}
public function RCP_IRAN_Currencies_By_HANNANStd($currencies)
{
unset($currencies['RIAL'], $currencies['IRR'], $currencies['IRT']);
$iran_currencies = array(
'IRT' => __('تومان ایران (تومان)', 'rcp'),
'IRR' => __('ریال ایران (ریال)', 'rcp'),
);
return array_unique(array_merge($iran_currencies, $currencies));
}
public function ZarinPal_Register_By_HANNANStd($gateways)
{
global $rcp_options;
if (version_compare(RCP_PLUGIN_VERSION, '2.1.0', '<')) {
$gateways['ZarinPal'] = isset($rcp_options['zarinpal_name']) ? $rcp_options['zarinpal_name'] : __('زرین پال', 'rcp_zarinpal');
} else {
$gateways['ZarinPal'] = array(
'label' => isset($rcp_options['zarinpal_name']) ? $rcp_options['zarinpal_name'] : __('زرین پال', 'rcp_zarinpal'),
'admin_label' => isset($rcp_options['zarinpal_name']) ? $rcp_options['zarinpal_name'] : __('زرین پال', 'rcp_zarinpal'),
'class' => 'rcp_zarinpal',
);
}
return $gateways;
}
public function ZarinPal_Setting_By_HANNANStd($rcp_options)
{
?>
<hr/>
<table class="form-table">
<?php do_action('RCP_ZarinPal_before_settings', $rcp_options);?>
<tr valign="top">
<th colspan=2><h3><?php _e('تنظیمات زرین پال', 'rcp_zarinpal');?></h3></th>
</tr>
<tr valign="top">
<th>
<label for="rcp_settings[zarinpal_server]"><?php _e('سرور زرین پال', 'rcp_zarinpal');?></label>
</th>
<td>
<select id="rcp_settings[zarinpal_server]" name="rcp_settings[zarinpal_server]">
<option value="German" <?php selected('German', isset($rcp_options['zarinpal_server']) ? $rcp_options['zarinpal_server'] : '');?>><?php _e('آلمان', 'rcp_zarinpal');?></option>
<option value="Iran" <?php selected('Iran', isset($rcp_options['zarinpal_server']) ? $rcp_options['zarinpal_server'] : '');?>><?php _e('ایران', 'rcp_zarinpal');?></option>
</select>
</td>
</tr>
<tr valign="top">
<th>
<label for="rcp_settings[zarinpal_merchant]"><?php _e('مرچنت زرین پال', 'rcp_zarinpal');?></label>
</th>
<td>
<input class="regular-text" id="rcp_settings[zarinpal_merchant]" style="width: 300px;"
name="rcp_settings[zarinpal_merchant]"
value="<?php if (isset($rcp_options['zarinpal_merchant'])) {
echo $rcp_options['zarinpal_merchant'];
}?>"/>
</td>
</tr>
<tr valign="top">
<th>
<label for="rcp_settings[zarinpal_query_name]"><?php _e('نام لاتین درگاه', 'rcp_zarinpal');?></label>
</th>
<td>
<input class="regular-text" id="rcp_settings[zarinpal_query_name]" style="width: 300px;"
name="rcp_settings[zarinpal_query_name]"
value="<?php echo isset($rcp_options['zarinpal_query_name']) ? $rcp_options['zarinpal_query_name'] : 'ZarinPal'; ?>"/>
<div class="description"><?php _e('این نام در هنگام بازگشت از بانک در آدرس بازگشت از بانک نمایان خواهد شد . از به کاربردن حروف زائد و فاصله جدا خودداری نمایید . این نام باید با نام سایر درگاه ها متفاوت باشد .', 'rcp_zarinpal');?></div>
</td>
</tr>
<tr valign="top">
<th>
<label for="rcp_settings[zarinpal_name]"><?php _e('نام نمایشی درگاه', 'rcp_zarinpal');?></label>
</th>
<td>
<input class="regular-text" id="rcp_settings[zarinpal_name]" style="width: 300px;"
name="rcp_settings[zarinpal_name]"
value="<?php echo isset($rcp_options['zarinpal_name']) ? $rcp_options['zarinpal_name'] : __('زرین پال', 'rcp_zarinpal'); ?>"/>
</td>
</tr>
<tr valign="top">
<th>
<label><?php _e('تذکر ', 'rcp_zarinpal');?></label>
</th>
<td>
<div class="description"><?php _e('از سربرگ مربوط به ثبت نام در تنظیمات افزونه حتما یک برگه برای بازگشت از بانک انتخاب نمایید . ترجیحا نامک برگه را لاتین قرار دهید .<br/> نیازی به قرار دادن شورت کد خاصی در برگه نیست و میتواند برگه ی خالی باشد .', 'rcp_zarinpal');?></div>
</td>
</tr>
<?php do_action('RCP_ZarinPal_after_settings', $rcp_options);?>
</table>
<?php
}
public function ZarinPal_Request_By_HANNANStd($subscription_data)
{
$new_subscription_id = get_user_meta($subscription_data['user_id'], 'rcp_subscription_level', true);
if (!empty($new_subscription_id)) {
update_user_meta($subscription_data['user_id'], 'rcp_subscription_level_new', $new_subscription_id);
}
$old_subscription_id = get_user_meta($subscription_data['user_id'], 'rcp_subscription_level_old', true);
update_user_meta($subscription_data['user_id'], 'rcp_subscription_level', $old_subscription_id);
global $rcp_options;
ob_start();
$query = isset($rcp_options['zarinpal_query_name']) ? $rcp_options['zarinpal_query_name'] : 'ZarinPal';
$amount = str_replace(',', '', $subscription_data['price']);
//fee is just for paypal recurring or ipn gateway ....
//$amount = $subscription_data['price'] + $subscription_data['fee'];
$zarinpal_payment_data = array(
'user_id' => $subscription_data['user_id'],
'subscription_name' => $subscription_data['subscription_name'],
'subscription_key' => $subscription_data['key'],
'amount' => $amount,
);
$HANNANStd_session = HANNAN_Session::get_instance();
@session_start();
$HANNANStd_session['zarinpal_payment_data'] = $zarinpal_payment_data;
$_SESSION["zarinpal_payment_data"] = $zarinpal_payment_data;
//Action For ZarinPal or RCP Developers...
do_action('RCP_Before_Sending_to_ZarinPal', $subscription_data);
if (!in_array($rcp_options['currency'], array(
'irt',
'IRT',
'تومان',
__('تومان', 'rcp'),
__('تومان', 'rcp_zarinpal'),
))) {
$amount = $amount / 10;
}
//Start of ZarinPal
$MerchantID = isset($rcp_options['zarinpal_merchant']) ? $rcp_options['zarinpal_merchant'] : '';
$Amount = intval($amount);
$Email = isset($subscription_data['user_email']) ? $subscription_data['user_email'] : '-';
$CallbackURL = add_query_arg('gateway', $query, $subscription_data['return_url']);
$Description = sprintf(__('خرید اشتراک %s برای کاربر %s', 'rcp_zarinpal'), $subscription_data['subscription_name'], $subscription_data['user_name']);
$Mobile = '-';
//Filter For ZarinPal or RCP Developers...
$Description = apply_filters('RCP_ZarinPal_Description', $Description, $subscription_data);
$Mobile = apply_filters('RCP_Mobile', $Mobile, $subscription_data);
$data = array('merchant_id' => $MerchantID,
'amount' => $Amount,
'callback_url' => $CallbackURL,
'description' => $Description);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData),
));
$result = curl_exec($ch);
$err = curl_error($ch);
$result = json_decode($result, true);
curl_close($ch);
if ($result['data']['code'] == 100) {
ob_end_clean();
if (!headers_sent()) {
header('Location: https://www.zarinpal.com/pg/StartPay/' . $result['data']["authority"] . '/ZarinGate');
exit;
} else {
$redirect_page = 'https://www.zarinpal.com/pg/StartPay/' .$result['data']["authority"] . '/ZarinGate';
echo "<script type='text/javascript'>window.onload = function () { top.location.href = '" . $redirect_page . "'; };</script>";
exit;
}
} else {
wp_die(sprintf(__('متاسفانه پرداخت به دلیل خطای زیر امکان پذیر نمی باشد . <br/><b> %s </b>', 'rcp_zarinpal'), $this->Fault($result['errors']['code'])));
}
//End of ZarinPal
exit;
}
public function ZarinPal_Verify_By_HANNANStd()
{
if (!isset($_GET['gateway'])) {
return;
}
if (!class_exists('RCP_Payments')) {
return;
}
global $rcp_options, $wpdb, $rcp_payments_db_name;
@session_start();
$HANNANStd_session = HANNAN_Session::get_instance();
if (isset($HANNANStd_session['zarinpal_payment_data'])) {
$zarinpal_payment_data = $HANNANStd_session['zarinpal_payment_data'];
} else {
$zarinpal_payment_data = isset($_SESSION["zarinpal_payment_data"]) ? $_SESSION["zarinpal_payment_data"] : '';
}
$query = isset($rcp_options['zarinpal_query_name']) ? $rcp_options['zarinpal_query_name'] : 'ZarinPal';
if (($_GET['gateway'] == $query) && $zarinpal_payment_data) {
$user_id = $zarinpal_payment_data['user_id'];
$user_id = intval($user_id);
$subscription_name = $zarinpal_payment_data['subscription_name'];
$subscription_key = $zarinpal_payment_data['subscription_key'];
$amount = $zarinpal_payment_data['amount'];
/*
$subscription_price = intval(number_format( (float) rcp_get_subscription_price( rcp_get_subscription_id( $user_id ) ), 2)) ;
*/
$payment_method = isset($rcp_options['zarinpal_name']) ? $rcp_options['zarinpal_name'] : __('زرین پال طلایی', 'rcp_zarinpal');
$new_payment = 1;
if ($wpdb->get_results($wpdb->prepare("SELECT id FROM " . $rcp_payments_db_name . " WHERE `subscription_key`='%s' AND `payment_type`='%s';", $subscription_key, $payment_method))) {
$new_payment = 0;
}
unset($GLOBALS['zarinpal_new']);
$GLOBALS['zarinpal_new'] = $new_payment;
global $new;
$new = $new_payment;
if ($new_payment == 1) {
//Start of ZarinPal
$MerchantID = isset($rcp_options['zarinpal_merchant']) ? $rcp_options['zarinpal_merchant'] : '';
$Amount = intval($amount);
if (!in_array($rcp_options['currency'], array(
'irt',
'IRT',
'تومان',
__('تومان', 'rcp'),
__('تومان', 'rcp_zarinpal'),
))) {
$Amount = $Amount / 10;
}
$Authority = isset($_GET['Authority']) ? sanitize_text_field($_GET['Authority']) : '';
$__param = $Authority;
RCP_check_verifications(__CLASS__, $__param);
if (isset($_GET['Status']) && $_GET['Status'] == 'OK') {
$data = array('merchant_id' => $MerchantID, 'authority' => $Authority, 'amount' => $Amount);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData),
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
$result = json_decode($result, true);
if ($result['data']['code'] == 100) {
$payment_status = 'completed';
$fault = 0;
$transaction_id = $result ['data']['ref_id'];
} else {
$payment_status = 'failed';
$fault = $result ['data']['code'];
$transaction_id = 0;
}
} else {
$payment_status = 'cancelled';
$fault = 0;
$transaction_id = 0;
}
//End of ZarinPal
unset($GLOBALS['zarinpal_payment_status']);
unset($GLOBALS['zarinpal_transaction_id']);
unset($GLOBALS['zarinpal_fault']);
unset($GLOBALS['zarinpal_subscription_key']);
$GLOBALS['zarinpal_payment_status'] = $payment_status;
$GLOBALS['zarinpal_transaction_id'] = $transaction_id;
$GLOBALS['zarinpal_subscription_key'] = $subscription_key;
$GLOBALS['zarinpal_fault'] = $fault;
global $zarinpal_transaction;
$zarinpal_transaction = array();
$zarinpal_transaction['zarinpal_payment_status'] = $payment_status;
$zarinpal_transaction['zarinpal_transaction_id'] = $transaction_id;
$zarinpal_transaction['zarinpal_subscription_key'] = $subscription_key;
$zarinpal_transaction['zarinpal_fault'] = $fault;
if ($payment_status == 'completed') {
$payment_data = array(
'date' => date('Y-m-d g:i:s'),
'subscription' => $subscription_name,
'payment_type' => $payment_method,
'subscription_key' => $subscription_key,
'amount' => $amount,
'user_id' => $user_id,
'transaction_id' => $transaction_id,
);
//Action For ZarinPal or RCP Developers...
do_action('RCP_ZarinPal_Insert_Payment', $payment_data, $user_id);
$rcp_payments = new RCP_Payments();
RCP_set_verifications($rcp_payments->insert($payment_data), __CLASS__, $__param);
$new_subscription_id = get_user_meta($user_id, 'rcp_subscription_level_new', true);
if (!empty($new_subscription_id)) {
update_user_meta($user_id, 'rcp_subscription_level', $new_subscription_id);
}
$membership = (array) rcp_get_memberships()[0];
$old_status_level = $membership;
$replace = str_replace('\u0000*\u0000', '', json_encode($old_status_level));
$replace = json_decode($replace, true);
$status = $replace['status'];
$idMemberShip = (int) $replace['id'];
$arrayMember = array(
'status' => 'active',
);
if ($status == 'pending') {
rcp_update_membership($idMemberShip, $arrayMember);
} else {
rcp_set_status($user_id, 'active');
}
if (version_compare(RCP_PLUGIN_VERSION, '2.1.0', '<')) {
rcp_email_subscription_status($user_id, 'active');
if (!isset($rcp_options['disable_new_user_notices'])) {
wp_new_user_notification($user_id);
}
}
update_user_meta($user_id, 'rcp_payment_profile_id', $user_id);
update_user_meta($user_id, 'rcp_signup_method', 'live');
//rcp_recurring is just for paypal or ipn gateway
update_user_meta($user_id, 'rcp_recurring', 'no');
$subscription = rcp_get_subscription_details(rcp_get_subscription_id($user_id));
$member_new_expiration = date('Y-m-d H:i:s', strtotime('+' . $subscription->duration . ' ' . $subscription->duration_unit . ' 23:59:59'));
rcp_set_expiration_date($user_id, $member_new_expiration);
delete_user_meta($user_id, '_rcp_expired_email_sent');
$log_data = array(
'post_title' => __('تایید پرداخت', 'rcp_zarinpal'),
'post_content' => __('پرداخت با موفقیت انجام شد . کد تراکنش : ', 'rcp_zarinpal') . $transaction_id . __(' . روش پرداخت : ', 'rcp_zarinpal') . $payment_method,
'post_parent' => 0,
'log_type' => 'gateway_error',
);
$log_meta = array(
'user_subscription' => $subscription_name,
'user_id' => $user_id,
);
$log_entry = WP_Logging::insert_log($log_data, $log_meta);
//Action For ZarinPal or RCP Developers...
do_action('RCP_ZarinPal_Completed', $user_id);
}
if ($payment_status == 'cancelled') {
$log_data = array(
'post_title' => __('انصراف از پرداخت', 'rcp_zarinpal'),
'post_content' => __('تراکنش به دلیل انصراف کاربر از پرداخت ، ناتمام باقی ماند .', 'rcp_zarinpal') . __(' روش پرداخت : ', 'rcp_zarinpal') . $payment_method,
'post_parent' => 0,
'log_type' => 'gateway_error',
);
$log_meta = array(
'user_subscription' => $subscription_name,
'user_id' => $user_id,
);
$log_entry = WP_Logging::insert_log($log_data, $log_meta);
//Action For ZarinPal or RCP Developers...
do_action('RCP_ZarinPal_Cancelled', $user_id);
}
if ($payment_status == 'failed') {
$log_data = array(
'post_title' => __('خطا در پرداخت', 'rcp_zarinpal'),
'post_content' => __('تراکنش به دلیل خطای رو به رو ناموفق باقی باند :', 'rcp_zarinpal') . $this->Fault($fault) . __(' روش پرداخت : ', 'rcp_zarinpal') . $payment_method,
'post_parent' => 0,
'log_type' => 'gateway_error',
);
$log_meta = array(
'user_subscription' => $subscription_name,
'user_id' => $user_id,
);
$log_entry = WP_Logging::insert_log($log_data, $log_meta);
//Action For ZarinPal or RCP Developers...
do_action('RCP_ZarinPal_Failed', $user_id);
}
}
add_filter('the_content', array($this, 'ZarinPal_Content_After_Return_By_HANNANStd'));
//session_destroy();
}
}
public function ZarinPal_Content_After_Return_By_HANNANStd($content)
{
global $zarinpal_transaction, $new;
$HANNANStd_session = HANNAN_Session::get_instance();
@session_start();
$new_payment = isset($GLOBALS['zarinpal_new']) ? $GLOBALS['zarinpal_new'] : $new;
$payment_status = isset($GLOBALS['zarinpal_payment_status']) ? $GLOBALS['zarinpal_payment_status'] : $zarinpal_transaction['zarinpal_payment_status'];
$transaction_id = isset($GLOBALS['zarinpal_transaction_id']) ? $GLOBALS['zarinpal_transaction_id'] : $zarinpal_transaction['zarinpal_transaction_id'];
$fault = isset($GLOBALS['zarinpal_fault']) ? $this->Fault($GLOBALS['zarinpal_fault']) : $this->Fault($zarinpal_transaction['zarinpal_fault']);
if ($new_payment == 1) {
$zarinpal_data = array(
'payment_status' => $payment_status,
'transaction_id' => $transaction_id,
'fault' => $fault,
);
$HANNANStd_session['zarinpal_data'] = $zarinpal_data;
$_SESSION["zarinpal_data"] = $zarinpal_data;
} else {
if (isset($HANNANStd_session['zarinpal_data'])) {
$zarinpal_payment_data = $HANNANStd_session['zarinpal_data'];
} else {
$zarinpal_payment_data = isset($_SESSION["zarinpal_data"]) ? $_SESSION["zarinpal_data"] : '';
}
$payment_status = isset($zarinpal_payment_data['payment_status']) ? $zarinpal_payment_data['payment_status'] : '';
$transaction_id = isset($zarinpal_payment_data['transaction_id']) ? $zarinpal_payment_data['transaction_id'] : '';
$fault = isset($zarinpal_payment_data['fault']) ? $this->Fault($zarinpal_payment_data['fault']) : '';
}
$message = '';
if ($payment_status == 'completed') {
$message = '<br/>' . __('پرداخت با موفقیت انجام شد . کد تراکنش : ', 'rcp_zarinpal') . $transaction_id . '<br/>';
}
if ($payment_status == 'cancelled') {
$message = '<br/>' . __('تراکنش به دلیل انصراف شما نا تمام باقی ماند .', 'rcp_zarinpal');
}
if ($payment_status == 'failed') {
$message = '<br/>' . __('تراکنش به دلیل خطای زیر ناموفق باقی باند :', 'rcp_zarinpal') . '<br/>' . $fault . '<br/>';
}
return $content . $message;
}
private function Fault($error)
{
$response = '';
switch ($error) {
case '-1':
$response = __('اطلاعات ارسال شده ناقص است .', 'rcp_zarinpal');
break;
case '-2':
$response = __('آی پی یا مرچنت زرین پال اشتباه است .', 'rcp_zarinpal');
break;
case '-3':
$response = __('با توجه به محدودیت های شاپرک امکان پرداخت با رقم درخواست شده میسر نمیباشد .', 'rcp_zarinpal');
break;
case '-4':
$response = __('سطح تایید پذیرنده پایین تر از سطح نقره ای میباشد .', 'rcp_zarinpal');
break;
case '-11':
$response = __('درخواست مورد نظر یافت نشد .', 'rcp_zarinpal');
break;
case '-21':
$response = __('هیچ نوع عملیات مالی برای این تراکنش یافت نشد .', 'rcp_zarinpal');
break;
case '-22':
$response = __('تراکنش نا موفق میباشد .', 'rcp_zarinpal');
break;
case '-33':
$response = __('رقم تراکنش با رقم وارد شده مطابقت ندارد .', 'rcp_zarinpal');
break;
case '-40':
$response = __('اجازه دسترسی به متد مورد نظر وجود ندارد .', 'rcp_zarinpal');
break;
case '-54':
$response = __('درخواست مورد نظر آرشیو شده است .', 'rcp_zarinpal');
break;
case '100':
$response = __('اتصال با زرین پال به خوبی برقرار شد و همه چیز صحیح است .', 'rcp_zarinpal');
break;
case '101':
$response = __('تراکنش با موفقیت به پایان رسیده بود و تاییدیه آن نیز انجام شده بود .', 'rcp_zarinpal');
break;
}
return $response;
}
}
}
new RCP_ZarinPal();
if (!function_exists('change_cancelled_to_pending_By_HANNANStd')) {
add_action('rcp_set_status', 'change_cancelled_to_pending_By_HANNANStd', 10, 2);
function change_cancelled_to_pending_By_HANNANStd($status, $user_id)
{
if ('cancelled' == $status) {
rcp_set_status($user_id, 'expired');
}
return true;
}
}
if (!function_exists('RCP_User_Registration_Data_By_HANNANStd') && !function_exists('RCP_User_Registration_Data')) {
add_filter('rcp_user_registration_data', 'RCP_User_Registration_Data_By_HANNANStd');
function RCP_User_Registration_Data_By_HANNANStd($user)
{
$old_subscription_id = get_user_meta($user['id'], 'rcp_subscription_level', true);
if (!empty($old_subscription_id)) {
update_user_meta($user['id'], 'rcp_subscription_level_old', $old_subscription_id);
}
$user_info = get_userdata($user['id']);
$old_user_role = implode(', ', $user_info->roles);
if (!empty($old_user_role)) {
update_user_meta($user['id'], 'rcp_user_role_old', $old_user_role);
}
return $user;
}
}
if (!function_exists('RCP_check_verifications')) {
function RCP_check_verifications($gateway, $params)
{
if (!function_exists('rcp_get_payment_meta_db_name')) {
return;
}
if (is_array($params) || is_object($params)) {
$params = implode('_', (array) $params);
}
if (empty($params) || trim($params) == '') {
return;
}
$gateway = str_ireplace(array('RCP_', 'bank'), array('', ''), $gateway);
$params = trim(strtolower($gateway) . '_' . $params);
$table = rcp_get_payment_meta_db_name();
global $wpdb;
$check = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE meta_key='_verification_params' AND meta_value='%s'", $params));
if (!empty($check)) {
wp_die('وضعیت این تراکنش قبلا مشخص شده بود.');
}
}
}
if (!function_exists('RCP_set_verifications')) {
function RCP_set_verifications($payment_id, $gateway, $params)
{
if (!function_exists('rcp_get_payment_meta_db_name')) {
return;
}
if (is_array($params) || is_object($params)) {
$params = implode('_', (array) $params);
}
if (empty($params) || trim($params) == '') {
return;
}
$gateway = str_ireplace(array('RCP_', 'bank'), array('', ''), $gateway);
$params = trim(strtolower($gateway) . '_' . $params);
$table = rcp_get_payment_meta_db_name();
global $wpdb;
$wpdb->insert($table, array(
'rcp_payment_id' => $payment_id,
'meta_key' => '_verification_params',
'meta_value' => $params,
), array('%d', '%s', '%s'));
}
}
?>
<file_sep>/HANNANStd_Session.php
<?php
if( !defined( 'HANNAN_SESSION_COOKIE' ) )
define( 'HANNAN_SESSION_COOKIE', '_HANNANStd_session' );
if ( !class_exists( 'Recursive_ArrayAccess' ) ) {
class Recursive_ArrayAccess implements ArrayAccess {
protected $container = array();
protected $dirty = false;
protected function __construct( $data = array() ) {
foreach ( $data as $key => $value ) {
$this[ $key ] = $value;
}
}
public function __clone() {
foreach ( $this->container as $key => $value ) {
if ( $value instanceof self ) {
$this[ $key ] = clone $value;
}
}
}
public function toArray() {
$data = $this->container;
foreach ( $data as $key => $value ) {
if ( $value instanceof self ) {
$data[ $key ] = $value->toArray();
}
}
return $data;
}
public function offsetExists( $offset ) {
return isset( $this->container[ $offset ]) ;
}
public function offsetGet( $offset ) {
return isset( $this->container[ $offset ] ) ? $this->container[ $offset ] : null;
}
public function offsetSet( $offset, $data ) {
if ( is_array( $data ) ) {
$data = new self( $data );
}
if ( $offset === null ) {
$this->container[] = $data;
}
else {
$this->container[ $offset ] = $data;
}
$this->dirty = true;
}
public function offsetUnset( $offset ) {
unset( $this->container[ $offset ] );
$this->dirty = true;
}
}
}
if ( !class_exists( 'HANNAN_Session' ) ) {
final class HANNAN_Session extends Recursive_ArrayAccess implements Iterator, Countable {
protected $session_id;
protected $expires;
protected $exp_variant;
private static $instance = false;
public static function get_instance() {
if ( !self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
protected function __construct() {
if ( isset( $_COOKIE[HANNAN_SESSION_COOKIE] ) ) {
$cookie = stripslashes( $_COOKIE[HANNAN_SESSION_COOKIE] );
$cookie_crumbs = explode( '||', $cookie );
$this->session_id = $cookie_crumbs[0];
$this->expires = $cookie_crumbs[1];
$this->exp_variant = $cookie_crumbs[2];
if ( time() > $this->exp_variant ) {
$this->set_expiration();
delete_option( "_HANNANStd_session_expires_{$this->session_id}" );
add_option( "_HANNANStd_session_expires_{$this->session_id}", $this->expires, '', 'no' );
}
}
else {
$this->session_id = $this->generate_id();
$this->set_expiration();
}
$this->read_data();
$this->set_cookie();
}
protected function set_expiration() {
$this->exp_variant = time() + (int) apply_filters( 'HANNANStd_session_expiration_variant', 24 * 60 );
$this->expires = time() + (int) apply_filters( 'HANNANStd_session_expiration', 30 * 60 );
}
protected function set_cookie(){
if( !headers_sent() )
setcookie(HANNAN_SESSION_COOKIE,$this->session_id.'||'.$this->expires.'||'.$this->exp_variant,$this->expires,COOKIEPATH,COOKIE_DOMAIN );
}
protected function generate_id() {
require_once( ABSPATH . 'wp-includes/class-phpass.php');
$hasher = new PasswordHash( 8, false );
return md5( $hasher->get_random_bytes( 32 ) );
}
protected function read_data() {
$this->container = get_option( "_HANNANStd_session_{$this->session_id}", array() );
return $this->container;
}
public function write_data() {
$option_key = "_HANNANStd_session_{$this->session_id}";
if ( $this->dirty ) {
if ( false === get_option( $option_key ) ) {
add_option( "_HANNANStd_session_{$this->session_id}", $this->container, '', 'no' );
add_option( "_HANNANStd_session_expires_{$this->session_id}", $this->expires, '', 'no' );
}
else {
delete_option( "_HANNANStd_session_{$this->session_id}" );
add_option( "_HANNANStd_session_{$this->session_id}", $this->container, '', 'no' );
}
}
}
public function json_out() {
return json_encode( $this->container );
}
public function json_in( $data ) {
$array = json_decode( $data );
if ( is_array( $array ) ) {
$this->container = $array;
return true;
}
return false;
}
public function regenerate_id( $delete_old = false ) {
if ( $delete_old ) {
delete_option( "_HANNANStd_session_{$this->session_id}" );
}
$this->session_id = $this->generate_id();
$this->set_cookie();
}
public function session_started() {
return !!self::$instance;
}
public function cache_expiration() {
return $this->expires;
}
public function reset() {
$this->container = array();
}
public function current() {
return current( $this->container );
}
public function key() {
return key( $this->container );
}
public function next() {
next( $this->container );
}
public function rewind() {
reset( $this->container );
}
public function valid() {
return $this->offsetExists( $this->key() );
}
public function count() {
return count( $this->container );
}
}
function HANNANStd_session_cache_expire() {
$HANNANStd_session = HANNAN_Session::get_instance();
return $HANNANStd_session->cache_expiration();
}
function HANNANStd_session_commit() {
HANNANStd_session_write_close();
}
function HANNANStd_session_decode( $data ) {
$HANNANStd_session = HANNAN_Session::get_instance();
return $HANNANStd_session->json_in( $data );
}
function HANNANStd_session_encode() {
$HANNANStd_session = HANNAN_Session::get_instance();
return $HANNANStd_session->json_out();
}
function HANNANStd_session_regenerate_id( $delete_old_session = false ) {
$HANNANStd_session = HANNAN_Session::get_instance();
$HANNANStd_session->regenerate_id( $delete_old_session );
return true;
}
function HANNANStd_session_start() {
$HANNANStd_session = HANNAN_Session::get_instance();
do_action( 'HANNANStd_session_start' );
return $HANNANStd_session->session_started();
}
add_action( 'plugins_loaded', 'HANNANStd_session_start' );
function HANNANStd_session_status() {
$HANNANStd_session = HANNAN_Session::get_instance();
if ( $HANNANStd_session->session_started() ) {
return PHP_SESSION_ACTIVE;
}
return PHP_SESSION_NONE;
}
function HANNANStd_session_unset() {
$HANNANStd_session = HANNAN_Session::get_instance();
$HANNANStd_session->reset();
}
function HANNANStd_session_write_close() {
$HANNANStd_session = HANNAN_Session::get_instance();
$HANNANStd_session->write_data();
do_action( 'HANNANStd_session_commit' );
}
add_action( 'shutdown', 'HANNANStd_session_write_close' );
function HANNANStd_session_cleanup() {
global $wpdb;
if ( defined( 'HANNAN_SETUP_CONFIG' ) ) {
return;
}
if ( ! defined( 'HANNAN_INSTALLING' ) ) {
$expiration_keys = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE '_HANNANStd_session_expires_%'" );
$now = time();
$expired_sessions = array();
foreach( $expiration_keys as $expiration ) {
if ( $now > intval( $expiration->option_value ) ) {
$session_id = substr( $expiration->option_name, 20 );
$expired_sessions[] = $expiration->option_name;
$expired_sessions[] = "_HANNANStd_session_$session_id";
}
}
if ( ! empty( $expired_sessions ) ) {
$option_names = implode( "','", $expired_sessions );
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name IN ('$option_names')" );
}
}
do_action( 'HANNANStd_session_cleanup' );
}
add_action( 'HANNANStd_session_garbage_collection', 'HANNANStd_session_cleanup' );
function HANNANStd_session_register_garbage_collection() {
if ( !wp_next_scheduled( 'HANNANStd_session_garbage_collection' ) ) {
wp_schedule_event( time(), 'hourly', 'HANNANStd_session_garbage_collection' );
}
}
add_action( 'wp', 'HANNANStd_session_register_garbage_collection' );
}
?> | 0be614b102981724afd58a9405f4c9ed559d4bc8 | [
"PHP"
] | 2 | PHP | ZarinPal-Lab/RestrictContentPro | 31bc17f6b040e4ec416e12c1d2018bd862cf539b | 0de41656e775e7ae0ddf5d6a774c703ae8e5aabf |
refs/heads/master | <file_sep>import exceptions
from product import Product
items = []
# add item to shop
def addItem(name, price, amount):
global items
product = Product(name, price, amount)
if product in items:
raise exceptions.ItemExists("Item {} already exists".format(name))
else:
items.append(product)
# show items
def showItems():
global items
# control if items exists
if len(items) == 0:
raise exceptions.ItemExists("List of items is empty.")
else:
return items
# show item
def showItem(name):
global items
# control all items step by step
for item in items:
# if the name is the same as we search
if(item.getName() == name):
return item
else:
continue
raise exceptions.ItemExists("Did not find item {}.".format(name))
# delete ONE item
def deleteItem(name):
global items
for item in items:
# if the name is the same as we search
if (item.getName() == name):
items.remove(item)
else:
continue
raise exceptions.ItemExists("Couldn't find item {}.".format(name))
# delete all
def deleteAll():
global items
items.clear()
# update item
def updateItem(name, price, amount):
global items
for item in items:
if (item.getName() == name):
price = item.setPrice(price)
amount = item.setAmount(amount)
else:
raise exceptions.ItemNotExists("Item {} can't be updated, because it does not exist.".format(name))
<file_sep>class ViewStock:
def showItems(self, items):
print("Stock items:")
print("============================")
print("name\t|\tprice\t|\tamount")
print("============================")
for item in items:
print(item.getName() + "\t|\t" +
str(item.getPrice()) + "\t\t|\t" +
str(item.getAmount()))
print("============================")
# show item
def showItem(self, item):
print("Stock item {}".format(item.getName()))
print("============================")
print("name\t|\tprice\t|\tamount")
print(item.getName()+"\t|\t"+
str(item.getPrice())+"\t\t|\t"+
str(item.getAmount()))
print("============================")
# no item error
def noItemError(self, name):
print("============================")
print("Stock does not have item {} in it".format(name))
print("============================")
# no item to update error
def noItemToUpdateError(self, name):
print("============================")
print("Couldn't update item {}".format(name))
print("============================")
# update item
def updateItem(self, name):
print("Stock item {} has been updated".format(name))
print("============================")
# no item to delete error
def noItemToDeleteError(self, name):
print("============================")
print("Coudln't delete item {}".format(name))
print("============================")
# delete item
def deleteItem(self, name):
print("Stock item {} has been deleted".format(name))
print("============================")
# delete all items
def deleteItems(self):
print("All stock items are deleted")
print("============================")
# delete all items error
def noItemsToDeleteError(self):
print("============================")
print("Couldn't delete all items")
print("============================")<file_sep>import stock_helpers
class StockModel:
# get shop data - [] of products
def __init__(self, stockItems):
self.stockItems = stockItems
# add item to stockItems
def addItem(self, name, price, amount):
stock_helpers.addItem(name, price, amount)
# show items
def showItems(self):
return stock_helpers.showItems()
# show item
def showItem(self, name):
return stock_helpers.showItem(name)
# delete item
def deleteItem(self, name):
stock_helpers.deleteItem(name)
# delete all items
def deleteAll(self):
stock_helpers.deleteAll()
# elemendi uuendamine
def updateItem(self, name, price, amount):
stock_helpers.updateItem(name, price, amount)<file_sep>import exceptions
class ControllerStock:
def __init__(self, model, view):
self.stock_model = model
self.view_stock = view
def addItem(self, name, price, amount):
self.stock_model.addItem(name, price, amount)
def showItems(self):
try:
items = self.stock_model.showItems()
self.view_stock.showItems(items)
except:
print("No items to show.")
def showItem(self, name):
try:
item = self.stock_model.showItem(name)
self.view_stock.showItem(item)
except:
self.view_stock.noItemError(name)
def deleteItem(self, name):
try:
self.stock_model.deleteItem(name)
self.view_stock.deleteItem(name)
except:
print("Failed to delete item.")
def deleteAll(self):
try:
self.stock_model.deleteAll()
self.view_stock.deleteAll()
except:
print("There are no items to show.")
# elemendi uuendamine
def updateItem(self, name, price, amount):
if (price <= 0):
print("Price must be higher than 0 EUR")
elif (amount <= 0):
print("Amount must be higher than 0")
try:
self.stock_model.updateItem(name, price, amount)
self.view_stock.updateItem()
except:
self.view_stock.noItemError(name)<file_sep>class ItemExists(Exception):
pass
class ItemNotExists(Exception):
pass<file_sep>from product import Product
from shop import Shop
from controller_shop import Controller
from model import Model
from view import View
from stock_model import StockModel
from stock import Stock
from controller_stock import ControllerStock
from view_stock import ViewStock
# create shop
shop = Controller(Model(Shop()), View())
# create stock
stock = ControllerStock(StockModel(Stock()), ViewStock())
stock.addItem("wine", 5.60, 5)
stock.addItem("car", 1200, 1)
stock.showItems()
shop.restockItem("car", 1200, 1)
shop.restockItem("wine", 5.60, 3)
shop.showItems()
stock.showItems()
<file_sep>import exceptions
class Controller:
def __init__(self, model, view):
self.model = model
self.view = view
def showItems(self):
try:
items = self.model.showItems()
self.view.showItems(items)
except:
print("No items to show.")
def showItem(self, name):
try:
item = self.model.showItem(name)
self.view.showItem(item)
except:
self.view.noItemError(name)
def deleteItem(self, name):
try:
self.model.deleteItem(name)
self.view.deleteItem(name)
except:
print("Failed to delete item.")
def deleteAll(self):
try:
self.model.deleteAll()
self.view.deleteAll()
except:
print("There are no items to show.")
# elemendi uuendamine
def updateItem(self, name, price, amount):
if (price <= 0):
print("Price must be higher than 0 EUR")
elif (amount <= 0):
print("Amount must be higher than 0")
try:
self.model.updateItem(name, price, amount)
self.view.updateItem()
except:
self.view.noItemError(name)
def restockItem(self, name, price, amount):
self.model.restockItem(name, price, amount)<file_sep>import exceptions
from product import Product
import stock_model
stockItems = []
# add item to items
def addItem(name, price, amount):
global stockItems
product = Product(name, price, amount)
if product in stockItems:
raise exceptions.ItemExists("Item {} already exists".format(name))
else:
stockItems.append(product)
# show items
def showItems():
global stockItems
# control if items exists
if len(stockItems) == 0:
raise exceptions.ItemExists("There are no items to show.")
else:
return stockItems
# show item
def showItem(name):
global stockItems
# control all items step by step
for item in stockItems:
# if the name is the same as we search
if(item.getName() == name):
return item
else:
continue
raise exceptions.ItemExists("Couldn't find item {}.".format(name))
# delete ONE item
def deleteItem(name):
global stockItems
for item in stockItems:
# if the name is the same as we search
if (item.getName() == name):
stockItems.remove(item)
else:
continue
raise exceptions.ItemExists("Did not find item {}.".format(name))
# delete all
def deleteAll():
global stockItems
stockItems.clear()
# update item
def updateItem(name, price, amount):
global stockItems
for item in stockItems:
if item.getName() == name:
price = item.setPrice(price)
amount = item.setAmount(amount)
else:
raise exceptions.ItemNotExists("Item {} can't be updated, because it does not exist.".format(name))
def transferItem(name, amount):
global stockItems
for item in stockItems:
if item.getName() == name:
if item.getAmount() == amount:
deleteItem(name)
else:
item.setAmount(item.getAmount() - amount)
| 775b6ac281ba2189a5b6ee62a18e5fca7facdd02 | [
"Python"
] | 8 | Python | hipponen03/mvc_pood | 26ba4a904a4037fec6495400d7028a9c6bdfb6aa | a79e1982bad29e0363dc69ce8c425e4a721f0016 |
refs/heads/master | <file_sep>(function($) {
// var bookmarks = {};
var methods = {
init: function() {
// Remove error message
// $(this).removeClass('error').empty();
// Prepare HTML5 audio player
var audioUrl = $(this).find('a:first').attr('href');
var $player = $('<audio controls="controls" preload="metadata">'
+ ' <source src="' + audioUrl + '" type="audio/mp3" />' // TODO support ogg
+ '</audio><br/>');
$player.bookmarks = {};
/* Append player to DOM and register callback that is fired every time
* the player's position updates
*/
// $player.appendTo(this); return;
$player.prependTo(this).bind('timeupdate', function() {
var currentTime = $player.get(0).currentTime;
$.each($player.bookmarks, function(index, element) {
if(index <= currentTime && !element.hasClass('current')) {
$(this).parent().find('dd, dt').removeClass('current');
element.addClass('current');
element.next().addClass('current');
}
});
});
/* Scan uFormat
* Extract and convert time of each bookmark
* Store in hash to minimise DOM traversal
*/
$(this).find('dl dt').each(function(el) {
$this = $(this);
var seconds = $this.noobPlayer('timeInSeconds',
$this.html().trim()
);
$player.bookmarks[seconds] = $this;
});
/* Bind a callback that seeks the audio player when a bookmark
* is clicked
*/
$(this).find('dl dt').bind('click', function() {
// copypasta
var seconds = $(this).noobPlayer('timeInSeconds',
$(this).html().trim()
);
$player.get(0).currentTime = seconds;
}).attr('title', 'Click to skip to this timecode');
},
/*
* Take a string in the format mm:ss and convert it to seconds
* @todo: intelligently parse hh:mm:ss as well
*/
timeInSeconds: function(time) {
var components = time.split(':');
var r = parseInt(components[1], 10) + parseInt(components[0], 10) * 60;
return parseInt(r, 10);
}
};
$.fn.noobPlayer = function(method) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.noobPlayer' );
}
};
})(jQuery);
<file_sep># Never Out Of Beta Audio Player
## Introduction
A jQuery plugin that adds a HTML5 audio player to an MP3 and provides a list of
bookmarks.
By providing a `<dl />` of timecodes and links, the player will highlight them
at the appropriate time. Each `<dt />` becomes a link that will seek the
`<audio />` player appropriately.
## Usage
The player expects HTML in the following format:
```html
<div class="bookmarked-audio">
<div class="metadata">
<h1 class="title">Friendly and possibly verbose title</h1>
<h2 class="timestamp">August 27, 2011</h2>
<div class="description">
<p>A description of the audio. Can contain as much or a little markup as required.</p>
</div>
</div>
<a class="source" href="http://www.example.com/source-audio-file.mp3">Download audio.</a>
<dl class="bookmarks">
<h3>Bookmarks in this podcast:</h3>
<dt>00:01</dt>
<dd>
<a class="link" href="http://www.google.com">Google</a>
</dd>
<dt>00:02</dt>
<dd>
<a class="link" href="http://www.bbc.co.uk">BBC</a>
</dd>
</dl>
</div>
```
Each `<dt />` should be a timestamp in the format mm:ss
The corresponding `<dd />` may contain any number of `<p />` and `<a />`
elements relevant to that bookmark.
To transform the player, simply call `$.noobPlayer()`, for example:
```javascript
$(document).ready(function() {
$('.bookmarked-audio').each(function(index, value) {
$(this).noobPlayer();
});
});
```
## Contributions
If you find any bugs or have a feature suggestion, please feel free to use the
GitHub tracker. In the spirit of things, you're encouraged to fork this
repository and do whatever you like with it.
Win the game by raising a pull request and having your changes accepted.
| a7ba5260fb49943cd79150d7ee2d243733bbf2a1 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | gavD/noob | 82fc934b262d819ff71b6b0235dc5ff099eed4fd | 089978a1e742b2c97cf1f31cc170574ed128572f |
refs/heads/master | <file_sep>from django.contrib import admin
from api.models import KillerManager, Victim, Link, ContractToVictim, Contract
# Register your models here.
admin.site.register(KillerManager)
admin.site.register(Victim)
admin.site.register(Link)
admin.site.register(ContractToVictim)
admin.site.register(Contract)<file_sep>from rest_framework import serializers
from api.models import User, Victim, Contract
class VictimSerializer(serializers.ModelSerializer):
class Meta:
model = Victim
fields = '__all__'
class ContractSerializer(serializers.ModelSerializer):
class Meta:
model = Contract
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'email']<file_sep>import datetime
from django.forms.models import model_to_dict
from django.contrib.auth.models import User
from django.db import models
from queue import PriorityQueue
class Contract(models.Model):
payed = models.BooleanField(default=False)
amount = models.IntegerField(null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
payment_time = models.DateTimeField(null=True)
def append_victim(self, victim):
ContractToVictim.objects.create(contract=self, victim=victim)
def get_victim_list(self):
contract_to_victims = ContractToVictim.objects.filter(contract=self)
victim_list = []
for x in contract_to_victims:
victim_list.append(x.victim)
return victim_list
def pay(self, amount):
res = {}
res['result'] = 'failed'
res['comment'] = ''
if (self.payed):
res['comment'] = 'already payed'
elif (self.amount == None):
res['comment'] = 'no amount yet'
return res
elif (amount == self.amount):
res['result'] = 'success'
self.payed = True
self.payment_time = datetime.datetime.now()
self.save()
elif (amount < self.amount):
res['comment'] = 'not enough credit'
elif (amount > self.amount):
res['comment'] = 'too much credit'
return res
class Victim(models.Model):
time_of_death = models.DateTimeField(null=True)
username = models.CharField(max_length=250, unique=True)
age = models.IntegerField()
difficulty = models.IntegerField()
priority = models.IntegerField()
def __str__(self):
return self.username
class ContractToVictim(models.Model):
contract = models.ForeignKey(Contract, on_delete=models.CASCADE)
victim = models.ForeignKey(Victim, on_delete=models.CASCADE)
class Link(models.Model):
pre_victim = models.ForeignKey(Victim, related_name='pre_victim', on_delete=models.CASCADE)
post_victim = models.ForeignKey(Victim, related_name='post_victim', on_delete=models.CASCADE)
class KillerManager(models.Model):
start_of_work_time = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.pk = 1
super(KillerManager, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
pass
@classmethod
def load(cls):
obj, created = cls.objects.get_or_create(pk=1)
return obj
def process_order(self, target_list, user):
contract = Contract.objects.create(user=user)
per_target_hours = {}
target_list = sorted(target_list, key=lambda x: int(x['priority']), reverse=True)
target_orm = []
for target in target_list:
try:
user = User.objects.get(username=target['username'])
res = {'result': 'failed', 'reason': 'cant process own client'}
return res
except models.ObjectDoesNotExist:
if (Victim.objects.filter(username=target['username']).first() != None):
return {'result': 'failed', 'reason': 'recheck the targets, it contains targets which where murdered or duplicates'}
new_victim = Victim.objects.create(username = target['username'], age = int(target['age']),
difficulty = int(target['difficulty']), priority = int(target['priority']))
target_orm.append(new_victim)
contract.append_victim(new_victim)
was_multiplied = {}
for target in target_list:
pre_victim = Victim.objects.filter(username=target['username']).first()
post_victim = Victim.objects.filter(username=target['link']).first()
if (target['username'] not in per_target_hours):
per_target_hours[target['username']] = int(target['difficulty'])
if (post_victim == None):
continue
if target['link'] not in per_target_hours:
per_target_hours[target['link']] = int(post_victim.difficulty)
if (target['link'] not in was_multiplied):
per_target_hours[target['link']] *= 2 if post_victim.age >= 40 else 1.5
was_multiplied[target['link']] = True
Link.objects.create(pre_victim=pre_victim,post_victim=post_victim)
# here I'm just using PriorityQueue to every time get target with most priority
targets_q = PriorityQueue()
for target in target_orm:
link = Link.objects.filter(post_victim = target).first()
if (link == None):
targets_q.put([int(target.priority), target])
order = []
while (not targets_q.empty()):
top_target = targets_q.get()
order.append(top_target[1].username)
top_target_links = Link.objects.filter(pre_victim=top_target[1])
for link in top_target_links:
post_victim = link.post_victim
link.delete()
try:
Link.objects.get(post_victim=post_victim)
except models.ObjectDoesNotExist:
targets_q.put([int(link.post_victim.priority), link.post_victim])
start_date = self.start_of_work_time
total_hours = 0
for x in order:
total_hours += per_target_hours[x]
current_time = self.start_of_work_time
current_time += datetime.timedelta(hours=per_target_hours[x])
killed_target = Victim.objects.get(username=x)
killed_target.time_of_death = current_time
killed_target.save()
self.start_of_work_time = current_time
self.save()
end_date = self.start_of_work_time
order_response = {
'start_date': start_date,
'end_date': end_date,
'order': order,
'hours': total_hours
}
amount = len(target_orm) * 10 * total_hours
contract.amount = amount
contract.save()
print (total_hours)
return order_response
<file_sep>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir code/
WORKDIR code/
COPY . /code/
RUN pip install -r requirements.txt
<file_sep>asgiref==3.2.10
Django==3.0.8
django-rest-framework==0.1.0
djangorestframework==3.11.0
djangorestframework-stubs==1.2.0
pytz==2020.1
sqlparse==0.3.1
xmltodict==0.12.0
<file_sep>Solution: basically I just keep PriorityQueue to every time extract most prior target, after I see is there any new targets can be added to PQ and then I repeat this steps while I have something in my PQ
Dockerfiles can be found in this repo
purchase_request/ - requires xml file with targets information, returns json in the statement if success otherwise failure reason
login/ - requires username & password and returns Token
logout/ - just logout
contract_list/ - returns list of all contract with the information about all victims
pay_contract/ - requires contract_Id & amount of money, returns success if correct amount of money otherwise failure reason
get_success_payments/ - get all the success payments<file_sep>from django.http import HttpResponse, JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveUpdateDestroyAPIView, ListAPIView
from api.models import KillerManager, Contract
from rest_framework.views import APIView
from api.serializers import ContractSerializer, VictimSerializer
from django.db import models
import json
import xmltodict
class SuccessPaymentListView(ListAPIView):
permission_classes = (IsAuthenticated, )
serializer_class = ContractSerializer
def get_queryset(self):
return Contract.objects.filter(payed=True).filter(user=self.request.user)
class PayContractView(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request):
json_body = json.loads(request.body)
contract_id = json_body['contract_id']
amount = json_body['amount']
try:
contract = Contract.objects.get(id = contract_id)
except models.ObjectDoesNotExist:
return JsonResponse({'result': 'contract_id does not exist'})
return JsonResponse(contract.pay(amount), safe=False)
class ContractListView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request):
user = request.user
res = []
queryset = Contract.objects.filter(user=user)
for contract in queryset:
cur_contract = ContractSerializer(contract).data
victims = contract.get_victim_list()
for victim in victims:
cur_contract[victim.username] = VictimSerializer(victim).data
res.append(cur_contract)
return JsonResponse(res, safe=False)
class PurchaseRequestHandler(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request):
xml_body = xmltodict.parse(request.body)
killer_manager = KillerManager.load()
res = killer_manager.process_order(xml_body['order']['targets']['target'], request.user)
return JsonResponse(res)<file_sep># Generated by Django 3.0.8 on 2020-07-19 16:23
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='contract',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='victim',
name='username',
field=models.CharField(max_length=250, unique=True),
),
]
<file_sep>from django.contrib import admin
from django.urls import path
from api.views import PurchaseRequestHandler, ContractListView, PayContractView, SuccessPaymentListView
from api.auth_view import logout, login
urlpatterns = [
path('purchase_request/', PurchaseRequestHandler.as_view()),
path('login/', login),
path('logout/', logout),
path('contract_list/', ContractListView.as_view()),
path('pay_contract/', PayContractView.as_view()),
path('get_success_payments/', SuccessPaymentListView.as_view())
]
| 56d766408d28df98ebc5321ec12ed37e1862634d | [
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 9 | Python | SeitzhanSanzhar/killer_crm | 3e3cbd892bbe813c0bc534aa4bcc99421d14a3b3 | 6430f25f9c486073734bbb5a81cb1a1944eee9c7 |
refs/heads/master | <repo_name>HarmonicTons/ControlledPromise<file_sep>/exemple.js
const ControlledPromise = require('./ControlledPromise');
//------------------------------------------------------------------------------
// DISTANT SERVER SIMULATION
//------------------------------------------------------------------------------
const N = 1000;
const data = [...Array(N)].map((v, i) => i);
const timeToAnswer = 1000;
function getData(top, skip) {
let reponse;
if (top >= 0 && skip >= 0) {
response = data.slice(skip, skip + top);
} else {
response = data;
}
return getSomething(response, timeToAnswer);
}
function getSomething(what, when, isError = false) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
let send = resolve;
if (isError) send = reject;
send(what);
}, when);
});
}
//------------------------------------------------------------------------------
// LOCAL REQUEST FUNCTION WITH PAGINATION
//------------------------------------------------------------------------------
function getDataWithPagination(pageSize) {
return new ControlledPromise(function(resolve, reject, sendPage, controller) {
let fullResponse = [];
let wait = false;
let pageIndex = 0;
controller.on('wait', function() {
wait = true;
});
controller.on('continue', function() {
if (wait) {
wait = false;
getPage();
}
});
function getPage() {
let top = pageSize;
let skip = pageSize * pageIndex;
getData(top, skip).then(page => {
if (page.length === 0) {
return resolve(fullResponse);
}
sendPage(page);
fullResponse.push(response);
pageIndex++;
// request next page
if (!wait) {
getPage();
}
});
}
getPage();
});
}
//------------------------------------------------------------------------------
// USE
//------------------------------------------------------------------------------
let pageSize = 100;
console.log('Requesting data...')
getDataWithPagination(pageSize)
.onPage(page => {
console.log('Got a page: ' + page);
console.log('Treating data...');
return doSomethingWithThePageThatTakesTime(2500)
.then(() => {
console.log('Data processed.')
});
})
.catch(error => {
console.error('Got an error: ' + error);
})
.then(fullResponse => {
console.log('Got everything.');
});
function doSomethingWithThePageThatTakesTime(howLong) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve()
}, howLong);
});
}
<file_sep>/ControlledPromise.js
/**
* ControlledPromise.js
* Define a new type of promise with the possibility of sending half responses (page) before the full response is availableToken
* Give the possibility to controle the promise by stoping and continuing requesting pages.
*
* Based on: https://gist.github.com/dmvaldman/12a7e46be6c3097aae31
*
* Created by troncin on 27/12/2016.
*/
'use strict';
// dependencies
var EventEmitter = require('events').EventEmitter;
EventEmitter.prototype._maxListeners = 100;
class ControlledPromise extends EventEmitter {
// Define a Promise with a function taking 4 parameters:
// a `resolve` function, `reject` function, a `sendPage` function and a controller
constructor(executor) {
super(); // Extend the EventEmitter super class
this.PromiseStatus = "pending";
this.PromiseValue;
// When `resolve` is called with a value, it emits a `resolve` event
// passing the value downstream. Similarly for `reject` and for `sendPage`
var resolve = (value) => {
this.PromiseStatus = "resolved";
this.PromiseValue = value;
this.emit('resolve', value)
};
var reject = (reason) => {
this.PromiseStatus = "rejected";
this.PromiseValue = reason;
this.emit('reject', reason)
};
var sendPage = (page) => {
this.emit('page', page)
};
if (executor) executor(resolve, reject, sendPage, this);
}
// Add a control to wait
wait() {
this.emit('wait');
}
// Add a control to continue
continue () {
this.emit('continue');
}
// Add downstream onPage listener
onPage(onPageHandler) {
// When a `onPage` event upstream is fired, execute the `onPageHandler`
// if the handler returns a promise the event wait is fired
// when the promise is resolved the event continue is fired
// if the promise is rejected pass the `reject` event downstream with the reason
// pass the full promise downstream so in 'p.onPage().then()' the 'then' is for 'p', not for 'p.onPage()'
if (onPageHandler) {
var onPage = (data) => {
this.wait();
Promise.resolve(onPageHandler.call(this, data))
.then(() => {
this.continue();
})
.catch(e => {
this.PromiseStatus = "rejected";
this.PromiseValue = data;
this.emit('reject', e);
});
};
this.on('page', onPage);
}
return this;
}
// Add downstream resolve and reject listeners
then(resolveHandler, rejectHandler) {
// If the promise has already been resolved
if (this.PromiseStatus === "resolved") {
if (resolveHandler) {
resolveHandler(this.PromiseValue);
}
}
// If the promise has already been rejected
else if (this.PromiseStatus === "rejected") {
if (rejectHandler) {
rejectHandler(this.PromiseValue);
}
}
// If the promise is pending
else if (this.PromiseStatus === "pending") {
var promise = new ControlledPromise();
// When a `resolve` event upstream is fired, execute the `resolveHandler`
// and pass the `resolve` event downstream with the result
if (resolveHandler) {
var resolve = (data) => {
var result = resolveHandler(data);
promise.PromiseStatus = "resolved";
promise.PromiseValue = result;
promise.emit('resolve', result);
};
this.on('resolve', resolve);
}
// When a `reject` event upstream is fired, execute the `rejectHandler`
// and pass the `resolve` event downstream with the result
if (rejectHandler) {
var reject = (data) => {
var result = rejectHandler(data);
// no longer rejected
promise.PromiseStatus = "resolved";
promise.PromiseValue = result;
promise.emit('resolve', result);
};
this.on('reject', reject);
} else {
// Downstream listeners always listen to `reject` so that an
// eventual `catch` can intercept them
this.on('reject', (data) => {
promise.PromiseStatus = "rejected";
promise.PromiseValue = data;
promise.emit('reject', data);
});
}
return promise;
}
}
// Handle an error from a rejected Promise upstream
catch (handler) {
// If the promise has already been rejected
if (this.PromiseStatus === "rejected") {
if (handler) {
return handler(this.PromiseValue);
}
}
// If the promise is pending
else if (this.PromiseStatus === "pending") {
this.on('reject', handler);
}
return this;
}
}
module.exports = ControlledPromise;
<file_sep>/README.md
# ControlledPromise
Create a type of promise with an 'onPage' control adapted to heavy requests GET with pagination.
```javascript
getSomething()
.catch(e => {
//
})
.then(r => {
//
});
```
Turns into:
```javascript
getSomethingWithPagination()
.onPage(p => {
//
});
.catch(e => {
//
})
.then(r => {
//
});
```
If the onPage handler returns a promise, the next page is not requested until this promise is resolved.
'.then()' is called only when every page has been requested and handled.
'.catch()' is called when the requester encounters an issue, when an exception is thrown in the onPage handler or when the onPage return a promise that is rejected.
See the exemple file to build a requester with this kind of promises.
| b9539eb520b13bdccfabb46aef02f074616b5d03 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | HarmonicTons/ControlledPromise | 733ab95347e6d8c63510e3bbc6b4502d2fefb1a9 | 4c11f0c2e8ec68b1afb5805fc203488fae142acf |
refs/heads/master | <file_sep>package RN;
public class Ativacao1 implements FuncaoDeAtivacao{
@Override
public double ativa(Neuronio neuronio) {
if (neuronio.calcularValor() > 0.0) {
neuronio.setValor(1.0);
return(1.0);
}
neuronio.setValor(0.0);
return(0.0);
}
}
<file_sep>package RN;
public interface FuncaoDeAtivacao {
public double ativa(Neuronio neuronio);
}
<file_sep>package tests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import QTEstatico.ArvoreDeEstados;
public class ArvoreTestes {
private static String getFileContents(File file) {
try(
BufferedReader br = new BufferedReader(new FileReader(file));
){
StringBuilder aux = new StringBuilder();
String lineRead;
while (true) {
lineRead = br.readLine();
if (lineRead==null) {
break;
}
aux.append(lineRead);
}
br.close();
return(aux.toString());
}catch(IOException e) {
e.printStackTrace();
}
return(null);
}
public static void t1() throws IOException {
ArvoreDeEstados av = new ArvoreDeEstados(2, 4, 4);
String path = "C:\\Users\\TotemSistemas\\Desktop\\paulopasta\\iaTestes";
File f = new File(path + File.separator + "arvore.txt");
av.saveToFile(f);
File f2 = new File(path + File.separator + "arvore2.txt");
ArvoreDeEstados av2 = ArvoreDeEstados.loadFromFile(f);
av2.saveToFile(f2);
String s1 = getFileContents(f);
String s2 = getFileContents(f2);
if (s1.equals(s2)) {
System.out.println("TRUE");
}else {
System.out.println("FALSE");
}
}
public static void main(String[] args) throws IOException {
t1();
}
}
<file_sep>package QTEstatico;
public class No {
private No[] filhos = null;
private double[] valor = null;
private int id = -1;
private static int idCounter = 0;
private void setId() {
this.id = idCounter;
idCounter++;
}
public No(No[] filhos) {
this.setId();
this.filhos = filhos;
}
public No(double[] valor) {
this.setId();
this.valor = valor;
}
public No[] getFilhos() {
return(filhos);
}
public double[] getValor() {
return(valor);
}
@Override
public String toString() {
return(Integer.toString(id));
}
}
<file_sep>package RN;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Blackbox {
List<List<Neuronio>> hiddenLayer;
private static final String nl = System.getProperty("line.separator");
protected Blackbox(int numeroDeLayers,int neuroniosPorLayer,List<Neuronio> outputLayer) {
hiddenLayer = new ArrayList<>();
for (int i=0;i<numeroDeLayers;i++) { // cria N layers
List<Neuronio> novaLista = new ArrayList<>(); // cria layer
hiddenLayer.add(novaLista); // associa layer a lista de layers
for (int j=0;j<neuroniosPorLayer;j++) { // seta cada layer seta X neuronios
Neuronio nr = new Neuronio(); // cria neuronio
novaLista.add(nr); // inclue neuronios em lista
}
}
for (int i=hiddenLayer.size()-1;i>=0;i--) { // iteracoes por cada nivel associa nivel i com nivel i-1
List<Neuronio> proximaLayer; //layer de neuronios que para cada neuronio associara conexoes
List<Neuronio> layerAtual = hiddenLayer.get(i);
if (i==hiddenLayer.size()-1) {
proximaLayer = outputLayer; // se for ultima lista de neuronios associa a outputlayer
System.out.println("Setando conexoes em layer :" + (i)+"->outputLayer");
}else {
proximaLayer = hiddenLayer.get(i+1); // se nao for ultima lista de neuronio associa essa lista de hidden layer a proxima lista
System.out.println("Setando conexoes em layer :" + (i)+"->"+(i+1));
}
for (int j=0;j<proximaLayer.size();j++){ // iteracao por cada neuronio
Neuronio neuronioSetado = proximaLayer.get(j); //neuronio selecionado
List<Arestas> conexoes = new ArrayList<>(); // conexoes que serao adicionadas ao neuronio
for (int k=0;k<layerAtual.size();k++) { // lista de neuronios para criar lista de arestas
Neuronio nr = layerAtual.get(k); // selecionado neuronio
Arestas ar = new Arestas(nr); // cria aresta associada a neuronio acima
conexoes.add(ar); // adiciona aresta a lista de arestas
}
neuronioSetado.setConexoes(conexoes); // seta lista de conexoes para neuronio selecionado
}
}
}
protected void ativarHiddenLayer(FuncaoDeAtivacao fda) {
//ativa layers em ordem 1,2...ultima
int numeroLayer = 0;
for (List<Neuronio> layer : hiddenLayer) {
//System.out.println("Ativando layer " + numeroLayer);
numeroLayer++;
for (Neuronio nr : layer) {
fda.ativa(nr);
}
}
}
public void conectarInputLayer(List<Neuronio> inputLayer) {
// TODO Auto-generated method stub
for (Neuronio hiddenLayerNr : hiddenLayer.get(0)) {
List<Arestas> conexoes = new ArrayList<>();
for (int k=0;k<inputLayer.size();k++) {
Neuronio inputLayerNr = inputLayer.get(k);
Arestas ar = new Arestas(inputLayerNr);
conexoes.add(ar);
}
hiddenLayerNr.setConexoes(conexoes);
}
}
protected void setArestasPesos(List<List<List<Double>>> arestaPesos) {
int numeroDeLayers = arestaPesos.size();
int neuroniosPorLayer = arestaPesos.get(0).size();
if (numeroDeLayers != hiddenLayer.size()) {
throw new IllegalArgumentException("numeroDeLayers != hiddenLayer.size()");
}
if (neuroniosPorLayer != hiddenLayer.get(0).size()) {
throw new IllegalArgumentException("neuroniosPorLayer != arestaPesos.get(0).size();");
}
for (int i=0;i<numeroDeLayers;i++) {
List<Neuronio> layerNeuronio = hiddenLayer.get(i);
List<List<Double>> arestaLayer = arestaPesos.get(i);
for (int j=0;j<neuroniosPorLayer;j++) {
Neuronio nr = layerNeuronio.get(j);
List<Arestas> arLista = nr.getArestas();
List<Double> arestaP = arestaLayer.get(j);
for (int k=0;k<arLista.size();k++) {
Arestas ar = arLista.get(k);
Double peso = arestaP.get(k);
ar.peso = peso;
}
nr.bias = arestaP.get(arestaP.size()-1);
}
}
}
@Override
public String toString() {
StringBuilder aux = new StringBuilder();
for (List<Neuronio> l : hiddenLayer) {
for (Neuronio nr : l) {
aux.append(nr.toString()).append(" ");
}
aux.append(nl);
}
return(aux.toString());
}
}
<file_sep>package undefinied;
public enum Acoes {
CIMA,
BAIXO,
ESQUERDA,
DIREITA;
private static Acoes[] listaAcoes;
static {
listaAcoes = new Acoes[4];
listaAcoes[0] = CIMA;
listaAcoes[1] = BAIXO;
listaAcoes[2] = ESQUERDA;
listaAcoes[3] = DIREITA;
}
public static Acoes getAcaoFromValor(int valor) {
return(listaAcoes[valor]);
}
public static Acoes[] getListaAcoes() {
return(listaAcoes);
}
@Override
public String toString() {
switch(this) {
case CIMA :
return("CIMA");
case BAIXO :
return("BAIXO");
case ESQUERDA :
return("ESQUERDA");
case DIREITA :
return("DIREITA");
}
return("???");
}
}
<file_sep>package RN;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RedeNeuralInterface {
private static final String nl = System.getProperty("line.separator");
List<Neuronio> inputLayer;
List<Neuronio> outputLayer;
Blackbox bb;
Double[] inputValores;
FuncaoDeAtivacao fda = null;
public RedeNeuralInterface(int tamanhoInputLayer,int tamanhoOutputLayer,int numeroDeHiddenLayers,int neuroniosPorLayerInHiddenaLayer,FuncaoDeAtivacao fda) {
outputLayer = new ArrayList<>();
for (int i=0;i<tamanhoOutputLayer;i++) { //cria outputLayer
Neuronio nr = new Neuronio();
outputLayer.add(nr);
}
bb = new Blackbox(numeroDeHiddenLayers, neuroniosPorLayerInHiddenaLayer, outputLayer);//cria blackbox
inputLayer = new ArrayList<>();//cria inputLayer
for (int i=0;i<tamanhoInputLayer;i++) {
Neuronio nr = new Neuronio();
inputLayer.add(nr);
}
bb.conectarInputLayer(inputLayer);
inputValores = null;
this.fda = fda;
}
public List<Double> getOutput() {
//seta valores da primeira layer
for (int i=0;i<inputLayer.size();i++) {
Neuronio inputNr = inputLayer.get(i);
double valor = inputNr.setValor(inputValores[i]);
}
//agora os neuronios da inputlayer estado ou ativos ou inativo
//com base na inputlayer eh possivel ativar a blackbox(hidden layer)
bb.ativarHiddenLayer(fda); // ativa hidden layer
List<Double> lastLayerOutput = new ArrayList<>();
for (int i=0;i<outputLayer.size();i++) {
Neuronio outputNr = outputLayer.get(i);
fda.ativa(outputNr);
Double valor = outputNr.getValor();
lastLayerOutput.add(valor);
}
return lastLayerOutput;
}
public void setInput(Double[] valoresInput) {
if (valoresInput.length != inputLayer.size()) {
throw new IllegalArgumentException("valores.size != inputLayer.size() => " + valoresInput.length +" != " + inputLayer.size());
}
inputValores = valoresInput;
}
@Override
public String toString() {
StringBuilder aux = new StringBuilder();
for (int i=0;i<inputLayer.size();i++) {
aux.append(inputLayer.get(i).getValor() + " ");
}
aux.append(nl);
aux.append(bb.toString());
for (int i=0;i<outputLayer.size();i++) {
aux.append(outputLayer.get(i) + " ");
}
return(aux.toString());
}
public void setOutputLayerArestas(List<List<Double>> pesos) {
int tamanhoOutputlayer = outputLayer.size();
int numeroDeArestas = outputLayer.get(0).getArestas().size();
if (pesos.size() != tamanhoOutputlayer) {
throw new IllegalArgumentException("tamanhoOutputlayer != outputLayer.size()");
}
if ((pesos.get(0).size()-1) != numeroDeArestas) {
throw new IllegalArgumentException("numeroDeArestas != (pesos.get(0).size()-1)");
}
List<Neuronio> layerNeuronio = outputLayer;
for (int i=0;i<tamanhoOutputlayer;i++) {
Neuronio nr = layerNeuronio.get(i);
List<Arestas> arLista = nr.getArestas();
List<Double> arestaP = pesos.get(i);
for (int j=0;j<arLista.size();j++) {
Arestas ar = arLista.get(j);
ar.peso = arestaP.get(j);
}
nr.bias = arestaP.get(arestaP.size()-1);
}
}
public void iniciarBackpropagation(List<Double> erro) {
int outputlayerTam = outputLayer.size();
if (erro.size()!=outputlayerTam) {
throw new IllegalArgumentException();
}
}
public static void main(String args[]) {
int tamanhoInputLayer = 2;
int tamanhoOutputLayer = 2;
int tamanhoHiddenLayer = 1;
int numeroNeuronioPorLayer = 2;
FuncaoDeAtivacao fda = new Ativacao2();
RedeNeuralInterface rni = new RedeNeuralInterface(tamanhoInputLayer, tamanhoOutputLayer, tamanhoHiddenLayer, numeroNeuronioPorLayer, fda);
List<List<List<Double>>> pesosArestas = new ArrayList<>();
List<List<Double>> layer1 = new ArrayList<>();
pesosArestas.add(layer1);
List<Double> pesos1 = new ArrayList<>();
List<Double> pesos2 = new ArrayList<>();
layer1.add(pesos1);
layer1.add(pesos2);
pesos1.add(0.15);
pesos1.add(0.20);
pesos1.add(0.35);
pesos2.add(0.25);
pesos2.add(0.30);
pesos2.add(0.35);
List<List<Double>> outputPesos = new ArrayList<>();
List<Double> pesoOutput1 = new ArrayList<>();
pesoOutput1.add(0.40);
pesoOutput1.add(0.45);
pesoOutput1.add(0.60);
List<Double> pesoOutput2 = new ArrayList<>();
pesoOutput2.add(0.50);
pesoOutput2.add(0.55);
pesoOutput2.add(0.60);
outputPesos.add(pesoOutput1);
outputPesos.add(pesoOutput2);
rni.setOutputLayerArestas(outputPesos);
Double[] valoresInput = { 0.05 , 0.1 };
rni.setInput(valoresInput);
rni.bb.setArestasPesos(pesosArestas);
List<Double> ret = rni.getOutput();
for (Double v : ret) {
System.out.println(" " + v);
}
System.out.println("toString:"+nl+rni.toString());
}
}
<file_sep>package undefinied;
public enum ValorTile {
NADA(0),
NADAMOVIDO(1),
RECOMPENSA(2),
MORTE(3),
PAREDE(4),
VITORIA(5);
private int valor;
private static ValorTile[] lista;
static {
lista = new ValorTile[6];
lista[0] = NADA;
lista[1] = NADAMOVIDO;
lista[2] = RECOMPENSA;
lista[3] = MORTE;
lista[4] = PAREDE;
lista[5] = VITORIA;
}
private ValorTile(int v) {
this.valor = v;
}
public int getValor() {
return(valor);
}
public static ValorTile getTileFromValor(int valor) {
return(lista[valor]);
}
public static ValorTile[][] transformToValorTileMatrix(int[][] entrada){
int linha = entrada.length;
int coluna = entrada[0].length;
ValorTile[][] ret = new ValorTile[linha][coluna];
for (int i=0;i<linha;i++) {
for (int j=0;j<coluna;j++) {
ret[i][j] = getTileFromValor(entrada[i][j]);
}
}
return(ret);
}
public static ValorTile[] getListaValorTile() {
return(lista);
}
}
<file_sep>package tests;
import java.io.File;
import java.io.RandomAccessFile;
import QTEstatico.ArvoreDeEstados;
import QTEstatico.QTPlayer;
import undefinied.Acoes;
import undefinied.ValorTile;
public class QTTeste {
private final static String nl = System.getProperty("line.separator");
private static final String path = "dados";
public static void treinar(File arvoreInput,File arvoreOutput,File mapaFile) {
long start = System.nanoTime();
int numeroDeTestes = 100000;
int testesPorAmostra = numeroDeTestes/100;
StringBuilder aux = new StringBuilder();
ArvoreDeEstados arvoreUsada = null;
if (arvoreInput != null) {
arvoreUsada = ArvoreDeEstados.loadFromFile(arvoreInput);
}else {
arvoreUsada = new ArvoreDeEstados( Acoes.getListaAcoes().length, ValorTile.getListaValorTile().length, Acoes.getListaAcoes().length);
}
int contadorTeste = 0;
aux.append("teste pontuacao taxaAleatoria").append(nl);
for (int i=0;i<numeroDeTestes;i++) {
QTPlayer qt = new QTPlayer();
//double taxaAleatoria = (1.0 - (i+0.00)/(numeroDeTestes+0.0));
double taxaAleatoria = 0.0;
//System.out.println("taxaAleatoria:"+taxaAleatoria);
qt.init(arvoreUsada,mapaFile,taxaAleatoria,false);
arvoreUsada = qt.getArvore();
if (i%testesPorAmostra==0) {
//aux.append(contadorTeste).append(' ').append(qt.getPontuacao()).append(' ').append(Double.toString(taxaAleatoria*100).replaceFirst("[.]", ",")).append(nl);
aux.append(contadorTeste).append(' ').append(qt.getPontuacao()).append(nl);
contadorTeste++;
}
if (i==(numeroDeTestes-1)) {
arvoreUsada.saveToFile(arvoreOutput);
}
}
try(
RandomAccessFile raf = new RandomAccessFile(new File(path + File.separator + "testesOutput" + mapaFile.getName()), "rw");
){
raf.setLength(0);
raf.writeBytes(aux.toString());
}catch(Exception e) {
e.printStackTrace();
}
double elapsed = (0.0 + System.nanoTime() - start)/(Math.pow(10, 9));
System.out.println(String.format("%.4f", elapsed));
}
public static void t2(File arvoreFile , File mapaFile) {
long start = System.nanoTime();
String path = "dados";
int numeroDeTestes = 1;
ArvoreDeEstados arvoreUsada = ArvoreDeEstados.loadFromFile(arvoreFile);
for (int i=0;i<numeroDeTestes;i++) {
QTPlayer qt = new QTPlayer();
qt.init(arvoreUsada,mapaFile,0.0,true);
arvoreUsada = qt.getArvore();
System.out.println("Pontuacao:"+qt.getPontuacao());
}
double elapsed = (0.0 + System.nanoTime() - start)/(Math.pow(10, 9));
System.out.println(String.format("%.4f", elapsed));
}
public static void main(String[] args) {
final File mapaFile = new File(path + File.separator + "mapa10x10.txt");
final File mapaFile2 = new File(path + File.separator + "mapa10x10_v2.txt");
final File mapaFile3 = new File(path + File.separator + "mapa10x10_v3.txt");
final File arvore1_ = new File(path + File.separator + "arvore1.txt");
final File arvore2_ = new File(path + File.separator + "arvore2.txt");
//File arvoreInput = new File(path + File.separator + "arvoreTeste.txt");
treinar(arvore1_,arvore1_,mapaFile3);
t2(arvore1_,mapaFile3);
}
}
<file_sep>package undefinied;
public class Estados {
}
| d6778e2a7f1b0f116faa77c0615e3d8570561034 | [
"Java"
] | 10 | Java | pauloht/QT_Teste | 835e1e88f88268a28de75d5b34c5715db32fccf0 | b1acc9a45b3aa996629505d55ad9349e93138ff4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.