branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>Hylan129/WEB_TRANSFER_DOCUMENTS<file_sep>/main.py # -*- coding: utf8 -*- from bottle import run, route, static_file,request,template,default_app,response,redirect import random,Email_Custom from collections import defaultdict import csv,datetime,bottle,traceback user_information = {} paths = {} with open('data/data_sources.csv','r') as f: content = csv.reader(f) for items in content: paths[items[0].strip()] =items[1:] @route('/counter') def counter(): try: count = int(request.cookies.get('counter_test', '0')) count += 1 response.set_cookie('counter_test', str(count)) return 'You visited this page %d times' % count except : traceback.print_exc(file=open('error.txt','a')) @route('/') def index(): return static_file('index.html', root='./webpage') @route('/feedback/<path>') def feedback(path): return static_file(path, root='./webpage/feedback') @route('/<path>') def webpage_root(path): return static_file(path, root='./webpage') @route('/download/<path>') def webpage(path): return static_file(path, root='./download',download=path) @route('/images/<path>') def images(path): return static_file(path, root='./webpage/images') @route('/assets/css/<path>') def css1(path): return static_file(path, root='./webpage/assets/css') @route('/assets/js/<path>') def js2(path): return static_file(path, root='./webpage/assets/js') @route('/assets/fonts/<path>') def fonts(path): return static_file(path, root='./webpage/assets/fonts') @route('/robots') def submit_get_mails(): try: mail_address = request.query.email.strip() user_ip = request.remote_addr #response.set_cookie('param',mail_address,path='/documents') user_information[user_ip] = mail_address with open('records.csv','a',newline='') as code: m = csv.writer(code,dialect='excel') m.writerow([datetime.datetime.now().strftime('%Y-%m-%d'),datetime.datetime.now().strftime('%H:%M:%S'),user_ip,mail_address]) return static_file('document_choose.html', root='./webpage') except Exception as e: traceback.print_exc(file=open('error.txt','a')) return 'something wrong' @route('/documents') def submit_get_document_number(): document_number = request.query.theone user_ip = request.remote_addr try: #count = request.cookies.get('param') thepaths = paths[document_number] if thepaths: flag = Email_Custom.sendEmail(mail_address, authorization_code,thepaths[0].strip(),open(thepaths[2],'rb').read(),user_information[user_ip],thepaths[1]) if flag: return '<p style=\"width:100%;font-size: 45px;text-align:center;margin-top:20%;\"><p style=\"color: crimson;\">'+user_information[user_ip]+'</p>你好,资料已发送,请注意查收!</p>' else: return '<p style=\"width:100%;font-size: 45px;text-align: center; margin-top: 20%;color: crimson;\">邮箱地址异常,发送失败;请检查邮箱地址后重试!</p>' except Exception as e: traceback.print_exc(file=open('error.txt','a')) with open('error.txt','a') as code: code.write("错误信息:"+str(e)+',来访地址:'+user_ip+ "\n") return '<p style=\"width:100%;font-size: 45px;text-align:center;margin-top:20%;color: crimson;\">发送失败。请清除缓存后重试!<br><br>如多次重试失败,请联系微信:hylan129</p>' #return redirect('http://www.baidu.com') #重定向外链 @route('/try') def submit_try(): return "<html><img src=\"images/slide05.jpg\" /></html>" if __name__ == '__main__': run(host="0.0.0.0", port=8129,debug=False,reloader=True) else: application = default_app() <file_sep>/README.md # Web应用部署(bottle+uwsgi+nginx) 项目实现功能文档自助发送,自助提取;熟悉web应用部署操作; 开发过程说明: 使用bottle框架开发了一个文档软件自助提取的网站。代码开发完成后,本地测试没有问题,但上线之后非常不稳定,网站使用一段时间后自己卡死了(多个访问造成进程阻塞)。查找原因发现,bottle自建web应用不适合用于生产环境,稳定性比较差。使用uwsgi+nginx,web应用会更加安全稳定,性能更优。 至于为什么用bottle,是因为手头有个之前自己开发的现成网站代码,当时就是用bottle写的,懒得改;Python版本是3.6.8;服务器是花98块买的阿里云ecs,买来玩的。 由于以前没用过uwsgi/nginx,而且网上关于bottle框架下应用uwsgi/nginx部署的资源很少(确实少,中文英文的都少),资料看起来非常费劲,研究了两天总算把这事理了大概,跑起来了。 项目详细情况如下: ##0. 系统环境及软件版本说明 ``` [root@aliyun ~]# uname -a Linux aliyun 4.18.0-147.5.1.el8_1.x86_64 #1 SMP Wed Feb 5 02:00:39 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux [root@aliyun ~]# python3 --version Python 3.6.8 [root@aliyun ~]# uwsgi --version 192.168.127.12 [root@aliyun ~]# nginx -v nginx version: nginx/1.14.1 [root@aliyun ~]# pip3 show bottle Name: bottle Version: 0.12.18 Summary: Fast and simple WSGI-framework for small web-applications. Home-page: http://bottlepy.org/ Author: <NAME> Author-email: <EMAIL> License: MIT Location: /usr/local/lib/python3.6/site-packages Requires: [root@aliyun ~]# cd /var/www/html/WEB_TRANSFER_DOCUMENTS/ [root@aliyun WEB_TRANSFER_DOCUMENTS]# ls 50x.html download error.txt __pycache__ reload test.py webpage data Email_Custom.py main.py records.csv run.log uwsgi.ini [root@aliyun WEB_TRANSFER_DOCUMENTS]# ``` ##1. uwsgi配置文件:uwsgi.ini 文件路径:/var/www/html/WEB_TRANSFER_DOCUMENTS log路径:/var/www/html/WEB_TRANSFER_DOCUMENTS/run.log ``` [uwsgi] chdir = /var/www/html/WEB_TRANSFER_DOCUMENTS socket =0.0.0.0:8129 master = true worker = 4 wsgi-file=main.py callable=application enable-threads = true py-autoreload= 1 processes = 8 threads =1 daemonize = /var/www/html/WEB_TRANSFER_DOCUMENTS/run.log ``` ##2. Nginx 配置文件:nginx.conf 文件路径:/etc/nginx/nginx.conf access log路径:/var/log/nginx/access.log error log路径:/var/log/nginx/error.log ``` # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80 default_server; listen [::]:80 default_server; server_name www.creditlife.top; root /var/www/html/WEB_TRANSFER_DOCUMENTS; proxy_connect_timeout 600; proxy_read_timeout 600; proxy_send_timeout 600; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { uwsgi_pass 0.0.0.0:8129; include uwsgi_params; uwsgi_send_timeout 600; uwsgi_connect_timeout 600; uwsgi_read_timeout 600; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } } ``` ##3. bottle app 主程序代码:main.py ``` # -*- coding: utf8 -*- from bottle import run, route, static_file,request,template,default_app,response,redirect import random,Email_Custom from collections import defaultdict import csv,datetime,bottle,traceback user_information = {} paths = {} with open('data/data_sources.csv','r') as f: content = csv.reader(f) for items in content: paths[items[0].strip()] =items[1:] @route('/counter') def counter(): try: count = int(request.cookies.get('counter_test', '0')) count += 1 response.set_cookie('counter_test', str(count)) return 'You visited this page %d times' % count except : traceback.print_exc(file=open('error.txt','a')) @route('/') def index(): return static_file('index.html', root='./webpage') @route('/feedback/<path>') def feedback(path): return static_file(path, root='./webpage/feedback') @route('/<path>') def webpage_root(path): return static_file(path, root='./webpage') @route('/download/<path>') def download_display(path): return static_file(path, root='./download',download=path) @route('/images/<path>') def images(path): return static_file(path, root='./webpage/images') @route('/assets/css/<path>') def css_display(path): return static_file(path, root='./webpage/assets/css') @route('/assets/js/<path>') def js_display(path): return static_file(path, root='./webpage/assets/js') @route('/assets/fonts/<path>') def fonts_display(path): return static_file(path, root='./webpage/assets/fonts') @route('/robots') def submit_get_mails(): try: mail_address = request.query.email.strip() user_ip = request.remote_addr #response.set_cookie('param',mail_address,path='/documents') user_information[user_ip] = mail_address with open('records.csv','a',newline='') as code: m = csv.writer(code,dialect='excel') m.writerow([datetime.datetime.now().strftime('%Y-%m-%d'),datetime.datetime.now().strftime('%H:%M:%S'),user_ip,mail_address]) return static_file('document_choose.html', root='./webpage') except Exception as e: traceback.print_exc(file=open('error.txt','a')) return 'something wrong' @route('/documents') def submit_get_document_number(): document_number = request.query.theone user_ip = request.remote_addr try: #count = request.cookies.get('param') thepaths = paths[document_number] if thepaths: flag = Email_Custom.sendEmail(mail_address,authorization——code,thepaths[0].strip(),open(thepaths[2],'rb').read(),user_information[user_ip],thepaths[1]) #前两个参数为个人邮箱地址和授权码,需自行补充添加。 if flag: return '<p style=\"width:100%;font-size: 45px;text-align:center;margin-top:20%;\"><p style=\"color: crimson;\">'+user_information[user_ip]+'</p>你好,资料已发送,请注意查收!</p>' else: return '<p style=\"width:100%;font-size: 45px;text-align: center; margin-top: 20%;color: crimson;\">邮箱地址异常,发送失败;请检查邮箱地址后重试!</p>' except Exception as e: traceback.print_exc(file=open('error.txt','a')) with open('error.txt','a') as code: code.write("错误信息:"+str(e)+',来访地址:'+user_ip+ "\n") return '<p style=\"width:100%;font-size: 45px;text-align:center;margin-top:20%;color: crimson;\">发送失败。请清除缓存后重试!<br><br>如多次重试失败,请联系微信:hylan129</p>' @route('/try') def submit_try(): return "<html><img src=\"images/slide05.jpg\" /></html>" if __name__ == '__main__': run(host="0.0.0.0", port=8129,debug=False,reloader=True) else: application = default_app() ``` ##4. 部署相关说明 ``` 1、bottle app 主程序中必须包含application函数,'application'名字固定,否则uwsgi 启动时会出现no app loaded 错误; 2、uwsgin配置时callable=application 不能少;配置端口时采用socket,socket = 0.0.0.0:8129;如果使用http,则是将uwsgi直接当作服务器使用,没法连接nginx; 3、uwsgi配置中参数daemonize建议配置,daemonize = /var/www/html/WEB_TRANSFER_DOCUMENTS/run.log;uwsgi程序后置后台运行同时指定日志路径,方便查看异常错误; 4、uwsgi参数众多,可以使用uwsgi -h命令查看相关帮助文档。 5、nginx配置文件路径不要改(建议直接在原始配置文件中更改),nginx.conf文件在nginx安装后会自动生成,而且安装完成后会提示配置文件的路径。 6、nginx配置文件中,只需要更新listen、server_name、root、uwsgi_pass、include参数即可。其他参数根据需要以及出错问题再补充;(因为我的程序后台耗时比较久,出现过超时错误,后来我增加了多个timeout参数) 7、命令运行顺序:uwsgi --ini uwsgi.ini & nginx,或者逐个命令运行; 8、使用uwsgi服务,不需要单独启动main.py(python main.py不需要); 9、部署过程中可以查看log确认具体问题,uwsgi log:/var/www/html/WEB_TRANSFER_DOCUMENTS/run.log;nginx log:/var/log/nginx/error.log; 10、web应用部署涉及使用两个端口,nginx配置的是外网访问http端口,即listen端口号;uwsgi 配置端口为uwsgi与nginx socket连接端口,即uwsgi参数:socket=0.0.0.0:8129;nginx参数:uwsgi_pass 0.0.0.0:8129;bottle app main.py中配置端口与uwsgin端口号相同,即run(host="0.0.0.0", port=8129); ``` ##5. web应用源码 登录[creditlife.top](www.creditlife.top)网站提供邮箱地址即可下载获取。 *** *** 参照文章:[1:django为什么用uwsgi+nginx](https://blog.csdn.net/qq_35318838/article/details/61198183?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduend~default-1-61198183.nonecase&utm_term=uwsgi%20和直接运行区别&spm=1000.2123.3001.4430) ;[2:python web服务部署](https://blog.csdn.net/Together_CZ/article/details/105518419) <file_sep>/uwsgi.ini [uwsgi] chdir = /var/www/html/WEB_TRANSFER_DOCUMENTS socket =0.0.0.0:8129 master = true worker = 4 wsgi-file=main.py callable=application enable-threads = true py-autoreload= 1 processes = 8 threads =1 daemonize = /var/www/html/WEB_TRANSFER_DOCUMENTS/run.log <file_sep>/Email_Custom.py #-*- coding : utf-8 -*- import smtplib,re from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.utils import formataddr from email.mime.application import MIMEApplication #检查邮件地址合法性 def verifyEmail(email): pattern = r'^[\.a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$' if re.match(pattern,email) is not None: return True else: return False #添加邮件附件 def uploadPdf(path): """ 参数说明:path为本地图片路径,id_name为邮件附件呈现的附件名称,自己指定。 """ file_content = open(path,'rb') pdf_part = MIMEApplication(file_content.read()) file_content.close() pdf_part.add_header('Content-Disposition', 'attachment', filename=path.split('/')[-1]) #msgImage["Content-Disposition"] = 'attachment; filename="' + id_name +'.' + path.strip().split('.')[-1] + '"' return pdf_part #添加图片编号 def uploadPicture(path,id_name): # 指定图片为当前目录 fp = open(path, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # 定义图片 ID,在 HTML 文本中引用 msgImage.add_header('Content-ID', '<'+id_name+'>') msgImage["Content-Disposition"] = 'attachment; filename="' + id_name +'.jpeg"' return msgImage #发送邮件 def sendEmail(email,password,email_subject,content_page,towhos,attach_paths): # 第三方 SMTP 服务 mail_host="smtp.163.com" #设置服务器 mail_user= email #用户名 mail_pass= <PASSWORD> #口令 message = MIMEMultipart() sender = email receivers = formataddr(['上帝',towhos]) # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 message['From'] = formataddr(['早鸟有饭','<EMAIL>']) message['To'] = receivers #添加设置邮件主题 subject = email_subject message['Subject'] = Header(subject, 'utf-8') #添加设置邮件正文,网页表单。 message.attach(MIMEText(content_page, 'html', 'utf-8')) message.attach(uploadPicture('webpage/feedback/thanksforyourpraise.jpeg','praise')) message.attach(uploadPdf(attach_paths)) #邮件发送 smtpObj = smtplib.SMTP_SSL(mail_host,465) #smtpObj.connect(mail_host, 465) #qq:465,163:25 smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) return True
c50e914875153570965ff009b609573fab6e3025
[ "Markdown", "Python", "INI" ]
4
Python
Hylan129/WEB_TRANSFER_DOCUMENTS
cab01607a8d502d87bb9efa217baacb259e10684
0005f88f3c31875c8f420145ac17988af44625c9
refs/heads/master
<repo_name>KevMamba/Data-Analytics<file_sep>/README.md # Data-Analytics UE17CS322 Prof. Nagegowda KS Data Analytics Assignments Team: 1) <NAME> - PES1201700659 2) <NAME> - PES1201700294 3) <NAME> - PES1201700794 <file_sep>/Assignment 1/Graphs.py import numpy as np import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns from pylab import * # For global titile using fig.suptitle import os print(os.listdir("C:/Users/kevin/Desktop/PES University/Junior Year/DA/Assignment 1")) # Reading 2009 candidate dataset LS09Cand = pd.read_csv('C:/Users/kevin/Desktop/PES University/Junior Year/DA/Assignment 1/LS2009Candidate.csv') print(LS09Cand.shape) LS09Cand.head() # Reading 2014 candidate dataset LS14Cand = pd.read_csv('../input/LS2014Candidate.csv') print(LS14Cand.shape) LS14Cand.head() #Merging 2009 & 2014 Candidate datasets on one another LS0914Cand = pd.concat([LS09Cand,LS14Cand]) print(LS0914Cand.shape) LS0914Cand.head() #Checking all political parties abbreviation so that we can make it conscise by including alliance & significant parties LS0914Cand['Party Abbreviation'].unique() #Introducing Alliance column for optimized substitution of Winning Party Abbreviation column LS0914Cand['Alliance']=LS0914Cand['Party Abbreviation'] LS0914Cand['Alliance']=LS0914Cand['Alliance'].replace(to_replace=['INC','NCP', 'RJD', 'DMK', 'IUML', 'JMM','JD(s)','KC(M)','RLD','RSP','CMP(J)','KC(J)','PPI','MD'],value='UPA') LS0914Cand['Alliance']=LS0914Cand['Alliance'].replace(to_replace=['BJP','SS', 'LJP', 'SAD', 'RLSP', 'AD','PMK','NPP','AINRC','NPF','RPI(A)','BPF','JD(U)','SDF','NDPP','MNF','RIDALOS','KMDK','IJK','PNK','JSP','GJM','MGP','GFP','GVP','AJSU','IPFT','MPP','KPP','JKPC','KC(T)','BDJS','AGP','JSS','PPA','UDP','HSPDP','PSP','JRS','KVC','PNP','SBSP','KC(N)','PDF','MDPF'],value='NDA') LS0914Cand['Alliance']=LS0914Cand['Alliance'].replace(to_replace=['YSRCP','AAAP', 'IND', 'AIUDF', 'BLSP', 'JKPDP', 'JD(S)', 'INLD', 'CPI', 'AIMIM', 'KEC(M)','SWP', 'NPEP', 'JKN', 'AIFB', 'MUL', 'AUDF', 'BOPF', 'BVA', 'HJCBL', 'JVM','MDMK'],value='Others') LS0914Cand # Winning seats distribution by Major Political Parties & Alliances for 2009 & 2014 SeatsWin = LS0914Cand[(LS0914Cand.Position==1)].groupby(['Alliance','Year'])['Position'].sum().reset_index().pivot(index='Alliance', columns='Year',values='Position').reset_index().fillna(0).sort_values([2014,2009], ascending=False).reset_index(drop = True) # Removing Index Name #SeatsWin = pd.DataFrame(data=SeatsWin.values,columns=['Alliance','2009','2014']) print(SeatsWin['Alliance'].unique()) SeatsWin #plotting pie chart plt.pie(SeatsWin[2009]) #plt.show() # add a circle at the center my_circle=plt.Circle( (0,0), 0.7, color='white') #fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot # (or if you have an existing figure) fig = plt.gcf() #gcf means get current figure ax = fig.gca() # gca means get current axis ax.add_patch(my_circle) label = ax.annotate("2009", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.show() # White circle with label at center fig, ax = plt.subplots() ax = fig.add_subplot(111) x = 0 y = 0 circle = plt.Circle((x, y), radius=1,color='red') ax.add_patch(circle) label = ax.annotate("2009", xy=(x, y), fontsize=30, ha="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.show() # Seats won by Alliances and Major Political Parties colors = ("orange", "green", "red", "cyan", "brown", "grey", "blue", "indigo", "beige", "yellow","cadetblue","khaki") plt.figure(figsize=(20,8)) plt.subplot(1,2,1) plt.pie(SeatsWin[2009], labels=SeatsWin['Alliance'], colors=colors,autopct='%1.1f%%') my_circle1=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() #gcf means get current figure fig.suptitle("Winning Percentages by Alliances and Major Political Parties", fontsize=14) # Adding supertitle with pyplot import ax = fig.gca() # gca means get current axis ax.add_patch(my_circle1) label = ax.annotate("2009", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() #plt.figure(figsize=(20,10)) plt.subplot(1,2,2) plt.pie(SeatsWin[2014], labels=SeatsWin['Alliance'], colors=colors,autopct='%1.1f%%') my_circle2=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() #gcf means get current figure ax = fig.gca() # gca means get current axis ax.add_patch(my_circle2) label = ax.annotate("2014", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() ## function to add value label to plot def annot_plot(ax,w,h): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) for p in ax.patches: ax.annotate('{}'.format(p.get_height()), (p.get_x()+w, p.get_height()+h)) CatWin = LS0914Cand[(LS0914Cand.Position==1)].groupby(['Candidate Category','Year'])['Position'].sum().reset_index().pivot(index='Candidate Category', columns='Year',values='Position').reset_index().fillna(0).sort_values([2014,2009], ascending=False).reset_index(drop = True) #print(CatWin['Candidate Category'].unique()) #CatWin nx = CatWin.plot(kind='bar', title ="Winning Category", figsize=(15, 10), legend=True, fontsize=12) nx.set_xlabel("Candidate Category", fontsize=12) nx.set_ylabel("Seats Won", fontsize=12) # Modifying Axis Labels labels = [item.get_text() for item in nx.get_xticklabels()] labels[0] = 'GEN' labels[1]= 'SC' labels[2]='ST' nx.set_xticklabels(labels) annot_plot(nx,0.05,5) CatAlliance09 = LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)].groupby(['Alliance','Candidate Category'])['Position'].sum().unstack().reset_index().fillna(0) CatAlliance14 = LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)].groupby(['Alliance','Candidate Category'])['Position'].sum().unstack().reset_index().fillna(0) nx = CatAlliance09.plot(kind='bar', title ="2009 Winning Category", figsize=(15, 10), legend=True, fontsize=12) nx.set_xlabel("Candidate Category", fontsize=12) nx.set_ylabel("Seats Won", fontsize=12) # Modifying Axis Labels labels = [item.get_text() for item in nx.get_xticklabels()] labels[0:11] = CatAlliance09['Alliance'] #labels[1]= 'SC' #labels[2]='ST' nx.set_xticklabels(labels) annot_plot(nx,0.05,5) nx = CatAlliance14.plot(kind='bar', title ="2014 Winning Category", figsize=(15, 10), legend=True, fontsize=12) nx.set_xlabel("Candidate Category", fontsize=12) nx.set_ylabel("Seats Won", fontsize=12) # Modifying Axis Labels labels = [item.get_text() for item in nx.get_xticklabels()] labels[0:11] = CatAlliance14['Alliance'] #labels[1]= 'SC' #labels[2]='ST' nx.set_xticklabels(labels) annot_plot(nx,0.05,5) plt.style.use('seaborn-deep') Age09=LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)]['Candidate Age'].tolist() Age14=LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)]['Candidate Age'].tolist() bins = np.linspace(20, 90, 10) plt.hist([Age09, Age14], bins, label=['2009', '2014']) plt.legend(loc='upper right') plt.xlabel('Age Of winners in years') plt.ylabel('Total Number of winners') plt.title('Distribution of Age of the winners') plt.show() # Age Distribution of Winning Candidates in 2009 & 2014 for NDA & UPA in India Elections plt.figure(figsize=(20,8)) plt.subplot(1,2,1) plt.style.use('seaborn-deep') Age09UPA=LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)& (LS0914Cand.Alliance=='UPA')]['Candidate Age'].tolist() Age14UPA=LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)& (LS0914Cand.Alliance=='UPA')]['Candidate Age'].tolist() Age09NDA=LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)& (LS0914Cand.Alliance=='NDA')]['Candidate Age'].tolist() Age14NDA=LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)& (LS0914Cand.Alliance=='NDA')]['Candidate Age'].tolist() bins = np.linspace(20, 90, 10) plt.hist([Age09NDA, Age14NDA], bins, label=['2009', '2014']) plt.legend(loc='upper right') plt.xlabel('Age Of NDA winners in years') plt.ylabel('Total Number of NDA winners') plt.title('Distribution of Age of NDA winners') plt.subplot(1,2,2) bins = np.linspace(20, 90, 10) plt.hist([Age09UPA, Age14UPA], bins, label=['2009', '2014']) plt.legend(loc='upper right') plt.xlabel('Age Of UPA winners in years') plt.ylabel('Total Number of UPA winners') plt.title('Distribution of Age of UPA winners') plt.show(); # Gender Distribution of Winning Candidates in 2009 & 2014 India Elections colors = ['#0000CD','#CD3333'] plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.pie(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)]['Candidate Sex'].value_counts(), labels=['Male','Female'],autopct='%1.1f%%',colors=colors, startangle=90) my_circle1=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() fig.suptitle("Gender Distribution in 2009 & 2014 India Elections", fontsize=14) # Adding supertitle with pyplot import ax = fig.gca() ax.add_patch(my_circle1) label = ax.annotate("2009", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.subplot(1,2,2) plt.pie(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)]['Candidate Sex'].value_counts(), labels=['Male','Female'],autopct='%1.1f%%',colors=colors, startangle=90) my_circle2=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() #gcf means get current figure ax = fig.gca() # gca means get current axis ax.add_patch(my_circle2) label = ax.annotate("2014", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.show(); # Gender Distribution of Winning Candidates in 2009 - NDA vs UPA in India Elections colors = ['#0000CD','#CD3333'] plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.pie(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)& (LS0914Cand.Alliance=='NDA')]['Candidate Sex'].value_counts(), labels=['Male','Female'],autopct='%1.1f%%',colors=colors, startangle=90) my_circle1=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() fig.suptitle("Gender Distribution in 2009 - NDA vs UPA", fontsize=14) # Adding supertitle with pyplot import ax = fig.gca() ax.add_patch(my_circle1) label = ax.annotate("NDA", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.subplot(1,2,2) plt.pie(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)& (LS0914Cand.Alliance=='UPA')]['Candidate Sex'].value_counts(), labels=['Male','Female'],autopct='%1.1f%%',colors=colors, startangle=90) my_circle2=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() #gcf means get current figure ax = fig.gca() # gca means get current axis ax.add_patch(my_circle2) label = ax.annotate("UPA", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.show(); # Gender Distribution of Winning Candidates in 2014 - NDA vs UPA in India Elections colors = ['#0000CD','#CD3333'] plt.figure(figsize=(10,5)) plt.title('2014') plt.subplot(1,2,1) plt.pie(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)& (LS0914Cand.Alliance=='NDA')]['Candidate Sex'].value_counts(), labels=['Male','Female'],autopct='%1.1f%%',colors=colors, startangle=90) my_circle1=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() fig.suptitle("Gender Distribution in 2014 - NDA vs UPA", fontsize=14) # Adding supertitle with pyplot import ax = fig.gca() ax.add_patch(my_circle1) label = ax.annotate("NDA", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.subplot(1,2,2) plt.pie(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)& (LS0914Cand.Alliance=='UPA')]['Candidate Sex'].value_counts(), labels=['Male','Female'],autopct='%1.1f%%',colors=colors, startangle=90) my_circle2=plt.Circle( (0,0), 0.7, color='white') fig = plt.gcf() #gcf means get current figure ax = fig.gca() # gca means get current axis ax.add_patch(my_circle2) label = ax.annotate("UPA", xy=(0, 0), fontsize=30, ha="center",va="center") ax.axis('off') ax.set_aspect('equal') ax.autoscale_view() plt.show(); # Distribution of Winning Seats across states in 2009 & 2014 for NDA & UPA in India Elections color = ("green","orange") State09UPA=pd.DataFrame(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)& (LS0914Cand.Alliance=='UPA')]['State name'].value_counts()) State14UPA=pd.DataFrame(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)& (LS0914Cand.Alliance=='UPA')]['State name'].value_counts()) State09NDA=pd.DataFrame(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2009)& (LS0914Cand.Alliance=='NDA')]['State name'].value_counts()) State14NDA=pd.DataFrame(LS0914Cand[(LS0914Cand.Position==1) & (LS0914Cand.Year==2014)& (LS0914Cand.Alliance=='NDA')]['State name'].value_counts()) State09 = pd.concat([State09UPA, State09NDA], axis=1, sort=False).fillna(0) State09.columns = ['UPA','NDA'] State14 = pd.concat([State14UPA, State14NDA], axis=1, sort=False).fillna(0) State14.columns = ['UPA','NDA'] nx = State09.plot(kind='bar', # Plot a bar chart legend=True, # Turn the Legend off title = "NDA vs UPA across States of India (In 2009)", width=0.75, # Set bar width as 75% of space available figsize=(15,5), # Set area size (width,height) of plot in inches colors= color) nx.set_xlabel("Election States", fontsize=12) nx.set_ylabel("Seats Won", fontsize=12) annot_plot(nx,0.05,0.5); kx = State14.plot(kind='bar', # Plot a bar chart legend=True, # Turn the Legend off title = "NDA vs UPA across States of India (In 2014)", width=0.75, # Set bar width as 75% of space available figsize=(15,5), # Set area size (width,height) of plot in inches colors= color) kx.set_xlabel("Election States", fontsize=12) kx.set_ylabel("Seats Won", fontsize=12) annot_plot(kx,0.05,0.5); # Reading 2009 Electors dataset LS09Elec = pd.read_csv('../input/LS2009Electors.csv') print(LS09Elec.shape) LS09Elec.head() # Reading 2014 Electors dataset LS14Elec = pd.read_csv('../input/LS2014Electors.csv') print(LS09Elec.shape) LS14Elec.head() LS09Elec.STATE.unique() LS14Elec.STATE.unique() LS14Elec['STATE']=LS14Elec['STATE'].replace(to_replace=['Odisha'],value='Orissa') LS14Elec['STATE']=LS14Elec['STATE'].replace(to_replace=['Chhattisgarh'],value='Chattisgarh') LS09Elec = LS09Elec.groupby('STATE').mean() LS09 = LS09Elec[['POLL PERCENTAGE']].sort_values('POLL PERCENTAGE',ascending=False).to_dict() Y09=[2009 for i in range(35)] S09=list(LS09['POLL PERCENTAGE'].keys()) P09=list(LS09['POLL PERCENTAGE'].values()) LS14Elec = LS14Elec.groupby('STATE').mean() LS14 = LS14Elec[['POLL PERCENTAGE']].sort_values('POLL PERCENTAGE',ascending=False).to_dict() Y14=[2014 for i in range(35)] S14=list(LS14['POLL PERCENTAGE'].keys()) P14=list(LS14['POLL PERCENTAGE'].values()) Data = {'YEAR':Y09+Y14,'STATE':S09+S14,'Poll_Percentage':P09+P14} DF = pd.DataFrame(data=Data) ax = plt.subplots(figsize=(6, 20)) sns.barplot(x=DF.Poll_Percentage,y=DF.STATE,hue=DF.YEAR) plt.title('Poll Percentage of States 2009 and 2014')<file_sep>/Assignment 4/Multiple Regression/multiple_regression.R data=read.csv("D:\\R-3.6.1\\obese.csv") summary(data) model=lm(data$obese~ data$ ï..sex +data$sbp + data$dbp + data$scl +data$age +data$bmi) plot(model) plot(data) summary(model) resid(model) fitted(model) par(mfrow=c(2,2)) model=lm(data$obese ~ data$sbp +data$dbp) summary(model) plot(model)
eac0918cb7075631a0172cb9b692b0bc87baa79f
[ "Markdown", "Python", "R" ]
3
Markdown
KevMamba/Data-Analytics
10798ae572efd9a3d41397f7e533aa09d18bbd10
d7e4b6f6b7869875ae85d97a088bd602c22d56b8
refs/heads/master
<file_sep>package com.frankegan.foodsavers; import android.util.Log; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.messaging.FirebaseMessagingService; public class FoodMessagingService extends FirebaseMessagingService { private static final String TAG = FoodMessagingService.class.getSimpleName(); private FirebaseFirestore firestore = FirebaseFirestore.getInstance(); @Override public void onNewToken(String newToken) { Log.d(TAG, "Refreshed token: " + newToken); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { firestore.collection("users").document(user.getUid()) .update("fcmToken", newToken); } } } <file_sep>package com.frankegan.foodsavers; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Matrix; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.frankegan.foodsavers.model.Food; import com.frankegan.foodsavers.model.Post; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.GeoPoint; import com.google.firebase.ml.vision.FirebaseVision; import com.google.firebase.ml.vision.common.FirebaseVisionImage; import com.google.firebase.ml.vision.label.FirebaseVisionLabel; import com.google.firebase.ml.vision.label.FirebaseVisionLabelDetector; 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.ArrayList; import java.util.List; public class CreatePostActivity extends AppCompatActivity { private final static int IMAGE_CAPTURE_REQ = 201; private final static int LOCATION_REQ = 202; private static final String TAG = CreatePostActivity.class.getSimpleName(); protected Location lastLocation; private AddressResultReceiver addressResultReceiver; private ListView foodItemListView; ArrayAdapter<String> adapter; private FirebaseFirestore firestore; private FirebaseStorage storage; private EditText addressInput; private EditText descInput; private ImageView thumbnail; private String photoUrl; private List<String> generateTags = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_post); firestore = FirebaseFirestore.getInstance(); storage = FirebaseStorage.getInstance(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); addressInput = findViewById(R.id.addressInput); descInput = findViewById(R.id.descInput); thumbnail = findViewById(R.id.theumbnail); foodItemListView = findViewById(R.id.food_list_view); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); foodItemListView.setAdapter(adapter); findViewById(R.id.attachPhotoButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openCamera(); } }); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { uploadFoodItem(); } }); findViewById(R.id.addFoodItem).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addFoodItem(); } }); addressResultReceiver = new AddressResultReceiver(new Handler()); fetchAddress(); } private void uploadFoodItem() { final List<Food> foods = new ArrayList<>(); for (int i = 0; i < adapter.getCount(); i++) { foods.add(new Food(adapter.getItem(i), 1)); } FirebaseUser producer = FirebaseAuth.getInstance().getCurrentUser(); firestore.collection("posts").add( new Post( new GeoPoint(lastLocation.getLatitude(), lastLocation.getLongitude()), addressInput.getText().toString(), generateTags, photoUrl, descInput.getText().toString(), false, "users/" + producer.getUid(), ""/*A new post hasn't been consumed yet*/) ).addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { for (Food f : foods) { firestore.collection("posts") .document(documentReference.getId()) .collection("foodItems") .add(f); } Toast.makeText(CreatePostActivity.this, "Post created successfully!", Toast.LENGTH_SHORT).show(); finish(); } }); } protected void fetchAddress() { int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); //If the app currently has access to the location permission... if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQ); return; } FusedLocationProviderClient fusedLocationClient = LocationServices .getFusedLocationProviderClient(this); fusedLocationClient .getLastLocation() .addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { lastLocation = location; // In some rare cases the location returned can be null if (lastLocation == null) return; // Start service and update UI to reflect new location Intent intent = new Intent(CreatePostActivity.this, FetchAddressIntentService.class) .putExtra(FetchAddressIntentService.Constants.RECEIVER, addressResultReceiver) .putExtra(FetchAddressIntentService.Constants.LOCATION_DATA_EXTRA, lastLocation); startService(intent); } }); } /** * This callback is ran after the external camera has taken a photo. The photo is provided to us * as intent extras. * * @param data Contains an Intent extra called "data" which contains the bitmap of our photo. */ @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == IMAGE_CAPTURE_REQ && resultCode == RESULT_OK && data != null) { Bundle extras = data.getExtras(); if (extras == null) return; Bitmap photo = rotate((Bitmap) extras.get("data")); if (photo == null) return; thumbnail.setVisibility(View.VISIBLE); thumbnail.setImageBitmap(photo); generateTags(photo); ByteArrayOutputStream baos = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); final StorageReference imageRef = storage.getReference(System.currentTimeMillis() + ".jpg"); final UploadTask uploadTask = imageRef.putBytes(bytes); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Log.e("CreatePostActivity", exception.getMessage(), exception); } }).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) throw task.getException(); // Continue with the task to get the download URL return imageRef.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { photoUrl = task.getResult().toString(); Log.d("CreatePostActivity", photoUrl); } else { Log.e("CreatePostActivity", task.getException().getMessage(), task.getException()); } } }); } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == LOCATION_REQ && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { fetchAddress(); } } private void openCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, IMAGE_CAPTURE_REQ); } } private void generateTags(Bitmap photo) { FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo); FirebaseVisionLabelDetector detector = FirebaseVision.getInstance() .getVisionLabelDetector(); detector.detectInImage(image) .addOnSuccessListener( new OnSuccessListener<List<FirebaseVisionLabel>>() { @Override public void onSuccess(List<FirebaseVisionLabel> labels) { // Task completed successfully for (FirebaseVisionLabel l : labels) { if (l.getConfidence() > 0.5) generateTags.add(l.getLabel()); Log.d(TAG, String.format("%s: %f %%", l.getLabel(), l.getConfidence())); } } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception Log.d(TAG, e.getMessage(), e); } }); } private void addFoodItem() { final EditText foodInput = new EditText(this); new AlertDialog .Builder(this) .setTitle("Add a Food Item") .setMessage("Type the name of the food you are posting") .setView(foodInput) .setPositiveButton("SAVE", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String foodName = foodInput.getText().toString(); adapter.add(foodName); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(foodInput.getWindowToken(), 0); } }) .setCancelable(true) .show(); } private Bitmap rotate(Bitmap bitmap) { Matrix matrix = new Matrix(); // setup rotation degree matrix.postRotate(90); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } class AddressResultReceiver extends ResultReceiver { public AddressResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultData == null) return; // Display the address string // or an error message sent from the intent service. String addressRes = resultData.getString(FetchAddressIntentService.Constants.RESULT_DATA_KEY); if (addressRes == null) addressRes = ""; // Show a toast message if an address was found. if (resultCode == FetchAddressIntentService.Constants.SUCCESS_RESULT) { addressInput.setText(addressRes); } } } } <file_sep>const functions = require('firebase-functions'); const admin = require('firebase-admin'); // Initialize the Firebase Admin SDK admin.initializeApp(functions.config().firebase); const ONE_KM_DEG = 0.01270486596 //Send a notification to user near newly posted food exports.notifyNewPost = functions.firestore .document('posts/{postId}') .onCreate((snap, context) => { console.log("snap data is :") console.log(Object.keys(snap.data())) const loc = snap.data().location console.log("new post location:") console.log(loc) console.log("latitude is " + loc['_latitude']) console.log("longitude is " + loc._longitude) return admin.firestore() .collection('users').get() .then(snap => snap.docs.filter(userSnap => { const userLoc = userSnap.data().location console.log("user is at " + userLoc) return Math.abs(loc._latitude - userLoc._latitude) < ONE_KM_DEG || Math.abs(loc._longitude - userLoc._longitude) < ONE_KM_DEG }).map(u => { const token = u.get('fcmToken') console.log(`FCMToken= ${token}`) return token })) .then(nearByTokens => { const payload = { notification: { title: 'New Food Posted Nearby', body: 'Help save some food' } }; // Send notifications to all tokens. console.log("sending to tokens:", nearByTokens); return admin.messaging().sendToDevice(nearByTokens, payload) }) .catch(err => { console.log('Error getting documents', err); }); });<file_sep># foodSavers CS 528 Final Project This project consists of Firebase project wit an Android client application and server side Cloud Functions. ## Contributors <NAME> [<NAME>](<EMAIL>) <NAME> <NAME>
7bc5b09aef825f0f933f83c7e48d7c30fc0df96f
[ "JavaScript", "Java", "Markdown" ]
4
Java
MeghanaVKasal/foodSavers
b1bd908e7430d622ede8b283b6f197d253def1a9
56d1d287318b65ab00dea26637c80fc04396e831
refs/heads/master
<file_sep>using UnityEngine; public class Key : ItemPickup { } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item", order = 1)] public class Item : ScriptableObject { public string itemName = "Item Name"; // Name in the inventory slot public Texture2D itemIcon = null; // Icon in the inventory slot public GameObject itemDropPrefab = null; // Item that will appear when dropped } <file_sep>using UnityEngine; public class InteractableItem : MonoBehaviour { public bool isActive = true; public string interactText; public bool canInteract = true; public ActionPanelUI actionPanel; public virtual void onInteract() { } public virtual void onItemDetected() { actionPanel.setActionText(this.interactText); } public virtual void onItemUndetected() { actionPanel.resetActionText(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; public abstract class TextButton : MonoBehaviour { // Each subclass must specify the text on the button protected abstract string buttonText { get; } // They also need to specify the callback for onClick protected abstract void clickAction(); private Text text; private Button button; // Create the button transition color that every TextButton will use // This is static so that we don't recreate it for every new button private static ColorBlock BUTTON_COLOURS = new ColorBlock { colorMultiplier = 1, fadeDuration = 0.15f, normalColor = Color.white, disabledColor = Color.grey, highlightedColor = new Color(1.0f, 0.65f, 0.0f), pressedColor = new Color(1.0f, 0.0f, 0.0f), }; static Font loadFont() { const string FONT_NAME = "NaziTypewriterRegular"; // Try to find the font if it's already loaded foreach (Font font in Resources.FindObjectsOfTypeAll<Font>()) { if (font.name == FONT_NAME) { return font; } } // Or else load it if it's the first time return Resources.Load<Font>("Fonts/NaziTypewriter/" + FONT_NAME); } // Use this for initialization void Start () { // Set up the text field that will be rendered text = gameObject.AddComponent<Text>(); text.font = loadFont(); text.fontSize = 30; text.text = buttonText; text.alignment = TextAnchor.MiddleCenter; // Create the button to handle clicking button = gameObject.AddComponent<Button>(); button.targetGraphic = text; button.colors = BUTTON_COLOURS; button.onClick.AddListener(clickAction); } // Update is called once per frame void Update () { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Keypad : MonoBehaviour { public string codeAnswer = "9654"; public string codeGuess = ""; public bool isCorrect = false; public Fuse fuse; public void updateGuess(string newVal) { codeGuess += newVal; checkGuess(); } private void checkGuess() { if(codeGuess.Length == codeAnswer.Length) { if(codeGuess == codeAnswer) { isCorrect = true; fuse.canInteract = true; } else { resetCodeGuess(); } } } private void resetCodeGuess() { this.codeGuess = ""; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Laser : MonoBehaviour { public int maxReflections = 1; private int numReflections = 0; public float maxStepDistance = 1000f; private LineRenderer laser; // Use this for initialization void Start () { laser = GetComponentInChildren<LineRenderer>(); laser.positionCount = maxReflections + 1; // Make sure there are enough verticies to keep up with the number of lines we want } // Update is called once per frame void Update () { // As of right now, the reflections are being updated every frame which seems a little dumb // What we are going to want to do is create all the reflections in the Start method and then // we can check when something intersects with the reflection and if it is a mirror, then we // will update it so we aren't rerendering all the lines every update redrawLaser(); } private void redrawLaser() { // Reset the first node since we might be moving it numReflections = 0; addPoint(this.transform.position); // Draw the rest of the nodes based on this position drawLine(this.transform.position, this.transform.forward, maxReflections); } private void drawLine(Vector3 fromPos, Vector3 direction, int reflectionsRemaining) { if(reflectionsRemaining == 0) { return; } Ray ray = new Ray(fromPos, direction); RaycastHit hit; // If we hit something, find the position of where we hit, and get the direction so we can properly figure out the next line if(Physics.Raycast(ray, out hit, maxStepDistance)) { fromPos = hit.point; // This point is calculated using the direction that was given originally direction = Vector3.Reflect(direction, hit.normal); } else { fromPos += direction * maxStepDistance; } // Actually add the new point addPoint(fromPos); drawLine(fromPos, direction, reflectionsRemaining - 1); } private void addPoint(Vector3 position) { laser.SetPosition(numReflections, position); numReflections++; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemPickup : InteractableItem { public Item item; public override void onInteract() { this.pickupItem(); this.onItemUndetected(); Destroy(this.gameObject); } private void pickupItem() { if(Inventory.instance.add(this.item)) { Destroy(this.gameObject); } } } <file_sep>using UnityEngine; using UnityEngine.UI; public class InventorySlot : MonoBehaviour { public RawImage icon; public Item item; // Set the item for the current inventory slot public void setItem(Item toAdd) { this.item = toAdd; icon.texture = toAdd.itemIcon; icon.enabled = true; } // Get rid of the item that is in the current slot public void clearItem() { this.item = null; icon.texture = null; icon.enabled = false; } } <file_sep>using UnityEngine; using System.Collections; public class Door : InteractableItem { protected Animator animator; protected virtual void Start () { animator = GetComponent<Animator>(); } public override void onInteract() { animator.SetTrigger("Interact"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Inventory : MonoBehaviour { public int slots = 5; public List<Item> items = new List<Item>(); public int activeItem = 0; public delegate void onItemChanged(); public onItemChanged onItemChangedCallback; public static Inventory instance; /* Awake is only called once during the lifetime of this script. This is so we can set an instance of this class so it can be used throughout the entire game */ public void Awake() { if(instance != null) { Debug.LogWarning("There is already another inventory"); return; } instance = this; } // Add something to the inventory if there is room public bool add(Item toAdd) { if(items.Count >= slots) { return false; } items.Add(toAdd); if(onItemChangedCallback != null) { onItemChangedCallback.Invoke(); } return true; } // Remove someting from the inventory public void remove(Item toRemove) { items.Remove(toRemove); if(onItemChangedCallback != null) { onItemChangedCallback.Invoke(); } } // Get the item in the inventory for the slot this is active public Item getActiveItem() { if(this.items.Count > 0 && this.items.Count >= this.activeItem) { return this.items[this.activeItem]; } return null; } // Set which slot is active public void setActiveItem(int newActive) { this.activeItem = newActive; } } <file_sep>using UnityEngine; using UnityEngine.UI; class MouseSensSlider : MonoBehaviour { void Start() { // Set the initial value of the slider to what's in the options right now Slider slider = GetComponent<Slider>(); slider.value = (float) Options.Instance.mouseSensitivity; } } <file_sep>using System; /// <summary> /// This is our options singleton. The instance must be used to set or get any options. /// </summary> public class Options { // This is the instance that anyone can access public static Options Instance = new Options(); // Create the default options public static readonly OptionsBuilder DEFAULTS = new OptionsBuilder() { mouseSensitivity = 10, }; // This is the lock we will use whenever we try to change something in the options private readonly object myLock = new object(); //////// Keep all of our options private (Build another level for synchronization) private uint _mouseSensitivity; /////// Make getters for all of our options public uint mouseSensitivity { get { lock(myLock) { return _mouseSensitivity; } } } // Make our constructor private so that nothing else can create other Options private Options() {} static Options() { // Always merge with the defaults on start-up Instance.merge(DEFAULTS); // We can load in any options read from a file later, and overwrite the defaults } /// <summary> /// Merges the options from the options builder. Checks all of the options to make sure that they're good. Just skips bad options. /// </summary> public void merge(OptionsBuilder builder) { // Lock everything, so that no-one else can read it while we're updating lock(myLock) { /// Sets the mouse sensitivity. The range is 1 - 100, so nothing happens if the given value is greater than 100 or 0 if (builder.mouseSensitivity.HasValue && (1 <= builder.mouseSensitivity.Value && builder.mouseSensitivity.Value <= 100)) { _mouseSensitivity = builder.mouseSensitivity.Value; } } } /// <summary> /// This is a builder for the options, so that we can stage our options before pushing them into our global options. /// All of our options in the builder need to be nullable, so we can see which ones were set /// </summary> public class OptionsBuilder { public uint? mouseSensitivity; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fuse : ItemPickup { } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InventoryUI : MonoBehaviour{ private Inventory inventory; public InventorySlot[] slots; // Use this for initialization void Start () { inventory = Inventory.instance; inventory.onItemChangedCallback += this.updateInventoryUI; slots = this.transform.GetComponentsInChildren<InventorySlot>(); } // This is the method that is called whenever the inventory is updated private void updateInventoryUI() { for(int i = 0; i < slots.Length; i++) { if(i < inventory.items.Count) { slots[i].setItem(inventory.items[i]); } else { slots[i].clearItem(); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public Camera cam; private ItemDetector itemDetector; private bool cursorLocked = false; void Start() { itemDetector = GetComponent<ItemDetector>(); Cursor.visible = cursorLocked; Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)) { Ray ray = new Ray(cam.transform.position, cam.transform.forward); RaycastHit hit; if(Physics.Raycast(ray, out hit, 2.0f)) { ST_PuzzleTile temp = hit.collider.GetComponent<ST_PuzzleTile>(); // Call detectedItem.onFocus() or whatever so that updates the UI instead of the player class if(temp != null) { // get the puzzle display and return the new target location from this tile. temp.LaunchPositionCoroutine(GameObject.Find("Slide Puzzle").GetComponent<ST_PuzzleDisplay>().GetTargetLocation(temp)); } } } if(Input.GetKeyDown("e")) { if(itemDetector.getDetectedItem() != null && itemDetector.getDetectedItem().isActive) { itemDetector.getDetectedItem().onInteract(); } } else if(Input.GetKeyDown("1")) { Inventory.instance.setActiveItem(0); } else if(Input.GetKeyDown("2")) { Inventory.instance.setActiveItem(1); } else if(Input.GetKeyDown("3")) { Inventory.instance.setActiveItem(2); } else if(Input.GetKeyDown("4")) { Inventory.instance.setActiveItem(3); } else if(Input.GetKeyDown("5")) { Inventory.instance.setActiveItem(4); } } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; // This is a generic-ish back button that will unload the current scene class BackButton : TextButton { protected override string buttonText { get { return "Back"; } } protected override void clickAction() { // Go back to the main menu SceneManager.LoadSceneAsync("Main Menu"); } } <file_sep>using UnityEngine; class ExitButton : TextButton { protected override string buttonText { get { return "Exit"; } } protected override void clickAction() { Application.Quit(); } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; class DefaultButton : TextButton { protected override string buttonText { get { return "Revert to Defaults"; } } protected override void clickAction() { // Revert to default options Options.Instance.merge(Options.DEFAULTS); // Reload the scene so that the UI can get reset SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FuseBox : InteractableItem { public Transform fuseSlot; public Gate gate; private Inventory inventory; // The fuse that will be connected GameObject fuse; // Also save the item that will be removed from and added to the inventory Item fuseItem; // Keep track of the old interact text string oldInteractText; void Start() { inventory = Inventory.instance; inventory.onItemChangedCallback += checkHasFuse; this.canInteract = false; } private void checkHasFuse() { // If there is a fuse in the box, then we can still remove it if (fuse != null) { canInteract = true; return; } this.canInteract = false; for(int i = 0; i < inventory.items.Count; i++) { if(inventory.items[i].itemName == "Fuse") { this.canInteract = true; return; } } } public override void onInteract() { this.onItemUndetected(); Item activeItem = inventory.getActiveItem(); if (fuse == null) { // Check for a fuse to use if it isn't connected yet if(activeItem != null && activeItem.itemName == "Fuse") { fuse = Instantiate(activeItem.itemDropPrefab, fuseSlot, false); fuse.GetComponent<InteractableItem>().isActive = false; inventory.remove(activeItem); fuseItem = activeItem; oldInteractText = interactText; interactText = "Press 'E' to remove the fuse"; // Grab the Gate script object from the gate and increment the fuses gate.connectFuse(); } } else { // Take the fuse out of the box and back into the player's inventory Destroy(fuse); fuse = null; // Add the fuse back to our inventory inventory.add(fuseItem); fuseItem = null; interactText = oldInteractText; oldInteractText = null; gate.disconnectFuse(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChocolateBar : InteractableItem { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public override void onInteract() { Debug.Log("You are picking up a chocolate bar"); } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; class StartButton : TextButton { protected override string buttonText { get { return "Start"; } } protected override void clickAction() { SceneManager.LoadScene("Asylum"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemDetector : MonoBehaviour { public int radius = 2; public InteractableItem detectedItem; public Camera cam; void Update() { detectItem(); } public void detectItem() { Ray ray = new Ray(cam.transform.position, cam.transform.forward); RaycastHit hit; // I don't like this... I am resetting the detectedItem every time... I want to update it when it changes instead // detectedItem = null; if(Physics.Raycast(ray, out hit, radius)) { InteractableItem temp = hit.collider.GetComponent<InteractableItem>(); // Call detectedItem.onFocus() or whatever so that updates the UI instead of the player class if(temp != null) { this.setItemDetected(temp); } else { this.setItemUndetected(); } } else { this.setItemUndetected(); } } private void setItemDetected(InteractableItem newItem) { if(newItem != detectedItem && newItem.canInteract) { this.setItemUndetected(); detectedItem = newItem; detectedItem.onItemDetected(); } } private void setItemUndetected() { if(detectedItem != null) { detectedItem.onItemUndetected(); detectedItem = null; } } public InteractableItem getDetectedItem() { return this.detectedItem; } } <file_sep>using UnityEngine; using Firebase; using Firebase.Database; using Firebase.Unity.Editor; public class DataBase { public static string fbUrl = "https://goons-13756.firebaseio.com/"; // Retrieves player data from database. public void retrievePlayerData() { // Set up editor & get root reference location. FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(fbUrl); DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference; FirebaseDatabase.DefaultInstance.GetReference("goons-13756").GetValueAsync().ContinueWith(task => { if (task.IsFaulted) { Debug.Log("Fail"); } else if (task.IsCompleted) { Debug.Log("Pass!"); DataSnapshot snapshot = task.Result; Debug.Log(snapshot.GetRawJsonValue()); } }); } // Once game is completed, game data is added to the database. public void addPlayerData() { playerData newPlayer = new playerData(2/*"Kushal", 1899, 22, 165*/); string jason = JsonUtility.ToJson(newPlayer); // Set up editor & get root reference location. FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(fbUrl); DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference; // Push gives data a unique ID. Once we get more player data we don't have to use push. reference.Push().SetRawJsonValueAsync(jason); Debug.Log("We are winning!"); } // Json string format. public class playerData { /*public string id = ""; public int time = 0; public string inventory = "";*/ public int levels_completed = 0; public playerData(int levels_completed/*string id, int time, string inventory*/) { /*this.id = id; this.time = time; this.inventory = inventory;*/ this.levels_completed = levels_completed; } public string toString() { return ("Levels Completed: " + this.levels_completed); } } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; class OptionsButton : TextButton { protected override string buttonText { get { return "Options"; } } protected override void clickAction() { // Load the options menu without unloading this one SceneManager.LoadSceneAsync("Options Menu"); } } <file_sep>using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; class SaveButton : TextButton { protected override string buttonText { get { return "Save Changes"; } } protected override void clickAction() { // Create an option builder that will hold all of the options before we merge it Options.OptionsBuilder builder = new Options.OptionsBuilder(); Slider mouseSens = findObject<Slider>("MouseSens"); if (mouseSens != null) { builder.mouseSensitivity = (uint) mouseSens.value; } else { Debug.Log("Failed to find the mouse sensitivity slider"); } // Merge the options that we built Options.Instance.merge(builder); // Go back to the main menu after the new options have been saved SceneManager.LoadSceneAsync("Main Menu"); } // Tries to find the object of the given type in the scene with the same name private T findObject<T>(string name) where T: UnityEngine.Object { foreach (T obj in FindObjectsOfType<T>()) { if (obj.name == name) { return obj; } } return null; } } <file_sep># Horror-Game Horror game made in Unity for my cis*4500 university project. <file_sep>using UnityEngine; using UnityEngine.UI; public class ActionPanelUI : MonoBehaviour { public Text messageBox; public bool messageSet = false; public void setActionText(string msg) { this.messageBox.text = msg; messageSet = true; } public void resetActionText() { this.messageBox.text = ""; messageSet = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class KeypadButton : InteractableItem { public string buttonVal = "0"; public Keypad keypad; void Start() { } public override void onInteract() { keypad.updateGuess(this.buttonVal); } } <file_sep>using UnityEngine; public class EndTrigger : MonoBehaviour { private void OnTriggerEnter() { DataBase save = new DataBase(); save.addPlayerData(); Debug.Log("Congratulations! You have escaped!!"); } } <file_sep>using UnityEngine; public class Gate : MonoBehaviour { // The number of fuses that are needed to unlock the gate public uint fusesNeeded = 1; // The number of fuses so far connected to the gate private uint fuseCount = 0; // The animation that we will play when the gate gets unlocked private Animator animator; void Start() { animator = GetComponent<Animator>(); } public void connectFuse() { fuseCount++; if (fuseCount >= fusesNeeded) { // Play the unlocking animation animator.SetTrigger("Interact"); } } public void disconnectFuse() { fuseCount--; // Only do the gate close once if (fuseCount == fusesNeeded - 1) { // Close the gate since there aren't enough fuses animator.SetTrigger("Interact"); } } } <file_sep>using UnityEngine; public class LockedDoor : Door { Inventory inventory; bool locked = true; protected override void Start() { base.Start(); // Make it usable but uninteractable to start isActive = true; canInteract = false; // Add a callback method for the inventory inventory = Inventory.instance; inventory.onItemChangedCallback += checkForKey; } public void checkForKey() { // Don't do anything if it's unlocked if (!locked) { return; } // We need to reset if this everytime because a key may have been used on a different door canInteract = false; // Look through all of the items and try to find a key for(int i = 0; i < inventory.items.Count; i++) { if(inventory.items[i].itemName == "Key") { canInteract = true; return; } } } public override void onInteract() { if (locked) { // Unlock the door if the player uses a key onItemUndetected(); Item activeItem = inventory.getActiveItem(); if(activeItem != null && activeItem.itemName == "Key") { // Set the locked status before we remove the item so our callback will see it locked = false; interactText = "Press 'E' to open"; inventory.remove(activeItem); // Still open the door here for ease of use base.onInteract(); } } else { // Work like a normal door once it's unlocked base.onInteract(); } } }
2315ea751b4ad7829b8c9e254700e8b0b65f6345
[ "Markdown", "C#" ]
31
C#
lgiancol/Horror-Game
01d671df787482e796fce3fc51869e31beeb35e9
40d22238fda0b3809c33bec29609dfbc6a8bb96e
refs/heads/master
<repo_name>shawnxjf1/java4learning<file_sep>/module11Tool/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"> <modelVersion>4.0.0</modelVersion> <groupId>com.shawn</groupId> <artifactId>module11Tool</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <slf4j.api.version>1.7.21</slf4j.api.version> <lombok.version>1.16.16</lombok.version> </properties> <dependencies> <!--begin pdf 相关操作api--> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.1</version> </dependency> <!-- 支持中文 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <!--end pdf 相关操作api--> <dependency> <!-- jsoup HTML parser library @ https://jsoup.org/ --> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.api.version}</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.15</version> </dependency> <!--begin支持正则表达式--> <dependency> <groupId>oro</groupId> <artifactId>oro</artifactId> <version>2.0.8</version> </dependency> <!--end 支持正则表达式--> </dependencies> </project><file_sep>/module11Tool/src/main/java/com/shawn/cap02/file/RelativeToFullPathUtil.java package com.shawn.cap02.file; import java.io.File; import java.util.regex.Matcher; public class RelativeToFullPathUtil { String fileSeparator = System.getProperty("file.separator"); public static String getFullPathByPackage(Class clz,String fileName) { String packageUrl = clz.getPackage().getName(); String packagePath = packageConvertPath(packageUrl); String userDir = System.getProperty("user.dir"); String fileSeparator = System.getProperty("file.separator"); return userDir + fileSeparator+ "src" +fileSeparator + "test" + fileSeparator + "java" + packagePath +fileSeparator + fileName; } /** * 自定义方法 * 将获取到的包路径中的点号换成斜杠 * @param packageName 传入的包路径 * @return 路径前后都加上斜杠中间也替换成斜杠返回 */ public static String packageConvertPath(String packageName) { String fileSeparator = System.getProperty("file.separator"); /** * 错误的写法,参考:https://www.liangzl.com/get-article-detail-39961.html<br> * return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName); */ return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", Matcher.quoteReplacement(File.separator)) : packageName); } public static String getPackagePath(Class clz) { String packageUrl = clz.getPackage().getName(); String packagePath = packageConvertPath(packageUrl); return packagePath; } } <file_sep>/module11Tool/src/test/java/com/shawn/cap02/file/SystemPropertiesTest.java package com.shawn.cap02.file; import cn.hutool.core.io.FileUtil; import org.junit.Test; import java.io.File; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.Properties; /** * */ public class SystemPropertiesTest { @Test public void testPrintSystemProperties() { Properties properties = System.getProperties(); Enumeration pnames = properties.propertyNames(); while (pnames.hasMoreElements()) { String pname = (String) pnames.nextElement(); System.out.print(pname + ":"); System.out.println(properties.getProperty(pname)); } /** * user.dir:D:\500-java\j2seCode\module11Tool 工程当前目录<br> * 你也可以通过relativelyPath=System.getProperty("user.dir");来执行<br> * 对于不同平台我们可以通过user.dir + 包名来获取真实路径;<br> */ } @Test public void testFileDefaultPath(){ //new File("src/test/java")默认从工程路径下 File f=new File("src/test/java/" + RelativeToFullPathUtil.getPackagePath(SystemPropertiesTest.class) + SystemPropertiesTest.class.getSimpleName() + ".java"); String fileStr = FileUtil.readString(f, Charset.forName("UTF-8")); System.out.println(fileStr); /** * 执行成功,把java文件内容打印出来了<br> * 注意:SystemPropertiesTest.class.getSimpleName()打印简单的文字<br> * SystemPropertiesTest.class.getName()打印带有package路径的文件名<br> */ } } <file_sep>/module11Tool/src/test/java/com/shawn/cap02/file/ClassLoaderStreamTest.java package com.shawn.cap02.file; /** * FIXME shawn 待完善https://www.jb51.net/article/144315.htm<br> */ public class ClassLoaderStreamTest { } <file_sep>/pom.xml <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"> <groupId>com.shawn</groupId> <artifactId>java-code-parent</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>pom</packaging> <name>java-code-parent</name> <description>parent project for company</description> <modelVersion>4.0.0</modelVersion><!--不能去掉不然会报错的--> <modules> <module>arithmetic</module> <module>module11Tool</module> <module>module10Dao</module> </modules> <properties> <parent.version>1.0.0-SNAPSHOT</parent.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.5.RELEASE</spring.version> <slf4j.api.version>1.7.21</slf4j.api.version> <mybatis.spring.version>1.3.1</mybatis.spring.version> <dbcp.version>1.4</dbcp.version> <mybatis.version>3.2.3</mybatis.version> <mysql.version>5.1.26</mysql.version> <elasticsearch>2.3.3</elasticsearch> <jodatime>2.9.4</jodatime> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.SR3</spring-cloud.version> <lombok.version>1.16.16</lombok.version> <swagger2.version>2.8.0</swagger2.version> <junit.version>4.12</junit.version> <druid.version>1.0.31</druid.version> <hutool.version>4.0.6</hutool.version> <fastjson.version>1.2.44</fastjson.version> <spring4all.swagger.version>1.8.0.RELEASE</spring4all.swagger.version> <j2se.project.version>1.0.0-SNAPSHOT</j2se.project.version> <mybatisplus.spring.boot.version>1.0.5</mybatisplus.spring.boot.version> <mybatisplus.version>2.2.0</mybatisplus.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.8.0</version> <scope>test</scope> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.4.2</version> </dependency> </dependencies> </dependencyManagement> <dependencies> </dependencies> <build> <finalName>j2se-code-parent</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <fork>true</fork> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib/</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> </configuration> </execution> </executions> </plugin> </plugins> </build> <repositories> <repository> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project> <!-- 错误1:Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflow a).org.apache.activemq引入的slf4j-log4j12.jar与pom文件中的 log4j-over-slf4j.jar循环调用导致的异常,从名字上可以看出slf4j-log4j12是将slf4j的日志桥接到log4j12上, log4j-over-slf4j则是将log4j的日志桥接到slf4j上,因而产生了循环调用。 -->
80e334b1075bc2a0e936da3cb935a33e8b2d72e4
[ "Java", "Maven POM" ]
5
Maven POM
shawnxjf1/java4learning
03d42a148c836cf407a84cc9c8516e7ce0d5aea8
f2f9c4ce01517f0cdbcfe088618d6278a0332277
refs/heads/test
<file_sep>package org.firstinspires.ftc.teamcode.TestProject; import com.arcrobotics.ftclib.command.CommandOpMode; import com.arcrobotics.ftclib.gamepad.GamepadEx; import com.arcrobotics.ftclib.hardware.SimpleServo; import com.arcrobotics.ftclib.hardware.motors.MotorImplEx; import com.arcrobotics.ftclib.vision.SkystoneDetector; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvInternalCamera; @com.qualcomm.robotcore.eventloop.opmode.Autonomous(name="Test Project") // @Autonomous(...) is the other common choice public class Auto extends CommandOpMode { SkystoneDetector pipeline; OpenCvCamera camera; DriveSubsystem driveSubsystem; GamepadEx driverGamepad; @Override public void initialize() { driverGamepad = new GamepadEx(gamepad1); driveSubsystem = new DriveSubsystem(driverGamepad, hardwareMap, telemetry); driveSubsystem.initialize(); int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createInternalCamera(OpenCvInternalCamera.CameraDirection.BACK, cameraMonitorViewId); camera.openCameraDevice(); pipeline = new SkystoneDetector(10, 40, 50, 50); camera.setPipeline(pipeline); camera.startStreaming(640, 480, OpenCvCameraRotation.UPSIDE_DOWN); } @Override public void run() { SkystoneDetector.SkystonePosition position = pipeline.getSkystonePosition(); switch (position) { case LEFT_STONE: addSequential(new DriveForwardCommand(driveSubsystem, 4, 0.2), 1); break; case CENTER_STONE: break; case RIGHT_STONE: addSequential(new DriveForwardCommand(driveSubsystem, -4, 0.2), 1); break; default: break; } // Turn 90 degrees with a timeout of 2 seconds addSequential(new TurnAngleCommand(driveSubsystem, 90, telemetry), 10); } }
6c963712301148e3f9a9b4086f531f2c9d57dfc2
[ "Java" ]
1
Java
14470/FTCLib
62ada1291c544b07e2c134d72db7a6d27d7d53bf
ca6007942d9fd179496e83e920b443427f2ad655
refs/heads/master
<repo_name>Sadzeih/wolf3d<file_sep>/draw/my_put_pixel_to_image.c /* ** my_put_pixel_to_image.c for FDF in /home/guervi_a/rendu/Igraph/MUL_2014_fdf ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Fri Nov 21 20:34:31 2014 <NAME> ** Last update Sat Dec 20 15:37:15 2014 <NAME> */ #include "mlx.h" #include "my.h" void my_pixel_put_to_image(t_game *game, int x, int y, unsigned int color) { int bpp; int sizeline; int endian; int img_color; if (x < WIN_X && y < WIN_Y && x > 0 && y > 0) { img_color = mlx_get_color_value(game->window->mlx_ptr, color); game->window->data = mlx_get_data_addr(game->window->img, &bpp,\ &sizeline, &endian); game->window->data[(y * sizeline) + x * (bpp / 8)] = img_color & 255; game->window->data[(y * sizeline) + x * (bpp / 8) + 1] =\ img_color >> 8 & 255; game->window->data[(y * sizeline) + x * (bpp / 8) + 2] =\ img_color >> 16 & 255; } } void my_pixel_put_to_minimap(t_game *game, int x, int y, unsigned int color) { int bpp; int sizeline; int endian; int img_color; if (x < WIN_X && y < WIN_Y && x > 0 && y > 0) { img_color = mlx_get_color_value(game->window->mlx_ptr, color); game->window->data = mlx_get_data_addr(game->window->mini_map, &bpp,\ &sizeline, &endian); game->window->data[(y * sizeline) + x * (bpp / 8)] = img_color & 255; game->window->data[(y * sizeline) + x * (bpp / 8) + 1] =\ img_color >> 8 & 255; game->window->data[(y * sizeline) + x * (bpp / 8) + 2] =\ img_color >> 16 & 255; } } <file_sep>/main.c /* ** main.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 9 14:00:10 2014 <NAME> ** Last update Fri Dec 19 19:00:58 2014 <NAME> */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <X11/X.h> #include "mlx.h" #include "my.h" t_game *init_game(t_game *game) { if ((game = malloc(sizeof(t_game))) == NULL) return (0); if ((game->window = malloc(sizeof(t_window))) == NULL) return (0); if ((game->keys = malloc(sizeof(t_keys))) == NULL) return (0); if ((game->vec = malloc(sizeof(t_vec))) == NULL) return (0); if ((game->player = malloc(sizeof(t_player))) == NULL) return (0); if ((game->player->pos = malloc(sizeof(t_vec))) == NULL) return (0); if ((game->draw_minimap = malloc(sizeof(t_draw_minimap))) == NULL) return (0); if ((game->window->mlx_ptr = mlx_init()) == 0) return (0); game->window->mlx_win = mlx_new_window(game->window->mlx_ptr, 1280, 720, \ "wolf ta maman"); game->player->pos->x = 8.5; game->player->pos->y = 1.5; game->player->angle = 90; game->window->img = mlx_new_image(game->window->mlx_ptr, 1280, 720); game->window->mini_map = mlx_new_image(game->window->mlx_ptr, 150, 150); return (game); } int get_map(t_game *game) { char **tab_char; int fd; fd = open("map", O_RDONLY); if (fd == 0 || fd == -1) exit(1); tab_char = get_tab_lines(fd, "map"); game->map = tab_tab_int(tab_char, "map"); game->map_x = count_words(tab_char[0]); game->map_y = count_lines("map"); } int main() { t_game *game; game = init_game(game); if (game == 0) return (0); get_map(game); events(game); } <file_sep>/README.md # wolf3d A wolfenstein 3D-like I made at school Realised in 1 month during my first semester of my first year at Epitech <file_sep>/parsing/parsing.c /* ** parsing.c for FDF in /home/guervi_a/rendu/Igraph/MUL_2014_fdf ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Nov 6 09:45:33 2014 <NAME> ** Last update Tue Dec 16 14:03:51 2014 <NAME> */ #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "my.h" #include "get_next_line.h" int count_lines(char *file_name) { int fd; int lines; lines = 0; fd = open(file_name, O_RDONLY); if (fd == 0 || fd == -1) return (0); while (get_next_line(fd) != NULL) lines++; close(fd); return (lines); } char **get_tab_lines(int fd, char *file_name) { char *line; char **tab_lines; int i; i = 0; if ((tab_lines = malloc((count_lines(file_name) + 1) *\ sizeof(*tab_lines))) == NULL) return (0); while ((line = get_next_line(fd))) { tab_lines[i] = my_strdup(line); free(line); i++; } return (tab_lines); } int **tab_tab_int(char **tab_lines, char *file_name) { int **tab; int i; i = 0; if ((tab = malloc((count_lines(file_name) + 1) * sizeof(int *))) == NULL) return (0); while (i < count_lines(file_name)) { tab[i] = my_str_to_wordtab(tab_lines[i]); i++; } return (tab); } <file_sep>/parsing/get_next_line.c /* ** get_next_line.c for get_next_line in /home/guervi_a/rendu/C_Prog_Elem/CPE_2014_getnextline ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Nov 10 11:17:07 2014 <NAME> ** Last update Sat Dec 13 18:56:02 2014 <NAME> */ #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "get_next_line.h" char *my_strcat(char *dest, char *src) { int i; int j; i = 0; j = 0; while (dest[i] != '\0') { i++; } while (src[j] != '\0') { dest[i] = src[j]; i++; j++; } dest[i] = '\0'; return (dest); } char *my_strcpy(char *dest, char *src) { int i; i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; return (dest); } char *my_realloc(char *str, int size) { char *tmp; if (str != NULL) { if ((tmp = malloc(size * sizeof(char))) == NULL) return (0); my_strcpy(tmp, str); free(str); return (tmp); } else { if ((tmp = malloc(size * sizeof(char))) == NULL) return (0); tmp[0] = '\0'; return (tmp); } } char *get_line(char *reading, int size) { static int i = 0; char *line; int j; j = 0; if ((line = malloc(size * sizeof(char))) == NULL) return (0); while (reading[i] != '\n' && reading[i] != '\0') { line[j] = reading[i]; i++; j++; } if (reading[i] == '\n') { line[j] = '\0'; i++; return (line); } if (reading[i] == '\0') { free(line); return (NULL); } return (NULL); } char *get_next_line(const int fd) { char buffer[BUFFER + 1]; static char *reading; static int size = 0; int ret; ret = 1; while (ret > 0) { ret = read(fd, buffer, BUFFER); if (ret != 0) { buffer[ret] = '\0'; size += ret + 1; reading = my_realloc(reading, size); my_strcat(reading, buffer); } } return (get_line(reading, size)); } <file_sep>/events/move.c /* ** move.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Dec 15 15:36:45 2014 <NAME> ** Last update Wed Aug 26 00:24:39 2015 <NAME> */ #include <math.h> #include "mlx.h" #include "my.h" int forward(t_game *game) { float x; float y; float angle; angle = game->player->angle / 180 * M_PI; x = game->player->pos->x + (0.5 * cos(angle)); y = game->player->pos->y + (0.5 * sin(angle)); if (game->map[(int)y][(int)x] == 0) { game->player->pos->x = game->player->pos->x + (0.07 * cos(angle)); game->player->pos->y = game->player->pos->y + (0.07 * sin(angle)); } } int backward(t_game *game) { float x; float y; float angle; angle = game->player->angle / 180 * M_PI; x = game->player->pos->x - (0.5 * cos(angle)); y = game->player->pos->y - (0.5 * sin(angle)); if (game->map[(int)y][(int)x] == 0) { game->player->pos->x = game->player->pos->x - (0.07 * cos(angle)); game->player->pos->y = game->player->pos->y - (0.07 * sin(angle)); } } int move(t_game *game) { if (game->keys->up == 1) forward(game); if (game->keys->down == 1) backward(game); if (game->keys->left == 1) game->player->angle += 1.75; if (game->keys->right == 1) game->player->angle -= 1.75; if (game->keys->up == 1 || game->keys->down == 1 ||\ game->keys->left == 1 || game->keys->right == 1) { view(game); draw_mini_map(game); mlx_put_image_to_window(game->window->mlx_ptr, game->window->mlx_win, \ game->window->img, 0, 0); mlx_put_image_to_window(game->window->mlx_ptr, game->window->mlx_win,\ game->window->mini_map, 30, 30); } } <file_sep>/parsing/my_str_to_wordtab.c /* ** my_str_to_wordtab.c for fdf in /home/guervi_a/rendu/Igraph/MUL_2014_fdf ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Nov 16 14:01:31 2014 <NAME> ** Last update Tue Dec 16 13:57:59 2014 <NAME> */ #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include "my.h" #include "get_next_line.h" int count_words(char *str) { int i; int words; i = 0; words = 0; while (str[i] != '\0') { while (str[i] != '\0' && (str[i++] == ' ' || str[i] == '\t')); while (str[i] != '\0' && (str[i] != ' ' && str[i] != '\t')) { i++; } if (str[i - 1] != ' ' && str[i - 1] != '\t') words++; } return (words); } int wordlen(char *str, int nb_word) { int i; int j; int wordlen; i = 0; j = 1; wordlen = 1; while (str[i] != '\0' && j <= nb_word) { while (str[i] != '\0' && (str[i++] == ' ' || str[i] == '\t')); while (str[i] != '\0' && (str[i] != ' ' && str[i] != '\t')) { if (j == nb_word) wordlen++; i++; } j++; } return (wordlen); } int get_word(char *str, int nb) { int i; int j; int k; char *word; i = 0; k = 1; if ((word = malloc(wordlen(str, nb) + 1 * sizeof(char))) == NULL) return (0); while (str[i] != '\0' && k <= nb) { j = 0; while (str[i] != '\0' && (str[i] == ' ' || str[i] == '\t')) i++; while (str[i] != '\0' && (str[i] != ' ' && str[i] != '\t')) { if (k == nb) word[j] = str[i]; i++; j++; } k++; } word[j] = '\0'; return (my_getnbr(word)); } int *my_str_to_wordtab(char *str) { int *tab; int nbr_words; int i; int j; i = 0; j = 1; nbr_words = count_words(str); if ((tab = malloc(nbr_words * sizeof(int))) == NULL) return (0); while (j <= count_words(str)) { tab[i] = get_word(str, j); i++; j++; } return (tab); } <file_sep>/draw/draw.c /* ** draw.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Dec 13 18:52:53 2014 <NAME> ** Last update Fri Dec 19 19:17:07 2014 <NAME> */ #include "my.h" #include "mlx.h" int draw_roof(t_game *game, int x) { int y; int y_two; y = -1; y_two = (WIN_Y / 2) - game->h; while (++y <= y_two) { my_pixel_put_to_image(game, x, y, 0xCCCCFF); } } int draw_floor(t_game *game, int x) { int y; int y_two; y = (WIN_Y / 2) + game->h - 1; y_two = WIN_Y; while (++y <= y_two) my_pixel_put_to_image(game, x, y, 0x55CC55); } int draw_walls(t_game *game, int x) { int y; int y_two; y = (WIN_Y / 2) - game->h - 1; y_two = (WIN_Y / 2) + game->h; while (++y <= y_two) { if (game->or_color == 0) my_pixel_put_to_image(game, x, y, 0xDDDDDD); else if (game->or_color == 1) my_pixel_put_to_image(game, x, y, 0xCCCCCC); } } <file_sep>/draw/vision.c /* ** vision.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Dec 10 09:11:04 2014 <NAME> ** Last update Fri Dec 19 14:19:32 2014 <NAME> */ #include <stdlib.h> #include <math.h> #include "my.h" void calc_xy(t_game *game, int x_draw) { float x; float y; float a; float tmpx; a = game->player->angle * M_PI / 180; x = DIST; y = (float)(SEGMENT *\ (((float)(WIN_X / 2) - (float)x_draw) / WIN_X)); tmpx = x; x = (x * cos(a)) - (y * sin(a)); y = (tmpx * sin(a)) + (y * cos(a)); game->vec->x = x + game->player->pos->x; game->vec->y = y + game->player->pos->y; } int k_x(t_game *game) { int x; int y; float k; x = 0; while (x < game->map_x) { k = (x - game->player->pos->x) / \ (game->vec->x - game->player->pos->x); y = (game->player->pos->y +\ (k * (game->vec->y - game->player->pos->y))); if (k < game->k && k > 0 && y < game->map_y && y > 0 &&\ (game->map[y][x] != 0 ||\ game->map[y][x - 1] != 0)) { game->or_color = 0; game->k = k; } x++; } } int k_y(t_game *game) { int x; int y; float k; y = 0; while (y < game->map_y) { k = (y - game->player->pos->y) / \ (game->vec->y - game->player->pos->y); x = (game->player->pos->x +\ (k * (game->vec->x - game->player->pos->x))); if (k < game->k && k > 0 && x < game->map_x && x > 0 &&\ (game->map[y][x] != 0 ||\ game->map[y - 1][x] != 0)) { game->or_color = 1; game->k = k; } y++; } } int view(t_game *game) { int x; x = 0; while (x < WIN_X) { game->k = 40; calc_xy(game, x); k_x(game); k_y(game); game->h = WIN_Y / (2 * game->k); draw_roof(game, x); draw_walls(game, x); draw_floor(game, x); x++; } } <file_sep>/Makefile ## ## Makefile for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ## ## Made by <NAME> ## Login <<EMAIL>> ## ## Started on Tue Dec 9 16:50:16 2014 <NAME> ## Last update Wed Aug 26 00:14:52 2015 <NAME> ## CC = cc NAME = wolf3d RM = rm -f SRC = parsing/parsing.c \ parsing/my_str_to_wordtab.c \ parsing/get_next_line.c \ events/events.c \ events/move.c \ draw/vision.c \ draw/draw.c \ draw/draw_mini_map.c \ draw/my_put_pixel_to_image.c \ functions.c \ main.c CFLAGS = -I./include OBJ = $(SRC:.c=.o) LIB = -lm -lmlx -L./minilibx -lX11 -lXext all: $(NAME) $(NAME): $(OBJ) $(CC) -o $(NAME) $(OBJ) $(LIB) clean: $(RM) $(OBJ) fclean: clean $(RM) $(NAME) re: fclean all <file_sep>/events/events.c /* ** events.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 9 17:39:28 2014 <NAME> ** Last update Fri Dec 19 19:12:04 2014 <NAME> */ #include <stdlib.h> #include <stdio.h> #include <X11/X.h> #include <math.h> #include "mlx.h" #include "my.h" int hook_press(int keycode, t_game *game) { if (keycode == ARROW_UP) game->keys->up = 1; if (keycode == ARROW_DOWN) game->keys->down = 1; if (keycode == ARROW_LEFT) game->keys->left = 1; if (keycode == ARROW_RIGHT) game->keys->right = 1; if (keycode == ESCAPE) game->keys->escape = 1; } int hook_release(int keycode, t_game *game) { if (keycode == ARROW_UP) game->keys->up = 0; if (keycode == ARROW_DOWN) game->keys->down = 0; if (keycode == ARROW_LEFT) game->keys->left = 0; if (keycode == ARROW_RIGHT) game->keys->right = 0; if (keycode == ESCAPE) game->keys->escape = 0; } int gere_key(t_game *game) { move(game); if (game->keys->escape == 1) exit(1); } int init_keys(t_game *game) { game->keys->up = 0; game->keys->down = 0; game->keys->left = 0; game->keys->right = 0; game->keys->escape = 0; } int events(t_game *game) { view(game); draw_mini_map(game); mlx_put_image_to_window(game->window->mlx_ptr, game->window->mlx_win, \ game->window->img, 0, 0); mlx_put_image_to_window(game->window->mlx_ptr, game->window->mlx_win,\ game->window->mini_map, 30, 30); init_keys(game); mlx_hook(game->window->mlx_win, KeyPress, KeyPressMask, &hook_press, game); mlx_hook(game->window->mlx_win, KeyRelease, KeyReleaseMask, &hook_release,\ game); mlx_loop_hook(game->window->mlx_ptr, &gere_key, game); mlx_loop(game->window->mlx_ptr); } <file_sep>/include/get_next_line.h /* ** get_next_line.h for get_next_line in /home/guervi_a/rendu/C_Prog_Elem/CPE_2014_getnextline/include ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Mon Nov 10 11:21:07 2014 <NAME> ** Last update Wed Nov 19 15:55:22 2014 <NAME> */ #ifndef GET_NEXT_LINE_H_ # define GET_NEXT_LINE_H_ # define BUFFER 30000 char *get_next_line(const int fd); #endif /* !GET_NEXT_LINE_H_ */ <file_sep>/include/my.h /* ** my.h for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 9 14:10:57 2014 <NAME> ** Last update Wed Aug 26 00:27:11 2015 <NAME> */ #ifndef MY_H_ # define MY_H_ # define ABS(value) ((value) < 0) ? ((value) * (-1)) : (value) # define ARROW_UP 65362 # define ARROW_DOWN 65364 # define ARROW_LEFT 65361 # define ARROW_RIGHT 65363 # define ESCAPE 65307 # define SEGMENT 1 # define DIST (0.5) # define ANGLE 60 # define WIN_X 1280 # define WIN_Y 720 typedef struct s_window { void *mlx_ptr; void *mlx_win; void *img; void *mini_map; char *data; } t_window; typedef struct s_vec { float x; float y; } t_vec; typedef struct s_line { int x; int y; } t_line; typedef struct s_keys { int up; int down; int left; int right; int escape; } t_keys; typedef struct s_player { float angle; t_vec *pos; } t_player; typedef struct s_draw_minimap { int x; int y; int size; } t_draw_minimap; typedef struct s_game { t_keys *keys; t_window *window; t_player *player; t_vec *vec; t_draw_minimap *draw_minimap; float k; float h; int **map; int map_x; int map_y; char or_color; } t_game; int hook_press(int keycode, t_game *game); int hook_release(int keycode, t_game *game); int gere_key(t_game *game); int **tab_tab_int(char **tab_lines, char *file_name); char **get_tab_lines(int fd, char *file_name); char *my_strdup(char *src); int *my_str_to_wordtab(char *str); int events(t_game *game); int count_lines(char *file_name); int count_words(char *tab_char); char *my_strcpy(char *dest, char *src); void my_pixel_put_to_minimap(t_game *game, int x, int y,\ unsigned int color); void my_pixel_put_to_image(t_game *game, int x, int y,\ unsigned int color); int draw_roof(t_game *game, int x); int draw_walls(t_game *game, int x); int draw_floor(t_game *game, int x); int my_getnbr(char *str); int move(t_game *game); int view(t_game *game); int draw_mini_map(t_game *game); #endif /* !MY_H_ */ <file_sep>/draw/draw_mini_map.c /* ** draw_mini_map.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sat Dec 13 19:00:53 2014 <NAME> ** Last update Sat Dec 20 15:38:48 2014 <NAME> */ #include "my.h" #include "mlx.h" int fill(t_game *game) { int x; int y; y = 0; while (y <= 150) { x = 0; while (x <= 150) { my_pixel_put_to_minimap(game, x, y, 0x000000); x++; } y++; } } int draw_square(t_game *game, unsigned int color) { int xp; int x_max; int y_max; int yp; yp = game->draw_minimap->y; y_max = yp + game->draw_minimap->size; while (yp <= y_max) { xp = game->draw_minimap->x; x_max = xp + game->draw_minimap->size; while (xp <= x_max) { my_pixel_put_to_minimap(game, xp, yp, color); xp++; } yp++; } } int init_minimap(t_game *game) { fill(game); game->draw_minimap->y = 0; game->draw_minimap->size = 30; } int draw_mini_map(t_game *game) { int x; int y; init_minimap(game); y = (int)game->player->pos->y - 3; while (++y <= ((int)game->player->pos->y + 2)) { x = (int)game->player->pos->x - 3; game->draw_minimap->x = 0; while (++x <= ((int)game->player->pos->x + 2)) { if (x >= 0 && y >= 0 && x < game->map_x && y < game->map_y) { if (game->draw_minimap->x == 60 && game->draw_minimap->y == 60) draw_square(game, 0xFF0000); else if (game->map[y][x] == 1) draw_square(game, 0x000000); else if (game->map[y][x] == 0) draw_square(game, 0xFFFFFF); } game->draw_minimap->x += 30; } game->draw_minimap->y += 30; } } <file_sep>/functions.c /* ** functions.c for wolf3d in /home/sadzeih/rendu/Igraph/MUL_2014_wolf3d ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 9 18:37:54 2014 <NAME> ** Last update Wed Aug 26 00:27:25 2015 <NAME> */ #include <stdlib.h> #include "my.h" int sign(char *str) { int i; int m; i = 0; m = 0; while (str[i] == '-' || str[i] == '+') { if (str[i] == '-') m++; i++; } return (m); } int my_getnbr(char *str) { int m; int i; int nb; int nb2; i = 0; nb = 0; m = sign(str); while (str[i] == '-' || str[i] == '+') i++; while (str[i] >= 48 && str[i] <= 57) { nb2 = str[i] - 48; nb = nb * 10 + nb2; i++; } if (m % 2 != 0) { nb = nb * (-1); } return (nb); } int my_strlen(char *str) { int i; i = 0; while (str[i++] != '\0'); return (i); } char *my_strdup(char *src) { int size; char *dest; size = my_strlen(src); if ((dest = malloc((size + 2) * sizeof(char))) != NULL) { my_strcpy(dest, src); return (dest); } else { free(dest); return (0); } }
5e09a17ac49ff8f9f63b0113ea2523cfb2dc836f
[ "Markdown", "C", "Makefile" ]
15
C
Sadzeih/wolf3d
e2a74030fb1f4788425efb73c48bc7a90bdbc5bd
787693c904557afcbeb15b3df2ec4454a50cd6da
refs/heads/main
<file_sep>const { Client } = require('discord.js') const dotenv = require('dotenv') const { fetchData } = require('./fetchData') dotenv.config() const client = new Client() // eslint-disable-next-line client.on('ready', () => console.log(`Bot successfully started as ${client.user.tag} 🤖`)) // Updates token price on bot's nickname every X amount of time client.setInterval(async () => { const data = await fetchData() if (!data) return const { gasPriceGwei, gasPriceUsd } = data client.guilds.cache.forEach(async (guild) => { const botMember = guild.me await botMember.setNickname(`Gas: ${gasPriceGwei} gwei`) }) client.user.setActivity( `transfer fee: $${parseFloat(gasPriceUsd).toFixed(2)}`, { type: 'WATCHING' }, ) }, 1 * 60 * 1000) client.login(process.env.DISCORD_API_TOKEN) <file_sep>const dotenv = require('dotenv') const fetch = require('node-fetch') dotenv.config() exports.fetchData = async () => { try { const { result: { ProposeGasPrice: gasPriceGwei } } = await (await fetch( `https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=${process.env.ETHERSCAN_API_KEY}`, )).json() const { result: { ethusd: ethPrice } } = await (await fetch( `https://api.etherscan.io/api?module=stats&action=ethprice&apikey=${process.env.ETHERSCAN_API_KEY}`, )).json() const gasPriceUsd = +gasPriceGwei * 0.000000001 * +ethPrice * 21000 return { gasPriceGwei, gasPriceUsd } } catch (err) { console.log(err) return undefined } }
76c6bd2ac804eb95f118036ad6caec95bcb8f0cf
[ "JavaScript" ]
2
JavaScript
hernandoagf/eth-gas-price-bot
a229a166c4713bed31e64b09057752ebf9f79d46
91ec4d1c8142288cd083b2e09a50b7d6df0251f9
refs/heads/master
<file_sep><?php namespace Bolt\Extensions\Bolt\Colourpicker\Tests; use Bolt\Tests\BoltUnitTest; use Bolt\Extensions\Bolt\Colourpicker\Extension; /** * This test ensures the Colourpicker Loads correctly. * * @author <NAME> <<EMAIL>> **/ class ColourpickerTest extends BoltUnitTest { public function testExtensionLoads() { $app = $this->getApp(); $extension = new Extension($app); $app['extensions']->register( $extension ); $this->assertSame($extension, $app['extensions.colourpicker']); } }<file_sep><?php define('TEST_ROOT', __DIR__.'/tmp'); define('PHPUNIT_ROOT', __DIR__); @mkdir('tmp/app/cache', 0777, true); @mkdir('tmp/app/config', 0777, true); @mkdir('tmp/app/database', 0777, true); require 'vendor/autoload.php';<file_sep>### Colourpicker Extension for Bolt
ad457e9a4d52f0da9cfa600549c9da2ab9655d99
[ "Markdown", "PHP" ]
3
PHP
Raistlfiren/bolt-extension-colourpicker
bde916d844868b72889fd68d0343857ac1599dc6
086a8ddac914141f935d3cb0295f739f98c5ae70
refs/heads/master
<file_sep>/*Chart 1*/ var ctx = document.getElementById('summaryChart'); var ctx2 = document.getElementById('scoreChart'); var stars = [135850, 52122, 148825, 16939, 9763]; var frameworks = ['React', 'Angular', 'Vue', 'Hyperapp', 'Omi']; var myChart = new Chart(ctx, { type: 'bar', data: { labels: frameworks, datasets: [{ label: 'Github Stars', data: stars }] }, options: { maintainAspectRatio: true, responsive: true, } }); var myChart2 = new Chart(ctx2, { type: 'bar', data: { labels: frameworks, datasets: [{ label: 'Github Stars', data: stars }] }, options: { maintainAspectRatio: true, } }); let summaryPage = document.querySelector(".summary"); let scorePage = document.querySelector(".score"); summaryPage.style.display = "none"; scorePage.style.display = "none";
63affc142481018777169d6f8dd9352263eb39c9
[ "JavaScript" ]
1
JavaScript
ace-smart/colaberation-bot
919ec41c085872141846573ebabf3c70db5ed1ce
14a3c9fa0734e4c66f40189325a214d9289d05d0
refs/heads/main
<file_sep>const users = require('../model/fakeUserData'); module.exports = { showUsers: (req, res, next) => { res.send(users); } }<file_sep>const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; const bodyParser = require('body-parser'); const cors = require('cors'); const userController = require('./controller/userController'); const homeController = require('./controller/homeController'); app.use(express.json()); // app.use(express.urlencoded({ extended: false })); app.use(bodyParser.urlencoded({ extended: false })); app.use(cors()); //Home route app.get('/', homeController.showUsers); //User routes app.post('/signin', userController.signin); app.post('/register', userController.register); app.get('/users/profile/:id', userController.findSingleUser); app.put('/users/updateEntries', userController.updateUserEntre); app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
bd5411f9d5fe491afea69271ba2866b03a6ddeb9
[ "JavaScript" ]
2
JavaScript
quagswagEthanZhao/FaceRecAppBackEnd
c96d9c7f531ec9e30fafb2221f901cc2e3779ff0
592708533f10ca54ed89d0c017ef5b1105d0b53e
refs/heads/master
<repo_name>psixsaba/api<file_sep>/app/Models/BalanceTransactionHistory.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class BalanceTransactionHistory extends Model { use HasFactory; protected $table = 'balance_transaction_historys'; protected $fillable = [ 'foreign_user_ID', 'transfer_amount', ]; public function user() { return $this->belongsTo( User::class, 'foreign_user_ID'); } } <file_sep>/app/Http/Controllers/Auth/UserFillBalanceController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\BalanceTransactionHistory; use Illuminate\Http\Request; use App\Models\User; use App\Models\Transaction; use Illuminate\Support\Facades\Validator; class UserFillBalanceController extends Controller { public function fill_balance(Request $request) { $data = $request->all(); $validator = Validator::make($data, [ 'user_id' => 'required', 'amount' => 'required|numeric|between:0,999.99' ]); $id = $request->user_id; $user = User::find($id); if ($user == null) { return response(['error_message' => 'User not found'], 404); } elseif ($validator->fails()){ return response(['error' => $validator->errors(), 'Validation Error'], 422); } $user->update($request->all()); $user->balance += $request->amount; $user->update(); $transaction = new BalanceTransactionHistory(); $transaction->foreign_user_id = $id; $transaction->transfer_amount = $request->amount; $transaction->save(); return response(['user' => $user, 'message' => 'Success'], 200); } public function transaction(Request $request) { $data = $request->all(); $validator = Validator::make($data, [ 'user_id' => 'required' ]); $id = $request->user_id; $user = User::find($id); if ($user == null) { return response(['error_message' => 'User not found'], 404); } elseif ($validator->fails()){ return response(['error' => $validator->errors(), 'Validation Error'], 422); } $recipient_user_ID = $id; $transactions = BalanceHistory::query()->where('foreign_user_ID', $recipient_user_ID)->get(); return response(['transactions' => $transactions, 'message' => 'Success'], 200); } public function transfer(Request $request , $user_id ) { $data = $request->validate([ 'email' => 'email|required', 'password' => '<PASSWORD>', ]); $dataValidator = $request->all(); $validator = Validator::make($dataValidator, [ 'amount' => 'required' ]); // $id = $request->user_id; $id = $user_id; $user = User::find($id); if (!auth()->attempt($data)) { return response(['error_message' => 'momxmareblis paroli an meili arasworia. gtxovt scadot tavidan']); } elseif ($user == null) { return response(['error_message' => 'momxmarebeli ar moidzebna'], 404); } elseif ($validator->fails()){ return response(['error' => $validator->errors(), 'Validation Error'], 422); } $token = auth()->user()->createToken('API Token')->accessToken; // $user->update($request->all()); $id = auth()->user()->id; $auth_user = User::find($id); // $auth_user->balance -= $request->amount; $auth_user->balance -= $request->amount; $auth_user->update(); // $user->balance += ($request->amount)*99/100; $user->balance += ($request->amount)*99/100; $user->update(); return response(['user' => auth()->user(), 'token' => $token]); } public function mytransaction(Request $request){ $data = $request->validate([ 'email' => 'email|required', 'password' => '<PASSWORD>', ]); if (!auth()->attempt($data)) { return response(['error_message' => 'araswori informacia. Please try again'], 422); } $id = auth()->user()->id; $mytransaction = Transaction::where('sender_user_id', $id)->get(); return response(['message' => $mytransaction]); } public function history(Request $request) { $data = $request->all(); $validator = Validator::make($data, [ 'user_id' => 'required' ]); $id = $request->user_id; $user = User::find($id); if ($user == null) { return response(['error_message' => 'momxmarebeli ar moidzebna'], 404); } elseif ($validator->fails()){ return response(['error' => $validator->errors(), 'Validation Error'], 422); } $foreign_user_ID = $id; $transactions = BalanceTransactionHistory::query()->where('foreign_user_ID', $foreign_user_ID)->get(); return response(['transactions' => $transactions, 'message' => 'Success']); } public function transactions(Request $request){ $data = $request->validate([ 'email' => 'email|required', 'password' => '<PASSWORD>', ]); if (!auth()->attempt($data)) { return response(['error_message' => 'araswori informacia. Please try again'], 422); } $is_admin = auth()->user()->is_admin; $transaction = Transaction::all(); $commission_sum = Transaction::sum('commission_amount'); if ($is_admin == 1) { return response(['message' => [$transaction, $commission_sum]]); } else { return response(['message' => 'tkven ar gaqvt wvdoma']); } } }
3aa84c4fdbd825cc6d8be6d5738e427f56aacd5d
[ "PHP" ]
2
PHP
psixsaba/api
91813a01cb034841c74b9470796ae52647ed7123
4827cb830e8e94c532458e069d41163e88056038
refs/heads/master
<repo_name>Ivaylo-Georgiev/OOP-FMI<file_sep>/Reverse Polish Notation/Stack.cpp #include <iostream> #include <math.h> #include "Stack.h"; //default constructor Stack::Stack() { mCapacity = DEFAULT; mTop = -1; mElements = new double[mCapacity]; mElements[0] = 0; } //constructor with a parameter Stack::Stack(int capacity) { mCapacity = capacity; mTop = -1; mElements = new double[mCapacity]; for (int i = 0; i < mCapacity; i++) { mElements[i] = 0; } } //copy constructor Stack::Stack(const Stack & rhs) { mCapacity = rhs.mCapacity; mTop = rhs.mTop; mElements = new double[mCapacity]; for (int i = 0; i < mCapacity; i++) { mElements[i] = rhs.mElements[i]; } } //operator overload Stack & Stack::operator=(const Stack & rhs) { if (this != &rhs) { delete[] mElements; mCapacity = rhs.mCapacity; mTop = rhs.mTop; mElements = new double[mCapacity]; for (int i = 0; i < mCapacity; i++) { mElements[i] = rhs.mElements[i]; } } return *this; } //destructor Stack::~Stack() { delete[] mElements; } //---member functions--- bool Stack::isEmpty() const { if (mTop == -1) { return true; } else { return false; } } bool Stack::isFull() const { if (mCapacity - 1 == mTop) { return true; } else { return false; } } //double capacity void Stack::Grow() { double * update = new double[mCapacity * 2]; for (int i = 0; i < mCapacity; i++) { update[i] = mElements[i]; } delete[] mElements; mElements = update; mCapacity *= 2; } void Stack::Push(double token) { if (isFull()) { Grow(); } mTop++; mElements[mTop] = token; } //get upmost element double Stack::Peek() const { if (isEmpty()) { std::cout << "Stack is empty."; return 404; } else { return mElements[mTop]; } } //remove the upmost element and return it double Stack::Pop() { if (isEmpty()) { std::cout << "Stack is empty"; return 404; } else { mTop--; return mElements[mTop + 1]; } } double Stack::Calculate(const char * input) { //empty the stack mTop = -1; int i = 0; double operand1 = 0, operand2 = 0; int digits = 0; bool isDouble = false, isNegative = false; while (input[i] != '\0') { //operand if (input[i] >= 48 && input[i] <= 57) { if (input[i-1] == '-') { isNegative = true; } //count digits while (input[i+digits]!=' ') { digits++; if (digits>=1 && (input[i+digits]==',' || input[i+digits] == '.')) { isDouble = true; break; } } for (int j = digits - 1; j >= 0; j--) { operand1 += (input[i] - 48) * (pow(10, j)); i++; } if (isDouble) { i++; digits = 0; while (input[digits + i] != ' ') { digits++; } for (int j = 1; j <= digits; j++) { operand1 += (input[i] - 48)*(pow(10, (-1)*j)); i++; } } if (isNegative) { operand1 *= -1; } Push(operand1); digits = 0; operand1 = 0; isDouble = false; isNegative = false; } //operator else { switch (input[i]) { case '%': { if (mTop >= 1) { operand2 = Pop(); operand1 = Pop(); if (operand1 == floor(operand1) && operand1 == ceil(operand1) && operand2 == floor(operand2) && operand2==ceil(operand2)) { Push((int)operand1 % (int)operand2); } break; } else { std::cout << "Wrong expression." << std::endl; return 404; } } case '*': { if (mTop >= 1) { Push(Pop()*Pop()); break; } else { std::cout << "Wrong expression." << std::endl; return 404; } } case '+': //43 -> + in ASCII { if (mTop >= 1) { Push(Pop() + Pop()); break; } else { std::cout << "Wrong expression." << std::endl; return 404; } } case '-': { if (input[i+1] >= 48 && input[i+1] <= 57) { break; } if (mTop >= 1) { operand2 = Pop(); operand1 = Pop(); Push(operand1 - operand2); break; } else { std::cout << "Wrong expression." << std::endl; return 404; } } case '/': { if (mTop >= 1) { operand2 = Pop(); operand1 = Pop(); Push(operand1 / operand2); break; } else { std::cout << "Wrong expression." << std::endl; return 404; } } } } i++; operand1 = 0; operand2 = 0; } if (mTop == 0) { return mElements[mTop]; } else { std::cout << "Wrong expressiont." << std::endl; return 404; } } <file_sep>/Reverse Polish Notation/Stack.h #pragma once const int DEFAULT = 1; //growing stack class Stack { private: int mCapacity; int mTop; double * mElements; public: Stack(); Stack(int); Stack(const Stack &); Stack & operator=(const Stack &); ~Stack(); bool isEmpty() const; bool isFull() const; void Grow(); void Push(double); double Peek() const; double Pop(); double Calculate(const char *); }; <file_sep>/DeviceAndNet/Main.cpp #include <iostream> #include "ElectricNet.h" int main() { ElectricDevice microwave("Microwave", 750); ElectricDevice tv("TV", 500); ElectricDevice lamp("Lamp", 250); ElectricDevice pc("PC", 500); ElectricNet alpha(1500); ElectricNet beta = alpha; ElectricNet epsilon; std::cout << "alpha:\n"; alpha += microwave; alpha = alpha+tv; alpha.PrintNet(); std::cout<<"opertor[] for alpha: \n"; alpha["Microwave"].Print(); std::cout << "beta:\n"; beta--; beta += lamp; beta = beta + pc; ++beta; beta -= lamp; beta += tv; beta = beta - tv; beta.PrintNet(); std::cout << "operator! for epsilon: " << !epsilon << std::endl; return 0; } <file_sep>/Store/Product.cpp #include <iostream> #include <string.h> #include "Product.h"; //default constructor Product::Product() { mSKU = 0; strcpy_s(mBrand, 20, "Unspecified"); strcpy_s(mModel, 20, "Unspecified"); strcpy_s(mMaterial, 20, "Unspecified"); mPrice = 0; mSize = 0; mCount = 0; } //constructor with params Product::Product(int SKU, char brand[], char model[], char material[], double price, int size, int count) { mSKU = SKU; strcpy_s(mBrand, 20, brand); strcpy_s(mModel, 20, model); strcpy_s(mMaterial, 20, material); mPrice = price; mSize = size; mCount = count; } void Product::InitFromConsole() { std::cout << "Set the characteristics of the suit: \n"; std::cout << "SKU: "; std::cin >> mSKU; std::cin.ignore(); std::cout << "Brand: "; std::cin.getline(mBrand, 20); //std::cin.ignore(); std::cout << "Model: "; std::cin.getline(mModel, 20); //std::cin.ignore(); std::cout << "Material: "; std::cin.getline(mMaterial, 20); //std::cin.ignore(); std::cout << "Price: "; std::cin >> mPrice; //std::cin.ignore(); std::cout << "Size: "; std::cin >> mSize; //std::cin.ignore(); std::cout << "Count: "; std::cin >> mCount; } //getters int Product::GetSKU() const { return mSKU; } const char * Product::GetBrand() const { return (char *)mBrand; } const char * Product::GetModel() const { return (char *)mModel; } const char * Product::GetMaterial() const { return (char *)mMaterial; } double Product::GetPrice() const { return mPrice; } int Product::GetSize() const { return mSize; } int Product::GetCount() const { return mCount; } //setters void Product::SetSKU(int SKU) { mSKU = SKU; } void Product::SetBrand(char brand[]) { strcpy_s(mBrand, 20, brand); } void Product::SetModel(char model[]) { strcpy_s(mModel, 20, model); } void Product::SetMaterial(char material[]) { strcpy_s(mMaterial, 20, material); } void Product::SetPrice(double price) { mPrice = price; } void Product::SetSize(int size) { mSize = size; } void Product::SetCount(int count) { mCount = count; } void Product::Print() const { std::cout << "SKU: " << mSKU << std::endl; std::cout << "Brand: " << mBrand << std::endl; std::cout << "Model: " << mModel << std::endl; std::cout << "Material: " << mMaterial << std::endl; std::cout << "Price: " << mPrice <<" euros"<< std::endl; std::cout << "Size: " << mSize << std::endl; std::cout << mCount << " item(s) in stock. \n"; } <file_sep>/BankSystem/SavingsAccount.cpp #include "SavingsAccount.h" #include <string> SavingsAccount::SavingsAccount(std::string IBAN, int ownerID, double amount, double rate) :Account(IBAN, ownerID, amount) { m_InterestRate = rate; } void SavingsAccount::Deposit(double sum) { sum = sum > 0 ? sum : sum * (-1); SetAmount(sum); } bool SavingsAccount::Withdraw(double sum) { sum = sum > 0 ? sum : sum * (-1); if (GetBalance()<sum) { return false; } else { SetAmount(sum*(-1)); return true; } } void SavingsAccount::Display() const { std::cout << "Savings Account: \n"; std::cout << "IBAN: " << GetIBAN() << std::endl; std::cout << "Owner ID: " << GetOwnerID() << std::endl; std::cout << "Interest rate: " << m_InterestRate << std::endl; std::cout << "Balance: " << GetBalance() << std::endl; } <file_sep>/BankSystem/Bank.cpp #include "Bank.h" #include "CurrentAccount.h" #include "SavingsAccount.h" #include "PrivilegeAccount.h" #include <string> Bank::Bank(std::string name, std::string adress, std::vector<Customer> customers, std::vector<Account*> accounts) { m_Name = name; m_Adress = adress; m_Customers = customers; for (unsigned i = 0; i < accounts.size(); ++i) { m_Accounts.push_back(accounts[i]->Clone()); } } Bank::Bank(const Bank& rhs) { m_Name = rhs.m_Name; m_Adress = rhs.m_Adress; m_Customers = rhs.m_Customers; for (unsigned i = 0; i < rhs.m_Accounts.size(); ++i) { m_Accounts.push_back(rhs.m_Accounts[i]->Clone()); } } Bank& Bank::operator=(const Bank & rhs) { if (this!=&rhs) { m_Name = rhs.m_Name; m_Adress = rhs.m_Adress; m_Customers = rhs.m_Customers; for (unsigned i = 0; i < m_Accounts.size(); ++i) { delete m_Accounts[i]; m_Accounts.erase(m_Accounts.begin() + i); --i; } for (unsigned i = 0; i < rhs.m_Accounts.size(); ++i) { m_Accounts.push_back(rhs.m_Accounts[i]->Clone()); } } return *this; } Bank::~Bank() { for (unsigned i = 0; i < m_Accounts.size(); ++i) { delete m_Accounts[i]; } } Account* Bank::GetAccount(std::string IBAN) { for (unsigned i = 0; i <m_Accounts.size() ; ++i) { if (m_Accounts[i]->GetIBAN()==IBAN) { return m_Accounts[i]; } } return nullptr; } void Bank::AddCustomer(int customerID, std::string name, std::string adress) { bool isFound = false; for (unsigned i = 0; i < m_Customers.size(); ++i) { if (m_Customers[i].GetID() == customerID) { isFound = true; std::cout << "A customer with that ID is already in the list. \n"; break; } } if (!isFound) { m_Customers.push_back(Customer(customerID, name, adress)); } } void Bank::ListCustomers() const { for (unsigned i = 0; i < m_Customers.size(); ++i) { m_Customers[i].Display(); } std::cout << std::endl; } void Bank::DeleteCustomer(int customerID) { bool isFound = false; for (unsigned i = 0; i < m_Customers.size(); ++i) { if (m_Customers[i].GetID() == customerID) { isFound = true; m_Customers.erase(m_Customers.begin()+i); break; } } if (!isFound) { std::cout << "Customer not found. \n"; } else { for (unsigned j = 0; j < m_Accounts.size(); ++j) { if (m_Accounts[j]->GetOwnerID() == customerID) { delete m_Accounts[j]; m_Accounts.erase(m_Accounts.begin() + j); --j; } } } } void Bank::AddAccount(std::string accountType, std::string IBAN, int ownerID, double amount) { bool uniqueIBAN = true; bool ownerFound = false; for (unsigned i = 0; i < m_Customers.size(); ++i) { if (m_Customers[i].GetID()==ownerID) { ownerFound = true; break; } } for (unsigned i = 0; i < m_Accounts.size(); ++i) { if (m_Accounts[i]->GetIBAN()==IBAN) { uniqueIBAN = false; break; } } if (uniqueIBAN && ownerFound) { if (accountType=="Current Account") { m_Accounts.push_back(new CurrentAccount(IBAN, ownerID, amount)); } else if (accountType == "Savings Account") { std::cout << "Rate: "; double rate; std::cin >> rate; m_Accounts.push_back(new SavingsAccount(IBAN, ownerID, amount,rate)); } else if (accountType == "Privilege Account") { std::cout << "Overdraft: "; double overdraft; std::cin >> overdraft; m_Accounts.push_back(new PrivilegeAccount(IBAN, ownerID, amount,overdraft)); } else { std::cout << "Invalid account type. Choose between Current Account, Savings Account or Privilege Account. \n"; } } else { std::cout << "IBAN is not unique or customer not found. \n"; } } void Bank::ListAccounts() const { for (unsigned i = 0; i < m_Accounts.size(); ++i) { m_Accounts[i]->Display(); std::cout << std::endl; } } void Bank::ListCustomerAccounts(int customerID) const { bool IDfound = false; for (unsigned i = 0; i < m_Accounts.size(); ++i) { if (m_Accounts[i]->GetOwnerID()==customerID) { IDfound = true; m_Accounts[i]->Display(); std::cout << std::endl; } } if (!IDfound) { std::cout << "No accounts to display. \n"; } } void Bank::DeleteAccount(std::string IBAN) { bool isFound = false; for (unsigned i = 0; i < m_Accounts.size(); ++i) { if (m_Accounts[i]->GetIBAN()==IBAN) { isFound = true; delete m_Accounts[i]; m_Accounts.erase(m_Accounts.begin() + i); } } if (!isFound) { std::cout << "Account not found\n"; } } void Bank::Transfer(std::string fromIBAN, std::string toIBAN, double amount) { bool fromFound = false; bool toFound = false; bool WithDrawComplete = false; for (unsigned i = 0; i < m_Accounts.size(); ++i) { if (m_Accounts[i]->GetIBAN() == fromIBAN) fromFound = true; if (m_Accounts[i]->GetIBAN() == toIBAN) toFound = true; if (fromFound && toFound) break; } if (fromFound && toFound) { for (unsigned i = 0; i < m_Accounts.size(); ++i) { if ((m_Accounts[i]->GetIBAN() == fromIBAN && m_Accounts[i]->GetBalance() >= amount) || (m_Accounts[i]->GetIBAN() == fromIBAN && dynamic_cast<PrivilegeAccount*>(m_Accounts[i]) && m_Accounts[i]->GetBalance()+dynamic_cast<PrivilegeAccount*>(m_Accounts[i])->GetOverdraft()>=amount)) { m_Accounts[i]->Withdraw(amount); WithDrawComplete = true; } } if (!WithDrawComplete) { std::cout << "Impossible transfer. \n"; return; } for (unsigned i = 0; i < m_Accounts.size(); ++i) { if (m_Accounts[i]->GetIBAN() == toIBAN && WithDrawComplete) { m_Accounts[i]->Deposit(amount); } } } else { std::cout << "At least one of the accounts was not found. \n"; } } void Bank::Display() const { std::cout <<"Name: "<< m_Name<<std::endl; std::cout <<"Adress: "<< m_Adress << std::endl; std::cout << "--- Customers ---\n"; for (unsigned i = 0; i < m_Customers.size(); ++i) { m_Customers[i].Display(); std::cout << std::endl; } std::cout << "--- Accounts ---\n"; for (unsigned i = 0; i < m_Accounts.size(); ++i) { m_Accounts[i]->Display(); std::cout << std::endl; } } <file_sep>/Browser History/HistoryEntry.cpp #include <string.h> #include "HistoryEntry.h"; //default constructor HistoryEntry::HistoryEntry() { mMonth = January; strcpy_s(mURL, 100, "www.unknownadress.org"); } //constructor with params HistoryEntry::HistoryEntry(Month month, char URL[]) { mMonth = month; strcpy_s(mURL, 100, URL); } <file_sep>/Vehicle/Truck.cpp #include "Truck.h" #include <iostream> Truck::Truck() :Vehicle("","","",0,0) { m_size = 0; } Truck::Truck(const char * make, const char * model, const char * color, int year, int mileage, int size) :Vehicle(make,model,color,year,mileage) { m_size = size; } int Truck::GetSize() const { return m_size; } void Truck::SetSize(int size) { m_size = size; } void Truck::Details() const { std::cout << "Make: " << GetMake() << std::endl; std::cout << "Model: " << GetModel() << std::endl; std::cout << "Color: " << GetColor() << std::endl; std::cout << "Year: " << GetYear() << std::endl; std::cout << "Mileage: " << GetMileage() << std::endl; std::cout << "Size: " << GetSize() << std::endl; std::cout << std::endl; } <file_sep>/Vehicle/Main.cpp #include "Car.h" #include "Truck.h" #include "Motorcycle.h" int main() { //Vehicle v; Car TeslaRoadster("Tesla", "Roadster", "Red", 2008, 0); Car RRPhantom("Rolls-Royce", "Phantom", "Black", 2018, 0); Car Tesla = TeslaRoadster; Car RR; RR = RRPhantom; Tesla.Details(); RR.Details(); Truck NikolaOne("Nikola", "One", "White", 2016, 0, 12); Truck VolvoVNX("Volvo", "VNX", "Black", 2014, 0, 13); Truck Nikola = NikolaOne; Truck Volvo; Volvo = VolvoVNX; Nikola.Details(); Volvo.Details(); Motorcycle HDRoadKing("<NAME>", "Road King", "Blue", 2017, 0, "Touring"); Motorcycle HDFreewheeler("<NAME>", "Freewheeler", "Gray", 2018, 0, "Trike"); Motorcycle HD1 = HDRoadKing; Motorcycle HD2; HD2 = HDFreewheeler; HD1.Details(); HD2.Details(); Vehicle* c = new Car("Lada", "Vesta", "Red", 2018, 0); c->Details(); delete c; Vehicle* t; Truck MANTGM("MAN", "TGM", "Gray", 2015, 0, 11); t = &MANTGM; t->Details(); Vehicle* m = new Motorcycle("BMW", "HP 4 race", "Black", 2015, 0, "Sport"); m->Details(); delete m; return 0; } <file_sep>/Browser History/BrowserHistory.h #pragma once #include "HistoryEntry.h"; class BrowserHistory { private: int mCapacity, mTopEntry; HistoryEntry * mEntries; public: //constructor BrowserHistory(int); //copy constructor BrowserHistory(const BrowserHistory &); //operator overload BrowserHistory & operator=(const BrowserHistory &); //destructor ~BrowserHistory(); //member funcs void Write(); void Add(const HistoryEntry &); void Print(); int CountVisitedSites(Month); Month FindMostActiveMonth(); void Pop(); BrowserHistory Concatenate(const BrowserHistory &); }; <file_sep>/DeviceAndNet/ElectricDevice.h #pragma once class ElectricDevice { public: //canonical form ElectricDevice(); ElectricDevice(const char *, int); ElectricDevice(const ElectricDevice &); ElectricDevice& operator=(const ElectricDevice&); ~ElectricDevice(); //selectors const char * GetName() const; int GetkWs() const; void Print() const; private: char * m_Name; int m_kWs; void SetDevice(const char *, int); }; <file_sep>/DeviceAndNet/ElectricNet.cpp #include <iostream> #include "ElectricNet.h" //---ancillary functions void ElectricNet::Increase() //double capacity { ElectricDevice * temp = new ElectricDevice[m_Capacity*2]; for (int i = 0; i < m_Capacity; ++i) { temp[i] = m_Devices[i]; } delete[] m_Devices; m_Devices = temp; m_Capacity *= 2; } void ElectricNet::PrintNet() const { for (int i = 0; i < m_PluggedDevices; ++i) { m_Devices[i].Print(); } } //---canonical form //initially the net has no devices plugged in and capacity for 2, //which potentially can increase over time, as long as maxkWs is not reached ElectricNet::ElectricNet(int maxkWs) { m_PluggedDevices = 0; m_Capacity = 2; m_MaxkWs = maxkWs; m_Devices = new ElectricDevice[m_Capacity]; } ElectricNet::ElectricNet(const ElectricNet & rhs) { m_PluggedDevices = rhs.m_PluggedDevices; m_Capacity = rhs.m_Capacity; m_MaxkWs = rhs.m_MaxkWs; m_Devices = new ElectricDevice[m_Capacity]; for (int i = 0; i < m_PluggedDevices; ++i) { m_Devices[i] = rhs.m_Devices[i]; } } ElectricNet& ElectricNet::operator=(const ElectricNet & rhs) { if (this!=&rhs) { delete[]m_Devices; m_PluggedDevices = rhs.m_PluggedDevices; m_Capacity = rhs.m_Capacity; m_MaxkWs = rhs.m_MaxkWs; m_Devices = new ElectricDevice[m_Capacity]; for (int i = 0; i < m_PluggedDevices; ++i) { m_Devices[i] = rhs.m_Devices[i]; } } return *this; } ElectricNet::~ElectricNet() { delete[] m_Devices; } //---operators--- ElectricNet& ElectricNet::operator+=(const ElectricDevice & token) { //double net capacity if necessary if (m_PluggedDevices==m_Capacity) { Increase(); } int sum = token.GetkWs(); for (int i = 0; i < m_PluggedDevices; ++i) { sum += m_Devices[i].GetkWs(); } //add device if (sum<=m_MaxkWs) { m_Devices[m_PluggedDevices++] = token; } //max kWs is reached else { std::cout << "Circuit overload. Your device was not connected to the net. \n"; } return *this; } ElectricNet& ElectricNet::operator+(const ElectricDevice & token) { *this += token; return *this; } ElectricNet& ElectricNet::operator-=(const ElectricDevice & token) { //check for any connected devices if (m_PluggedDevices==0) { std::cout << "There are no devices, connected to the net. \n"; return *this; } //check if token is connected to the net bool found = false; for (int i = 0; i < m_PluggedDevices; ++i) { //if found then remove if (strcmp(m_Devices[i].GetName(),token.GetName())==0) { --m_PluggedDevices; found = true; for (int j = i; j < m_PluggedDevices; j++) { m_Devices[j] = m_Devices[j + 1]; } } } //if not found then do nothing if (!found) { std::cout << "No such item was found. \n"; } return *this; } ElectricNet& ElectricNet::operator-(const ElectricDevice & token) { *this -= token; return *this; } ElectricDevice& ElectricNet::operator[](const char * str) { //check for device with that name bool found = false; for (int i = 0; i < m_PluggedDevices; i++) { if (strcmp(m_Devices[i].GetName(), str)==0) { return m_Devices[i]; } } if (!found) { std::cout<<"No such device was found. \n"; } } bool ElectricNet::operator!() { if (m_PluggedDevices==0) { return false; } else { return true; } } ElectricNet& ElectricNet::operator++() { m_MaxkWs *= 2; return *this; } ElectricNet ElectricNet::operator++(int dummy) { ElectricNet temp = *this; ++*this; return temp; } ElectricNet& ElectricNet::operator--() { int sum = 0; for (int i = 0; i < m_PluggedDevices; ++i) { sum += m_Devices[i].GetkWs(); } if (sum<=m_MaxkWs/2) { m_MaxkWs /= 2; } else { std::cout << "It is impossible to halve max kWs. \n"; } return *this; } ElectricNet ElectricNet::operator--(int a) { ElectricNet temp = *this; --*this; return temp; } <file_sep>/Vehicle/Car.h #pragma once #include "Vehicle.h" class Car : public Vehicle { public: Car(); Car(const char *, const char *, const char *, int, int); Car(const Car &) = default; Car& operator=(const Car &) = default; ~Car() = default; void Details() const; }; <file_sep>/README.md # OOP-FMI Includes assignments from the OOP course, FMI. <file_sep>/Vehicle/Car.cpp #include "Car.h" #include <iostream> Car::Car() :Vehicle("","","",0,0) {} Car::Car(const char * make, const char * model, const char * color, int year, int mileage) :Vehicle(make, model, color, year, mileage) {} void Car::Details() const { std::cout << "Make: " << GetMake()<<std::endl; std::cout << "Model: " << GetModel() << std::endl; std::cout << "Color: " << GetColor() << std::endl; std::cout << "Year: " << GetYear() << std::endl; std::cout << "Mileage: " << GetMileage() << std::endl; std::cout << std::endl; } <file_sep>/Vehicle/Vehicle.cpp #include <string.h> #include "Vehicle.h" //---canonical form--- void Vehicle::Initialise(const char* make, const char * model, const char * color, int year, int mileage) { m_make = new char[strlen(make) + 1]; strcpy_s(m_make, strlen(make) + 1, make); m_model = new char[strlen(model) + 1]; strcpy_s(m_model, strlen(model) + 1, model); m_color = new char[strlen(color) + 1]; strcpy_s(m_color, strlen(color) + 1, color); m_year = year; m_mileage = mileage; } Vehicle::Vehicle() { Initialise("", "", "", 0, 0); } Vehicle::Vehicle(const char* make, const char * model, const char* color, int year, int mileage) { Initialise(make, model, color,year,mileage); } Vehicle::Vehicle(const Vehicle & rhs) { Initialise(rhs.m_make, rhs.m_model, rhs.m_color, rhs.m_year, rhs.m_mileage); } Vehicle& Vehicle::operator=(const Vehicle& rhs) { if (this!=&rhs) { delete[] m_make; delete[] m_model; delete[] m_color; Initialise(rhs.m_make, rhs.m_model, rhs.m_color, rhs.m_year, rhs.m_mileage); } return *this; } Vehicle::~Vehicle() { delete[] m_make; delete[] m_model; delete[] m_color; } //---getters--- const char * Vehicle::GetMake() const { return m_make; } const char * Vehicle::GetModel() const { return m_model; } const char * Vehicle::GetColor() const { return m_color; } int Vehicle::GetYear() const { return m_year; } int Vehicle::GetMileage() const { return m_mileage; } //---setters--- void Vehicle::SetMake(const char * make) { delete[] m_make; m_make = new char[strlen(make) + 1]; strcpy_s(m_make, strlen(make) + 1, make); } void Vehicle::SetModel(const char * model) { delete[] m_model; m_model = new char[strlen(model) + 1]; strcpy_s(m_model, strlen(model) + 1, model); } void Vehicle::SetColor(const char * color) { delete[] m_color; m_color = new char[strlen(color) + 1]; strcpy_s(m_color, strlen(color) + 1, color); } void Vehicle::SetYear(int year) { m_year = year; } void Vehicle::SetMileage(int mileage) { m_mileage = mileage; } <file_sep>/BankSystem/Bank.h #pragma once #include <iostream> #include <vector> #include "Account.h" #include "Customer.h" class Bank { public: Bank(std::string, std::string, std::vector<Customer>, std::vector<Account*>); Bank(const Bank&); Bank& operator=(const Bank &); ~Bank(); std::string GetAdress() const { return m_Adress; } std::string GetName() const { return m_Name; } Account* GetAccount(std::string IBAN); void AddCustomer(int customerID, std::string name, std::string adress); void ListCustomers() const; void DeleteCustomer(int customerID); void AddAccount(std::string accountType, std::string IBAN, int ownerID, double amount); void DeleteAccount(std::string IBAN); void ListAccounts() const; void ListCustomerAccounts(int customerID) const; void Transfer(std::string fromIBAN, std::string toIBAN, double amount); void Display() const; private: std::string m_Name; std::string m_Adress; std::vector<Customer> m_Customers; std::vector<Account*> m_Accounts; }; <file_sep>/BankSystem/CurrentAccount.cpp #include "CurrentAccount.h" #include <string> CurrentAccount::CurrentAccount(std::string IBAN, int ownerID, double amount) :Account(IBAN, ownerID,amount) {} void CurrentAccount::Deposit(double sum) { sum = sum > 0 ? sum : sum * (-1); SetAmount(sum); } bool CurrentAccount::Withdraw(double sum) { sum = sum > 0 ? sum : sum * (-1); if (GetBalance()<sum) { return false; } else { SetAmount(sum*(-1)); return true; } } void CurrentAccount::Display() const { std::cout << "Current Account: \n"; std::cout << "IBAN: " << GetIBAN() << std::endl; std::cout << "Owner ID: " << GetOwnerID() << std::endl; std::cout << "Balance: " << GetBalance() << std::endl; } <file_sep>/Vehicle/Motorcycle.cpp #include "Motorcycle.h" #include <iostream> #include <string.h> Motorcycle::Motorcycle() :Vehicle("","","",0,0) { m_type = new char[1]; m_type[0] = '\0'; } Motorcycle::Motorcycle(const char * make, const char * model, const char * color, int year, int mileage, const char * type) :Vehicle(make, model, color, year, mileage) { m_type = new char[strlen(type) + 1]; strcpy_s(m_type, strlen(type) + 1, type); } Motorcycle::Motorcycle(const Motorcycle & rhs) :Vehicle(rhs) { m_type = new char[strlen(rhs.m_type) + 1]; strcpy_s(m_type, strlen(rhs.m_type) + 1, rhs.m_type); } Motorcycle& Motorcycle::operator=(const Motorcycle & rhs) { if (this!=&rhs) { Vehicle::operator=(rhs); delete[] m_type; m_type = new char[strlen(rhs.m_type) + 1]; strcpy_s(m_type, strlen(rhs.m_type) + 1, rhs.m_type); } return *this; } Motorcycle::~Motorcycle() { delete[] m_type; } const char * Motorcycle::GetType() const { return m_type; } void Motorcycle::SetType(const char * type) { delete[] m_type; m_type = new char[strlen(type) + 1]; strcpy_s(m_type, strlen(type) + 1, m_type); } void Motorcycle::Details() const { std::cout << "Make: " << GetMake() << std::endl; std::cout << "Model: " << GetModel() << std::endl; std::cout << "Color: " << GetColor() << std::endl; std::cout << "Year: " << GetYear() << std::endl; std::cout << "Mileage: " << GetMileage() << std::endl; std::cout << "Type: " << GetType() << std::endl; std::cout << std::endl; } <file_sep>/BankSystem/Customer.h #pragma once #include "Account.h" #include <iostream> #include <vector> class Customer { public: Customer(int, std::string, std::string); int GetID() const { return m_ID; } std::string GetName() const { return m_Name; } std::string GetAdress() const { return m_Adress; } void Display() const; private: int m_ID; std::string m_Name; std::string m_Adress; }; <file_sep>/Browser History/Main.cpp #include <iostream> #include "BrowserHistory.h"; const char* ConvertMonthToString(Month m) { switch (m) { case January: return "January"; case February: return "Febraury"; case March: return "March"; case April: return "April"; case May: return "May"; case June: return "June"; case July: return "July"; case August: return "August"; case September: return "September"; case October: return "October"; case November: return "November"; case December: return "December"; } } int main() { //test char google[100] = "https://www.google.bg/"; char airbnb[100] = "https://www.airbnb.com/"; char evernote[100] = "https://www.evernote.com/"; char flickr[100] = "https://www.flickr.com/"; HistoryEntry first(June, flickr); HistoryEntry second(June, airbnb); HistoryEntry third(June, google); HistoryEntry fourth(June, airbnb); HistoryEntry fifth(July, airbnb); HistoryEntry sixth(August, evernote); BrowserHistory alpha(5); alpha.Add(first); alpha.Add(second); alpha.Add(fourth); alpha.Add(sixth); std::cout << "Please write your entry: \n"; alpha.Write(); std::cout << "alpha: \n"; alpha.Print(); std::cout<<"There are " << alpha.CountVisitedSites(June) << " visits in June."<<std::endl; std::cout <<"The most active month is: "<< ConvertMonthToString(alpha.FindMostActiveMonth()) << std::endl; std::cout << "\n\n --#--\n\n"; BrowserHistory beta(2); beta.Add(third); beta.Add(fourth); std::cout << "beta: \n"; beta.Print(); std::cout << "\n\n --#--\n\n"; BrowserHistory gamma(50); gamma = beta; gamma.Pop(); std::cout << "gamma: \n"; gamma.Print(); std::cout << "\n\n --#--\n\n"; BrowserHistory delta = alpha.Concatenate(beta); std::cout << "delta: \n"; delta.Print(); std::cout << "There are " << delta.CountVisitedSites(June) << " visits in June." << std::endl; std::cout << "The most active month is: " << ConvertMonthToString(delta.FindMostActiveMonth()) << std::endl; std::cout << "\n\n --#--\n\n"; return 0; } <file_sep>/BankSystem/Account.h #pragma once #include <iostream> //abstract class Account { public: Account(std::string, int, double); virtual void Deposit(double) = 0; virtual bool Withdraw(double) = 0; virtual void Display() const = 0; double GetBalance() const { return m_Amount; } std::string GetIBAN() const { return m_IBAN; } int GetOwnerID() const { return m_OwnerID; } void SetAmount(double); virtual Account* Clone() const = 0; private: int m_OwnerID; double m_Amount; std::string m_IBAN; }; <file_sep>/PairAndSettings/Pair.h #pragma once #include <string.h> template <class T> class Pair { public: Pair(); Pair(const char *, T); Pair(const Pair &); Pair& operator=(const Pair &); ~Pair(); char* GetKey() const; T GetValue() const; void SetValue(T); private: char * m_key; T m_value; }; template <class T> Pair<T>::Pair() { m_key = new char[1]; m_key[0] = '\0'; m_value = 0; } template <class T> Pair<T>::Pair(const char * key, T value) { m_key = new char[strlen(key) + 1]; strcpy_s(m_key, strlen(key) + 1, key); m_value = value; } template <class T> Pair<T>::Pair(const Pair & rhs) { m_key = new char[strlen(rhs.m_key) + 1]; strcpy_s(m_key, strlen(rhs.m_key) + 1, rhs.m_key); m_value = rhs.m_value; } template <class T> Pair<T>& Pair<T>::operator=(const Pair & rhs) { if (this != &rhs) { delete[] m_key; m_key = new char[strlen(rhs.m_key) + 1]; strcpy_s(m_key, strlen(rhs.m_key) + 1, rhs.m_key); m_value = rhs.m_value; } return *this; } template <class T> Pair<T>::~Pair() { delete[] m_key; } template <class T> char * Pair<T>::GetKey() const { return m_key; } template <class T> T Pair<T>::GetValue() const { return m_value; } template <class T> void Pair<T>::SetValue(T value) { m_value = value; } <file_sep>/BankSystem/PrivilegeAccount.h #pragma once #include "Account.h" class PrivilegeAccount : public Account { public: PrivilegeAccount(std::string, int, double, double); double GetOverdraft() const { return m_Overdraft; } void Deposit(double) override; bool Withdraw(double) override; void Display() const override; Account* Clone() const override { return new PrivilegeAccount(*this); } private: double m_Overdraft; }; <file_sep>/DeviceAndNet/ElectricNet.h #pragma once #include "ElectricDevice.h" class ElectricNet { public: //canonical form ElectricNet(int = 0); ElectricNet(const ElectricNet &); ElectricNet& operator=(const ElectricNet &); ~ElectricNet(); void PrintNet() const; //operators ElectricNet& operator+=(const ElectricDevice &); ElectricNet& operator+(const ElectricDevice &); ElectricNet& operator-=(const ElectricDevice &); ElectricNet& operator-(const ElectricDevice &); ElectricDevice& operator[](const char *); bool operator!(); ElectricNet& operator++(); ElectricNet operator++(int); ElectricNet& operator--(); ElectricNet operator--(int); private: int m_PluggedDevices; int m_Capacity; int m_MaxkWs; ElectricDevice * m_Devices; void Increase(); }; <file_sep>/DeviceAndNet/ElectricDevice.cpp #include <string.h> #include <iostream> #include "ElectricDevice.h" //---ancillary functions--- void ElectricDevice::SetDevice(const char * name, int kWs) { int len = strlen(name); m_Name = new char[len+1]; strcpy_s(m_Name, len + 1 , name); m_kWs = kWs; } void ElectricDevice::Print() const { std::cout <<"Device: "<< m_Name << std::endl; std::cout <<"KWs: "<< m_kWs << std::endl << std::endl; std::cout << std::endl; } //---canonical form--- ElectricDevice::ElectricDevice() { SetDevice("", 0); } ElectricDevice::ElectricDevice(const char * name, int kWs) { SetDevice(name, kWs); } ElectricDevice::ElectricDevice(const ElectricDevice& rhs) { SetDevice(rhs.m_Name, rhs.m_kWs); } ElectricDevice& ElectricDevice::operator=(const ElectricDevice& rhs) { if (this!=&rhs) { delete[] m_Name; SetDevice(rhs.m_Name, rhs.m_kWs); } return *this; } ElectricDevice::~ElectricDevice() { delete[] m_Name; } //selectors const char * ElectricDevice::GetName() const { return m_Name; } int ElectricDevice::GetkWs() const { return m_kWs; } <file_sep>/BankSystem/PrivilegeAccount.cpp #include "PrivilegeAccount.h" #include <string> PrivilegeAccount::PrivilegeAccount(std::string IBAN, int ownerID, double amount, double overdraft) :Account(IBAN, ownerID, amount) { m_Overdraft = overdraft; } void PrivilegeAccount::Deposit(double sum) { sum = sum > 0 ? sum : sum * (-1); SetAmount(sum); } bool PrivilegeAccount::Withdraw(double sum) { sum = sum > 0 ? sum : sum * (-1); if (GetBalance()+m_Overdraft<sum) { return false; } else { SetAmount(sum*(-1)); return true; } } void PrivilegeAccount::Display() const { std::cout << "Privilege Account: \n"; std::cout << "IBAN: " << GetIBAN() << std::endl; std::cout << "Owner ID: " << GetOwnerID() << std::endl; std::cout << "Overdraft: " << m_Overdraft << std::endl; std::cout << "Balance: " << GetBalance() << std::endl; } <file_sep>/PairAndSettings/Settings.h #pragma once #include <iostream> #include "Pair.h" template <class T> class Settings { public: Settings(); Settings(const Settings &); Settings& operator=(const Settings &); ~Settings(); int Count() const; Settings& Set(const char *, T); bool Get(const char *, T&); void Print() const; private: int m_capacity, m_elements; Pair<T> * m_container; //ancillary functions void Add(const Pair<T> &); void Increase(); }; template <class T> Settings<T>::Settings() { m_capacity = 1; m_elements = 0; m_container = new Pair<T>[m_capacity]; } template <class T> Settings<T>::Settings(const Settings & rhs) { m_capacity = rhs.m_capacity; m_elements = rhs.m_elements; m_container = new Pair<T>[m_capacity]; for (int i = 0; i < m_elements; ++i) { m_container[i] = rhs.m_container[i]; } } template <class T> Settings<T>& Settings<T>::operator=(const Settings & rhs) { if (this != &rhs) { delete[] m_container; m_capacity = rhs.m_capacity; m_elements = rhs.m_elements; m_container = new Pair<T>[m_capacity]; for (int i = 0; i < m_elements; ++i) { m_container[i] = rhs.m_container[i]; } } return *this; } template <class T> Settings<T>::~Settings() { delete[] m_container; } template <class T> int Settings<T>::Count() const { return m_elements; } template <class T> Settings<T>& Settings<T>::Set(const char * key, T value) { for (int i = 0; i < m_elements; ++i) { if (strcmp(m_container[i].GetKey(), key) == 0) { m_container[i].SetValue(value); return *this; } } Pair<T> token(key, value); Add(token); return *this; } template <class T> bool Settings<T>::Get(const char * key, T& value) { for (int i = 0; i < m_elements; ++i) { if (strcmp(m_container[i].GetKey(), key) == 0) { value = m_container[i].GetValue(); return true; } } return false; } //ancillary functions template <class T> void Settings<T>::Add(const Pair<T> & token) { if (m_elements == m_capacity) { Increase(); } m_container[m_elements++] = token; } template <class T> void Settings<T>::Increase() { Pair<T>* temp = new Pair<T>[m_capacity * 2]; for (int i = 0; i < m_elements; ++i) { temp[i] = m_container[i]; } delete[] m_container; m_container = temp; m_capacity *= 2; } template <class T> void Settings<T>::Print() const { for (int i = 0; i < m_elements; i++) { std::cout << "Key: " << m_container[i].GetKey() << std::endl; std::cout << "Value: " << m_container[i].GetValue() << std::endl; } } <file_sep>/Browser History/BrowserHistory.cpp #include <string.h> #include <iostream> #include "BrowserHistory.h"; //constructor BrowserHistory::BrowserHistory(int n) { mCapacity = n; mTopEntry = -1; mEntries = new HistoryEntry[mCapacity]; } //copy constructor BrowserHistory::BrowserHistory(const BrowserHistory & rhs) { mCapacity = rhs.mCapacity; mTopEntry = rhs.mTopEntry; mEntries = new HistoryEntry[mCapacity]; for (int i = 0; i < mTopEntry + 1; i++) { mEntries[i].mMonth = rhs.mEntries[i].mMonth; strcpy_s(mEntries[i].mURL, 100, rhs.mEntries[i].mURL); } } //operator overload BrowserHistory & BrowserHistory::operator=(const BrowserHistory & rhs) { if (this != &rhs) { delete[]mEntries; mCapacity = rhs.mCapacity; mTopEntry = rhs.mTopEntry; mEntries = new HistoryEntry[mCapacity]; for (int i = 0; i < mTopEntry + 1; i++) { mEntries[i].mMonth = rhs.mEntries[i].mMonth; strcpy_s(mEntries[i].mURL, 100, rhs.mEntries[i].mURL); } } return *this; } //destructor BrowserHistory::~BrowserHistory() { delete[] mEntries; } //----member funcs---- void BrowserHistory::Write() { mTopEntry++; std::cout << "Month (enter an integer bewteen 1 and 12, please): "; int input; std::cin >> input; mEntries[mTopEntry].mMonth = (Month)input; std::cin.ignore(); std::cout << "URL: "; std::cin.getline(mEntries[mTopEntry].mURL, 100); } void BrowserHistory::Add(const HistoryEntry & current) { if (mCapacity - 1 == mTopEntry) { std::cout << "Memory is full. You cannot add new entries." << std::endl; } else { mTopEntry++; mEntries[mTopEntry].mMonth = current.mMonth; strcpy_s(mEntries[mTopEntry].mURL, 100, current.mURL); } } void BrowserHistory::Print() { for (int i = 0; i < mTopEntry + 1; i++) { std::cout << mEntries[i].mMonth << " - " << mEntries[i].mURL << std::endl; } } int BrowserHistory::CountVisitedSites(Month month) { int counter = 0; for (int i = 0; i < mTopEntry + 1; i++) { if (mEntries[i].mMonth == month) { counter++; } } return counter; } Month BrowserHistory::FindMostActiveMonth() { Month mostActive = January; int visits = 0; int maxVisits = 0; for (int i = 1; i <= 12; i++) { for (int j = 0; j < mTopEntry + 1; j++) { if (mEntries[j].mMonth == (Month)i) { visits++; } } if (visits > maxVisits) { maxVisits = visits; mostActive = (Month)i; } visits = 0; } return mostActive; } void BrowserHistory::Pop() { if (mTopEntry >= 0) { mEntries[mTopEntry].mMonth = January; strcpy_s(mEntries[mTopEntry].mURL, 100, "www.unknownadress.org"); mTopEntry--; } else { std::cout << "Browser history is empty. There is nothing to remove." << std::endl; } } BrowserHistory BrowserHistory::Concatenate(const BrowserHistory & rhs) { BrowserHistory concatenated(mCapacity + rhs.mCapacity); for (int i = 0; i < mTopEntry + 1; i++) { concatenated.Add(mEntries[i]); } for (int i = 0; i < rhs.mTopEntry + 1; i++) { concatenated.Add(rhs.mEntries[i]); } return concatenated; } <file_sep>/BankSystem/CurrentAccount.h #pragma once #include "Account.h" class CurrentAccount : public Account { public: CurrentAccount(std::string, int, double); void Deposit(double) override; bool Withdraw(double) override; void Display() const override; Account* Clone() const override { return new CurrentAccount(*this); } }; <file_sep>/Browser History/HistoryEntry.h #pragma once enum Month { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12, }; struct HistoryEntry { Month mMonth; char mURL[100]; //default constructor HistoryEntry(); //constructor with params HistoryEntry(Month, char[]); }; <file_sep>/BankSystem/Account.cpp #include "Account.h" #include <string> Account::Account(std::string IBAN, int ownerID, double amount) { m_IBAN = IBAN; m_OwnerID = ownerID; m_Amount = amount; } void Account::SetAmount(double sum) { m_Amount += sum; } <file_sep>/PairAndSettings/Main.cpp #include <iostream> #include"Settings.h" int main() { //test Pair<T> Pair<double> epsilon("epsilon", 47.2); epsilon.SetValue(2.25); std::cout << epsilon.GetKey() << epsilon.GetValue(); std::cout << std::endl; //test Settings<T> Settings<double> alpha; alpha.Set("omega", 1.02); alpha.Set("beta", 0.285); alpha.Set("gamma", 0); alpha.Set("delta", 154); alpha.Set("gamma", 33); alpha.Print(); std::cout << alpha.Count() << std::endl; double flag = 404; std::cout << alpha.Get("eta", flag); std::cout << std::endl <<"Flag = "<< flag << std::endl; std::cout << alpha.Get("omega", flag); std::cout << std::endl << "Flag = "<< flag << std::endl; return 0; } <file_sep>/Vehicle/Vehicle.h #pragma once class Vehicle { public: //canonical form Vehicle(); Vehicle(const char *, const char *, const char *, int, int); Vehicle(const Vehicle &); Vehicle& operator=(const Vehicle &); virtual ~Vehicle(); //getters const char * GetMake() const; const char * GetModel() const; const char * GetColor() const; int GetYear() const; int GetMileage() const; //setters void SetMake(const char *); void SetModel(const char *); void SetColor(const char *); void SetYear(int); void SetMileage(int); virtual void Details() const = 0; //pure virtual function private: char * m_make; char * m_model; char * m_color; int m_year; int m_mileage; //ancillary functions void Initialise(const char*, const char *, const char*, int, int); }; <file_sep>/BankSystem/SavingsAccount.h #pragma once #include "Account.h" class SavingsAccount : public Account { public: SavingsAccount(std::string, int, double, double); double GetInterestRate() const { return m_InterestRate; } void Deposit(double) override; bool Withdraw(double) override; void Display() const override; Account* Clone() const override { return new SavingsAccount(*this); } private: double m_InterestRate; }; <file_sep>/BankSystem/Customer.cpp #include "Customer.h" #include <string> Customer::Customer(int id, std::string name, std::string adress) { m_ID = id; m_Name = name; m_Adress = adress; } void Customer::Display() const { std::cout << "ID: " << m_ID << std::endl; std::cout << "Name: " << m_Name << std::endl; std::cout << "Adress: " << m_Adress << std::endl; } <file_sep>/BankSystem/Main.cpp #include "Customer.h" #include "CurrentAccount.h" #include "SavingsAccount.h" #include "PrivilegeAccount.h" #include "Bank.h" #include <string> void ToggleMenu(Bank& bank) { std::cout << "\nChoose a command: "; int option; std::cin >> option; switch (option) { case 1: { bank.ListCustomers(); break; } case 2: { std::cout << "ID: "; int ID; std::cin >> ID; std::cout << "Name: "; std::string name; std::cin >> name; std::cout << "Adress: "; std::string adress; std::cin >> adress; bank.AddCustomer(ID, name,adress); break; } case 3: { std::cout << "ID: "; int ID; std::cin >> ID; bank.DeleteCustomer(ID); break; } case 4: { bank.ListAccounts(); break; } case 5: { std::cout << "ID: "; int ID; std::cin >> ID; bank.ListCustomerAccounts(ID); break; } case 6: { std::cin.get(); std::cout << "Type: "; std::string type; std::getline(std::cin, type); std::cout << "IBAN: "; std::string IBAN; std::getline(std::cin, IBAN); std::cout << "ID: "; int ID; std::cin >> ID; std::cout << "Amount: "; double amount; std::cin >> amount; bank.AddAccount(type, IBAN, ID, amount); break; } case 7: { std::cout << "IBAN: "; std::string IBAN; std::cin >> IBAN; bank.DeleteAccount(IBAN); break; } case 8: { std::cout << "IBAN: "; std::string IBAN; std::cin >> IBAN; std::cout << "Amount: "; double amount; std::cin >> amount; if (bank.GetAccount(IBAN) == nullptr) { std::cout << "IBAN not found \n"; } else { bank.GetAccount(IBAN)->Withdraw(amount); } break; } case 9: { std::cout << "IBAN: "; std::string IBAN; std::cin >> IBAN; std::cout << "Amount: "; double amount; std::cin >> amount; if (bank.GetAccount(IBAN) == nullptr) { std::cout << "IBAN not found \n"; } else { bank.GetAccount(IBAN)->Deposit(amount); } break; } case 10: { std::cout << "From: "; std::string fromIBAN; std::cin >> fromIBAN; std::cout << "To: "; std::string toIBAN; std::cin >> toIBAN; std::cout << "Amount: "; double amount; std::cin >> amount; bank.Transfer(fromIBAN, toIBAN, amount); break; } case 11: { bank.Display(); break; } case 12: { return; } default: std::cout << "Try again. \n"; break; } std::cout << "Command complete! \n"; ToggleMenu(bank); } int main() { std::cout << "1 List customers \n"; std::cout << "2 Add new customer \n"; std::cout << "3 Delete customer \n"; std::cout << "4 List all accounts \n"; std::cout << "5 List customer account \n"; std::cout << "6 Add new account \n"; std::cout << "7 Delete account \n"; std::cout << "8 Withdraw from account \n"; std::cout << "9 Deposit to account \n"; std::cout << "10 Transfer \n"; std::cout << "11 Display info for the bank \n"; std::cout << "12 Quit \n"; std::vector<Customer> cust; std::vector<Account*> acc; Bank bank("Societe Generale Expressbank", "Sofia, \"<NAME>\" 10", cust, acc); ToggleMenu(bank); return 0; } <file_sep>/Vehicle/Truck.h #pragma once #include "Vehicle.h" class Truck: public Vehicle { public: Truck(); Truck(const char *, const char *, const char *, int, int, int); Truck(const Truck &) = default; Truck& operator=(const Truck &) = default; ~Truck() = default; int GetSize() const; void SetSize(int); void Details() const; private: int m_size; }; <file_sep>/Reverse Polish Notation/Main.cpp #include <iostream> //#include <string> #include "Stack.h"; int main() { Stack a; std::cout << "Tests:\n\n"; std::cout << a.Calculate("11 10 % 3 + 9 10 - *") << std::endl; //-4 std::cout << a.Calculate("5 1 2 + 4 * + 3 -") << std::endl; //14 std::cout << a.Calculate("18 12 / 5 44 - -") << std::endl; //40.5 std::cout << a.Calculate("1.25 5.63 1.2 + 3 / -") << std::endl; //-1.026 std::cout << a.Calculate("-1 -1 - -1 -1 -1 - -1 - - -") << std::endl; //2 std::cout << a.Calculate("-1.1 2 44.708 * 10.8 / -1 + -") << std::endl; //-8.379 return 0; } <file_sep>/Store/Product.h #pragma once //SUITS class Product { private: int mSKU; //stock keeping unit char mBrand[20]; //e.g. Brioni, Dolce&Gabbana, etc. char mModel[20]; //fall/winter or spring/summer char mMaterial[20]; //e.g. satin, silk, etc. double mPrice; //in euros int mSize; //European standart int mCount; public: //constructors Product(); Product(int, char[] , char[], char[] , double, int ,int); //set all characteristics from the console void InitFromConsole(); int GetSKU() const; const char * GetBrand() const; const char * GetModel() const; const char * GetMaterial() const; double GetPrice() const; int GetSize() const; int GetCount() const; void SetSKU(int); void SetBrand(char []); void SetModel(char []); void SetMaterial(char []); void SetPrice(double); void SetSize(int); void SetCount(int); void Print() const; }; <file_sep>/Vehicle/Motorcycle.h #pragma once #include "Vehicle.h" class Motorcycle : public Vehicle { public: Motorcycle(); Motorcycle(const char *, const char *, const char *, int, int, const char *); Motorcycle(const Motorcycle &); Motorcycle& operator=(const Motorcycle &); ~Motorcycle(); const char * GetType() const; void SetType(const char *); void Details() const; private: char * m_type; }; <file_sep>/Store/Main.cpp #include <iostream> #include "Store.h"; void ToggleMenu(Store selected) { //menu std::cout << "Please choose a command from the menu: "; char option; std::cin >> option; switch (option) { case 'A': selected.Add(); std::cout << "Command complete! \n\n"; break; case 'X': selected.Delete(); std::cout << "Command complete! \n\n"; break; case 'C': selected.Change(); std::cout << "Command complete! \n\n"; break; case 'D': selected.Print(); std::cout << "Command complete! \n\n"; break; case 'Q': std::cout << "Command complete! \n\n"; return; default: std::cout << "Invalid option. \n\n"; break; } ToggleMenu(selected); } int main() { //brands char Gucci[20] = "Gucci"; char Burberry[20] = "Burberry"; char RL[20] = "<NAME>"; //models/collections char ss[20] = "Spring/Summer"; char fw[20] = "Fall/Winter"; //materials char twill[20] = "Twill"; char wool[20] = "Wool"; char gabardine[20] = "Gabardine"; Product one(56, Burberry, ss, gabardine, 3000, 44, 12); Product two(15, RL, fw, twill, 1890, 46, 4); //10 differents types of products can be added //DOES NOT HAVE ANYTHING TO DO WITH HOW MANY ITEMS OF EACH PRODUCT ARE THERE!!! Store alpha(10); alpha.Add(one); alpha.Add(two); std::cout << "Menu: \n"; std::cout << "Press A to add new product. \n"; std::cout << "Press X to delete product. \n"; std::cout << "Press C to change product. \n"; std::cout << "Press D to display products. \n"; std::cout << "Press Q to add item to quit. \n\n"; std::cout << "Initial state of store: \n"; alpha.Print(); std::cout << std::endl; ToggleMenu(alpha); return 0; } <file_sep>/Store/Store.h #pragma once #include "Product.h"; class Store { private: Product * mList; int mInventory; //capacity int mLast; //number of products public: Store(); Store(int); Store(const Store &); Store & operator=(const Store &); ~Store(); //add hardcoded product void Add(Product); //add product with characteristics from the console void Add(); //delete certain product void Delete(Product); //set the characteristics of the product you would like to delete from the console void Delete(); //write changes from the console void Change(); void Print() const; };
640d710775f47cc0698e13f97a770f49e6191dc0
[ "Markdown", "C", "C++" ]
43
C++
Ivaylo-Georgiev/OOP-FMI
627410d9648f8f91c3a7b4b759bb9fa3ae15bb75
281c003bddd1cd2d41e687f7cd5a9bdd653d6f2b
refs/heads/master
<file_sep>def prime?(integer) if integer < 2 return false end range = 2..integer - 1 range.each do |n| if (integer % n) == 0 return false end end return true end
ed15b422bca8579e19789c504734717967712552
[ "Ruby" ]
1
Ruby
ecargiohc/prime-ruby-seattle-web-062419
b99c6b8fb77aa52817f97eca1b3afda94c96ec4e
2dba8730d92fda3dbd311141a8c36edf1385dce6
refs/heads/master
<repo_name>davidmeunier79/AnDOChecker<file_sep>/ando/engine.py #!/usr/bin/python # -*- coding: utf-8 -*- import os import json import re import pathlib from ando.error import ExperimentError, SourceError, SourceNotFound, \ SessionError, SubjectError,MetaDataError,DerivativeDataError,RawDataError dir_rules = os.path.join(os.path.dirname(__file__)) + '/rules/' def parse_all_path(nested_list_of_dir): """ Transform this [ ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'], ['Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['Landing', 'sub-enyo'], ['Landing', 'sub-enyo', '180116_001_m_enyo_land-001'] ] to [ ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'], ['Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ] Checking for the longest chain with the same sub chain """ def _test_is_included(my_list_of_lists, list_elem): for my_list_elem in my_list_of_lists: if all([val[0] == val[1] for val in zip(my_list_elem, list_elem)]): return True return False def _merge_duplicates(my_list_of_lists, max_length=3): """Transform this [ ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'] ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'metadata'] ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'rawdata'] ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'derivatives'] ] to [ ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'rawdata', 'metadata', 'derivatives', 'source'] ] Args: my_list_of_lists ([list]): [list of path to process] max_length (int, optional): [number of folder in session directory corresponding to rawdata metadata derivatives and sources]. Defaults to 3. Returns: [list]: [list of concatenate sub folder at the end of the list ] todo: This might have to be re-implemented more efficiently. """ merged_list = [] for my_list_elem in my_list_of_lists: simil_list = [] for my_list_elem2 in my_list_of_lists: if all([val[0]==val[1] for i,val in enumerate(zip(my_list_elem, my_list_elem2)) if i < max_length]): simil_list.append(my_list_elem2) if len(simil_list) > 1: new_list = simil_list[0][:max_length] for remain_list in simil_list: new_list.append(remain_list[max_length]) merged_list.append(new_list) else: merged_list.append(simil_list[0]) return merged_list new_list_of_lists = [] for list_elem in sorted(nested_list_of_dir, key= lambda sublist: len(sublist), reverse=True): if not _test_is_included(new_list_of_lists, list_elem): new_list_of_lists.append(list_elem) # Removing duplicate new_list_of_lists = _merge_duplicates(new_list_of_lists) unique_data=[list(x) for x in set(tuple(x)for x in new_list_of_lists)] return unique_data def create_nested_list_of_path(directory): """ Function that get the path given in arg to create a list of path as follow take the last element of the path and walks through to get every sub dir as follow: /home/garciaj/AnDOChecker/checker/tests/ds001/Data/Landing/ to [['Landing', 'sub-enya', 'y180116-land-001', 'Sources']] """ list_of_dir = [] # take the last folder pass in arg: tests/ds007/data/Landing -> Landing path = pathlib.PurePath(directory) sub = directory.split(path.name)[0] # take everything before last tests/ds007/data/Landing -> tests/ds007/data for (root, dirs, _) in os.walk(directory): for d in dirs: list_of_dir.append(os.path.join(root, d).replace(sub, '')) nested_list_of_dir = [] for each in list_of_dir: nested_list_of_dir.append(each.split(os.sep)) nested_list_of_dir_parsed = parse_all_path(nested_list_of_dir) return nested_list_of_dir_parsed def is_AnDO_R(subpath, level, validate): """ Check if file path adheres to AnDO. Main method of the validator. uses other class methods for checking different aspects of the directory path. :param names: """ if level < len(subpath): if level == 0: validate.append(is_experiment(subpath[level])) is_AnDO_R(subpath, level + 1, validate) if level == 1: validate.append(is_subject(subpath[level])) is_AnDO_R(subpath, level + 1, validate) if level == 2: validate.append(is_session(subpath[level])) is_AnDO_R(subpath, level + 1, validate) if level == 3: validate.append(is_source(subpath[level])) is_AnDO_R(subpath, level + 1, validate) if level == 4: validate.append(is_metadata(subpath[level])) is_AnDO_R(subpath, level + 1, validate) if level == 5: validate.append(is_derivatives(subpath[level])) is_AnDO_R(subpath, level + 1, validate) if level == 6: validate.append(is_rawdata(subpath[level])) is_AnDO_R(subpath, level + 1, validate) elif level < 7: validate.append(False) return validate def is_AnDO(directory): """ Check if file path adheres to AnDO. Main method of the validator. uses other class methods for checking different aspects of the directory path. :param names: """ validate = [] names = create_nested_list_of_path(directory) for item in names: is_AnDO_R(item, 0, validate) return all(validate) def is_AnDO_verbose(directory): """ Call the function is_AnDO_verbose_Format on every path in the list :param names: """ validate = [] names = create_nested_list_of_path(directory) for item in names: validate.append(is_AnDO_verbose_Format(item)) return any(validate) def is_AnDO_verbose_Format(names): """ Check if file path adheres to AnDO. Main method of the validator. uses other class methods for checking different aspects of the directory path. :param names: list of names founds in the path """ bool_error = 0 # only error that exit without checking other folder if is_experiment(names[0]): bool_error = 0 else: try: raise ExperimentError(names) except ExperimentError as e: print(e.strerror) bool_error = 1 exit(1) if is_session(names): bool_error = 0 else: try: raise SessionError(names) except SessionError as e: print(e.strerror) bool_error = 1 if is_subject(names): bool_error = 0 else: try: raise SubjectError(names) except SubjectError as e: print(e.strerror) bool_error = 1 if len(names)==7 : if is_source(names): bool_error = 0 else: try: raise SourceError(names) except SourceError as e: print(e.strerror) bool_error = 1 if is_rawdata(names): bool_error = 0 else: try: raise RawDataError(names) except RawDataError as e: print(e.strerror) bool_error = 1 if is_derivatives(names): bool_error = 0 else: try: raise DerivativeDataError(names) except DerivativeDataError as e: print(e.strerror) bool_error = 1 if is_metadata(names): bool_error = 0 else: try: raise MetaDataError(names) except MetaDataError as e: print(e.strerror) bool_error = 1 else: if not is_metadata(names): try: raise MetaDataError(names) except MetaDataError as e: print(e.strerror) bool_error = 1 if not is_rawdata(names): try: raise RawDataError(names) except RawDataError as e: print(e.strerror) bool_error = 1 if not is_derivatives(names): try: raise DerivativeDataError(names) except DerivativeDataError as e: print(e.strerror) bool_error = 1 if not is_source(names): try: raise SourceNotFound(names) except SourceNotFound as e: print(e.strerror) bool_error = 1 return bool_error def is_experiment(names): """[Check names follows experiment rules] Args: names ([str]): [names founds in the path] Returns: [type]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'experiment_rules.json') conditions = [] print(names) if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) elif type(names) == list: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) print(flatten(conditions)) return any(flatten(conditions)) def is_rawdata(names): """[Check names follows rawdata rules] Args: names ([str]): [names founds in the path] Returns: [bool]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'rawdata_rules.json') conditions = [] if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) elif type(names) == list: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) # print(flatten(conditions)) return any(flatten(conditions)) def is_metadata(names): """[Check names follows metadata rules] Args: names ([str]): [names founds in the path] Returns: [bool]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'metadata_rules.json') conditions = [] if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) elif type(names) == list: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) # print(flatten(conditions)) return any(flatten(conditions)) def is_derivatives(names): """[Check names follows derivatives rules] Args: names ([str]): [names founds in the path] Returns: [bool]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'derivatives_rules.json') conditions = [] if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) elif type(names) == list: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) # print(flatten(conditions)) return any(flatten(conditions)) def is_session(names): """[Check names follows session rules] Args: names ([str]): [names founds in the path] Returns: [bool]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'session_rules.json') conditions = [] if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) else: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) # print(flatten(conditions)) return any(flatten(conditions)) def is_subject(names): """[Check names follows subject rules] Args: names ([str]): [names founds in the path] Returns: [bool]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'subject_rules.json') conditions = [] if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) else: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) # print(flatten(conditions)) return any(flatten(conditions)) def is_source(names): """[Check names follows sources rules] Args: names ([str]): [names founds in the path] Returns: [bool]: [true or false ] """ regexps = get_regular_expressions(dir_rules + 'source_rules.json') conditions = [] if type(names) == str: conditions.append([re.compile(x).search(names) is not None for x in regexps]) else: for word in names: conditions.append([re.compile(x).search(word) is not None for x in regexps]) # print(flatten(conditions)) return any(flatten(conditions)) def get_regular_expressions(fileName): ''' https://github.com/bids-standard/bids-validator/tree/master/bids-validator/ using function to read regex in rule files ''' regexps = [] with open(fileName, 'r') as f: rules = json.load(f) for key in list(rules.keys()): rule = rules[key] regexp = rule['regexp'] if 'tokens' in rule: tokens = rule['tokens'] for token in list(tokens): regexp = regexp.replace(token, '|'.join(tokens[token])) regexps.append(regexp) return regexps def flatten(seq): """ Format list the proper way example: [[x],[y],[z]]--->[x,y,z] :param seq: list to format """ list_flaten = [] for elt in seq: t = type(elt) if t is tuple or t is list: for elt2 in flatten(elt): list_flaten.append(elt2) else: list_flaten.append(elt) return list_flaten <file_sep>/ando/tests/test_Rules.py import unittest import ando.engine as andoE class Test_Rules(unittest.TestCase): def setUp(self): pass '''testing session rules''' def test_session_rules(self): list=["ses-18000116_001_land-001"] self.assertEqual(andoE.is_session(list), True) def test_session_rules_1(self): list=["180116_m_enya_land-001"] self.assertEqual(andoE.is_session(list), False) def test_session_rules_2(self): list=["180116_001_m_land-001"] self.assertEqual(andoE.is_session(list), False) def test_session_rules_3(self): list=["ses-180116_001_m_land_001"] self.assertEqual(andoE.is_session(list), False) '''testing source rules''' def test_source_rules(self): list=["source"] self.assertEqual(andoE.is_source(list), True) def test_source_rules_1(self): list=["Source"] self.assertEqual(andoE.is_source(list), False) def test_source_rules_2(self): list=["sources"] self.assertEqual(andoE.is_source(list), False) '''testing subject rules''' def test_subject_rules(self): list=["sub-001"] self.assertEqual(andoE.is_subject(list), True) def test_subject_rules_1(self): list=["sub_001"] self.assertEqual(andoE.is_subject(list), False) def test_subject_rules_2(self): list=["Sub_001"] self.assertEqual(andoE.is_subject(list), False) if __name__ == '__main__': unittest.main() <file_sep>/setup.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup, find_packages import os import re verstr = "unknown" try: verstrline = open('ando/_version.py', "rt").read() except EnvironmentError: pass # Okay, there is no version file. else: VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("unable to find version in yourpackage/_version.py") setup( name="ando", version=verstr, packages=find_packages(), author="<NAME>, <NAME>", description="Checks the validity of a directory with respect to the ANimal Data Organization (ANDO) specifications ", license='MIT', install_requires=[] ) <file_sep>/ando/checker.py #!/usr/bin/python # -*- coding: utf-8 -*- import os import argparse from ando.engine import is_AnDO, is_AnDO_verbose dir_rules = os.path.join(os.path.dirname(__file__)) + 'rules/' if __name__ == '__main__': """ Main function : usage: AnDOChecker.py [-h] [-v] pathToFolder positional arguments: path Path to your folder optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity """ # add argparse for verbose option parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true', help='increase output verbosity') parser.add_argument('path', help='Path to your folder ') args = parser.parse_args() if args.verbose: try: directory = args.path except IndexError: directory = '.' error = is_AnDO_verbose(directory) if error == 1: print("\n" + directory + ": Is Not validated by AnDOChecker") else: print("\n" + directory + ": Is validated by AnDOChecker") else: try: directory = args.path except IndexError: directory = '.' error_not_found = is_AnDO(directory) if not error_not_found: print("\n" + directory + ": Is Not validated by AnDOChecker") else: print("\n" + directory + ": Is validated by AnDOChecker") <file_sep>/docs/_build/html/_sources/modules.txt checker ======= .. toctree:: :maxdepth: 4 AnDOChecker AnDO_Error AnDO_engine tests <file_sep>/ando/tests/test_isAnDO.py import unittest import ando.engine as andoE import json import os currpath=os.path.dirname(os.path.abspath(__file__)) class test_AnDO(unittest.TestCase): def setUp(self): pass '''testing ds001 folder''' def test_AnDO_dataset_1(self): directory=currpath+"/ds001/Data/Landing" self.assertEqual(andoE.is_AnDO(directory), False) '''testing ds002 folder''' def test_AnDO_dataset_2(self): directory=currpath+"/ds002/data/exp-Landing" self.assertEqual(andoE.is_AnDO(directory),False) '''testing ds003 folder''' def test_AnDO_dataset_3(self): directory=currpath+"/ds003/data/my_experiment" self.assertEqual(andoE.is_AnDO(directory),False) '''testing ds004 folder''' def test_AnDO_dataset_4(self): directory=currpath+"/ds004/data/newexp_vision" self.assertEqual(andoE.is_AnDO(directory),False) '''testing ds005 folder''' def test_AnDO_dataset_5(self): directory=currpath+"/ds005/data/my_experiment" self.assertEqual(andoE.is_AnDO(directory),False) '''testing ds006 folder''' def test_AnDO_dataset_6(self): directory=currpath+"/ds006/data/Landing" self.assertEqual(andoE.is_AnDO(directory),False) '''testing ds007 folder''' def test_AnDO_dataset_7(self): directory=currpath+"/ds007/data/exp-Landing/" self.assertEqual(andoE.is_AnDO(directory),False) if __name__ == '__main__': unittest.main() <file_sep>/README.md # AnDOChecker Checks the validity of a directory with respect to the ANimal Data Organization (AnDO) specifications ![version](https://img.shields.io/badge/version-1-informational) [![PyPI license](https://img.shields.io/pypi/l/ansicolortags.svg)](https://pypi.python.org/pypi/ansicolortags/)[![Generic badge](https://travis-ci.org/Slowblitz/BidsValidatorA.svg?branch=master)](https://shields.io/)[![made-with-python](https://img.shields.io/badge/Made%20with-Python-1f425f.svg)](https://www.python.org/) ## Table of Contents - [AnDOChecker](#andochecker) - [Table of Contents](#table-of-contents) - [Use](#use) - [Clone](#clone) - [General usage](#general-usage) - [Specific usage](#specific-usage) - [Development](#development) - [Testing usage](#testing-usage) - [Details](#details) ## Use ### Clone - Clone this repo to your local machine using `https://github.com/INT-NIT/AnDOChecker.git` ### General usage ```term usage: AnDOChecker.py [-h] [-v] path positional arguments: path Path to your folder optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity ``` ### Specific usage ```bash $Python3 checker/AnDOChecker.py tests/ds001/data/Enya ``` <p align="center"><img src="doc/vids/AnDO_no_verbose.gif" /></p> OR verbose usage ```bash $Python3 checker/AnDOChecker.py -v tests/ds001/data/Enya ``` <p align="center"><img src="doc/vids/AnDO_with_verbose.gif" /></p> ## Development ### Testing usage ```bash $cd checker/ $python3.5 -m unittest discover -v ``` ## Details In checker folder : - file AnDOChecker.py is the main file - file AnDO_Error.py is the custom error exception file - file AnDO_Engine.py is the file that verify with the rules In the rules folder : - session_rules.json regex for session rules - subject_rules.json regex for subject rules - source_rules.json regex for source rules <file_sep>/ando/error.py #!/usr/bin/python # -*- coding: utf-8 -*- class ExperimentError(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 1 error [experiment folder] at : ' + names[0] + '\n' \ + ' It should follow the exp-NAME format, where:\n' \ + ' - NAME is a string designating the name of your experiment\n' class SubjectError(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 2 error [subject folder] at : ' + names[1] + '\n' \ + ' It should follow the sub-ID format, where:\n' \ + ' - ID is a string designating the IDentifier of the animal\n' class SessionError(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 3 error [session folder] at : ' + names[2] + '\n' \ + ' It should follow the ses-YYYYMMDD_XXX_BBBB format, where:\n' \ + ' - ‘ses-’ is an imposed prefix\n' \ + ' - ‘YYYYMMDD’ is the date of the session (8 digits, for instance 20180430 for April 30, 2018)\n' \ + ' - XXX is the number of the session acquired on that date (3 digits, for instance 001 for the first session)\n' \ + ' - BBBB is a string freely usable by the research group / user\n' \ + ' (is a string freely usable by the research group / user (for instance to add extra info on \n' \ + ' the version of the experimental protocol, on the type of preparation, on the user-friendly name of the animal etc.);\n' \ + ' this string cannot contain the underscore character.\n' class SourceError(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 4 error [source folder] at : ' + names[2] + '\n' \ + ' A single folder called source is authorized within a session folder\n' class RawDataError(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 4 error [rawdata folder missing]\n' \ + ' A folder called rawdata should be present in the session folder ' + names[2] + '\n' class MetaDataError(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 4 error [metadata folder missing]\n' \ + ' A folder called metadata should be present in the session folder ' + names[2] + '\n' class DerivativeDataError(Exception): def __init__(self, arg): names = arg self.strerror ='Level 4 error [derivatives folder missing]\n' \ + ' A folder called derivatives should be present in the session folder ' + names[2] + '\n' class SourceNotFound(Exception): def __init__(self, arg): names = arg self.strerror = 'Level 4 error [source folder missing]\n' \ + ' A folder called source should be present in the session folder ' + names[2] + '\n' <file_sep>/ando/tests/test_engine.py import unittest import ando.engine as andoE import json import os path=os.getcwd() class test_AnDO(unittest.TestCase): """Overall check of the rules given in the rules directory Args: unittest ([unittest]): [check every level of a given list of path ] """ def setUp(self): pass def test_AnDO_Func_experiment_level(self): """ Check if the experiment level follow the rules given in rules/experiment_rules.json """ names=list() names=['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'] validate=list() self.assertEqual(all(andoE.is_AnDO_R(names,0,validate)), False) def test_AnDO_Func_subject_level(self): """ Check if the subject level follow the rules given in rules/subject_rules.json """ names=list() names=['exp-Landing', 'anye', 'sess-180116_001_m_anye_land-001', 'source'] validate=list() self.assertEqual(all(andoE.is_AnDO_R(names,0,validate)), False) def test_AnDO_Func_session_level(self): """ Check if the session level follow the rules given in rules/session_rules.json """ names=list() names=['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'] validate=list() self.assertEqual(all(andoE.is_AnDO_R(names,0,validate)), False) def test_AnDO_Func_sources_level(self): """ Check if the sources level follow the rules given in rules/sources_rules.json """ names=list() names=['exp-Landing', 'sub-anye', 'sess-180116_001_m_anye_land-001', 'sources'] validate=list() self.assertEqual(all(andoE.is_AnDO_R(names,0,validate)), False) if __name__ == '__main__': unittest.main() <file_sep>/ando/tests/test_parse_all_path.py import unittest import ando.engine as andoE import os path=os.getcwd() class test_parse_all_path(unittest.TestCase): """Test the function parse_all_path Args: unittest (unittest): [parse_all_path should Transform this [ ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'], ['Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['Landing', 'sub-enyo'], ['Landing', 'sub-enyo', '180116_001_m_enyo_land-001'] ] to [ ['Landing', 'sub-anye', '180116_001_m_anye_land-001', 'source'], ['Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ] Checking for the longest chain with the same sub chain] """ def setUp(self): pass def test_parse_all_path(self): result=[['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001'],['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'],['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source']] list1=[['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['exp-Landing', 'sub-enyo'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001']] e=andoE.parse_all_path(list1) self.assertEqual(e.sort(),result.sort()) def test_parse_all_path_1(self): result=[['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001'], ['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001']] list1=[['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['exp-Landing', 'sub-enyo'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001']] e=andoE.parse_all_path(list1) self.assertEqual(e.sort(),result.sort()) def test_parse_all_path_2(self): list1=[['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source'], ['exp-Landing', 'sub-enyo'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-002'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'derivatives'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'metadata'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'rawdata'] ] result=[['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-001'], ['exp-Landing', 'sub-enyo', '180116_001_m_enyo_land-002'], ['exp-Landing', 'sub-anye', '180116_001_m_anye_land-001'], ['exp-Landing', 'sub-enya', '180116_001_m_enya_land-001', 'source', 'rawdata', 'derivatives', 'metadata']] e=andoE.parse_all_path(list1) self.assertEqual(e.sort(),result.sort()) if __name__ == '__main__': unittest.main()
1a8806fb80cd9074efe7630552341c8cd9eb9f6c
[ "Markdown", "Python", "reStructuredText" ]
10
Python
davidmeunier79/AnDOChecker
22d901fc8722d7309c9727940c064567972089ab
b3394249b534275ebb906bc30c180d628c2e859f
refs/heads/master
<repo_name>vicpo/casting<file_sep>/casting.rb  class Casting AGE = { man: 14..30, woman: 16..35 }.freeze def initialize enter_data end #Блок ввода данных участника кастинга def enter_data puts "Введите Ваше имя:" name = gets.chomp! puts "Выберите Ваш пол (м/m = мужской, ж/w - женский):" pol = gets.chomp! raise ArgumentError, "Неверно введны данные" unless pol.capitalize == "м" || pol.capitalize == "ж" || pol == "m" || pol == "w" pol = pol.capitalize == "м" || pol == "m" ? "man" : "woman" puts "Введите Ваш возраст:" age = gets.to_i abort "Извините, Вы не подходите по возрасту" unless AGE[pol.to_sym].include?(age) abort "Вы уже подали заявку, ожидайте результата" if uniq_data(name.capitalize, age, pol.capitalize) puts "Введите тему выступления:" theme = gets.chomp! puts "Введите текст выступления(для завершения ввода наберите .):" $/ = "." text = STDIN.gets save_data(name, age, pol, theme, text) puts "Спасибо! Ваша заяака принята и будет рассмотрена в ближайшее время." end #сохранение данных в файл def save_data(name, age, pol, theme, text) casting_h = { name: name.capitalize, age: age, pol: pol, theme: theme.capitalize, text: text.capitalize} break_d = [] break_d << casting_h if File.exists?("casting.json") data = JSON.parse(File.read("casting.json"), symbolize_names: true) data.each do |j| break_d << j end end File.open("casting.json", "w") { |file| file.write(break_d.to_json) } end # проверка уникальности def uniq_data(name, age, pol) if File.exists?("casting.json") unless File.zero?("casting.json") data = JSON.parse(File.read("casting.json"), symbolize_names: true) res = false data.each do |i| res = name.capitalize == i[:name] && age == i[:age] && pol == i[:pol] end res else false end end end #Unicode def capitalize Unicode::capitalize(self) end end <file_sep>/init.rb require "json" require "unicode" require_relative('casting') require_relative('jury') loop{ if File.exist?("casting.json") puts "Выберите действие:" puts " учавствовать в кастинге (Y)," puts " посмотреть результ кастинга (R)," puts " посмотреть продолжительность выступлений(P)," puts " завершить программу (E)," vr = gets.chomp! case when vr == "Y" then Casting.new when vr == "R" then Jury.new.get_result when vr == "P" then Jury.new.get_time when vr == "E" then abort end else puts "Вы первый кандидат кастинга, заполните анкету" Casting.new end }<file_sep>/jury.rb require "json" class Jury MEMBER = 4 def initialize @result = [] if get_data.length > 1 p get_data get_data.each do |i| i[:sum_s] = 0 i[:time_text] = i[:text].to_s.gsub(".", "").split("\n").size @result << i end MEMBER.times do member = ["man", "woman"].sample member == "man" ? age_check : text_check end else puts "Не хватает кандидатов" end end # check man def member_man?(member) member == "man" end #получение данных def get_data if File.exist?("casting.json") res = JSON.parse(File.read("casting.json"), symbolize_names: true) else puts "Нет кандидатов" end end # check text size def text_check @result.each do |r| r[:sum_s] = r[:time_text] < 30 ? Random.rand(7) : Random.rand(10) end end # check age woman def age_check @result.each do |r| r[:sum_s] = [18..25].include?(r[:age].to_i) && ( r[:pol] == "woman") ? Random.rand(7..10) : Random.rand(10) end end # get result casting def result(name, sum) @result.each { |i| i[:sum_s] += sum if i[:name] == name } end def search_max max = 0 @result.each do |i| max = i[:sum_s] if max < i[:sum_s] end @result.each do |e| if e[:sum_s] == max @fin_result = { :name => e[:name], :pol => e[:pol], :time_text => e[:time_text] } end end @fin_result end def get_result if get_data.length > 1 fresult = search_max puts "#{fresult[:name]} get #{fresult[:pol]} role" puts "#{fresult[:name]} time performances #{fresult[:time_text]} seconds" end end def get_time @result.each do |i| puts "У участника #{i[:name]} продолжительность выступления составила #{i[:time_text]} секунд" end end end
14d4bb687d8d3cbc1be461dbcca31dce816bfcbe
[ "Ruby" ]
3
Ruby
vicpo/casting
bc067bd72cd3abbb2692868e92ad13c1142f88e9
6d9fe6d46101834beab0e7e22092fa260f8f9d39
refs/heads/main
<repo_name>koreahong/study_Python_OOP<file_sep>/01 파이썬, 객체지향 프로그래밍/10-inheritance-master.py """ * [클래스 상속] * 1. 부모 클래스가 갖는 모든 메서드와 속성이 자식 클래스에 그대로 상속된다. * 2. 자식 클래스에서 별도의 메서드나 속성을 추가할 수 있다. * 3. 메서드 오버라이딩 * 4. super() * 5. Python의 모든 클래스는 object 클레스를 상속한다. : 모든 것은 객체이다. * MyClass.mro() --> 상속 관계를 보여준다. """ class Robot(object): """ Robot Class """ population = 0 def __init__(self, name): self.name = name Robot.population += 1 def say_hi(self): print(f"Greetings, my masters call me {self.name}.") def cal_add(self, a, b): return a + b @classmethod def how_many(cls): return f"We have {cls.population} robots." class Siri(Robot): def call_me(self): print("네?") def cal_mul(self, a, b): return a * b siri = Siri("iphone8") print( Siri.mro() ) # * [<class '__main__.Siri'>, <class '__main__.Robot'>, <class 'object'>] print(Robot.mro()) # * [<class '__main__.Robot'>, <class 'object'>] print(object) print(dir(object)) print(object.__name__) print(int.mro()) print(int.__init__(8.9)) print(int(8.9)) class A: pass class B: pass class C: pass class D(A, B, C): pass print(D.mro())<file_sep>/01 파이썬, 객체지향 프로그래밍/04-self.py # [self의 이해] # ** self는 인스턴스 객체이다!! # ** 클래스 안에 있는 self의 주소와 만들어진 인스턴스의 주소는 같다! 즉, self는 인스턴스 그 자체이다! class SelfTest: # 클래스 변수 name = "amamov" def __init__(self, x): self.x = x # 인스턴스 변수 # 클래스 메서드 @classmethod def func1(cls): print(f"cls: {cls}") print("func1") # 인스턴스 메서드 def func2(self): print(f"self : {self}") print("class안의 Slef 주소 : ", id(self)) print("func2") test_obj = SelfTest(17) test_obj.func2() SelfTest.func1() # SelfTest.func2() # print(SelfTest.x) print("인스턴스의 주소: ", id(test_obj)) """ self : <__main__.SelfTest object at 0x7f845f70c310> class안의 Slef 주소 : 140206513636112 func2 cls: <class '__main__.SelfTest'> func1 인스턴스의 주소: 140206513636112 """ test_obj.func1() print(test_obj.name)<file_sep>/03 보너스 - 배운 것 응용하기/04-deep-learing-example.py # deep-learing-example # * 해당 파일은 Colab에서 실행해야 합니다. from google.colab import drive drive.mount("/content/mai_drive") import time import math from torch import nn, optim, cuda from torch.utils import data from torchvision import datasets, transforms import torch import torchvision class VGG(nn.Module): """ VGG model """ def __init__(self, features): super().__init__() self.features = features self.classifier = nn.Sequential( nn.Dropout(), nn.Linear(512, 512), nn.ReLU(True), nn.Dropout(), nn.Linear(512, 512), nn.ReLU(True), nn.Linear(512, 10), ) # Initialize weights for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.0 / n)) m.bias.data.zero_() def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x class Machine: """ dataset : cifar10 model : VGG16 """ BASE_DIR = "/content/mai_drive/MyDrive/deep_learning" DATASETS_DIR = f"{BASE_DIR}/datasets" def __init__(self, batch_size: int = 64, epoch_size: int = 1): self.batch_size = batch_size self.epoch_size = epoch_size self.device = "cuda" if cuda.is_available() else "cpu" self.get_data() self.model = Machine.vgg16() self.model.to(self.device) self.criterion = nn.CrossEntropyLoss() self.optimizer = optim.SGD(self.model.parameters(), lr=0.01, momentum=0.5) def get_data(self): normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) self.train_dataset = datasets.CIFAR10( root=f"{Machine.DATASETS_DIR}/cifar10_datasets/", train=True, transform=transforms.Compose( [ transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, 4), transforms.ToTensor(), normalize, ] ), download=True, ) self.test_dataset = datasets.CIFAR10( root=f"{Machine.DATASETS_DIR}/cifar10_datasets/", train=False, transform=transforms.Compose( [ transforms.ToTensor(), normalize, ] ), ) self.train_loader = torch.utils.data.DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, shuffle=True ) self.test_loader = torch.utils.data.DataLoader( dataset=self.test_dataset, batch_size=self.batch_size, shuffle=False ) @staticmethod def vgg16(): """VGG 16-layer model (configuration)""" cfg = [ 64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M", ] def make_layers(cfg, batch_norm=False): layers = [] in_channels = 3 for v in cfg: if v == "M": layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = nn.Conv2d( in_channels=in_channels, out_channels=v, kernel_size=3, padding=1, ) if batch_norm: layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v return nn.Sequential(*layers) return VGG(make_layers(cfg)) def train(self, epoch): self.model.train() for batch_idx, (data, target) in enumerate(self.train_loader): data, target = data.to(self.device), target.to(self.device) self.optimizer.zero_grad() output = self.model(data) loss = self.criterion(output, target) loss.backward() self.optimizer.step() if batch_idx % 10 == 0: print( ( f"Train Epoch : {epoch} | Batch Status : {batch_idx*len(data)}/{len(self.train_loader.dataset)}" f"({100. * batch_idx / len(self.train_loader)}%) | Loss : {loss.item()}" ) ) def test(self): self.model.eval() test_loss = 0 correct = 0 for data, target in self.test_loader: data, target = data.to(self.device), target.to(self.device) output = self.model(data) test_loss += self.criterion(output, target).item() pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() test_loss /= len(self.test_loader.dataset) print( f"\nTest set: Accuracy : {correct}/{len(self.test_loader.dataset)}" f"({100. * correct / len(self.test_loader.dataset):.0f}%)" ) def learning(self): since = time.time() for epoch in range(1, self.epoch_size + 1): epoch_start = time.time() self.train(epoch) m, s = divmod(time.time() - epoch_start, 60) print(f"Training time: {m:.0f}m {s:.0f}s") self.test() m, s = divmod(time.time() - epoch_start, 60) print(f"Tesing time: {m:.0f}m {s:.0f}s") m, s = divmod(time.time() - epoch_start, 60) print(f"Total time : {m:.0f}m {s: .0f}s \nModel was trained on {self.device}!") class ResNetMachine(Machine): """ [Machine based in ResNet Model] """ def __init__(self, batch_size=64, epoch_size=1): super().__init__(batch_size, epoch_size) model = torchvision.models.resnet.ResNet(pretrained=True, progress=True) self.setup_model(model) if __name__ == "__main__": machine = Machine(batch_size=64, epoch_size=300) machine.learning() <file_sep>/01 파이썬, 객체지향 프로그래밍/01-4-using-class.py """ # * 객체지향 프로그래밍 # * [로봇 관리 프로그램] # * siri, bixby, jarvis, droid # * 로봇 이름(name), 로봇 코드번호(code), 로복 제조일자(created_at), 로봇 작동 여부(is_ok), # * 로봇 스킬(skill) 점수 : 번역(translate), 계산(cal), 학습(learning) # * 하드코딩 -> array list 자료구조 사용 -> hash map 자료구조 사용 -> function 자료구조 사용 -> class 자료구조 사용 """ # * 객체지향 프로그래밍 : using class from datetime import datetime class Robot: def __init__(self, name, code, created_at, is_ok): self.name = name self.code = code self.created_at = datetime(created_at, 8, 2) self.is_ok = is_ok self.skills = {} def save_skill_grade(self, trans, cal, learn=0): self.skills["trans"] = trans self.skills["cal"] = cal self.skills["learn"] = learn @classmethod def grade_total(cls, robots): total = 0 for robot in robots: total += robot.skills["trans"] + robot.skills["cal"] + robot.skills["learn"] return total @classmethod def all_code(cls, robots): codes = [] for robot in robots: codes.append(robot.code) return codes siri = Robot("siri", 129083, 2021, True) bixby = Robot("bixby", 4637824, 2020, False) jarvis = Robot("siri", 129083, 2023, True) droid = Robot("droid", 2364786, 2018, False) # * robot의 점수를 합산해주는 프로그램 robots = [siri, bixby, jarvis, droid] robot_total = Robot.grade_total(robots) print(robot_total) # * jarvis에서 learn 기능이 사라졌다면?? jarvis.skills["learn"] = 0 print(robot_total) # * robot의 코드를 반환하는 리스트가 필요하다면? print(Robot.all_code(robots)) # * droid에서 code 번호 수정이 필요하다면?? droid.code = 12389712 print(Robot.all_code(robots)) <file_sep>/01 파이썬, 객체지향 프로그래밍/03-namespace.py """ #* namespace : 개체를 구분할 수 있는 범위 #* __dict__ : 네임스페이스를 확인할 수 있다. #* dir() : 네임스페이스의 key 값을 확인할 수 있다. #* __doc__ : class의 주석을 확인한다. #* __class__ : 어떤 클래스로 만들어진 인스턴스인지 확인할 수 있다. """ class Robot: """ [Robot Class] Author : 윤상석 Role : ???? """ # 클래스 변수 : 인스턴스들이 공유하는 변수 population = 0 # 생성자 함수 def __init__(self, name): self.name = name # 인스턴스 변수 Robot.population += 1 # 인스턴스 메서드 def say_hi(self): # code print(f"Greetings, my masters call me {self.name}.") # 인스턴스 메서드 def cal_add(self, a, b): return a + b # 인스턴스 메서드 def die(self): print(f"{self.name} is being destroyed!") Robot.population -= 1 if Robot.population == 0: print(f"{self.name} was the last one.") else: print(f"There are still {Robot.population} robots working.") # 클래스 메서드 @classmethod def how_many(cls): print(f"We have {cls.population} robots.") siri = Robot("siri") # {'name': 'siri'} jarvis = Robot("jarvis") bixby = Robot("bixby") print(Robot.__dict__) print(siri.__dict__) print(jarvis.__dict__) print(siri.name) print(bixby.name) siri.cal_add(2, 3) print(siri.population) siri.how_many() Robot.say_hi(siri) siri.say_hi() print(dir(siri)) print(dir(Robot)) print(Robot.__doc__) print(siri.__class__) <file_sep>/01 파이썬, 객체지향 프로그래밍/01-3-procedure.py """ # * 절차지향 프로그래밍 # * [로봇 관리 프로그램] # * siri, bixby, jarvis, droid # * 로봇 이름(name), 로봇 코드번호(code), 로복 제조일자(created_at), 로봇 작동 여부(is_ok), # * 로봇 스킬(skill) 점수 : 번역(translate), 계산(cal), 학습(learning) # * 하드코딩 -> array list 자료구조 사용 -> hash map 자료구조 사용 -> function 자료구조 사용 -> class 자료구조 사용 """ # * 절차지향 프로그래밍 from datetime import datetime def robot(name, code, created_at, is_ok, skill_grade): return { "name": name, "code": code, "created_at": datetime(created_at, 8, 2), "is_ok": is_ok, "skill_grade": skill_grade, } siri = robot("siri", 129083, 2021, True, {"trans": 98, "cal": 50, "learn": 40}) bixby = robot("bixby", 4637824, 2020, False, {"trans": 45, "cal": 98, "learn": 67}) jarvis = robot("siri", 129083, 2023, True, {"trans": 25, "cal": 78, "learn": 68}) droid = robot("droid", 2364786, 2018, False, {"trans": 67, "cal": 30, "learn": 21}) # * robot의 점수를 합산해주는 프로그램 def robot_grade_total(robots): total = 0 for robot in robots: total += ( robot["skill_grade"]["trans"] + robot["skill_grade"]["cal"] + robot["skill_grade"]["learn"] ) return total robots = [siri, bixby, jarvis, droid] robot_total = robot_grade_total(robots) print(robot_total) # * jarvis에서 learn 기능이 사라졌다면?? jarvis = robot("siri", 129083, 2023, True, {"trans": 25, "cal": 78}) # robots = [siri, bixby, jarvis, droid] # robot_total = robot_grade_total(robots) # print(robot_total) robots = [siri, bixby, droid] robot_total = robot_grade_total(robots) def special_robot_total(robot): return robot["skill_grade"]["trans"] + robot["skill_grade"]["cal"] print(robot_total + special_robot_total(jarvis)) # * robot의 코드를 반환하는 리스트가 필요하다면? robots.append(jarvis) codes = [] for robot in robots: codes.append(robot["code"]) print(codes) # * droid에서 code 번호 수정이 필요하다면?? droid["code"] = 23189712 codes = [] for robot in robots: codes.append(robot["code"]) print(codes) <file_sep>/02 타입파이썬, 파이썬에서 타이핑하는 방법/README.md # typing 1. 가상환경에 들어간다. 2. `pip install mypy` 3. `mypy main.py` ## 주의사항 - python은 애초에 타이핑이 없는 언어이고 mypy라는 패키지의 도움을 받는 것이므로 타이핑에 너무 집착하지 말자 - 특정 단위의 알고리즘을 개발할 때 국소적으로 mypy를 사용하여 예상치 못한 에러를 잡아내자. mypy에 깊게 의존하지 말자. - 타입힌트는 적극적으로 사용하자. 실제로 현재 공식문서에서 적극적으로 지원되고 있다. - 협업 시에 매우 유용하고 변수 네이밍에도 효율적이다. ```python def train(): input_data = Asjdkl data: str = "123" # asdjljkasd ```<file_sep>/hello_world.py print("hello world") def hello(ss): return ss hello("ss") <file_sep>/03 보너스 - 배운 것 응용하기/01-linked-list.py """ * 스택(stack)이란 쌓아 올린다는 것을 의미한다. * 따라서 스택 자료구조라는 것은 책을 쌓는 것처럼 차곡차곡 쌓아 올린 형태의 자료구조를 말한다. * [Node Class] * - item * - pointer : 다음 node를 가리키므로 다음 node를 저장하고 아무것도 가리키지 않으면 None을 저장한다. * [LinkedList] * - head : 가장 첫 번째 node, node가 없으면 None을 저장한다. * - length : int 타입, 현재 노드(데이터)의 개수를 의미한다. * [Stack] : LinkedList를 상속받는다. * - push(item) : Stack 자료구조에 item을 받아 노드로 만든 다음 밀어넣는다. * - pop() : Stack 자료구조에서 마지막 node를 제거하고 해당 Item을 반환한다. """ <file_sep>/01 파이썬, 객체지향 프로그래밍/05-magic-method.py class Robot: """ [Robot Class] Date : ??:??:?? Author : Amaco """ def __init__(self, name): self.name = name Robot.population += 1 def die(self): print(f"{self.name} is being destroyed!") Robot.population -= 1 if Robot.population == 0: print(f"{self.name} was the last one.") else: print(f"There are still {Robot.population} robots working.") def say_hi(self): print(f"Greetings, my masters call me {self.name}.") def cal_add(self, a, b): return a + b @classmethod def how_many(cls): return f"We have {cls.population} robots." @staticmethod def are_you_robot(): print("yes!!") def __str__(self): return f"{self.name} robot!!" def __call__(self): print("call!") return f"{self.name} call!!" droid1 = Robot("R2-D2") droid1.say_hi() print(dir(droid1)) print(droid1) # <__main__.Robot object at 0x7fde1c742110> -> R2-D2 robot!! droid1() <file_sep>/README.md # Python OOP 스터디 # 배경 - Python OOP를 활용하여 더 효율적이고 생산적인 코딩을 하기 위함 # 출처 - 인프런 OOP 강의 - 각코드는 해당 강의의 git에서 가져옴 - 각 장 readme에 자세한 설명 기재 <file_sep>/03 보너스 - 배운 것 응용하기/02-linked-list-hint.py from typing import Optional class Node: __slots__ = ("item", "pointer") def __init__(self, item, pointer: Optional["Node"]): self.item = item self.pointer: Optional["Node"] = pointer class LinkedList: def __init__(self): self.head: Optional[Node] = None @property def length(self) -> int: if self.head is None: return 0 else: pass class Stack(LinkedList): def push(self, item): pass def pop(): pass <file_sep>/01 파이썬, 객체지향 프로그래밍/02-abstraction-basic.py """ #* 추상화 : abstraction #* 불필요한 정보는 숨기고 중요한(필요한) 정보만을 표현함으로써 #* 공통의 속성 값이나 행위(methods)를 하나로 묶어 이름을 붙이는 것이다. """ class Robot: # 클래스 변수 : 인스턴스들이 공유하는 변수 population = 0 # 생성자 함수 def __init__(self, name, code): self.name = name # 인스턴스 변수 self.code = code # 인스턴스 변수 Robot.population += 1 # 인스턴스 메서드 def say_hi(self): # code print(f"Greetings, my masters call me {self.name}.") # 인스턴스 메서드 def cal_add(self, a, b): return a + b # 인스턴스 메서드 def die(self): print(f"{self.name} is being destroyed!") Robot.population -= 1 if Robot.population == 0: print(f"{self.name} was the last one.") else: print(f"There are still {Robot.population} robots working.") # 클래스 메서드 @classmethod def how_many(cls): print(f"We have {cls.population} robots.") print(Robot.population) # 0 siri = Robot("siri", 21039788127) print(Robot.population) # 1 jarvis = Robot("jarvis", 2311213123) print(Robot.population) # 2 bixby = Robot("bixby", 124312423) print(Robot.population) # 3 bixby2 = Robot("bixby2", 124312423) bixby23 = Robot("bixby2", 124312423) print(siri.name) print(siri.code) jarvis.say_hi() siri.say_hi() siri.cal_add(2, 3) Robot.how_many() <file_sep>/01 파이썬, 객체지향 프로그래밍/00-decorator.py # decorator def copyright(func): def new_func(): print("@ amamovsdfjkldjsakfljdskaljfkdsla") func() return new_func @copyright def smile(): print("🙃") @copyright def angry(): print("🤯") @copyright def love(): print("🥰") smile() angry() love() <file_sep>/02 타입파이썬, 파이썬에서 타이핑하는 방법/test.py def cal_add(x: int, y: int) -> int: # code return x + y cal_add(1, 3) <file_sep>/01 파이썬, 객체지향 프로그래밍/14-composition.py """ #* composition #* 다른 클래스의 일부 메서드를 사용하고 싶지만, 상속은 하고 싶지 않을 경우 #* 1. 부모 클래스가 변하면 자식 클래스는 계속 수정되어야 한다. #* 2. 부모 클래스의 메서드를 오버라이딩 하는 경우 내부 구현 방식의 얕은 이해로 오류가 생길 가능성 증가 """ class Robot: """ Robot Class """ __population = 0 def __init__(self, name, age): self.__name = name self.__age = age Robot.__population += 1 @property def name(self): return f"yoon {self.__name}" @property def age(self): return self.__age @age.setter def age(self, new_age): if new_age - self.__age == 1: self.__age = new_age else: raise ValueError() def __say_hi(self): self.cal_add(1, 3) print(f"Greetings, my masters call me {self.__name}.") def cal_add(self, a, b): return a + b + 1 @classmethod def how_many(cls): return f"We have {cls.__population} robots." class Siri(Robot): def say_apple(self): print("hello my apple") class SiriKo(Robot): def say_apple(self): print("안녕 사과") class Bixby(Robot): def say_sanmgsung(self): print("hello my sangsung") class BixbyKo(Robot): def say_samsung(self): print("안녕 삼성") class BixbyCal: def __init__(self, name, age): self.Robot = Robot(name, age) def cal_add(self, a, b): return self.Robot.cal_add(a, b) <file_sep>/01 파이썬, 객체지향 프로그래밍/01-1-class.py # * 객체(object)의 **속성과 행위(methods)**를 하나로 묶고, 구현된 일부를 외부에 감추어 은닉한다. # ** 사칙연산 계산기 def add(a, b): return a + b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): return a / b print(add(1, 2)) print(sub(1, 2)) print(mul(1, 2)) print(div(1, 2)) <file_sep>/02 타입파이썬, 파이썬에서 타이핑하는 방법/07-final-type.py from typing_extensions import Final RATE: Final = "dasdsa" # RATE = 300 <file_sep>/02 타입파이썬, 파이썬에서 타이핑하는 방법/08-generic-type-class.py """ * 데이터 형식에 의존하지 않고, 하나의 값이 여러 다른 데이터 타입들을 가질 수 있는 기술 """ from typing import Union, Optional, TypeVar, Generic T = TypeVar("T", int, float, str) K = TypeVar("K", int, float, str) class Robot(Generic[T, K]): def __init__(self, arm: T, head: K): self.arm = arm self.head = head def decode(self): # 암호를 해독하는 코드 # 복잡 pass robot1 = Robot[int, int](12231413, 23908409) robot2 = Robot[str, int]("12890309123", 79878789) robot3 = Robot[float, str](1239.01823, "3243245") class Siri(Generic[T, K], Robot[T, K]): pass siri1 = Siri[int, int](12231413, 23908409) siri2 = Siri[str, int]("12890309123", 79878789) siri3 = Siri[float, str](1239.01823, "3243245") print(siri1.arm) # * function def test(x: T) -> T: print(x) print(type(x)) return x test(898) <file_sep>/02 타입파이썬, 파이썬에서 타이핑하는 방법/06-type-alias.py # https://mypy.readthedocs.io/en/stable/kinds_of_types.html#type-aliases from typing import Union, List, Tuple, Dict, Optional from typing_extensions import TypedDict # * type alias Value = Union[ int, bool, Union[List[str], List[int], Tuple[int, ...]], Optional[Dict[str, float]] ] X = int x: X = 8 value: Value = 17 def cal(v: Value) -> Value: # ddmasda return v # * dict alias ddd: Dict[str, Union[str, int]] = {"hello": "world", "world": "wow!!", "hee": 17} class Point(TypedDict): x: int y: float z: str hello: int point: Point = {"x": 8, "y": 8.4, "z": "hello", "hello": 12} <file_sep>/03 보너스 - 배운 것 응용하기/03-linked-list.py from typing import Optional, Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, item: T, pointer: Optional["Node"] = None): self.item = item self.pointer = pointer class LinkedList(Generic[T]): def __init__(self): self.head: Optional[Node[T]] = None @property def length(self) -> int: if self.head is None: return 0 cur_node = self.head count: int = 1 while cur_node.pointer is not None: cur_node = cur_node.pointer count += 1 return count def __str__(self) -> str: result: str = "" if self.head is None: return result cur_node = self.head result += f"{cur_node.item}" while cur_node.pointer is not None: cur_node = cur_node.pointer result += f", {cur_node.item}" return result class Stack(Generic[T], LinkedList[T]): def push(self, item: T) -> None: new_node: Node[T] = Node[T](item=item) if self.head is None: self.head = new_node return cur_node = self.head while cur_node.pointer is not None: cur_node = cur_node.pointer cur_node.pointer = new_node def pop(self) -> T: if self.head is None: raise ValueError("stack is empty") cur_node = self.head if cur_node.pointer is None: self.head = None return cur_node.item while cur_node.pointer.pointer is not None: cur_node = cur_node.pointer result = cur_node.pointer cur_node.pointer = None return result.item class Queue(Generic[T], LinkedList[T]): def enqueue(self, item: T) -> None: new_node: Node[T] = Node[T](item=item) if self.head is None: self.head = new_node return cur_node = self.head while cur_node.pointer is not None: cur_node = cur_node.pointer cur_node.pointer = new_node def dequeue(self) -> T: if self.head is None: raise ValueError("queue is empty") cur_node = self.head if cur_node.pointer is None: self.head = None return cur_node.item result = cur_node.item self.head = cur_node.pointer return result if __name__ == "__main__": stack = Stack[int]() stack.push(12) stack.push(2) stack.push(3) stack.push(4) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.length) print(stack) queue = Queue[int]() queue.enqueue(12) queue.enqueue(1) queue.enqueue(13) queue.enqueue(16) queue.dequeue() queue.dequeue() queue.dequeue() queue.dequeue() queue.dequeue() print(queue) print(queue.length) <file_sep>/01 파이썬, 객체지향 프로그래밍/README.md # Object Oriented Programming (OOP) > 데이터(data)를 추상화시켜 상태(속성)와 행위(methods)를 가진 객체(object)로 만들고 그 객체들 간의 유기적인 상호작용을 통해 로직(흐름)을 구성하는 프로그래밍 방법 > 프로그램을 실제 세상에 가깝게 모델링하는 기법 ## class > 어떤 문제를 해결하기 위한 데이터를 만들기 위해 OOP 원칙에 따라 집단(현실 세계)에 속하는 속성과 행위(methods)를 변수와 메서드로 정의한 것 > **"로봇 설계도"** ## instance (object) > class에서 정의한 것(설계도)을 토대로 실제 메모리상에 할당된 것(실제 사물, object)으로 실제 프로그램에서 사용되는 데이터이다. > 하나의 class로 만들어진 여러 instance(object)는 각각 **독립적**이다. > **"실제 로봇"** ## OOP 원칙 ### 캡슐화 : encapsulation > 객체(object)의 **속성과 행위(methods)**를 하나로 묶고, 구현된 일부를 외부에 감추어 은닉한다. ### 추상화 : abstraction > 불필요한 정보는 숨기고 중요한(필요한) 정보만을 표현함으로써 공통의 속성이나 행위(methods)를 하나로 묶어 이름을 붙이는 것이다. ### 상속 : Inheritance > 부모 class의 속성과 행위(methods)을 그대로 상속 받고 행위(methods)의 일부분을 수정해야 할 경우 상속받은 자식 class에서 해당 행위(methods)만 다시 수정하여 사용할 수 있도록 한다. 또한 자식 class에서 추가적으로 속성이나 행위(methods)를 정의할 수 있게 한다. ### 다형성 : Polymorphism > 여러 형태를 가질 수 있도록 한다. 즉, 객체를 부품화할 수 있도록 한다. - A 공장에서 만든 타이어를 YSS 자동차 회사에서 사용할 수 있고 YYR 자동차 회사에서도 사용할 수 있다. - 또한, 이 타이어는 탱크의 타이어 개발에 재료로 사용될 수도 있다.<file_sep>/01 파이썬, 객체지향 프로그래밍/01-2-hard-coding.py """ # * hard-coding # * [로봇 관리 프로그램] # * siri, bixby, jarvis, droid # * 로봇 이름(name), 로봇 코드번호(code), 로봇 제조일자(created_at), 로봇 작동 여부(is_ok), # * 로봇 스킬(skill) 점수 : 번역(translate), 계산(cal), 학습(learning) # * 하드코딩 -> array list 자료구조 사용 -> hash map 자료구조 사용 -> function 자료구조 사용 -> class 자료구조 사용 """ from datetime import datetime # * 하드코딩 robot_name_1 = "siri" robot_code_1 = 912083902 robot_created_at_1 = datetime(2012, 4, 3) robot_is_ok_1 = True robot_skill_grade_1 = { "trans": 98, "cal": 48, "learn": 88, } robot_name_2 = "bixby" robot_code_2 = 12348979128 robot_created_at_2 = datetime(2032, 6, 4) robot_is_ok_2 = False robot_skill_grade_2 = { "trans": 45, "cal": 32, "learn": 22, } robot_name_3 = "jarvis" robot_code_3 = 234792387 robot_created_at_3 = datetime(2012, 6, 3) robot_is_ok_3 = True robot_skill_grade_3 = { "trans": 21, "cal": 19, "learn": 90, } robot_name_4 = "droid" robot_code_4 = 12749234 robot_created_at_4 = datetime(2032, 6, 3) robot_is_ok_4 = True robot_skill_grade_4 = { "trans": 432, "cal": 324, "learn": 123, } # * list 자료구조 사용 robot_name = ["siri", "bixby", "jarvis", "droid"] robot_code = [912083902, 12348979128, 234792387, 12749234] robot_created_at = [ datetime(2012, 4, 3), datetime(2032, 6, 4), datetime(2012, 6, 3), datetime(2032, 6, 3), ] robot_is_ok = [True, False, True, True] robot_skill_grade = [ { "trans": 98, "cal": 48, "learn": 88, }, { "trans": 45, "cal": 32, "learn": 22, }, { "trans": 21, "cal": 19, "learn": 90, }, { "trans": 432, "cal": 324, "learn": 123, }, ] print(robot_name[0]) print(robot_name[2]) print(robot_name[3]) # * dict 자료구조 siri = { "name": "siri", "code": 129083, "created_at": datetime(2021, 8, 2), "is_ok": True, "skill_grade": {"trans": 98, "cal": 50, "learn": 40}, } bixby = { "name": "bixby", "code": 4637824, "created_at": datetime(2020, 8, 2), "is_ok": False, "skill_grade": {"trans": 45, "cal": 98, "learn": 67}, } jarvis = { "name": "jarvis", "code": 2364786, "created_at": datetime(2023, 8, 2), "is_ok": True, "skill_grade": {"trans": 25, "cal": 78, "learn": 68}, } droid = { "name": "droid", "code": 2364786, "created_at": datetime(2018, 8, 2), "is_ok": False, "skill_grade": {"trans": 67, "cal": 30, "learn": 21}, } # * fucntion def robot(name, code, created_at, is_ok, skill_grade): return { "name": name, "code": code, "created_at": created_at, "is_ok": is_ok, "skill_grade": skill_grade, } siri = robot("siri", 129083, 2021, True, {"trans": 98, "cal": 50, "learn": 40}) bixby = robot("bixby", 4637824, 2020, False, {"trans": 45, "cal": 98, "learn": 67}) jarvis = robot("siri", 129083, 2023, True, {"trans": 25, "cal": 78, "learn": 68}) droid = robot("droid", 2364786, 2018, False, {"trans": 67, "cal": 30, "learn": 21}) droid_2 = robot( "droid-2", 2364781236, 2018, False, {"trans": 67, "cal": 30, "learn": 21} ) # * class class Robot: def __init__(self, name, code, created_at, is_ok, skill_grade): self.name = name self.code = code self.created_at = created_at self.is_ok = is_ok self.skill_grade = skill_grade siri = Robot("siri", 129083, 2021, True, {"trans": 98, "cal": 50, "learn": 40}) bixby = Robot("bixby", 4637824, 2020, False, {"trans": 45, "cal": 98, "learn": 67}) jarvis = Robot("siri", 129083, 2023, True, {"trans": 25, "cal": 78, "learn": 68}) droid = Robot("droid", 2364786, 2018, False, {"trans": 67, "cal": 30, "learn": 21}) droid_2 = Robot( "droid-2", 2364781236, 2018, False, {"trans": 67, "cal": 30, "learn": 21} )
91846719f83684fb61d5c9e4d80212a4dd518702
[ "Markdown", "Python" ]
23
Python
koreahong/study_Python_OOP
6128c18e7e4882abc822bfab573c5ce90a24b61f
d683c278d5f2673a65356adee3ff7180e7ecbbb1
refs/heads/master
<repo_name>iwandi/GameEngineToyHouse<file_sep>/GameEngineToyHouse/GameEngineToyHouse/JobManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameEngineToyHouse { public class JobManager { public int CpuCount { get { return 1; } } public void AddJob(Job job) { } public void ExcuteJobs() { } } } <file_sep>/GameEngineToyHouse/GameEngineToyHouse/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace GameEngineToyHouse { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LoopManager loop = new LoopManager(); loop.Init(); loop.Run(); loop.DeInit(); } } } <file_sep>/GameEngineToyHouse/GameEngineToyHouse/SceneRenderer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameEngineToyHouse { public class SceneRenderer { } } <file_sep>/GameEngineToyHouse/GameEngineToyHouse/Job.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameEngineToyHouse { public class Job { public void AddJob(Action action) { } public void AddJob<T>(Action<T> action, T state) { } } } <file_sep>/GameEngineToyHouse/GameEngineToyHouse/LoopManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameEngineToyHouse { public class LoopManager { JobManager job; RenderManager render; public bool Active { get; set; } public void Init() { job = new JobManager(); render = new RenderManager(); } public void Run() { Active = true; RunWorker(); } void RunWorker() { while (Active) { RunUpdate(); } } void RunUpdate() { render.CollectJobs(job); job.ExcuteJobs(); } public void Stop() { Active = false; } public void DeInit() { } } } <file_sep>/GameEngineToyHouse/GameEngineToyHouse/RenderManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameEngineToyHouse { public class RenderManager { struct CompositionNode { } struct Renderlet { } Renderlet[] m_renderlets; public void CollectJobs(JobManager manager) { // alot of this can be created onece and then just updated per frame int cpus = manager.CpuCount; int pos = 0; int elementsPerJob = (m_renderlets.Length / cpus) + 1; for (int i = 0; i < cpus; i++) { int elemntsInThisJob = elementsPerJob; if (pos + elemntsInThisJob > m_renderlets.Length) { elemntsInThisJob = m_renderlets.Length - pos; } Renderlet[] work = new Renderlet[elemntsInThisJob]; Buffer.BlockCopy(m_renderlets, pos, work, 0, elemntsInThisJob); Job job = new Job(); job.AddJob<Renderlet[]>(RenderletWorker, work); manager.AddJob(job); pos += elementsPerJob; } // TODO : we require to depend on alle the render jobs to be finished Job pressent = new Job(); pressent.AddJob(PresentWorker); manager.AddJob(pressent); } void RenderletWorker(Renderlet[] work) { } void PresentWorker() { } } }
003dfb966ae26140416a0430b448d8535cc1d4a8
[ "C#" ]
6
C#
iwandi/GameEngineToyHouse
029fd29cbe9de970db7504c9170b8ba9ee9dee16
0dbd91ddf3fa2201b24e38bd927d1f5741948be8
refs/heads/master
<repo_name>woorim960/algorithm<file_sep>/README.md # algorithm 알고리즘 모음 <file_sep>/search/sequensial.py # 순차 탐색 def sequensial_search(ls, x) : for i in range(len(ls)) : if ls[i] == x : return i return -1 # 입력 x = int(input()) # 찾을 값 ls = sorted(map(int, input().split())) # 검색 리스트 # 실행 print( sequensial_search(ls, x) )<file_sep>/sort/bouble.py ''' 자신과 자신 바로 옆의 원소와 비교하여 더 작은 값을 앞으로 배치하는 정렬 + 교환 정렬과 다르다. ''' # 버블 정렬 def bouble(n, ls) : for i in range(n-1, -1, -1) : # 맨 끝에서 1씩 감소하는게 포인트(끝 데이터는 정렬된 상태기에 다시 검사하지 않기 위함) for j in range(n-1) : if ls[j] > ls[j+1] : ls[j], ls[j+1] = ls[j+1], ls[j] return ls # 입력 ls = list(map(int, input().split())) # 실행 print( bouble(len(ls), ls) )<file_sep>/bfs/bfs.py # BFS 구현을 위한 deque 포함 from collections import deque # 연결된 노드들끼리 리스트에 담아준다. graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [6, 8], [1, 7] ] # 방문 처리를 위한 방문 여부 변수 선언 is_visitable = [False] * 9 # BFS 함수 def bfs(graph, start, is_visitable) : # 시작 노드를 큐로 만들어준다. q = deque([start]) # 시작 노드 방문 처리 is_visitable[start] = True # 큐가 빌 때 까지 반복 while q : # FIFO 처리 node = q.popleft() # out 노드 출력 print(node, end=' ') # 인접 노드 순회 for i in graph[node] : # 해당 노드에 미방문시 실행 if is_visitable[i] == False : # 큐에 추가 q.append(i) # 방문 처리 is_visitable[i] = True # BFS(너비 우선 탐색) 시작 bfs(graph, 1, is_visitable) <file_sep>/search/binary.py # 이진 탐색 def binary_search(ls, x) : i = 0 # 인덱스 변수 선언 low, high = 0, len(ls)-1 # low와 high는 검색할 리스트의 시작과 끝 주소를 의미한다. while low <= high : i = (low+high) // 2 # 인덱스는 항상 가운데를 탐색하도록 한다. if ls[i] == x : # 찾았다면 인덱스 반환 return i elif ls[i] < x : # x가 더 크다면 low를 현재 인덱스에서 1 증가시킨다. low = i+1 else : # x가 더 작다면 high를 현재 인덱스에서 1 증가시킨다. high = i-1 return -1 # 입력 x = int(input()) # 찾을 값 ls = sorted(map(int, input().split())) # 검색 리스트(항상 정렬되어있는 리스트내에서의 탐색만 허용된다.) # 실행 print( binary_search(ls, x) )<file_sep>/recursion/fibonacci.py # 공간과 시간복잡도를 최대한 줄여보자. # 피보나치 def fibo(n) : global a, b # 함수 밖의 imutable 데이터를 제어하기 위해 global 선언 # 피보나치 구현 for i in range(2, n+1) : a, b = b, a+b return b if n != 0 else a # 입력 값이 0이면 0 반환 # 찾을 피보나치 값 입력 n = int(input()) # 공간 효율성을 위해 두개의 변수만 선언 a, b = 0, 1 # 실행 print( fibo(n) )<file_sep>/sort/exchange.py ''' 자신과 자신 앞에 있는 모든 원소들과 비교해서 자신보다 작은 것이 있으면 자신의 위치랑 바꾼다. 자신의 위치에는 항상 가장 작은 값이 위치해있게 되는 정렬. ''' # 교환 정렬 def exchange(n, ls) : for i in range(n-1) : for j in range(i+1, n) : if ls[i] > ls[j] : ls[i], ls[j] = ls[j], ls[i] return ls # 입력 ls = list(map(int, input().split())) # 실행 print( exchange(len(ls), ls) )<file_sep>/sort/merge.py # 합병 정렬 def merge_sort(ls) : n = len(ls) # 여러번 호출되기에 미리 선언해준다. if n <= 1 : return ls # 리스트의 길이가 1이면 자기 자신 반환 u = merge_sort(ls[:n//2]) # 반으로 나눈 좌측 리스트 v = merge_sort(ls[n//2:]) # 반으로 나눈 우측 리스트 return merge(u, v) # 합병 # 합병 => 각 원소를 비교하여 크기 순으로 정렬하면서 합친다. def merge(u, v) : ls = [] # 정렬된 요소가 담길 리스트 i = j = 0 # 인덱스 u_max, v_max = len(u), len(v) # while문에서 매번 조건 검사시 len()을 호출하지 않도록 미리 할당 while i < u_max and j < v_max : # 비교가 마무리될 때까지 반복 # 작은 것 순서대로 삽입 if u[i] <= v[j] : ls.append(u[i]) i += 1 else : ls.append(v[j]) j += 1 # 비교 후 남은 리스트를 마지막에 합쳐준다. if i > j : ls += v[j:] else : ls += u[i:] return ls # 정렬할 리스트 입력 ls = list(map(int, input().split())) # 실행 print( merge_sort(ls) ) <file_sep>/search/binary-recursion.py # 이진 탐색 def binary_search(ls, x, low, high) : if low > high : # x가 리스트 내에 없다면 return -1 i = (low+high) // 2 # 인덱스는 항상 가운데를 탐색하도록 한다. if ls[i] == x : # 찾았다면 인덱스 반환 return i elif ls[i] < x : # x가 더 크다면 low를 현재 인덱스에서 1 증가시킨다. return binary_search(ls, x, i+1, high) else : # x가 더 작다면 high를 현재 인덱스에서 1 증가시킨다. return binary_search(ls, x, low, i-1) # 입력 x = int(input()) # 찾을 값 ls = sorted(map(int, input().split())) # 검색 리스트(항상 정렬되어있는 리스트내에서의 탐색만 허용된다.) # 실행 print( binary_search(ls, x, 0, len(ls)-1) )<file_sep>/dfs/dfs.py # 연결된 노드들끼리 리스트에 담아준다. graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [6, 8], [1, 7] ] # 방문 처리를 위한 방문 여부 변수 선언 is_visitable = [False] * 9 # DFS 함수 def dfs(graph, node, is_visitable) : # 방문 처리 is_visitable[node] = True # 방문한 노드 출력 print(node, end=' ') # 인접 노드 중 방문하지 않은 노드 방문 for i in graph[node] : # 방문하지 않았다면 실행 if is_visitable[i] == False : # 노드 방문 처리 및 출력 dfs(graph, i, is_visitable) # DFS 실행 dfs(graph, 1, is_visitable)
7027f3bcaf8ad0237141dd81e30099f055586d75
[ "Markdown", "Python" ]
10
Markdown
woorim960/algorithm
386dad158e5db01256c78cd120c0405bd7281716
e7b81845a36a08c351a88a9d456f9712ac486d54
refs/heads/master
<repo_name>terenceponce/codes_wholesale<file_sep>/README.md # CodesWholesale A Ruby interface to the [CodesWholesale](http://codeswholesale.com) API ## Installation Add this line to your application's Gemfile: ```ruby gem 'codes_wholesale' ``` And then execute: $ bundle Or install it yourself as: $ gem install codes_wholesale ## Usage ```ruby # Authentication client = CodesWholesale::Client.new(client_id: "ff72ce315d1259e822f47d87d02d261e", client_secret: <KEY>") # Find a product product = client.products('ffe2274d-5469-4b0f-b57b-f8d21b09c24c') # Get all products products = client.products # Get your current account details account = client.account # Order a product order = client.order('ffe2274d-5469-4b0f-b57b-f8d21b09c24c') ``` ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/terenceponce/codes_wholesale. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). <file_sep>/test/lib/client_test.rb require 'test_helper' class ClientTest < Minitest::Test def test_it_configures_through_a_block CodesWholesale.configure do |config| config.client_id = 'ff72ce315d1259e822f47d87d02d261e' config.client_secret = <KEY>' end assert_equal 'ff72ce315d1259e822f47d87d02d261e', CodesWholesale.client_id assert_equal '$2a$10$E2jVWDADFA5gh6zlRVcrlOOX01Q/HJoT6hXuDMJxek.YEo.lkO2T6', CodesWholesale.client_secret end def test_it_configures_through_a_hash client = CodesWholesale::Client.new(client_id: 'ff72ce315d1259e822f47d87d02d261e', client_secret: <KEY>') assert_equal 'ff72ce315d1259e822f47d87d02d261e', client.client_id assert_equal '$2a$10$E2jVWDADFA5gh6zlRVcrlOOX01Q/HJoT6hXuDMJxek.YEo.lkO2T6', client.client_secret end def test_it_authenticates_successfully VCR.use_cassette('successful_authentication') do client = CodesWholesale::Client.new(client_id: 'ff72ce315d1259e822f47d87d02d261e', client_secret: <KEY>', environment: 'test') token = client.token assert_equal '<KEY>', token.token assert_equal 'bearer', token.params['token_type'] assert_equal 266, token.expires_in end end end <file_sep>/lib/codes_wholesale.rb require "codes_wholesale/client" require "codes_wholesale/configurable" require "codes_wholesale/default" require "codes_wholesale/version" require 'faraday' require 'sawyer' require 'oauth2' require 'json' module CodesWholesale class << self include CodesWholesale::Configurable end end CodesWholesale.setup <file_sep>/lib/codes_wholesale/configurable.rb module CodesWholesale # Configuration options for {Client}, defaulting to values in {Default} module Configurable # @!attribute [w] client_id # @return [String] Configure OAuth app key # @!attribute [w] client_secret # @return [String] Configure OAuth app secret # @!attribute [w] environment # @return [String] Configure API environment # @!attribute user_agent # @return [String] Configure User-Agent for requests # @!attribute api_version # @return [String] Configure API version attr_accessor :client_id, :client_secret, :environment, :user_agent, :api_version class << self # List of configurable keys for {CodesWholesale::Client} # @return [Array] of option keys def keys @keys ||= [ :client_id, :client_secret, :environment, :user_agent, :api_version ] end end # Set configuration options through a block def configure yield self end # Reset configuration options to default values def reset! CodesWholesale::Configurable.keys.each do |key| instance_variable_set(:"@#{key}", CodesWholesale::Default.options[key]) end self end alias setup reset! def api_endpoint "https://#{api_subdomain}.codeswholesale.com/#{@api_version}" end private def api_subdomain case environment when 'production' 'api' when 'test' 'sandbox' end end end end <file_sep>/lib/codes_wholesale/models/product.rb module CodesWholesale module Models class Product attr_reader :id, :identifier, :name, :platform, :quantity, :regions, :languages, :prices, :links, :release_date def initialize(opts = {}) @id = opts[:productId] @identifier = opts[:identifier] @name = opts[:name] @platform = opts[:platform] @quantity = opts[:quantity] @regions = opts[:regions] @languages = opts[:languages] @prices = opts[:prices] @links = opts[:links] @release_date = opts[:releaseDate] end end end end <file_sep>/lib/codes_wholesale/models/account.rb module CodesWholesale module Models class Account attr_reader :full_name, :email, :current_balance, :current_credit, :total_to_use def initialize(opts = {}) @full_name = opts[:fullName] @email = opts[:email] @current_balance = opts[:currentBalance] @current_credit = opts[:currentCredit] @total_to_use = opts[:totalToUse] end end end end <file_sep>/lib/codes_wholesale/client/orders.rb require 'codes_wholesale/models/order' module CodesWholesale class Client # Methods for the Orders API # # @see https://docs.codeswholesale.com/api-documentation module Orders # Order a product # # @param product_id [String] ID of the product # @return [CodesWholesale::Models::Order] Order details # @see https://docs.codeswholesale.com/api-documentation/#api-single-code # @example Order a product # CodesWholesale.order('6313677f-5219-47e4-a067-7401f55c5a3a') def order(product_id) CodesWholesale::Models::Order.new(post("orders?productId=#{product_id}")) end end end end <file_sep>/lib/codes_wholesale/default.rb require 'codes_wholesale/version' module CodesWholesale # Default configuration options for {Client} module Default # Default API environment ENVIRONMENT = 'production'.freeze # Default API version API_VERSION = 'v1'.freeze # Default User-Agent header string USER_AGENT = "CodesWholesale Ruby Gem #{CodesWholesale::VERSION}".freeze class << self # Configuration options # @return [Hash[ def options Hash[CodesWholesale::Configurable.keys.map { |key| [key, send(key)] }] end # Default API version # @return [String] def api_version ENV['CODES_WHOLESALE_API_VERSION'] ||= API_VERSION end # Default API environment # @ return [String] def environment ENV['CODES_WHOLESALE_ENVIRONMENT'] ||= ENVIRONMENT end # Default OAuth app key from ENV # @return [String] def client_id ENV['CODES_WHOLESALE_CLIENT_ID'] end # Default OAuth app secret from ENV # @return [String] def client_secret ENV['CODES_WHOLESALE_CLIENT_SECRET'] end # Default User-Agent header string from ENV or {USER_AGENT} # @return [String] def user_agent ENV['CODES_WHOLESALE_USER_AGENT'] || USER_AGENT end end end end <file_sep>/test/test_helper.rb $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'codes_wholesale' require 'minitest/autorun' require 'webmock/minitest' require 'vcr' require 'byebug' VCR.configure do |config| config.cassette_library_dir = 'test/fixtures' config.hook_into :webmock end <file_sep>/test/lib/client/orders_test.rb require 'test_helper' class OrdersTest < Minitest::Test def setup @client = CodesWholesale::Client.new(client_id: 'ff72ce315d1259e822f47d87d02d261e', client_secret: <KEY>', environment: 'test') end def test_it_preorders_a_product VCR.use_cassette('orders/preorder_a_product') do order = @client.order('33e3e81d-2b78-475a-8886-9848116f5133') assert_equal 'CODE_PREORDER', order.code_type end end end <file_sep>/test/lib/client/products_test.rb require 'test_helper' class ProductTest < Minitest::Test def setup @client = CodesWholesale::Client.new(client_id: 'ff72ce315d1259e822f47d87d02d261e', client_secret: <KEY>', environment: 'test') end def test_it_returns_single_preorder_product VCR.use_cassette('products/return_single_preorder_product') do product = @client.products('33e3e81d-2b78-475a-8886-9848116f5133') assert_equal '33e3e81d-2b78-475a-8886-9848116f5133', product.id assert_equal 'TPP', product.identifier assert_equal 'Test pre order product', product.name assert_equal 'Origin', product.platform assert_equal 0, product.quantity assert_equal ['ASIA'], product.regions assert_equal ['Multilanguage'], product.languages assert_equal 0.1, product.prices.first.value assert_equal 100, product.prices.first.from assert_equal nil, product.prices.first.to assert_equal 0.4, product.prices.last.value assert_equal 10, product.prices.last.from assert_equal 99, product.prices.last.to assert_equal '2055-04-30T22:00:00.000Z', product.release_date end end def test_it_returns_single_high_priced_product VCR.use_cassette('products/return_single_high_priced_product') do product = @client.products('04aeaf1e-f7b5-4ba9-ba19-91003a04db0a') assert_equal '04aeaf1e-f7b5-4ba9-ba19-91003a04db0a', product.id assert_equal 'TPWHP', product.identifier assert_equal 'Test product with high price', product.name assert_equal 'None', product.platform assert_equal 0, product.quantity assert_equal ['WORLDWIDE'], product.regions assert_equal ['Multilanguage'], product.languages assert_equal 1038999996.88, product.prices.first.value assert_equal 100, product.prices.first.from assert_equal 0, product.prices.first.to assert_equal 1038999998.96, product.prices.last.value assert_equal 1, product.prices.last.from assert_equal 9, product.prices.last.to assert_equal nil, product.release_date end end def test_it_returns_single_image_code_product VCR.use_cassette('products/return_single_image_code_product') do product = @client.products('6313677f-5219-47e4-a067-7401f55c5a3a') assert_equal '6313677f-5219-47e4-a067-7401f55c5a3a', product.id assert_equal 'TWICO', product.identifier assert_equal 'Test with image codes only', product.name assert_equal 'Steam', product.platform assert_equal 0, product.quantity assert_equal ['EU'], product.regions assert_equal ['fr'], product.languages assert_equal 0.1, product.prices.first.value assert_equal 100, product.prices.first.from assert_equal nil, product.prices.first.to assert_equal 1.1, product.prices.last.value assert_equal 1, product.prices.last.from assert_equal 9, product.prices.last.to assert_equal nil, product.release_date end end def test_it_returns_single_text_code_product VCR.use_cassette('products/return_single_text_code_product') do product = @client.products('ffe2274d-5469-4b0f-b57b-f8d21b09c24c') assert_equal 'ffe2274d-5469-4b0f-b57b-f8d21b09c24c', product.id assert_equal 'TWTCO', product.identifier assert_equal 'Test with text codes only', product.name assert_equal 'Uplay', product.platform assert_equal 0, product.quantity assert_equal ['PL'], product.regions assert_equal ['pl'], product.languages assert_equal 1.11, product.prices.first.value assert_equal 1, product.prices.first.from assert_equal 9, product.prices.first.to assert_equal 0.41, product.prices.last.value assert_equal 10, product.prices.last.from assert_equal 99, product.prices.last.to assert_equal nil, product.release_date end end def test_it_returns_all_products VCR.use_cassette('products/return_all_products') do products = @client.products assert_equal 4, products.count assert_equal '33e3e81d-2b78-475a-8886-9848116f5133', products.first.id assert_equal 'ffe2274d-5469-4b0f-b57b-f8d21b09c24c', products.last.id end end end <file_sep>/lib/codes_wholesale/client.rb require 'codes_wholesale/configurable' require 'codes_wholesale/client/accounts' require 'codes_wholesale/client/products' require 'codes_wholesale/client/orders' module CodesWholesale # Client for the CodesWholesale API # # @see https://docs.codeswholesale.com/api-documentation/ class Client include CodesWholesale::Configurable include CodesWholesale::Client::Accounts include CodesWholesale::Client::Products include CodesWholesale::Client::Orders def initialize(options = {}) # Use options passed in, but fall back to module defaults CodesWholesale::Configurable.keys.each do |key| instance_variable_set(:"@#{key}", options[key] || CodesWholesale.instance_variable_get(:"@#{key}")) end end # Authenticates and get the token in order to make requests to the API # # @return [OAuth2::AccessToken] def token OAuth2::Client.new(client_id, client_secret, site: "#{api_endpoint}/oauth/token").client_credentials.get_token end # The actual client that talks to the CodesWholesale API # # @return [Sawyer::Agent] def agent @agent ||= Sawyer::Agent.new(api_endpoint, sawyer_options) do |http| http.headers[:content_type] = 'application/json' http.headers[:user_agent] = user_agent http.authorization :Bearer, token.token http.response :logger http.adapter Faraday.default_adapter end end # Make a HTTP GET request # # @param url [String] The path relative to {#api_endpoint} # @param options [Hash] Query and other params for the request # @return [Sawyer::Resource] def get(url, options = {}) request(:get, url, options) end # Make a HTTP POST request # # @param url [String] The path relative to {#api_endpoint} # @param options [Hash] Query and other params for the request # @return [Sawyer::Resource] def post(url, options = {}) request(:post, url, options) end private def request(method, url, options = {}) @last_response = response = agent.call(method, URI::Parser.new.escape(url.to_s), options) response.data end def sawyer_options { link_parser: Sawyer::LinkParsers::Simple.new } end end end <file_sep>/test/lib/client/accounts_test.rb require 'test_helper' class AccountsTest < Minitest::Test def setup @client = CodesWholesale::Client.new(client_id: 'ff72ce315d1259e822f47d87d02d261e', client_secret: <KEY>', environment: 'test') end def test_it_returns_current_account_details VCR.use_cassette('accounts/return_account_details') do account = @client.account assert_equal 'Sandbox', account.full_name assert_equal '<EMAIL>', account.email assert_equal 999995745.58, account.current_balance assert_equal 0, account.current_credit assert_equal 999995745.58, account.total_to_use end end end <file_sep>/lib/codes_wholesale/models/order.rb module CodesWholesale module Models class Order attr_reader :code_type def initialize(opts = {}) @code_type = opts[:codeType] end end end end <file_sep>/lib/codes_wholesale/client/products.rb require 'codes_wholesale/models/product' module CodesWholesale class Client # Methods for the Products API # # @see https://docs.codeswholesale.com/api-documentation module Products # Get all products or get a specific product # # @param id [String] ID of the product # @return [Array<CodesWholesale::Models::Product>] A list of products # @return [CodesWholesale::Models::Product] A product # @see https://docs.codeswholesale.com/api-documentation/#api-products-list # @see https://docs.codeswholesale.com/api-documentation/#api-id-product # @example Get all products # CodesWholesale.products # @example Get a specific product # CodesWholesale.products('6313677f-5219-47e4-a067-7401f55c5a3a') def products(id = nil) if id.nil? products = get('products') products[:items].map { |attributes| CodesWholesale::Models::Product.new(attributes) } else CodesWholesale::Models::Product.new(get("products/#{id}")) end end end end end <file_sep>/lib/codes_wholesale/client/accounts.rb require 'codes_wholesale/models/account' module CodesWholesale class Client # Methods for the Accounts API # # @see https://docs.codeswholesale.com/api-documentation module Accounts # Return the current account details # # @return [CodesWholesale::Models::Account] Account of the authenticated user # @see https://docs.codeswholesale.com/api-documentation/#api-account-details # @example Get current account details # CodesWholesale.account def account CodesWholesale::Models::Account.new(get('accounts/current')) end end end end
0f1ee0aaa83c6210914a2bdc84273affdf8afa99
[ "Markdown", "Ruby" ]
16
Markdown
terenceponce/codes_wholesale
0524e4f5b7448d2a47085160399579414a8999b5
b1455479eefe8a666e42ea93a5d2e2d411281380
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { observable, computed, toJS } from 'mobx'; import { observer, inject } from 'mobx-react'; import nj from 'nornj'; import { registerTmpl } from 'nornj-react'; import { autobind } from 'core-decorators'; import { Drawer} from 'antd'; import {tranBase58,stringToBase58,byteToLong,byteToString,Bytes2Str,Int32ToStr} from '../../../utils/util'; import { BlockCollapse,BlockCollapseSmall,BlockCollapsePanel } from '../../components/blockCollapse'; import styles from './transactionInfo.m.scss'; import tmpls from './transactionInfo.t.html'; import moment from 'moment'; //页面容器组件 @registerTmpl('TransactionInfo') @inject('store') @observer export default class TransactionInfo extends Component { @observable arr0 = [{ "disableLedgerPermissions": [], "disableTransactionPermissions": [], "roleName": "DEFAULT", "enableLedgerPermissions": ["CONFIGURE_ROLES", "AUTHORIZE_USER_ROLES", "SET_CONSENSUS", "SET_CRYPTO", "REGISTER_PARTICIPANT", "REGISTER_USER", "REGISTER_DATA_ACCOUNT", "REGISTER_CONTRACT", "UPGRADE_CONTRACT", "SET_USER_ATTRIBUTES", "WRITE_DATA_ACCOUNT", "APPROVE_TX", "CONSENSUS_TX"], "enableTransactionPermissions": ["DIRECT_OPERATION", "CONTRACT_OPERATION"] }]; @observable arr1 = [{ "unauthorizedRoles": ["A", "B"], "userAddresses": [{ "value": "LdeP3fY7jJbNwL8CiL2wU21AF9unDWQjVEW5w" }], "authorizedRoles": ["C", "D"], "policy": "UNION" }] // 关闭 @autobind onCloseblockDetails(){ return this.props.onClose(!this.props.visible); } formatData(type,data){ data=data&&data.value&&data.value||''; let result=''; switch (type.toUpperCase()) { case 'INT64': let int64=stringToBase58(data); result=byteToLong(int64); break; case 'TEXT': let text=stringToBase58(data); result=byteToString(text); break; case 'JSON': let json=stringToBase58(data); result=byteToString(json); break; case 'BYTES': let hex=stringToBase58(data); result=Bytes2Str(hex); break; case 'INT32': let int32=stringToBase58(data); result=Int32ToStr(int32); break; default: result=data; break; } return result; } argsToList(data){ let json=[]; if(data&&data.values&&data.values.length>0){ for (let i = 0; i < data.values.length; i++) { json.push({ type:data.values[i].type, value:this.formatData(data.values[i].type,data.values[i].value), }); } var str = JSON.stringify(json); return str; } } render() { const { data,visible} = this.props; return tmpls.container({ components: { 'ant-Drawer': Drawer, 'BlockCollapse':BlockCollapse, 'BlockCollapseSmall':BlockCollapseSmall, 'BlockCollapsePanel':BlockCollapsePanel, } },this.props, this, { styles, data, visible, tranBase58, moment: moment }); } }<file_sep>import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { observable, computed, toJS } from 'mobx'; import { observer, inject } from 'mobx-react'; import nj from 'nornj'; import { Drawer} from 'antd'; import { registerTmpl } from 'nornj-react'; import { autobind } from 'core-decorators'; import JSONTree from 'react-json-tree'; import {utf8ToString} from '../../../utils/util'; import TransactionInfo from '../transactionInfo'; import AccountRootHash from '../../components/accountRootHash'; import 'flarej/lib/components/antd/table'; import Message from 'flarej/lib/components/antd/message'; import KvCount from '../../components/kvcount'; import styles from './accountInfo.m.scss'; import tmpls from './accountInfo.t.html'; const theme = { base00: '#272822', base01: '#383830', base02: '#49483e', base03: '#75715e', base04: '#a59f85', base05: '#f8f8f2', base06: '#f5f4f1', base07: '#f9f8f5', base08: '#f92672', base09: '#fd971f', base0A: '#f4bf75', base0B: '#a6e22e', base0C: '#a1efe4', base0D: '#66d9ef', base0E: '#ae81ff', base0F: '#cc6633' }; //页面容器组件 @registerTmpl('AccountInfo') @inject('store') @observer export default class AccountInfo extends Component { @observable kvData=[]; @observable accountcount=0; @observable accountcurrent=1; @observable pageSize=10; @observable visible=false; @observable valueinfo=''; @observable valueinfotype='BYTES'; @observable jsondata =''; componentDidMount() { this.Search(); } Search(){ const { store: { account },accountData} = this.props; if (accountData&&accountData.address&&accountData.address.value) { const closeLoading = Message.loading('正在获取数据...', 0); let leader=this.props.store.common.getDefaultLedger(), param={ fromIndex:(this.accountcurrent-1)*this.pageSize, count:this.pageSize, }, address=accountData.address.value; Promise.all([ account.getEntriescount(leader,address) ]).then((data) => { if(data[0]>0){ this.accountcount=data[0]; Promise.all([ account.getEntries(leader,address, param ), ]).then((data) => { this.kvData=data[0]; closeLoading(); }); } else{ closeLoading(); } }); } } ////分页切换 @autobind onPageChange(page, pageSize) { const { store: { account } } = this.props; this.accountcurrent=page; this.Search(); } // 关闭详细信息 @autobind onClose(visible){ this.show=visible; } // 跳转到前置区块 @autobind goBlock(e){ const {goPrev}= this.props; if (goPrev) { goPrev(e.target.innerText); } } isJsonString(str) { try { if (typeof JSON.parse(str) == "object") { return true; } } catch(e) { } return false; } Jsontree=()=>{ if (this.isJsonString(this.jsondata)) { return <JSONTree theme={theme} data={JSON.parse(this.jsondata)} /> } else{ return <JSONTree theme={theme} data={this.jsondata} /> } }; // 查看详细信息 @autobind onShowBlockDetails(text,record){ this.onCloseblockDetails(); if(record.type.toUpperCase()=='BYTES'){ this.valueinfo=utf8ToString(text); this.valueinfotype='BYTES'; } else if(record.type.toUpperCase()=='JSON'){ this.valueinfotype='JSON'; this.jsondata = text; } else{ this.valueinfotype='other'; this.valueinfo=text; } } // 关闭 @autobind onCloseblockDetails(){ this.visible=!this.visible; } //字符串限制长度 strOfLength(str,l){ if(str.length>l){ return str.substring(0,l)+"..."; } else{ return str; } } // 交易列表 @computed get tableColumns() { return [{ title: '键', dataIndex: 'key', key:'key' },{ title: '值', dataIndex: 'value', key:'value', render: (text, record, index) => nj ` ${this.strOfLength(text,50)}&nbsp;&nbsp;&nbsp; <a onClick=${()=>this.onShowBlockDetails(text,record)}>详细</a> `() }, { title: '版本', dataIndex: 'version', width:'10%', key: 'version', },{ title: '类型', dataIndex: 'type', width:'10%', key: 'type', }]; } render() { const { store: { block },accountData } = this.props; return tmpls.container({ components: { 'ant-Drawer': Drawer, JSONTree }},this.props, this, { styles, block, accountData }); } }
c8cccd56b04bd478ec6195ea8de4fdee40f11ea1
[ "JavaScript" ]
2
JavaScript
midnightair/explorer
da3b9c925d7bc263474baf2c72ff0cee5c8308e1
c58a20f9c5bba6b5cae14b6c4ae49f35dbf16d88
refs/heads/master
<repo_name>sabbir25112/zoho-connect<file_sep>/database/migrations/2021_07_26_013324_create_sub_tasks_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSubTasksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sub_tasks', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('parent_task_id')->nullable(); $table->json('link')->nullable(); $table->longText('description')->nullable(); $table->unsignedBigInteger('created_by_zpuid')->nullable(); $table->string('work_form')->nullable(); $table->boolean('is_comment_added')->nullable(); $table->string('duration')->nullable(); $table->unsignedBigInteger('last_updated_time_long')->nullable(); $table->boolean('is_forum_associated')->nullable(); $table->json('details')->nullable(); $table->string('key')->nullable(); $table->string('created_person')->nullable(); $table->unsignedBigInteger('created_time_long')->nullable(); $table->date('created_time')->nullable(); $table->boolean('is_reminder_set')->nullable(); $table->boolean('is_recurrence_set')->nullable(); $table->string('created_time_format')->nullable(); $table->boolean('subtasks')->nullable(); $table->string('work')->nullable(); $table->json('custom_fields')->nullable(); $table->string('duration_type')->nullable(); $table->boolean('isparent')->nullable(); $table->unsignedBigInteger('parenttask_id')->nullable(); $table->string('work_type')->nullable(); $table->boolean('completed')->nullable(); $table->json('task_followers')->nullable(); $table->string('priority')->nullable(); $table->unsignedBigInteger('created_by')->nullable(); $table->float('percent_complete', 3, 2)->nullable(); $table->json('GROUP_NAME')->nullable(); $table->integer('depth')->nullable(); $table->date('last_updated_time')->nullable(); $table->unsignedBigInteger('root_task_id')->nullable(); $table->string('name')->nullable(); $table->boolean('is_docs_assocoated')->nullable(); $table->string('id_string')->nullable(); $table->json('log_hours')->nullable(); $table->json('tasklist')->nullable(); $table->string('last_updated_time_format')->nullable(); $table->string('billingtype')->nullable(); $table->integer('order_sequence')->nullable(); $table->json('status')->nullable(); $table->unsignedBigInteger('project_id')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sub_tasks'); } } <file_sep>/app/Zoho/BugSyncer.php <?php namespace App\Zoho; use App\Jobs\CreateOrUpdateBugsJob; class BugSyncer extends ZohoDataSyncer { private $project; public function __construct($project) { $this->project = $project; $project['link'] = json_decode($project['link'], 1); $this->API = $project['link']['bug']['url']; $this->method = static::GET_REQUEST; } function parseResponse($response) { return $response['bugs'] ?? []; } function processResponse($response) { CreateOrUpdateBugsJob::dispatch($response, $this->project); } function isCallable(): bool { return $this->project && $this->API && $this->method; } } <file_sep>/app/Jobs/CreateOrUpdateUserJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; class CreateOrUpdateUserJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; protected $project; protected $users; /** * Create a new job instance. * * @return void */ public function __construct($users, $project) { $this->users = $users; $this->project = $project; } /** * Execute the job. * * @return void */ public function handle() { $user_columns = Schema::getColumnListing((new User())->getTable()); foreach ($this->users as $user) { $user = Arr::only($user, $user_columns); try { $user['project_id'] = $this->project['id']; if ($user_model = User::find($user['id'])) { Logger::verbose("Found User with id ". $user['id'] . " , Updating..."); $user_model->update($user); } else { Logger::verbose("Creating User with id ". $user['id']); User::create($user); } } catch (\Exception $exception) { Logger::verbose("Unexpected Error in CreateOrUpdateUserJob. Line: ". $exception->getLine(). " . Message: ". $exception->getMessage()); Log::error($exception); } } } } <file_sep>/app/Http/Controllers/ZohoAuthController.php <?php namespace App\Http\Controllers; use App\Http\Constants; use App\Models\Settings; use Carbon\Carbon; use Hamcrest\Core\Set; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Redirect; class ZohoAuthController extends Controller { private $client_id, $client_secret, $redirect_uri; public function __construct() { $this->client_id = env('ZOHO_CLIENT_ID'); $this->client_secret = env('ZOHO_CLIENT_SECRET'); $this->redirect_uri = env('ZOHO_REDIRECT_URI'); } public function init() { $auth_url = config('zoho.authentication.url'); $scopes = implode(',', config('zoho.authentication.auth_scopes')); $client_id = $this->client_id; $client_secret = $this->client_secret; $redirect_uri = $this->redirect_uri; $prepared_auth_url = $auth_url . "?scope=$scopes&client_id=$client_id&client_secret=$client_secret&response_type=code&access_type=offline&redirect_uri=$redirect_uri&prompt=consent"; return Redirect::to($prepared_auth_url); } public function callback(Request $request) { $code = $request->has('code') ? $request->get('code') : ''; $account_server = $request->has('accounts-server') ? $request->get('accounts-server') : 'https://accounts.zoho.com'; $token_uri = "$account_server/oauth/v2/token"; $client_id = $this->client_id; $client_secret = $this->client_secret; $redirect_uri = $this->redirect_uri; $prepared_uri = $token_uri . "?code=$code&redirect_uri=$redirect_uri&client_id=$client_id&client_secret=$client_secret&grant_type=authorization_code"; $response = Http::post($prepared_uri); $json_response = $response->json(); if (!isset($json_response['access_token'])) { Log::error("ZOHO AUTH ERROR", $json_response); } else { $this->storeAuthInfoIntoCache($json_response); } return redirect()->route('welcome'); } private function storeAuthInfoIntoCache($response) { $expires_in = $response['expires_in'] - 60; $expires_in_datetime = Carbon::now()->addSeconds($expires_in); $settings = Settings::first(); if (!$settings) { $settings = new Settings(); } $settings->access_token = $response['access_token']; $settings->refresh_token = $response['refresh_token']; $settings->expires_in = $expires_in_datetime; $settings->save(); // Cache::put(Constants::ZOHO_ACCESS_KEY_CACHE, $response['access_token'], $expires_in); // Cache::put(Constants::ZOHO_REFRESH_KEY_CACHE, $response['refresh_token'], $expires_in); // this api domain doesn't work, that's why base api is in config // Cache::put('zoho_auth_api_domain', $response['api_domain'], $expires_in); } } <file_sep>/database/migrations/2021_07_25_222040_create_tasklists_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTasklistsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tasklists', function (Blueprint $table) { $table->id(); $table->string('id_string')->nullable(); $table->string('name')->nullable(); $table->unsignedBigInteger('created_time_long')->nullable(); $table->date('created_time')->nullable(); $table->string('flag')->nullable(); $table->string('created_time_format')->nullable(); $table->json('link')->nullable(); $table->boolean('completed')->nullable(); $table->boolean('rolled')->nullable(); $table->json('task_count')->nullable(); $table->integer('sequence')->nullable(); $table->date('last_updated_time')->nullable(); $table->unsignedBigInteger('last_updated_time_long')->nullable(); $table->string('last_updated_time_format')->nullable(); $table->unsignedBigInteger('project_id')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tasklists'); } } <file_sep>/app/Http/Controllers/ZohoConnectUserController.php <?php namespace App\Http\Controllers; use App\Models\ZohoConnectUser; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class ZohoConnectUserController extends Controller { public function addUser() { return view('add-user'); } public function storeUser(Request $request) { $this->validate($request, [ 'email' => ['required', 'string', 'email', 'max:255', 'unique:zoho_connect_users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); ZohoConnectUser::create([ 'email' => $request->email, 'password' => <PASSWORD>($request->password), ]); session()->flash('success', 'User Created Successfully'); return redirect()->route('welcome'); } public function changePassword() { return view('change-password'); } public function storePassword(Request $request) { $this->validate($request, [ 'old_password' => '<PASSWORD>', 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); if (Hash::check( $request->old_password, auth()->user()->password )) { auth()->user()->update([ 'password' => <PASSWORD>($request->password) ]); session()->flash('success', "Password Changed Successfully"); return redirect()->route('welcome'); } else { session()->flash('error', "Password doesn't match"); return redirect()->back(); } } } <file_sep>/app/Http/Middleware/CheckAccessToken.php <?php namespace App\Http\Middleware; use App\Http\Constants; use App\Models\Settings; use Carbon\Carbon; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; class CheckAccessToken { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { $settings = Settings::first(); if (!$settings) { return redirect()->route('zoho-auth-init'); } if (!Carbon::create($settings->expires_in)->isFuture()) { return redirect()->route('zoho-auth-init'); } return $next($request); } } <file_sep>/app/Jobs/CreateOrUpdateBugsJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\Bug; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; class CreateOrUpdateBugsJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; protected $project; protected $bugs; /** * Create a new job instance. * * @return void */ public function __construct($bugs, $project) { $this->bugs = $bugs; $this->project = $project; } /** * Execute the job. * * @return void */ public function handle() { $bug_columns = Schema::getColumnListing((new Bug())->getTable()); $json_columns = [ 'link', 'severity', 'reproducible', 'module', 'classification', 'GROUP_NAME', 'status', ]; foreach ($this->bugs as $bug) { $bug = Arr::only($bug, $bug_columns); try { $bug['project_id'] = $this->project['id']; if (isset($bug['updated_time'])) { $bug['updated_time'] = Carbon::createFromFormat('m-d-Y', $bug['updated_time']); } if (isset($bug['created_time'])) { $bug['created_time'] = Carbon::createFromFormat('m-d-Y', $bug['created_time']); } $bug = prepare_json_columns($bug, $json_columns); if ($bug_model = Bug::find($bug['id'])) { $bug_model->update($bug); } else { Bug::create($bug); } } catch (\Exception $exception) { Logger::verbose("Unexpected Error in CreateOrUpdateBugsJob. Line: ". $exception->getLine(). " . Message: ". $exception->getMessage()); Log::error($exception); } } } } <file_sep>/app/Zoho/TimeSheetSyncer.php <?php namespace App\Zoho; use App\Models\TimeSheet; use Carbon\Carbon; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; class TimeSheetSyncer extends ZohoDataSyncer { private $project, $component_type; public function __construct($project, $start_date, $end_date, $component_type) { $this->project = $project; $this->component_type = $component_type; $custom_date = ['start_date' => $start_date, 'end_date' => $end_date]; $this->params = [ 'users_list' => 'all', 'view_type' => 'custom_date', 'date' => $start_date, 'bill_status' => 'All', 'component_type' => $component_type, 'custom_date' => json_encode($custom_date) ]; $project['link'] = json_decode($project['link'], 1); $this->API = $project['link']['timesheet']['url']; $this->method = static::GET_REQUEST; // $this->disableSkipPrediction(); } function parseResponse($response): array { $output = []; $time_logs = $response['timelogs']['date'] ?? []; foreach ($time_logs as $time_log) { $log_date = Carbon::createFromFormat('m-d-Y', $time_log['date']); $log_date_long = $time_log['date_long']; $logs = $this->component_type == 'task' ? $time_log['tasklogs'] : $time_log['buglogs']; foreach ($logs as $log) { $log['log_date'] = $log_date; $log['log_date_long'] = $log_date_long; $log['type'] = $this->component_type; $output[] = $log; } } return $output; } function processResponse($response) { $timesheet_columns = Schema::getColumnListing((new TimeSheet())->getTable()); foreach ($response as $timesheet) { try { $timesheet = Arr::only($timesheet, $timesheet_columns); $timesheet_data = $this->prepareTimeSheetData($this->project, $timesheet); if ($timesheet_model = TimeSheet::find($timesheet_data['id'])) { $timesheet_model->update($timesheet_data); } else { TimeSheet::create($timesheet_data); } } catch (\Exception $exception) { Log::error($exception); continue; } } } function isCallable(): bool { return $this->project && in_array($this->component_type, ['task', 'bug']); } private function prepareTimeSheetData($project, $timesheet) { $json_fields = ['link', 'task', 'bug', 'added_by', 'task_list']; $timesheet['project_id'] = $project['id']; if (isset($timesheet['task']['is_sub_task']) && $timesheet['task']['is_sub_task']) { $timesheet['subtask_id'] = $timesheet['task']['id'] ?? null; $timesheet['subtask_name'] = $timesheet['task']['name'] ?? null; $timesheet['task_id'] = $timesheet['task']['root_task_id'] ?? null; } else { $timesheet['task_id'] = $timesheet['task']['id'] ?? null; $timesheet['task_name'] = $timesheet['task']['name'] ?? null; } if (isset($timesheet['created_date'])) { $timesheet['created_date'] = Carbon::createFromFormat('m-d-Y', $timesheet['created_date']); } if (isset($timesheet['last_modified_date'])) { $timesheet['last_modified_date'] = Carbon::createFromFormat('m-d-Y', $timesheet['last_modified_date']); } return prepare_json_columns($timesheet, $json_fields); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | 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::group(['namespace' => 'App\Http\Controllers', 'middleware' => 'auth'], function () { Route::get('/zoho-auth-init', 'ZohoAuthController@init')->name('zoho-auth-init'); Route::get('/zoho-auth-callback', 'ZohoAuthController@callback'); Route::group(['middleware' => 'check.access.token'], function () { Route::get('/', 'Controller@start')->name('welcome'); Route::get('sync-projects', 'SyncController@syncProjects')->name('sync-projects'); Route::get('sync-users', 'SyncController@syncUsers')->name('sync-users'); Route::get('sync-tasklists', 'SyncController@syncTaskLists')->name('sync-tasklists'); Route::get('sync-tasks', 'SyncController@syncTasks')->name('sync-tasks'); Route::get('sync-sub-tasks', 'SyncController@syncSubTasks')->name('sync-sub-tasks'); Route::get('sync-bugs', 'SyncController@syncBugs')->name('sync-bugs'); Route::post('sync-timesheets', 'SyncController@syncTimeSheet')->name('sync-timesheet'); }); Route::get('add-user', 'ZohoConnectUserController@addUser')->name('add-user'); Route::post('store-user', 'ZohoConnectUserController@storeUser')->name('store-user'); Route::get('change-password', 'ZohoConnectUserController@changePassword')->name('change-password'); Route::post('store-password', 'ZohoConnectUserController@storePassword')->name('store-password'); Route::get('logout', 'Auth\LoginController@logout'); }); Auth::routes(['register' => false]); Route::get('test-queue', function () { $project = \App\Models\Project::find(685798000013322790)->toArray(); dd((new \App\Zoho\TimeSheetSyncer($project, '07-01-2021', '07-30-2021', 'task'))->call(true)); }); <file_sep>/database/migrations/2021_07_25_164019_create_projects_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects', function (Blueprint $table) { $table->id(); $table->string('name')->nullable(); $table->string('status')->nullable(); $table->string('is_strict')->nullable(); $table->string('project_percent')->nullable(); $table->string('role')->nullable(); $table->json('bug_count')->nullable(); $table->boolean('IS_BUG_ENABLED')->nullable(); $table->unsignedBigInteger('owner_id')->nullable(); $table->string('bug_client_permission')->nullable(); $table->string('taskbug_prefix')->nullable(); $table->json('link')->nullable(); $table->unsignedBigInteger('custom_status_id')->nullable(); $table->longText('description')->nullable(); $table->json('milestone_count')->nullable(); $table->unsignedBigInteger('updated_date_long')->nullable(); $table->boolean('show_project_overview')->nullable(); $table->json('task_count')->nullable(); $table->string('updated_date_format')->nullable(); $table->string('workspace_id')->nullable(); $table->string('custom_status_name')->nullable(); $table->string('owner_zpuid')->nullable(); $table->string('is_client_assign_bug')->nullable(); $table->string('bug_defaultview')->nullable(); $table->string('billing_status')->nullable(); $table->string('key')->nullable(); $table->string('owner_name')->nullable(); $table->unsignedBigInteger('created_date_long')->nullable(); $table->string('group_name')->nullable(); $table->string('created_date_format')->nullable(); $table->unsignedBigInteger('group_id')->nullable(); $table->unsignedBigInteger('profile_id')->nullable(); $table->string('is_public')->nullable(); $table->string('id_string')->nullable(); $table->date('created_date')->nullable(); $table->date('updated_date')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('projects'); } } <file_sep>/database/migrations/2021_09_11_133614_additional_alter_commands.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AdditionalAlterCommands extends Migration { /** * Run the migrations. * * @return void */ public function up() { // ALTER TABLE `zoho-connect`.`tasks` // CHANGE COLUMN `order_sequence` `order_sequence` VARCHAR(30) NULL DEFAULT NULL ; // ALTER TABLE `zoho-connect`.`sub_tasks` // CHANGE COLUMN `percent_complete` `percent_complete` VARCHAR(10) NULL DEFAULT NULL ; // ALTER TABLE `zoho-connect`.`sub_tasks` // CHANGE COLUMN `order_sequence` `order_sequence` VARCHAR(30) NULL DEFAULT NULL ; } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/Jobs/SyncTimeSheetJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\Project; use App\Zoho\TimeSheetSyncer; use App\Zoho\UserSyncer; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SyncTimeSheetJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; private $start_date; private $end_date; /** * Create a new job instance. * * @return void */ public function __construct($start_date, $end_date) { $this->start_date = $start_date; $this->end_date = $end_date; } /** * Execute the job. * * @return void */ public function handle() { Logger::verbose("Starting SyncTimeSheetJob"); $projects = Project::all()->toArray(); $request_count = 0; $max_request_per_min = config('zoho.queue.max_request_per_min'); $sleep_after_max_request = config('zoho.queue.sleep_after_max_request'); foreach ($projects as $project) { try { Logger::verbose("Start Processing Task TimeSheetSyncer for ". $project['id']); $process_response = (new TimeSheetSyncer( $project, $this->start_date, $this->end_date, 'task' ))->call(true); $request_count += ($process_response['call_count'] % $max_request_per_min); Logger::verbose("TASK:: Request Count: " . $request_count . " . It made ". $process_response['call_count'] . " call(s) for ProjectID: ". $project['id']); Logger::verbose("End Processing Task TimeSheetSyncer for ". $project['id']); if ($request_count >= $max_request_per_min) { $request_count = 0; Logger::verbose("Sleep for " . $sleep_after_max_request . " Seconds after Max Request"); sleep($sleep_after_max_request); } Logger::verbose("Start Processing Bug TimeSheetSyncer for ". $project['id']); $process_response = (new TimeSheetSyncer( $project, $this->start_date, $this->end_date, 'bug' ))->call(true); $request_count += ($process_response['call_count'] % $max_request_per_min); Logger::verbose("BUG:: Request Count: " . $request_count . " . It made ". $process_response['call_count'] . " call(s) for ProjectID: ". $project['id']); Logger::verbose("End Processing Bug TimeSheetSyncer for ". $project['id']); if ($request_count >= $max_request_per_min) { $request_count = 0; Logger::verbose("Sleep for " . $sleep_after_max_request . " Seconds after Max Request"); sleep($sleep_after_max_request); } sleep(config('zoho.queue.sleep_after_processing_a_project')); } catch (\Exception $exception) { Logger::error("Unhandled error for SyncTimeSheetJob. ProjectID: ". $project['id']. " Line: ". $exception->getLine(). " Message: " . $exception->getMessage()); } } Logger::verbose("End SyncTimeSheetJob"); } } <file_sep>/config/zoho.php <?php return [ 'url' => [ 'api_base' => 'https://projectsapi.zoho.com/restapi' ], 'authentication' => [ 'url' => 'https://accounts.zoho.com/oauth/v2/auth', 'refresh_token' => 'https://accounts.zoho.com/oauth/v2/token', 'auth_scopes' => [ 'ZohoProjects.portals.READ', 'ZohoProjects.projects.READ', 'ZohoProjects.tasklists.READ', 'ZohoProjects.tasks.READ', 'ZohoProjects.timesheets.READ', 'ZohoProjects.users.READ', 'ZohoProjects.bugs.READ', ], ], 'queue' => [ 'sleep_after_processing_a_project' => 5, 'max_request_per_min' => 25, 'sleep_after_max_request' => 30, 'range' => 200, ] ]; <file_sep>/app/Http/Controllers/Controller.php <?php namespace App\Http\Controllers; use App\Models\Bug; use App\Models\Project; use App\Models\SubTask; use App\Models\Task; use App\Models\Tasklist; use App\Models\TimeSheet; use App\Models\User; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function start() { $count = [ 'projects' => Project::count(), 'users' => User::count(), 'tasklists' => Tasklist::count(), 'tasks' => Task::count(), 'subtasks' => SubTask::count(), 'timesheets'=> TimeSheet::count(), 'bugs' => Bug::count() ]; $projects = Project::pluck('name', 'id')->toArray(); return view('start', compact('count', 'projects')); } } <file_sep>/app/Zoho/UserSyncer.php <?php namespace App\Zoho; use App\Jobs\CreateOrUpdateUserJob; use App\Logger; class UserSyncer extends ZohoDataSyncer { private $project; public function __construct($project) { $this->project = $project; $project['link'] = json_decode($project['link'], 1); $this->API = $project['link']['user']['url']; $this->method = static::GET_REQUEST; } function isCallable(): bool { return $this->project && $this->API && $this->method; } function parseResponse($response): array { return $response['users'] ?? []; } function processResponse($response) { Logger::verbose("Dispatching CreateOrUpdateUserJob for ". $this->project['id']); CreateOrUpdateUserJob::dispatch($response, $this->project); } } <file_sep>/app/Jobs/ZohoSyncJobConfigTrait.php <?php namespace App\Jobs; trait ZohoSyncJobConfigTrait { public $timeout = 7200; public $tries = 10; } <file_sep>/app/Http/Constants.php <?php namespace App\Http; class Constants { const ZOHO_ACCESS_KEY_CACHE = 'zoho_auth_access_token'; const ZOHO_REFRESH_KEY_CACHE = 'zoho_auth_refresh_token'; } <file_sep>/app/Jobs/SyncSubTaskJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\Project; use App\Models\Task; use App\Zoho\SubTaskSyncer; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SyncSubTaskJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; /** * Create a new job instance. * * @return void */ public function __construct() { // } /** * Execute the job. * * @return void */ public function handle() { Logger::verbose("Starting SyncSubTaskJob"); $projects = Project::all()->toArray(); $request_count = 0; $max_request_per_min = config('zoho.queue.max_request_per_min'); $sleep_after_max_request = config('zoho.queue.sleep_after_max_request'); foreach ($projects as $project) { Logger::verbose("Start Processing TaskSyncer for ". $project['id']); $tasks = Task::where(['project_id' => $project['id'], 'subtasks' => 1])->get()->toArray(); $chunked_tasks = array_chunk($tasks, $max_request_per_min); foreach ($chunked_tasks as $chunked_task) { foreach ($chunked_task as $task) { $process_response = (new SubTaskSyncer($task, $project))->call(true); Logger::verbose("Request Count: " . $request_count . " . It made ". $process_response['call_count'] . " call(s) for TaskID: ". $task['id']); $request_count += $process_response['call_count']; if ($request_count > $max_request_per_min) { $request_count = 0; Logger::verbose("Sleep for " . $sleep_after_max_request . " Seconds after Max Request"); sleep($sleep_after_max_request); } } } Logger::verbose("End Processing TaskSyncer for ". $project['id']); Logger::verbose("Sleep for " . config('zoho.queue.sleep_after_processing_a_project') . " Seconds"); sleep(config('zoho.queue.sleep_after_processing_a_project')); } Logger::verbose("End SyncSubTaskJob"); } } <file_sep>/app/Models/ZohoConnectUser.php <?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticable; use Illuminate\Database\Eloquent\Factories\HasFactory; class ZohoConnectUser extends Authenticable { use HasFactory; protected $guarded = ['id']; } <file_sep>/app/Jobs/SyncUserJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\Project; use App\Zoho\UserSyncer; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SyncUserJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; /** * Create a new job instance. * * @return void */ public function __construct() { // } /** * Execute the job. * * @return void */ public function handle() { Logger::verbose("Starting SyncUserJob"); $projects = Project::all()->toArray(); foreach ($projects as $project) { Logger::verbose("Start Processing UserSyncer for ". $project['id']); (new UserSyncer($project))->call(); Logger::verbose("End Processing UserSyncer for ". $project['id']); sleep(config('zoho.queue.sleep_after_processing_a_project')); } Logger::verbose("End SyncUserJob"); } } <file_sep>/app/Jobs/CreateOrUpdateTaskListJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\Tasklist; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; class CreateOrUpdateTaskListJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; private $taskLists; private $project; /** * Create a new job instance. * * @return void */ public function __construct($taskLists, $project) { $this->taskLists = $taskLists; $this->project = $project; } /** * Execute the job. * * @return void */ public function handle() { $taskLists_columns = Schema::getColumnListing((new Tasklist())->getTable()); foreach ($this->taskLists as $taskList) { try { $taskList = Arr::only($taskList, $taskLists_columns); $taskList['project_id'] = $this->project['id']; if (isset($taskList['created_time'])) { $taskList['created_time'] = Carbon::createFromFormat('m-d-Y', $taskList['created_time']); } if (isset($taskList['last_updated_time'])) { $taskList['last_updated_time'] = Carbon::createFromFormat('m-d-Y', $taskList['last_updated_time']); } $formatted_tasklist_data = prepare_json_columns($taskList, ['task_count', 'link']); if ($taskList_model = Tasklist::find($formatted_tasklist_data['id'])) { Logger::verbose("Found Tasklist with id " . $formatted_tasklist_data['id'] . " , Updating..."); $taskList_model->update($formatted_tasklist_data); } else { Logger::verbose("Creating Tasklist with id " . $formatted_tasklist_data['id']); Tasklist::create($formatted_tasklist_data); } } catch (\Exception $exception) { Logger::verbose("Unexpected Error in CreateOrUpdateTaskListJob. Line: " . $exception->getLine() . " . Message: " . $exception->getMessage()); Log::error($exception); } } } } <file_sep>/app/Zoho/SubTaskSyncer.php <?php namespace App\Zoho; use App\Models\SubTask; use App\Models\TaskCustom; use Carbon\Carbon; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; class SubTaskSyncer extends ZohoDataSyncer { private $task; private $project; public function __construct($task, $project) { $this->task = $task; $this->project = $project; $task['link'] = json_decode($task['link'], 1); $this->API = $task['link']['subtask']['url']; $this->method = static::GET_REQUEST; } function parseResponse($response): array { return $response['tasks'] ?? []; } function processResponse($response) { $this->createOrUpdateSubTask($response, $this->project); } function isCallable(): bool { return $this->task && $this->API && $this->method; } private function createOrUpdateSubTask($tasks, $project) { $task_columns = Schema::getColumnListing((new SubTask())->getTable()); foreach ($tasks as $task) { try { $task = Arr::only($task, $task_columns); $task['percent_complete'] = (float) $task['percent_complete']; $task['project_id'] = $project['id']; if (isset($task['created_time'])) { $task['created_time'] = Carbon::createFromFormat('m-d-Y', $task['created_time']); } if (isset($task['last_updated_time'])) { $task['last_updated_time'] = Carbon::createFromFormat('m-d-Y', $task['last_updated_time']); } $json_columns = [ 'details', 'custom_fields', 'task_followers', 'GROUP_NAME', 'log_hours', 'tasklist', 'status', 'link', ]; $formatted_task_data = prepare_json_columns($task, $json_columns); if ($task_model = SubTask::find($formatted_task_data['id'])) { $task_model->update($formatted_task_data); } else { $task_model = SubTask::create($formatted_task_data); } $this->createOrUpdateTaskCustoms($formatted_task_data['custom_fields'] ? json_decode($formatted_task_data['custom_fields'], true) : [], $task_model); } catch (\Exception $exception) { Log::error($exception); } } } private function createOrUpdateTaskCustoms($customs, $task) { foreach ($customs as $custom) { try { if (!isset($custom['label_name']) || !isset($custom['label_value'])) continue; $customData = [ 'TaskID' => $task->id, 'label_name' => $custom['label_name'], 'label_value'=> $custom['label_value'], ]; $taskCustom = TaskCustom::where('TaskID', $task->id) ->where('label_name', $custom['label_name']) ->first(); if ($taskCustom) { $taskCustom->update($customData); } else { TaskCustom::create($customData); } } catch (\Exception $exception) { Log::error($exception); } } } } <file_sep>/app/Zoho/TaskSyncer.php <?php namespace App\Zoho; use App\Jobs\CreateOrUpdateTaskJob; class TaskSyncer extends ZohoDataSyncer { private $project; public function __construct($project) { $this->project = $project; $project['link'] = json_decode($project['link'], 1); $this->API = $project['link']['task']['url']; $this->method = static::GET_REQUEST; } function parseResponse($response): array { return $response['tasks'] ?? []; } function processResponse($response) { CreateOrUpdateTaskJob::dispatch($response, $this->project); } function isCallable(): bool { return $this->project && $this->API && $this->method; } } <file_sep>/database/seeders/SettingSeeder.php <?php namespace Database\Seeders; use App\Models\Settings; use Illuminate\Database\Seeder; class SettingSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Settings::create([ 'id' => 1, ]); } } <file_sep>/database/migrations/2021_07_27_234524_create_bugs_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBugsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bugs', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('updated_time_long')->nullable(); $table->string('comment_count')->nullable(); $table->string('updated_time')->nullable(); $table->unsignedBigInteger('assignee_zpuid')->nullable(); $table->string('flag')->nullable(); $table->string('updated_time_format')->nullable(); $table->json('link')->nullable(); $table->string('title')->nullable(); $table->string('assignee_name')->nullable(); $table->string('reporter_id')->nullable(); $table->string('escalation_level')->nullable(); $table->string('key')->nullable(); $table->unsignedBigInteger('created_time_long')->nullable(); $table->json('severity')->nullable(); $table->string('created_time')->nullable(); $table->string('created_time_format')->nullable(); $table->json('reproducible')->nullable(); $table->json('module')->nullable(); $table->json('classification')->nullable(); $table->json('GROUP_NAME')->nullable(); $table->string('bug_number')->nullable(); $table->string('reporter_non_zuser')->nullable(); $table->string('reported_person')->nullable(); $table->string('reporter_email')->nullable(); $table->string('id_string')->nullable(); $table->boolean('closed')->nullable(); $table->string('bug_prefix')->nullable(); $table->string('attachment_count')->nullable(); $table->json('status')->nullable(); $table->unsignedBigInteger('project_id')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('bugs'); } } <file_sep>/app/Zoho/TaskListSyncer.php <?php namespace App\Zoho; use App\Jobs\CreateOrUpdateTaskListJob; class TaskListSyncer extends ZohoDataSyncer { private $project; public function __construct($project) { $this->project = $project; $project['link'] = json_decode($project['link'], 1); $this->API = $project['link']['tasklist']['url']; $this->method = self::GET_REQUEST; $this->params = [ 'flag' => 'allflag', ]; } function parseResponse($response) { return $response['tasklists'] ?? []; } function processResponse($response) { CreateOrUpdateTaskListJob::dispatch($response, $this->project); } function isCallable(): bool { return $this->project && $this->API && $this->method; } } <file_sep>/database/migrations/2021_07_26_095520_create_time_sheets_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTimeSheetsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('time_sheets', function (Blueprint $table) { $table->id(); $table->string('type')->nullable(); $table->unsignedBigInteger('created_time_long')->nullable(); $table->integer('hours')->nullable(); $table->longText('notes')->nullable(); $table->longText('owner_name')->nullable(); $table->longText('created_time_format')->nullable(); $table->integer('minutes')->nullable(); $table->integer('total_minutes')->nullable(); $table->longText('owner_id')->nullable(); $table->longText('approval_status')->nullable(); $table->longText('end_time')->nullable(); $table->json('link')->nullable(); $table->date('last_modified_date')->nullable(); $table->longText('bill_status')->nullable(); $table->unsignedBigInteger('last_modified_time_long')->nullable(); $table->longText('start_time')->nullable(); $table->longText('last_modified_time_format')->nullable(); $table->json('task')->nullable(); $table->json('bug')->nullable(); $table->json('added_by')->nullable(); $table->longText('id_string')->nullable(); $table->date('created_date')->nullable(); $table->longText('hours_display')->nullable(); $table->json('task_list')->nullable(); $table->unsignedBigInteger('project_id')->nullable(); $table->unsignedBigInteger('task_id')->nullable(); $table->longText('task_name')->nullable(); $table->unsignedBigInteger('subtask_id')->nullable(); $table->longText('subtask_name')->nullable(); $table->longText('approver_name')->nullable(); $table->date('log_date')->nullable(); $table->unsignedBigInteger('log_date_long')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('time_sheets'); } } <file_sep>/app/Zoho/ZohoDataSyncer.php <?php namespace App\Zoho; use App\Logger; use App\Models\Settings; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; abstract class ZohoDataSyncer { const GET_REQUEST = 'get'; const POST_REQUEST = 'post'; protected $API, $method, $params = [], $token, $refresh_token, $with_call_count, $with_output, $skip_prediction = true; abstract function parseResponse($response); abstract function processResponse($response); abstract function isCallable(): bool; public function call($with_call_count = false, $with_output = false) { $settings = Settings::first(); $this->token = $settings->access_token; $this->refresh_token = $settings->refresh_token; $this->with_call_count = $with_call_count; $this->with_output = $with_output; if ($this->isCallable()) return $this->getResponse(); return false; } private function getResponse(): array { $max_request_per_min = config('zoho.queue.max_request_per_min'); $sleep_after_max_request = config('zoho.queue.sleep_after_max_request'); $range = config('zoho.queue.range'); $response_collection = []; $has_page = true; $index = 0; $method = $this->method; $call_count = 0; $output_call_count = 0; do { try { if ($call_count >= $max_request_per_min) { $call_count = 0; Logger::verbose("Sleeping for ". $sleep_after_max_request . " sec after ". $max_request_per_min . " calls"); sleep($sleep_after_max_request); continue; } $response = Http::withToken($this->token)->$method($this->API, $this->params + [ 'index' => $index, 'range' => $range, ]); $call_count += 1; $output_call_count += 1; $json_response = $response->json(); if ($response->successful()) { if ($response->status() == 204) { Logger::info("No Content Found for ". $this->API . " on index: $index"); break; } else { Logger::verbose("Response parsing for ". $this->API. " on index: $index"); $parsed_response = $this->parseResponse($json_response); if (count($parsed_response)) { Logger::verbose("Response processing for ". $this->API. " on index: $index"); $this->processResponse($parsed_response); if ($this->with_output) $response_collection = array_merge($response_collection, $parsed_response); if ($this->skip_prediction && count($parsed_response) < $range) { Logger::verbose("Skipping Next Call (Predicted No Content) for ". $this->API. " on index: $index"); break; } else { $index += 200; continue; } } else { Logger::verbose("Skipping Response (empty) for ". $this->API. " on index: $index"); continue; } } } if ($response->status() == 401 && str_contains($json_response['error']['message'], "Invalid OAuth access token")) { Logger::verbose("API token expired. Creating new API Token"); $token = $this->getAccessToken($this->refresh_token); if ($token == '') { Logger::error('Could not generate API token'); break; } else { Logger::verbose("New Token: $token"); Settings::first()->update([ 'access_token' => $token ]); $this->token = $token; continue; } } if ($response->failed()) { Logger::error("Call FAILED for ". $this->API . " on index $index"); Log::error(['api' => $this->API, 'response' => json_encode($response->json()), 'message' => 'FAILED']); $has_page = false; continue; } } catch (\Exception $exception) { Logger::verbose("Unhandled error occurred for ". $this->API . "on index $index"); Log::error($exception); continue; } } while ($has_page); $process_output = []; if ($this->with_output) $process_output['response_collection'] = $response_collection; if ($this->with_call_count) $process_output['call_count'] = $output_call_count; return $process_output; } public function getAccessToken($refresh_token) { $API = config('zoho.authentication.refresh_token'); $client_id = env('ZOHO_CLIENT_ID'); $client_secret = env('ZOHO_CLIENT_SECRET'); $redirect_uri = env('ZOHO_REDIRECT_URI'); $response = Http::asForm()->post($API, [ 'refresh_token' => $refresh_token, 'client_id' => $client_id, 'client_secret' => $client_secret, 'grant_type' => 'refresh_token', 'redirect_uri' => $redirect_uri ]); $json_response = $response->json(); if ($response->successful()) { return $json_response['access_token'] ?? ''; } return ''; } public function disableSkipPrediction(): ZohoDataSyncer { $this->skip_prediction = false; return $this; } } <file_sep>/app/helper.php <?php if (!function_exists('prepare_json_columns')) { function prepare_json_columns($array, $json_columns) { foreach ($json_columns as $column) { if (isset($array[$column])) { $array[$column] = json_encode($array[$column]); } } return $array; } } <file_sep>/app/Jobs/CreateOrUpdateTaskJob.php <?php namespace App\Jobs; use App\Logger; use App\Models\Task; use App\Models\TaskBilling; use App\Models\TaskOwner; use App\Models\TaskStatus; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; class CreateOrUpdateTaskJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, ZohoSyncJobConfigTrait; protected $project; protected $tasks; /** * Create a new job instance. * * @return void */ public function __construct($tasks, $project) { $this->tasks = $tasks; $this->project = $project; } /** * Execute the job. * * @return void */ public function handle() { $task_columns = Schema::getColumnListing((new Task())->getTable()); foreach ($this->tasks as $task) { try { $task = Arr::only($task, $task_columns); $task['project_id'] = $this->project['id']; if (isset($task['created_time'])) { $task['created_time'] = Carbon::createFromFormat('m-d-Y', $task['created_time']); } if (isset($task['last_updated_time'])) { $task['last_updated_time'] = Carbon::createFromFormat('m-d-Y', $task['last_updated_time']); } $json_columns = ['details', 'link', 'custom_fields', 'log_hours', 'status']; $formatted_task_data = prepare_json_columns($task, $json_columns); $task_model = Task::find($formatted_task_data['id']); if ($task_model) { $task_model->update($formatted_task_data); } else { $task_model = Task::create($formatted_task_data); } $owners = json_decode($task_model->details, true); $this->createOrUpdateTaskOwners($owners['owners'] ?? [], $task_model); $this->createOrUpdateTaskStatuses($task['status'] ?? [], $task_model); $bills = json_decode($task_model->log_hours, true); $taskBilling = TaskBilling::where('TaskID', $task_model->id)->first(); if (!$taskBilling) { TaskBilling::create([ 'non_billable_hours' => $bills['non_billable_hours'] ?? '0', 'billable_hours' => $bills['billable_hours'] ?? '0', 'TaskID' => $task_model->id ]); } else { $taskBilling->update([ 'non_billable_hours' => $bills['non_billable_hours'] ?? '0', 'billable_hours' => $bills['billable_hours'] ?? '0', ]); } } catch (\Exception $exception) { Logger::verbose("Unexpected Error in CreateOrUpdateTaskJob. Line: ". $exception->getLine(). " . Message: ". $exception->getMessage()); Log::error($exception); } } } private function createOrUpdateTaskOwners($owners, $task) { foreach ($owners as $owner) { try { if (!isset($owner['id'])) continue; $ownerData = [ 'TaskID' => $task->id, 'OwnerID' => $owner['id'], 'name' => $owner['name'] ?? '', 'email' => $owner['email'] ?? '', 'zpuid' => $owner['zpuid'] ?? '', ]; if ($taskOwner = TaskOwner::find($owner['id'])) { $taskOwner->update($ownerData); } else { TaskOwner::create($ownerData); } } catch (\Exception $exception) { Log::error($exception); } } } private function createOrUpdateTaskStatuses($status, $task) { try { if (!isset($status['id'])) return ; $statusData = [ 'status_id' => $status['id'], 'TaskID' => $task->id, 'name' => $status['name'], 'type' => $status['type'] ]; $taskStatus = TaskStatus::where('status_id', $status['id']) ->where('TaskID', $task->id) ->first(); if ($taskStatus) { $taskStatus->update($statusData); } else { TaskStatus::create($statusData); } } catch (\Exception $exception) { Log::error($exception); } } }
fe5f66aad43f40b4c756b0d817f2162caa9f9801
[ "PHP" ]
31
PHP
sabbir25112/zoho-connect
45ad665ce5a2873aee65f7cc86881801fe98c3d1
37262148ed0e11564499a03e9c7d28f3b45ca951
refs/heads/master
<file_sep> -- CREATE {DATABASE | SCHEMA } xyz_db CHARACTER SET = utf8 -- CREATE USER 'foo'@'192.168.0.1' IDENTIFIED BY 'pwd'; DROP TABLE tab_users; DROP TABLE tab_sites; DROP TABLE tab_galerie; DROP TABLE tab_carriere; DROP TABLE tab_courriels; CREATE TABLE IF NOT EXISTS tab_users ( user_id INT AUTO_INCREMENT PRIMARY KEY, nom VARCHAR(50) NOT NULL, prenom VARCHAR(50) NOT NULL, adr_courriel VARCHAR(70) NOT NULL, poste VARCHAR(50) NOT NULL, mot_de_passe TEXT NOT NULL, visibility VARCHAR(50) NOT NULL, date_creation TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=INNODB; CREATE TABLE IF NOT EXISTS tab_sites ( site_id INT AUTO_INCREMENT PRIMARY KEY, nom VARCHAR(50) NOT NULL, decription TEXT, ) ENGINE=INNODB; CREATE TABLE IF NOT EXISTS tab_galerie ( photo_id INT AUTO_INCREMENT PRIMARY KEY, chemin TEXT NOT NULL, nom TEXT, description TEXT, saison VARCHAR(70) -- peut-être ajouter la photo dans les attributs de cette table ) ENGINE=INNODB; CREATE TABLE IF NOT EXISTS tab_carriere ( carriere_id INT AUTO_INCREMENT PRIMARY KEY, poste VARCHAR(70) NOT NULL, salaire VARCHAR(20), type_poste TEXT NOT NULL, experience_re TEXT, formation_re TEXT, description TEXT NOT NULL, date_creation TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=INNODB; CREATE TABLE IF NOT EXISTS tab_courriels ( courriel_id INT AUTO_INCREMENT PRIMARY KEY, nom VARCHAR(50) NOT NULL, prenom VARCHAR(50) NOT NULL, adr_courriel VARCHAR(70) NOT NULL, titre TEXT NOT NULL, message TEXT NOT NULL, date_creation TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=INNODB;<file_sep>-------------- DKoncept -------------- Projet réaliser par: - <NAME> - <NAME> -------------------------------------------------- Ce site internet a été créer sur la base d'un template Boostrap de la compagnie ColorLib. Allez voir le site internet de https://colorlib.com pour obtenir plus d'information sur le site internet de base que nous avons utiliser pour la réalisation de se projet. Pour pouvoir utiliser le site internet, il vous faut une connection à internet, puisqu'il est nécessaire de faire des requêtes à la base de données mySql sur https://webmysql.notes-de-cours.com/phpmyadmin La majorité des informations contenu du site web sont basé sur de réel informations sur le Bistro le 633. Pour se connecter en tant qu'administrateur, il faut inscrire le mot "login" ou "login.php" dans la bar de navigation. ----------------------------------- -- Utilisateur et Mot de Passe -- ----------------------------------- --- Pour la base de donnée --- Utilisateur : chunkysoup Mdp : AAAaaa111 --- Sur le site web --- Utilisateur : chunkysoup Mdp : AAAaaa111 ------------------ -- EASTER EGG -- ------------------ 1 - Dans n'importe quel page du site web (lorsque vous êtes en mode utilisateur), il est possible de remarquer 3 petit boutons de lien dans le footer. Le boutton avec la lettre "F" redirige vers la page facebook du Bistro le 633. Le button avec une boule, redirige vers une article de "LaPresse" sur le restaurant. Finalement, le boutton avec les lettres "Be" permets l'apparition d'un père Noël qui distribut des cadeaux. Ce easter egg a été créer en lien avec la période de l'année que nous sommes actuellement. 2 - Possibilité de s'inscrire à la liste des personnes abonnées à l'infolettre. Dans le bas de chacuner des pages (lorsque vous êtes en mode utilisateur), il est possible de voir les infos du restaurant. Dans la section de droite de cette onglet, il est possible de remarquer une place pour inscrire son adresse courriel. Suite à l'inscription de son email dans la zone à cet effet, l'administrateur recevera un message automatiser par email, de là, l'administrateur sera en mesure d'ajouter la personne à la liste des gens abonnés à l'infolettre. En s'incrivant à l'infolettre, l'usager recevra un message de Joyeuses fêtes. 3 - Dans la page index.php, dans la section "Réserver vos places ...", il est possible créer une réservation fixive au restaurant. Les données inscrite dans les champs seront alors acheminés via un message email à l'administrateur ou le gestionnaire du site web. 4 - Sur la page de login.php ou sur la page password.php, dans le footer, il y a une section "Mot de passe oublié", où il est possible d'envoyer un message à l'administrateur afin de l'informer de l'oublie de notre mot de passe. Suite à l'inscription d'un email, un message est envoyé à l'administrateur et un message est également envoyé à l'usager qui a oublié son mot de passe. FEATURE à essayer. <file_sep><?php require_once("action/DAO/Connection.php"); class FatherDAO { protected static function getTexte($id){ $connection = Connection::getConnection(); $result = $connection->prepare("SELECT `texte` FROM `textes` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); return $result->fetch()[0]; } }<file_sep><?php require_once("action/CommonAction.php"); require_once("action/DAO/MealDAO.php"); class GalleryAction extends CommonAction { public $repas = []; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { if (isset($_POST["remove"])){ $delete_file = MealDAO::getFileRepas($_POST["id"]); unlink($delete_file); MealDAO::removeRepas($_POST["id"]); header("location:gallery.php"); exit; } else if(isset($_POST["submit"]) && isset($_POST["nom"]) && isset($_POST["group"]) && isset($_POST["desc"]) && isset($_FILES['image'])){ $extensions= array("jpeg","jpg","png"); $file_name = $_FILES['image']['name']; $file_ext=strtolower(end(explode('.',$file_name))); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } else { $check = getimagesize($_FILES["image"]["tmp_name"]); if($check !== false){ $file_size = $_FILES['image']['size']; $file_tmp = $_FILES['image']['tmp_name']; $file_type = $_FILES['image']['type']; if($file_size > 2097152){ $errors[]='File size must be excately 2 MB'; } if(empty($this->errors)==true){ $compteur = 0; $test = fopen("img/insert/".$compteur.$file_name,'r'); while ($test != FALSE){ $compteur++; $test = fopen("img/insert/".$compteur.$file_name,'r'); } $file = "img/insert/".$compteur.$file_name; move_uploaded_file($file_tmp,$file); MealDAO::addRepas($_POST["nom"], $_POST["group"], $_POST["desc"], $file); header("location:gallery.php#gallery"); exit; } } } } else if(isset($_POST["saveMeal"]) && isset($_POST["idItem"]) && isset($_POST["newMealName"]) && isset($_POST["newMealDesc"])){ if (isset($_FILES["newImage"])){ $extensions= array("jpeg","jpg","png"); $file_name = $_FILES['newImage']['name']; $file_ext=strtolower(end(explode('.',$file_name))); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } else { $check = getimagesize($_FILES["newImage"]["tmp_name"]); if($check !== false){ $file_size = $_FILES['newImage']['size']; $file_tmp = $_FILES['newImage']['tmp_name']; $file_type = $_FILES['newImage']['type']; if($file_size > 2097152){ $errors[]='File size must be excately 2 MB'; } if(empty($this->errors)==true){ move_uploaded_file($file_tmp,MealDAO::getFileRepas($_POST["idItem"])); } } } } MealDAO::updateRepas($_POST["idItem"], $_POST["newMealName"], $_POST["newMealDesc"]); header("location:gallery.php"); exit; } $this->repas = MealDAO::getRepas(); } }<file_sep><?php require_once("action/ContactAction.php"); $action = new ContactAction(); $action->execute(); require_once("partiel/header.php"); ?> <?php if($action->sendingError){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-danger"> <div class="h4 col-lg-8 text-justify"> Un problème est survenu dans l'envoie du message. Assurez-vous d'avoir bien rempli tous les champs du message</div></div> <?php } else if($action->messageSend){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-success"><div class="h4 col-lg-8 text-justify"> Message envoyé avec succès!</div></div> <?php } ?> <!-- start banner Area --> <section class="relative about-banner"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white">Nous joindre</h1> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start contact-page Area --> <section class="contact-page-area section-gap"> <div class="container"> <div class="row"> <iframe class="map-wrap" style="width:100%; height: 445px;" id="map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2805.4889519530834!2d-72.65542638418391!3d45.31874805115769!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4cc9da3d5e6a88ed%3A0x46d481f36800559f!2sBistro%20Le%20633!5e0!3m2!1sfr!2sca!4v1574708816264!5m2!1sfr!2sca" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen=""></iframe> <div class="col-lg-4 d-flex flex-column address-wrap"> <div class="single-contact-address d-flex flex-row"> <div class="icon"> <span class="lnr lnr-home"></span> </div> <div class="contact-details"> <h5>Bromont, Québec</h5> <p> 633 Rue Shefford, QC J2L 2K5 </p> </div> </div> <div class="single-contact-address d-flex flex-row"> <div class="icon"> <span class="lnr lnr-phone-handset"></span> </div> <div class="contact-details text-justify"> <h5>(450) 534-0633</h5> <p>Appelez-nous sur nos heures d'ouverture et il nous fera un plaisir de vous répondre.</p> </div> </div> <div class="single-contact-address d-flex flex-row"> <div class="icon"> <span class="lnr lnr-envelope"></span> </div> <div class="contact-details text-justify"> <h5><EMAIL></h5> <p>Si vous avez une question ou de l'intérêt dans nos services et nos produits, communiquer nous à n'importe quel moment!</p> </div> </div> </div> <div class="col-lg-8"> <form class="form-area contact-form text-right" id="myForm" action="contact.php" method="post"> <div class="row"> <div class="col-lg-6 form-group"> <input name="firstName" placeholder="<NAME>" onfocus="this.placeholder = ''" onblur="this.placeholder = '<NAME>'" class="common-input mb-20 form-control" required="" type="text"> <input name="lastName" placeholder="<NAME>" onfocus="this.placeholder = ''" onblur="this.placeholder = '<NAME>'" class="common-input mb-20 form-control" required="" type="text"> <input name="email" placeholder="Votre adresse courriel" pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Votre adresse courriel'" class="common-input mb-20 form-control" required="" type="email"> <input name="subject" placeholder="Entrer le sujet" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Entrer le sujet'" class="common-input mb-20 form-control" required="" type="text"> </div> <div class="col-lg-6 form-group"> <textarea class="common-textarea form-control" name="message" placeholder="Composer un message" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Composer un message'" required=""></textarea> </div> <div class="col-lg-12"> <div class="alert-msg" style="text-align: left;"></div> <button type="submit" class="genric-btn primary" style="float: right;">Envoyer un message</button> </div> </div> </form> </div> <div class="col-lg-12 text-center mt-60 mt-sm-20"> <img class="img-fluid" style="max-width:600px;width:100%; height:auto" height="auto" width="auto" src="img/autres/resto-exterieur.jpg" alt="Restaurant"> </div> </div> </div> </section> <!-- End contact-page Area --> <?php require_once("partiel/footer.php");<file_sep><?php require_once("action/DAO/FatherDAO.php"); class CarriereDAO extends FatherDAO{ public static function updateCarriere($id, $newName, $newSalary, $newDesc) { $connection = Connection::getConnection(); $result = $connection->query("SELECT `description` FROM `carrieres` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); $idDescription = $result->fetch()[0]; $statementDesc = $connection->prepare("UPDATE `textes` SET `texte`=? WHERE id=?"); $statementDesc->bindParam(1, $newDesc); $statementDesc->bindParam(2, $idDescription); $statementDesc->execute(); $statementNom = $connection->prepare("UPDATE `carrieres` SET `nom`=?, `salary`=? where `id`=?"); $statementNom->bindParam(1, $newName); $statementNom->bindParam(2, $newSalary); $statementNom->bindParam(3, $id); $statementNom->execute(); } public static function addCarriere($nom, $group, $salary, $description){ $connection = Connection::getConnection(); $statement = $connection->prepare("INSERT INTO `textes` (`texte`) VALUES(?)"); $statement->bindParam(1, $description); $statement->execute(); $result = $connection->query("SELECT LAST_INSERT_ID()"); $idDesc = $result->fetch()[0]; $statement = $connection->prepare("INSERT INTO `carrieres` (`nom`,`group`,`salary`,`description`) VALUES (?,?,?,?)"); $statement->bindParam(1, $nom); $statement->bindParam(2, $group); $statement->bindParam(3, $salary); $statement->bindParam(4, $idDesc); $statement->execute(); } public static function getCarrieres(){ $carrieres = []; $connection = Connection::getConnection(); $result = $connection->query("SELECT `id`,`nom`,`group`,`salary`,`description` FROM `carrieres`"); while($row = $result->fetch()) { $texte = CarriereDAO::getTexte($row["description"]); array_push($carrieres, [$row["id"],$row["nom"],$row["group"],$row["salary"], $texte]); } return $carrieres; } public static function removeCarriere($id){ $connection = Connection::getConnection(); $result = $connection->prepare("SELECT `description` FROM `carrieres` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); $idDescription = $result->fetch()[0]; $statement = $connection->prepare("DELETE FROM textes WHERE id=?"); $statement->bindParam(1, $idDescription); $statement->execute(); $statement = $connection->prepare("DELETE FROM carrieres WHERE id=?"); $statement->bindParam(1, $id); $statement->execute(); } } <file_sep>let gallery = null; let OPTION1 = "Entrées" let OPTION2 = "Dinners" let OPTION3 = "Souper" let OPTION4 = "Dessert" let GROUP1 = "entrees" let GROUP2 = "dinner" let GROUP3 = "souper" let GROUP4 = "dessert" window.addEventListener("load", ()=> { gallery = document.querySelector('#gallery .container') createAddItemBtn(); createActionModifyBtn(); }); const formToElement = () =>{ let sectionToFill = document.createElement('div'); sectionToFill.setAttribute("class", "row d-flex justify-content-center mt-80 mb-20"); sectionToFill.setAttribute("id", "formulaireItem"); let primaryDiv = document.createElement('div'); primaryDiv.setAttribute("class", "col-lg-10 col-md-8 col-sm-8 bg-secondary text-center"); let bottomDiv = document.createElement('div'); bottomDiv.setAttribute("class", "mt-20 mb-20"); let topText = document.createElement('h2'); topText.setAttribute("class", "text-black mt-50 mb-40"); topText.textContent = "Création d'un nouveau repas dans le menu"; let formulaire = document.createElement('form'); formulaire.setAttribute("action", "gallery.php"); formulaire.setAttribute("method", "post"); formulaire.setAttribute("enctype", "multipart/form-data"); //Balises contenu dans le form let nameDiv = document.createElement('div'); nameDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputName = document.createElement('input'); inputName.setAttribute("type", "text"); inputName.setAttribute("name", "nom"); inputName.setAttribute("placeholder", "Entrez le nom du dessert"); inputName.setAttribute("onfocus", "this.placeholder = ''"); inputName.setAttribute("onblur", "this.placeholder = 'Entrez le nom du repas'"); inputName.setAttribute("class", "form-input h4 pt-3 pb-3 mt-20 mb-20 col-lg-6 col-md-5 col-sm-4"); let groupDiv = document.createElement('div'); groupDiv.setAttribute("class", "mt-20 mb-20 inputDiv row justify-content-center"); let optionInputDef = document.createElement('option'); optionInputDef.textContent = "Choisissez parmi les options suivantes"; optionInputDef.setAttribute("selected", "selected"); optionInputDef.setAttribute("disabled", "disabled"); optionInputDef.setAttribute("hidden", "hidden"); let optionInput1 = document.createElement('option'); optionInput1.setAttribute("value", GROUP1); optionInput1.textContent = OPTION1; let optionInput2 = document.createElement('option'); optionInput2.setAttribute("value", GROUP2); optionInput2.textContent = OPTION2; let optionInput3 = document.createElement('option'); optionInput3.setAttribute("value", GROUP3); optionInput3.textContent = OPTION3; let optionInput4 = document.createElement('option'); optionInput4.setAttribute("value", GROUP4); optionInput4.textContent = OPTION4; let inputGroup = document.createElement('select'); inputGroup.setAttribute("type", "text"); inputGroup.setAttribute("name", "group"); inputGroup.setAttribute("id", "group"); inputGroup.setAttribute("class", "form-input h6 pt-3 pb-3 mt-20 mb-20 col-lg-6 col-md-5 col-sm-4"); let descDiv = document.createElement('div'); descDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputDesc = document.createElement('textarea'); inputDesc.setAttribute("type", "text"); inputDesc.setAttribute("name", "desc"); inputDesc.setAttribute("id", "desc"); inputDesc.setAttribute("placeholder", "Entrez une description"); inputDesc.setAttribute("onfocus", "this.placeholder = ''"); inputDesc.setAttribute("onblur", "this.placeholder = 'Entrez une description'"); inputDesc.setAttribute("rows", "10"); inputDesc.setAttribute("class", "form-input col-lg-8 col-md-6 col-sm-6 h4 pt-3 pb-3 mt-20 mb-20"); let picDiv = document.createElement('div'); picDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputPicture = document.createElement('input'); inputPicture.setAttribute("type", "file"); inputPicture.setAttribute("name", "image"); inputPicture.setAttribute("id", "image"); inputPicture.setAttribute("class", "form-input text-center text-black h4 pt-2 pb-2 mt-20 mb-40"); let inputSubmit = document.createElement('input'); inputSubmit.setAttribute("type", "submit"); inputSubmit.setAttribute("name", "submit"); inputSubmit.setAttribute("value", "Ajouter le repas"); inputSubmit.setAttribute("class", "form-input btn-info btn-lg col-lg-4 mx-lg-5 mx-md-5 text-center"); //Fin des balises dans le form let inputAnnulation = document.createElement('input'); inputAnnulation.setAttribute("type", "button"); inputAnnulation.setAttribute("class", "btn-warning btn-lg col-lg-4 mx-lg-5 mx-md-5 text-uppercase text-center"); inputAnnulation.setAttribute("name", "annulation"); inputAnnulation.setAttribute("value", "Annuler"); inputAnnulation.onclick = () =>{ var element = document.getElementById("formulaireItem"); element.parentNode.removeChild(element); createAddItemBtn(); }; inputGroup.appendChild(optionInputDef); inputGroup.appendChild(optionInput1); inputGroup.appendChild(optionInput2); inputGroup.appendChild(optionInput3); inputGroup.appendChild(optionInput4); bottomDiv.appendChild(inputSubmit); bottomDiv.appendChild(inputAnnulation); nameDiv.appendChild(inputName); groupDiv.appendChild(inputGroup); descDiv.appendChild(inputDesc); picDiv.appendChild(inputPicture); formulaire.appendChild(nameDiv); formulaire.appendChild(groupDiv); formulaire.appendChild(descDiv); formulaire.appendChild(picDiv); formulaire.appendChild(bottomDiv); primaryDiv.appendChild(topText); primaryDiv.appendChild(formulaire); sectionToFill.appendChild(primaryDiv); gallery.appendChild(sectionToFill); } const createAddItemBtn = () =>{ let sectionButton = document.createElement('div'); sectionButton.setAttribute("class", "row d-flex justify-content-center"); sectionButton.setAttribute("id", "sectBtnAddItem"); let btnSuppression = document.createElement('button'); btnSuppression.onclick = () =>{ var element = document.getElementById("sectBtnAddItem"); element.parentNode.removeChild(element); formToElement(); }; btnSuppression.setAttribute("class", "btn-info btn-lg col-lg-8 pt-40 pb-40 mt-80 text-uppercase text-center"); btnSuppression.textContent = "Ajouter un nouveau repas"; sectionButton.appendChild(btnSuppression); gallery.appendChild(sectionButton); } const createActionModifyBtn = () =>{ let allModifBtn = document.querySelectorAll('.modify'); for(let i=0; i < allModifBtn.length; i++){ allModifBtn[i].onclick = () =>{ modifyText(allModifBtn[i]); } } } const modifyText = (node) =>{ nodeParent = node.parentNode; nodeContent = nodeParent.querySelector(".itemContent"); nodeMealName = nodeParent.querySelector(".itemContent .mealName"); nodeMealDesc = nodeParent.querySelector(".itemContent .mealDesc"); nodeParent.removeChild(node); nodeDelete = nodeParent.querySelector("form"); let annulationBtn = document.createElement('input'); annulationBtn.setAttribute("type", "button"); annulationBtn.setAttribute("class", "btn-warning btn-lg h5 text-white col-lg-12 text-uppercase text-center mb-lg-2 mb-md-2 text-center cancelation"); annulationBtn.setAttribute("name", "annulation"); annulationBtn.setAttribute("value", "Annuler"); annulationBtn.onclick = () =>{ location.reload(); }; nodeParent.appendChild(annulationBtn); let formModify = document.createElement('form'); formModify.setAttribute("action", "gallery.php"); formModify.setAttribute("method", "post"); formModify.setAttribute("class", "attributeModifier") formModify.setAttribute("enctype", "multipart/form-data"); let nodeIdItem = document.createElement('input'); nodeIdItem.setAttribute("type", "hidden"); nodeIdItem.setAttribute("name", "idItem"); nodeIdItem.setAttribute("value", nodeParent.querySelector("form.deleteItem input").value); let inputPicture = document.createElement('input'); inputPicture.setAttribute("type", "file"); inputPicture.setAttribute("name", "newImage"); inputPicture.setAttribute("id", "newImage"); inputPicture.setAttribute("class", "form-input text-center text-white h5 pt-2 pb-2 mt-20 mb-40"); let textName = document.createElement('textarea'); textName.setAttribute("name", "newMealName"); textName.setAttribute("class", "h4 mt-2 toModify mealName nameModifier"); textName.setAttribute("cols", "20"); textName.setAttribute("rows", "1"); textName.textContent = nodeMealName.textContent; let textDesc = document.createElement('textarea'); textDesc.setAttribute("name", "newMealDesc"); textDesc.setAttribute("class", "h6 text-justify mb-2 toModify descModifier"); textDesc.setAttribute("cols", "30"); textDesc.setAttribute("rows", "10"); textDesc.textContent = nodeMealDesc.textContent; let inputSave = document.createElement('input'); inputSave.setAttribute("type", "submit"); inputSave.setAttribute("class", "btn-info btn-lg h5 text-white col-lg-12 text-uppercase text-center mt-lg-2 mt-md-2 mb-lg-2 mb-md-2 modify"); inputSave.setAttribute("name", "saveMeal"); inputSave.setAttribute("value", "sauvegarder"); formModify.appendChild(nodeIdItem); formModify.appendChild(inputPicture); formModify.appendChild(textName); formModify.appendChild(textDesc); formModify.appendChild(inputSave); nodeContent.appendChild(formModify); nodeContent.removeChild(nodeMealName); nodeContent.removeChild(nodeMealDesc); let config = { height:'400px', toolbar: [ 'Heading', 'bold', '|', 'italic', '|', 'Link'], } nodeParent.style.backgroundColor = '#0000E6'; nodeItemsToModify = nodeContent.querySelectorAll(".toModify"); for(let i=0; i < nodeItemsToModify.length; i++){ ClassicEditor .create( nodeItemsToModify[i], { height: config.height, toolbar: config.toolbar, }) .catch( error => { console.error( error ); } ); } } const reactiveModifyAction = (node) =>{ console.log("réactivation"); node.textContent = "Modifier"; node.onclick = () =>{ modifyText(node); }; } const annulationItemModification = (node) =>{ console.log("reconstruction"); node.removeChild(node.querySelector(".cancelation")); node.style.backgroundColor = 'white'; textName = node.querySelector("form .nameModifier").textContent; textDesc = node.querySelector("form .descModifier").textContent; let nodeName = document.createElement('div'); nodeName.setAttribute("class", "h4 mt-2 mealName"); nodeName.textContent = textName; let nodeDesc = document.createElement('div'); nodeDesc.setAttribute("class", "h6 text-justify mb-2 mealDesc"); nodeDesc.textContent = textDesc; node.appendChild(nodeName); node.appendChild(nodeName); node.removeChild(node.querySelector(".itemContent form.attributeModifier")); }<file_sep><?php require_once("action/CommonAction.php"); require_once("action/DAO/UserDAO.php"); class PasswordAction extends CommonAction { public $myError = NULL; public $messageSend = false; public $sendingError = false; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_MEMBER); } protected function executeAction() { if (isset($_POST["oldPassword"]) && isset($_POST["newPassword1"]) && isset($_POST["newPassword2"])) { if($_POST["newPassword1"] === $_POST["newPassword2"]){ $user = UserDAO::authenticate($_SESSION["username"], $_POST["oldPassword"]); if (!empty($user)) { UserDAO::updatePassword($_SESSION["username"], $_POST["newPassword1"]); $this->myError = "ALL_GOOD"; } else { $this->myError = "WRONG_LOGIN"; } } else { $this->myError = "WRONG_PASSWORD"; } } else if(isset($_POST["emailPasswordForgot"]) && $this->messageSend == false){ $emailUser = $_POST["emailPasswordForgot"]; $emailAdmin = '<EMAIL>'; $firstName = $lastName = $text= "DUDE.. come on, sérieux la. What a noob. On va t'envoyer ton mot de passe dans pas long"; $subject= "Cest la periode des fêtes... Attendez que les gars de la TI reviennes de voyage."; $headersUser = 'Mot de passe oublié Bistro le 633'; $messageUser ='From : les gars de la TI du Bistro le 633'.' Subject : '.$subject.' '.$text; $headerAdmin = "Reset de mot de passe"; $messageAdmin = 'Ya un dude qui a oublié son mot de passse'.' Email de la honte: '. $emailUser; if (mail($emailUser, $headersUser, $messageUser) && mail($emailAdmin, $headerAdmin, $messageAdmin)){ $this->messageSend = true; }else{ $this->sendingError = true; } } } } <file_sep><?php require_once("action/IndexAction.php"); $action = new IndexAction(); $action->execute(); require_once("partiel/header.php"); ?> <?php if($action->sendingError){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-danger"> <div class="h4 col-lg-8 text-justify"> Un problème est survenu dans l'envoie de la réservation. Assurez-vous d'avoir bien rempli tous les champs du message, puis réessayer</div></div> <?php } else if($action->messageSend){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-success"><div class="h4 col-lg-8 text-justify"> Réservation envoyé avec succès!</div></div> <?php } ?> <!-- start banner Area --> <section class="banner-area"> <div class="container"> <div class="row fullscreen align-items-center justify-content-between"> <div class="col-lg-12 banner-content"> <h6 class="text-white" tag='1'>Une expérience inégalable</h6> <h1 class="text-white" tag='2'>Bistro le 633</h1> <p class="text-white text-justify" tag='3'> Un endroit où vous mettez les pieds, et que vous voulez y rester. Ambiance chaleureuse et nourriture qui sait séduire les amateurs de fine gastronomie. Peu nombreux son ceux qui ne tombe pas sous le charme de ce petit restaurant. </p> <a href="gallery.php" class="primary-btn text-uppercase" tag='4'>Consulter le menu gastronomique</a> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start home-about Area --> <section class="home-about-area section-gap"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 home-about-left"> <h1 tag='5'>Un brin d'histoire</h1> <p class="text-justify" tag='6'> Situé sur la rue Shefford à Bromont dans une maison des années 1800, le Bistro 633 possède une salle de 80 places qui offre une vue imprenable sur le mont Bromont. Cet endroit est idéal pour vous recevoir des occasions de toutes sortes, tels que des rendez-vous galants, des réunions et des événements corporatifs, en passant par les fêtes de famille, les soirées animées ou autres! Possédant une inventaire de spiritueux composer principalement de Scotch et de Whisky, sans compter l'énorme cave à vin constituer principalement d'importation privée, <NAME> (propriétaire du Bistro 633) a su mettre à profit sa passion, son histoire et ses connaissances afin de faire vivre une expérience inoubliable à chacun des vervants visiteurs de son restaurant. </p> <a href="restaurant.php" class="primary-btn" tag='7'>Voir notre équipe</a> </div> <div class="col-lg-6 home-about-right"> <img class="img-fluid" src="img/nourriture/poutine.jpg" alt="Poutine au canard"> </div> </div> </div> </section> <!-- End home-about Area --> <!-- Start reservation Area --> <section class="reservation-area section-gap relative"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row justify-content-between align-items-center"> <div class="col-lg-6 reservation-left"> <h1 class="text-white" tag='8'>Réserver vos places <br> dès aujourd'hui <br>pour une expérience inoubliable.</h1> <p class="text-white pt-20 text-justify" tag='9'> En deux temps trois mouvements, votre réservation sera complété et acheminé dans l'agenda du restaurant. Un message vous sera transmis dans les 48 heures avant la réservation afin de valider votre disponibilité. </p> </div> <div class="col-lg-5 reservation-right"> <form class="form-wrap text-center" action="index.php" method="post"> <input type="text" class="form-control" name="firstName" placeholder="<NAME>" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Votre Prénom'" > <input type="text" class="form-control" name="lastName" placeholder="<NAME>" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Votre Nom'" > <input type="email" class="form-control" name="emailReservation" placeholder="Votre adresse courriel" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Votre adresse courriel'" > <input type="text" class="form-control" name="phone" placeholder="Numéro de téléphone" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Numéro de téléphone'" > <input type="text" class="form-control date-picker" name="dateReservation" placeholder="Choisissez une date & une heure" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Choisissez une date & une heure'" > <div class="form-select" id="service-select"> <select name="optionReservation"> <option data-display="">Choisissez le type d'évènement</option> <option value="1">Fête d'une personne proche</option> <option value="2">Souper de travail</option> <option value="3">Rendez-vous galant</option> <option value="4">Célébration d'un évenement spécial</option> <option value="5">Dégustation de vin</option> <option value="6">Dégustation de spiritueux</option> </select> </div> <button class="primary-btn text-uppercase mt-20">Faire une réservation</button> </form> </div> </form> </div> </div> </div> </section> <!-- End reservation Area --> <!-- Start gallery-area Area --> <section class="gallery-area section-gap" id="gallery"> <div class="container"> <div class="row d-flex justify-content-center"> <div class="menu-content pb-70 col-lg-8"> <div class="title text-justify"> <h1 class="mb-10" tag='10'>Galerie de nos réalisations</h1> <p tag='11'>À l'affût des saisons et des goûts de nos consommateurs, notre menu de tapas est modifier réguliairement.</p> </div> </div> </div> <ul class="filter-wrap filters col-lg-12 no-padding"> <li class="active" data-filter="*">Tous les menus</li> <li data-filter=".entrees">Nos entrées</li> <li data-filter=".dinner">Les dînners</li> <li data-filter=".souper">Les tapas du soir</li> <li data-filter=".dessert">Les desserts</li> </ul> <div class="filters-content"> <div class="row grid"> <?php if($action->isLoggedIn()){ foreach ($action->repas as $item){ ?> <div class="col-lg-4 col-md-6 col-sm-6 all <?= $item[2] ?>"> <div class="single-menu"> <div class="itemContent text-center"> <?php echo '<img class="img-fluid imgPerson" src="'.$item[4].'" alt="'.$item[1].'"/>'; ?> <div class="h4 mt-2"><?= $item[1] ?></div> <div class="text-justify mb-2"><?= $item[3] ?></div> </div> <form action="gallery.php" method="post"> <input type="hidden" value=<?=$item[0]?> name="id"> <button type="submit" name="remove" class="btn-danger btn-lg h5 text-white col-lg-12 text-uppercase text-center">Supprimer</button> </form> </div> </div> <?php } } else{ foreach ($action->repas as $item){ ?> <div class="col-lg-4 col-md-6 col-sm-6 all <?= $item[2] ?>"> <div class="single-menu"> <div class="itemContent text-center"> <?php echo '<img class="img-fluid imgPerson" src="'.$item[4].'" alt="'.$item[1].'"/>'; ?> <div class="h4 mt-2"><?= $item[1] ?></div> <div class="mb-2 text-justify"><?= $item[3] ?></div> </div> </div> </div> <?php } } ?> </div> </div> </div> </section> <!-- End gallery-area Area --> <!-- Start review Area --> <section class="review-area section-gap"> <div class="container"> <div class="row"> <div class="active-review-carusel"> <div class="single-review"> <img src="img/blog/user1.png" alt="user1"> <h4>Roger</h4> <div class="star"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> </div> <p> “Lorem ipsum dolor sit amet consectetur adipisicing elit. Non, iste.” </p> </div> <div class="single-review"> <img src="img/blog/user2.jpg" alt="user2"> <h4>Alice</h4> <div class="star"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> </div> <p> “Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores earum esse similique vero praesentium sit libero nemo iste, dolor debitis explicabo. Dolores enim hic facere tenetur dolore reiciendis ex commodi?” </p> </div> <div class="single-review"> <img src="img/blog/user3.png" alt="user3"> <h4>Nancy</h4> <div class="star"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> <span class="fa fa-star"></span> </div> <p> “Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima corrupti labore! Facilis unde praesentium corrupti quis minus. Nam at corrupti pariatur? Omnis praesentium deleniti assumenda architecto hic aspernatur sed, voluptate velit optio recusandae, perspiciatis modi tenetur ducimus deserunt. Officia voluptates impedit incidunt excepturi facilis quia odio eaque quae unde?” </p> </div> <div class="single-review"> <img src="img/blog/user4.jpg" alt="user4"> <h4>Robert</h4> <div class="star"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> </div> <p> “Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quae, architecto, eius similique reiciendis culpa esse sunt modi laboriosam vel, ut deserunt. Consectetur quae, dolores pariatur cupiditate veniam ipsam reiciendis facilis perferendis, iusto praesentium cum assumenda!” </p> </div> <div class="single-review"> <img src="img/blog/user5.png" alt="user5"> <h4>Denise</h4> <div class="star"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> </div> <p> “Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolore optio distinctio eaque. Animi quisquam, cum quasi sunt ipsa porro facere!” </p> </div> </div> </div> </div> </section> <!-- End review Area --> <?php require_once("partiel/footer.php");<file_sep><?php require_once("action/ServiceAction.php"); $action = new ServiceAction(); $action->execute(); require_once("partiel/header.php"); ?> <link rel="stylesheet" href="css/services.css"> <!-- start banner Area --> <section class="relative about-banner" id="home"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white">Service</h1> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start home-about Area --> <section class="home-about-area section-gap"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 home-about-left"> <h1>Service traiteur</h1> <p class="text-justify"> Bistro le 633 vous offre la possibilité de commander sous forme de traiteur une multitude de variétés de repas, de tapas et d'entrées du menu. Le restaurant offre la possibilité de commander du service traiteur, afin de réaliser des évènements inégalable chez vous ou ailleurs. Ce service vous permettera donc de commander votre menu gastronomique préférer dans la chaleur et le copmfort de votre maison. Si vous rétissez à commander du service traiteur, vous remarquerez que celui du Bistro 633 n'est pas comparable celui à de null part ailleurs. </p> </div> <div class="col-lg-6 home-about-right"> <img class="img-fluid" src="img/services/traiteur.jpg" alt="Traiteur"> </div> </div> </div> </section> <!-- End home-about Area --> <!-- Start reservation Area --> <section class="reservation-area section-gap relative "> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row justify-content-between align-items-center"> <div class="col-lg-6 reservation-left"> <h1 class="text-white">Évènements spéciaux</h1> <p class="text-white pt-20 text-justify"> Présentement en train d'organiser un évènement spécial telqu'un mariage ou un évènement de grand envergure? Le Bistro le 633 se fera un grand plaisir de vous aider à la réalisation de celui-ci. Tout dépendandament la saison, il sera possible d'acceuil un grand nomhbre de personne à l'intérieur, ou à l'extérieur du restaurant. Tous trouveront leur comble et leur bonheur. Sans pouvoir le garantir, nous vous garantissons un évèenement réussi avec du plaisir et de la joie. </p> </div> <div class="col-lg-5 reservation-right"> </div> </div> </div> </section> <!-- End reservation Area --> <!-- Start home-about Area --> <section class="home-about-area section-gap"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 home-about-right"> <img class="img-fluid" src="img/services/job_dinner.jpg" alt="Souper entre amis et corporatif"> </div> <div class="col-lg-6 home-about-left"> <h1>Souper entre amis et corporatif</h1> <p class="text-justify"> Avec son ambiance festive, Bistro le 633 est la place parfaite pour pour avoir une soirée inoubliable avce vos collègues de travail, ou encore mêmes vos amis. Réserver d'avance à la venu de groupe de grandes tailles, et réserver un mois à l'avance pour les groupes de plus petites tailes. Dans les périodes estivales, le Bistro le 633 est très prisé pour sa qualiter de service et de nourriture. </p> </div> </div> </div> </section> <!-- End home-about Area --> <!-- Start reservation Area --> <section class="reservation-area section-gap relative"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row justify-content-between align-items-center"> <div class="col-lg-5 reservation-right"> </div> <div class="col-lg-6 reservation-left"> <h1 class="text-white">Dégustation de spiritueux</h1> <p class="text-white pt-20 text-justify"> Ayant réaliser plusieurs voyages en Écosse, en Angletterre et en Irlande, <NAME> s'est découvert une passion pour le Whiskey, plus précisément le Scotch. Il est possible de constater l'amour du Whiskey que <NAME> a en comptant le nombre de bouteilles dans son restaurant. Pour transmettre sa passion, ce dernier effectue de nombreuses évènements environ une fois par mois pour faire une dégustation de ses coups de coeurs. Faites attention! Les places de ces évènements s'envolle d'ailleurs comme des petits pains chaud. <br><br> Il est possible d'effectuer une dégustation de Whiskey à n'importe quel moment, mais les bouteilles secrètent de Luc ne sortiront pas du placard. </p> </div> </div> </div> </section> <!-- End reservation Area --> <!-- Start home-about Area --> <section class="home-about-area section-gap"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 home-about-left"> <h1>Dégustation de vin</h1> <p class="text-justify"> La passion de Luc ne s'arrête pas seulement qu'à la nourriture et qu'au Whisky. Effectivement, <NAME> est également un grand amamteur de vin provenant du Portugal, de la France, de l'Italy ainsi que de l'Espagne. Écoutant les intérêts de ses clients ainsi que sa passion, <NAME> modernise et raffine sa cave à vin quelques fois par année. Pour une soirée entre amoureux le Samedi soir ou pour une soirée du Dimanche soir, le Bsitro 633 aura la consommation parfaite pour s'armonier avec votre repas et pour style l'occasion. Possédant une cave à vin principalement constituer d'importation privée, <NAME> organise des soirées de dégustation de vin pour ceux qui veulent découvrir les secrets cachés de la cave à vin du Bistro le 633. </p> </div> <div class="col-lg-6 home-about-right"> <img class="img-fluid" src="img/services/wine.jpg" alt="Vin"> </div> </div> </div> </section> <!-- End home-about Area --> <?php require_once("partiel/footer.php");<file_sep>let gallery = null; window.addEventListener("load", ()=> { gallery = document.querySelector('#teamBistro .container') createAddItemBtn(); createActionModifyBtn(); }); const formToElement = () =>{ let sectionToFill = document.createElement('div'); sectionToFill.setAttribute("class", "row d-flex justify-content-center mt-80 mb-20"); sectionToFill.setAttribute("id", "formulaireItem"); let primaryDiv = document.createElement('div'); primaryDiv.setAttribute("class", "col-lg-10 col-md-8 col-sm-8 bg-secondary text-center"); let bottomDiv = document.createElement('div'); bottomDiv.setAttribute("class", "mt-20 mb-20"); let topText = document.createElement('h2'); topText.setAttribute("class", "text-black mt-50 mb-40"); topText.textContent = "Création d'un nouveau employés"; let formulaire = document.createElement('form'); formulaire.setAttribute("action", "restaurant.php"); formulaire.setAttribute("method", "post"); formulaire.setAttribute("enctype", "multipart/form-data"); //Balises contenu dans le form let nameDiv = document.createElement('div'); nameDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputName = document.createElement('input'); inputName.setAttribute("type", "text"); inputName.setAttribute("name", "nom"); inputName.setAttribute("id", "nom"); inputName.setAttribute("placeholder", "Entrez le nom de l'employé"); inputName.setAttribute("onfocus", "this.placeholder = ''"); inputName.setAttribute("onblur", "this.placeholder = 'Entrez le nom de l employé'"); inputName.setAttribute("class", "form-input h4 pt-3 pb-3 mt-20 mb-20 col-lg-6 col-md-5 col-sm-4"); let posteDiv = document.createElement('div'); posteDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputPoste = document.createElement('input'); // inputPoste.setAttribute("type", "text"); inputPoste.setAttribute("name", "poste"); inputPoste.setAttribute("id", "poste"); inputPoste.setAttribute("placeholder", "Entrez le poste de la personne"); inputPoste.setAttribute("onfocus", "this.placeholder = ''"); inputPoste.setAttribute("onblur", "this.placeholder = 'Entrez le poste de la personne'"); inputPoste.setAttribute("class", "form-input h4 pt-3 pb-3 mt-20 mb-20 col-lg-6 col-md-5 col-sm-4"); let descDiv = document.createElement('div'); descDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputDesc = document.createElement('textarea'); inputDesc.setAttribute("type", "text"); inputDesc.setAttribute("name", "desc"); inputDesc.setAttribute("id", "desc"); inputDesc.setAttribute("placeholder", "Entrez une description"); inputDesc.setAttribute("onfocus", "this.placeholder = ''"); inputDesc.setAttribute("onblur", "this.placeholder = 'Entrez une description'"); inputDesc.setAttribute("rows", "10"); inputDesc.setAttribute("class", "form-input col-lg-8 col-md-6 col-sm-6 h4 pt-3 pb-3 mt-20 mb-20"); let picDiv = document.createElement('div'); picDiv.setAttribute("class", "mt-20 mb-20 inputDiv"); let inputPicture = document.createElement('input'); inputPicture.setAttribute("type", "file"); inputPicture.setAttribute("name", "image"); inputPicture.setAttribute("id", "image"); inputPicture.setAttribute("class", "form-input text-center text-black h4 pt-2 pb-2 mt-20 mb-40"); let inputSubmit = document.createElement('input'); inputSubmit.setAttribute("type", "submit"); inputSubmit.setAttribute("name", "submit"); inputSubmit.setAttribute("value", "Ajouter l'employé"); inputSubmit.setAttribute("class", "form-input btn-info btn-lg mx-lg-5 mx-md-5 col-lg-4 text-center"); //Fin des balises dans le form let inputAnnulation = document.createElement('input'); inputAnnulation.setAttribute("type", "button"); inputAnnulation.setAttribute("class", "btn-warning btn-lg col-lg-4 mx-lg-5 mx-md-5 text-uppercase text-center"); inputAnnulation.setAttribute("name", "annulation"); inputAnnulation.setAttribute("value", "Annuler"); inputAnnulation.onclick = () =>{ var element = document.getElementById("formulaireItem"); element.parentNode.removeChild(element); createAddItemBtn(); }; bottomDiv.appendChild(inputSubmit); bottomDiv.appendChild(inputAnnulation); nameDiv.appendChild(inputName); posteDiv.appendChild(inputPoste); descDiv.appendChild(inputDesc); picDiv.appendChild(inputPicture); formulaire.appendChild(nameDiv); formulaire.appendChild(posteDiv); formulaire.appendChild(descDiv); formulaire.appendChild(picDiv); formulaire.appendChild(bottomDiv); primaryDiv.appendChild(topText); primaryDiv.appendChild(formulaire); sectionToFill.appendChild(primaryDiv); gallery.appendChild(sectionToFill); } const createAddItemBtn = () =>{ let sectionButton = document.createElement('div'); sectionButton.setAttribute("class", "row d-flex justify-content-center"); sectionButton.setAttribute("id", "sectBtnAddItem"); let btnSuppression = document.createElement('button'); btnSuppression.onclick = () =>{ var element = document.getElementById("sectBtnAddItem"); element.parentNode.removeChild(element); formToElement(); }; btnSuppression.setAttribute("class", "btn-info btn-lg col-lg-8 pt-40 pb-40 mt-60 text-uppercase text-center"); btnSuppression.textContent = "Ajouter un nouvel employé"; sectionButton.appendChild(btnSuppression); gallery.appendChild(sectionButton); } const createActionModifyBtn = () =>{ let allModifBtn = document.querySelectorAll('.modify'); for(let i=0; i < allModifBtn.length; i++){ allModifBtn[i].onclick = () =>{ modifyText(allModifBtn[i]); } } } const modifyText = (node) =>{ nodeParent = node.parentNode; nodeContent = nodeParent.querySelector(".itemContent"); nodePersonFile = nodeParent.querySelector(".itemContent .imgPerson"); nodePersonName = nodeParent.querySelector(".itemContent .nomPerson"); nodePersonPoste = nodeParent.querySelector(".itemContent .postePerson"); nodePersonDesc = nodeParent.querySelector(".itemContent .descPerson"); nodeParent.removeChild(node); nodeDelete = nodeParent.querySelector("form"); let annulationBtn = document.createElement('input'); annulationBtn.setAttribute("type", "button"); annulationBtn.setAttribute("class", "btn-warning btn-lg h5 text-white col-lg-12 text-uppercase text-center mb-lg-2 mb-md-2 text-center cancelation"); annulationBtn.setAttribute("name", "annulation"); annulationBtn.setAttribute("value", "Annuler"); annulationBtn.onclick = () =>{ location.reload(); }; nodeParent.appendChild(annulationBtn); let formModify = document.createElement('form'); formModify.setAttribute("action", "restaurant.php"); formModify.setAttribute("method", "post"); formModify.setAttribute("class", "attributeModifier") formModify.setAttribute("enctype", "multipart/form-data"); let nodeIdItem = document.createElement('input'); nodeIdItem.setAttribute("type", "hidden"); nodeIdItem.setAttribute("name", "idItem"); nodeIdItem.setAttribute("value", nodeParent.querySelector("form.deleteItem input").value); let inputPicture = document.createElement('input'); inputPicture.setAttribute("type", "file"); inputPicture.setAttribute("name", "newImage"); inputPicture.setAttribute("id", "newImage"); inputPicture.setAttribute("class", "form-input text-center text-white h5 pt-2 pb-2 mt-20 mb-40"); let divName = document.createElement('div'); divName.setAttribute("class", "h4 mt-2 text-justify text-white"); divName.textContent = "Nom : "; let textName = document.createElement('textarea'); textName.setAttribute("name", "newName"); textName.setAttribute("class", "h4 toModify mealName nameModifier"); textName.setAttribute("cols", "20"); textName.setAttribute("rows", "1"); textName.textContent = nodePersonName.textContent; let divPoste = document.createElement('div'); divPoste.setAttribute("class", "h4 mt-2 text-justify text-white"); divPoste.textContent = "Poste : "; let textPoste = document.createElement('textarea'); textPoste.setAttribute("name", "newPoste"); textPoste.setAttribute("class", "h4 mt-2 toModify mealName posteModifier"); textPoste.setAttribute("cols", "20"); textPoste.setAttribute("rows", "1"); textPoste.textContent = nodePersonPoste.textContent; let divDesc = document.createElement('div'); divDesc.setAttribute("class", "h4 mt-2 text-justify text-white"); divDesc.textContent = "Description : "; let textDesc = document.createElement('textarea'); textDesc.setAttribute("name", "newDesc"); textDesc.setAttribute("class", "h6 text-justify mb-2 toModify descModifier"); textDesc.setAttribute("cols", "30"); textDesc.setAttribute("rows", "10"); textDesc.textContent = nodePersonDesc.textContent; let inputSave = document.createElement('input'); inputSave.setAttribute("type", "submit"); inputSave.setAttribute("class", "btn-info btn-lg h5 text-white col-lg-12 text-uppercase text-center mt-lg-2 mt-md-2 mb-lg-2 mb-md-2 modify"); inputSave.setAttribute("name", "savePerson"); inputSave.setAttribute("value", "sauvegarder"); formModify.appendChild(nodeIdItem); formModify.appendChild(inputPicture); formModify.appendChild(divName); formModify.appendChild(textName); formModify.appendChild(divPoste); formModify.appendChild(textPoste); formModify.appendChild(divDesc); formModify.appendChild(textDesc); formModify.appendChild(inputSave); nodeContent.appendChild(formModify); nodeContent.removeChild(nodePersonName); nodeContent.removeChild(nodePersonPoste); nodeContent.removeChild(nodePersonDesc); let config = { height:'400px', toolbar: [ 'Heading', '|', 'bold', '|', 'italic'], } nodeParent.parentNode.style.backgroundColor = '#0000E6'; nodeItemsToModify = nodeContent.querySelectorAll(".toModify"); for(let i=0; i < nodeItemsToModify.length; i++){ ClassicEditor .create( nodeItemsToModify[i], { height: config.height, toolbar: config.toolbar, }) .catch( error => { console.error( error ); } ); } } // const reactiveModifyAction = (node) =>{ // console.log("réactivation"); // node.textContent = "Modifier"; // node.onclick = () =>{ // modifyText(node); // }; // }<file_sep><?php require_once("action/CommonAction.php"); class ContactAction extends CommonAction { public $sendingError = false; public $messageSend = false; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { if(isset($_POST["firstName"]) && isset($_POST["lastName"]) && isset($_POST["email"]) && isset($_POST["message"])&& isset($_POST["subject"]) && $this->messageSend == false){ $to = '<EMAIL>'; $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $email= $_POST["email"]; $text= $_POST["message"]; $subject= $_POST["subject"]; $headers = 'Commentaire DKoncept'; $message ='From : '.$firstName.' '.$lastName.' Email : '.$email.' Subject : '.$subject.' '.$text; if (mail($to, $headers, $message)){ $this->messageSend = true; }else{ $this->sendingError = true; } } } }<file_sep><?php require_once("action/CommonAction.php"); class LogoutAction extends CommonAction{ public $signoutVal; public $errorSignout = false; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { session_unset(); session_destroy(); header("location:index.php"); exit; } } <file_sep><?php require_once("action/PasswordAction.php"); $action = new PasswordAction(); $action->execute(); require_once("partiel/header.php"); ?> <?php if($action->sendingError){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-danger"> <div class="h4 col-lg-8 text-justify"> Un problème est survenu dans l'envoie du message. Assurez-vous d'avoir bien rempli tous les champs du message</div></div> <?php } else if($action->messageSend){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-success"><div class="h4 col-lg-8 text-justify"> Message envoyé avec succès!</div></div> <?php } ?> <!-- start banner Area --> <section class="relative about-banner"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white">Changer de mot de passe</h1> </div> </div> </div> </section> <!-- End banner Area --> <section class="home-about-area section-gap"> <div class="container pb-5"> <div class="row d-flex justify-content-center align-items-center"> <div class="login-form-frame col-lg-4 position-center text-center"> <form action="password.php" method="POST"> <?php if ($action->myError == "WRONG_PASSWORD") { ?> <div class="error-div"><strong>Erreur : </strong>Les mots de passe que vous venez d'entrer ne sont pas identique</div> <?php } else if ($action->myError == "WRONG_LOGIN") { ?> <div class="error-div"><strong>Erreur : </strong>Identifier d'utilisateur éronner.</div> <?php } else if ($action->myError == "INFO_MANQUANTE") { ?> <div class="error-div"><strong>Erreur : </strong>Veuillez remplir tous les champs avant de continuer.</div> <?php } else if ($action->myError == "ALL_GOOD") { ?> <div class="error-div"><strong>Password updated</strong></div> <?php } ?> <div class="form-label h3"> <label for="username">Ancien mot de passe : </label> </div> <div class="form-input h4"> <input type="<PASSWORD>" name="oldPassword" id="<PASSWORD>" /> </div> <div class="form-separator pb-30"></div> <div class="form-label h3"> <label for="password">Nouveau mot de passe : </label> </div> <div class="form-input h4"> <input type="<PASSWORD>" name="<PASSWORD>" id="<PASSWORD>" /> </div> <div class="form-separator pb-30"></div> <div class="form-label h3"> <label for="password">Confirmation du mot de passe : </label> </div> <div class="form-input h4"> <input type="<PASSWORD>" name="<PASSWORD>" id="<PASSWORD>" /> </div> <div class="form-separator pb-30"></div> <div class="form-label"> &nbsp; </div> <div class="form-input"> <button type="submit" class="primary-btn text-uppercase">Changer mot de passe</button> </div> <div class="form-separator"></div> </form> </div> </div> </section> <!-- Beggining footer Area --> <footer class="footer-area"> <div class="footer-widget-wrap"> <div class="container"> <div class="row pt-5 d-flex justify-content-between align-items-center"> <div class="col-lg-4 col-md-6 col-sm-6"> <div class="single-footer-widget"> <h4>J'ai de besoin d'aide immédiat!</h4> <p> Contactez l'un de vos programmeurs étoiles </p> <p class="font-weight-bold"> <NAME><br> <NAME> </p> <p class="number"> (450) 534-0633 </p> </div> </div> <div class="col-lg-4 col-md-6 col-sm-6"> <div class="single-footer-widget"> <h4>Mot de passe oublier?</h4> <p>Enter votre adresse courriel afin de recevoir un message de réinitialisation de mot de passe.</p> <div class="d-flex flex-row" id="signup_infolettre"> <form class="navbar-form" action="" method="post"> <div class="input-group add-on align-items-center d-flex"> <input class="form-control text-black" name="emailPasswordForgot" id="emailPasswordForgot" pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$" placeholder="Votre adresse courriel" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Votre adresse courriel'" required="" type="email"> <div class="input-group-btn"> <button class="genric-btn"><span class="lnr lnr-arrow-right"></span></button> </div> </div> <div class="info mt-20"></div> </form> </div> </div> </div> </div> </div> </div> <div class="footer-bottom-wrap"> <div class="container"> <div class="row footer-bottom d-flex justify-content-between align-items-center"> <p class="col-lg-8 col-mdcol-sm-6 -6 footer-text m-0"><!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> Copyright &copy;<script>document.write(new Date().getFullYear());</script> Tous droits réservé | Ce site a été réaliser par <i class="fa fa-heart-o" aria-hidden="true"></i> Charles et <i class="fa fa-heart-o" aria-hidden="true"></i> Nicolas pour <a href="https://colorlib.com" target="_blank">Bistro le 633</a></p> <ul class="col-lg-4 col-mdcol-sm-6 -6 social-icons text-right"> <li><a href="https://fr-ca.facebook.com/pages/category/Gastropub/Bistro-LE-633-497792660269634/"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="https://www.lapresse.ca/vivre/restaurants/201509/29/01-4904923-bistro-633-un-resto-qui-fait-jaser-a-bromont.php"><i class="fa fa-dribbble"></i></a></li> <li><a href="#"><i class="fa fa-behance"></i></a></li> </ul> </div> </div> </div> </footer> <!-- End footer Area --> </body> </html><file_sep> CREATE TABLE `chunkysoup`.`users` ( `id` INT NOT NULL AUTO_INCREMENT, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `visibility` INT NOT NULL, PRIMARY KEY (id) ) ENGINE = InnoDB; CREATE TABLE `chunkysoup`.`equipes` ( `id` INT NOT NULL AUTO_INCREMENT, `nom` TEXT NOT NULL, `poste` TEXT NOT NULL, `description` TEXT NOT NULL, `image` BLOB NOT NULL, PRIMARY KEY(id) ) ENGINE = InnoDB; CREATE TABLE `chunkysoup`.`textes` ( `id` INT NOT NULL AUTO_INCREMENT, `texte` TEXT NOT NULL, PRIMARY KEY(id) ) ENGINE = InnoDB; CREATE TABLE `chunkysoup`.`carrieres` ( `id` INT NOT NULL AUTO_INCREMENT, `nom` TEXT NOT NULL, `group` TEXT NOT NULL, `salary` TEXT NOT NULL, `description` TEXT NOT NULL, PRIMARY KEY(id) ) ENGINE = InnoDB; CREATE TABLE `chunkysoup`.`repas` ( `id` INT NOT NULL AUTO_INCREMENT, `nom` TEXT NOT NULL, `group` TEXT NOT NULL, `description` TEXT NOT NULL , `image` BLOB NOT NULL, PRIMARY KEY(id) ) ENGINE = InnoDB; CREATE TABLE `chunkysoup`.`textespage` ( `id` INT NOT NULL AUTO_INCREMENT, `idpage` TEXT NOT NULL, `tag` TEXT NOT NULL, `idtext` TEXT NOT NULL, PRIMARY KEY(id) ) ENGINE = InnoDB; <file_sep><?php require_once("action/RestaurantAction.php"); $action = new RestaurantAction(); $action->execute(); require_once("partiel/header.php"); ?> <?php if($action->isLoggedIn()){ ?> <script src="js/backend/teamEditor.js"></script> <?php } ?> <!-- start banner Area --> <section class="about-banner relative"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white">Restaurant</h1> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start home-about Area --> <section class="home-about-area section-gap"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 home-about-left"> <h1>Un brin d'histoire</h1> <p class="text-justify"> Situé sur la rue Shefford à Bromont dans une maison des années 1800, le Bistro 633 possède une salle de 80 places qui offre une vue imprenable sur le mont Bromont. Cet endroit est idéal pour vous recevoir des occasions de toutes sortes, tels que des rendez-vous galants, des réunions et des évènements corporatives, en passant par les fêtes de famille, les soirées animées ou autres! Possédant une inventaire de spiritueux composer principalement de Scotch et de Wisky, sans compter l'énorme cave à vin constituer principalement d'importation privée, <NAME> (propriétaire du Bistro 633) a su mettre à profit sa passion, son histoire et ses connaissances afin de faire vivre une expérience inoubliable à chacun des vervants visiteurs de son resturant. </p> </div> <div class="col-lg-6 home-about-right"> <img class="img-fluid" src="img/nourriture/assiette.jpg" alt="Repas"> </div> </div> </div> </section> <!-- End home-about Area --> <!-- Start services Area --> <section class="services-area pb-120"> <div class="container"> <div class="row d-flex justify-content-center"> <div class="menu-content pt-60 pb-20 col-lg-8"> <div class="title text-center"> <h1 class="mb-10">Quel sont les types de service que nous offrons?</h1> <p class="text-justify">Notre vaste variété de service un peu plus personnalisé les uns que les autres sauront vous charmer et combler vos attentes, et ce, peu importe le type d’activité ou d’évènement que vous tentez de réaliser. Bref, vous aurez droit à un évènement sans égale, que vous ne pourrez pas reproduire nulle part ailleurs.</p> </div> </div> </div> <div class="row"> <!-- Service 1 --> <div class="col-lg-4"> <div class="single-service"> <div class="thumb"> <img src="img/services/panini.jpg" alt="rgilled panini"> </div> <h4>Service à table</h4> <p> Venez déguster l'un de nos repas ou tapas offert tous les dinners et les soupers, et ce toute la semaine. </p> </div> </div> <!-- Service 2 --> <div class="col-lg-4"> <div class="single-service"> <div class="thumb"> <img src="img/services/wedding_resize.jpg" alt="Dancing people"> </div> <h4>Service évènementiel</h4> <p> Vous désirez réaliser une évènement de grand envergure tels qu'un mariage, une célébration d'un anniversaire ou un souper corporatif, nous sommes là pour vous afin de vous épauler. </p> </div> </div> <!-- Service 3 --> <div class="col-lg-4"> <div class="single-service"> <div class="thumb"> <img src="img/services/ramen.jpg" alt="ramen soup"> </div> <h4>Service traiteur</h4> <p> Commandez ce que vous voulez, à l'heure que vous voulez et dans l'environnement que vous voulez. Le service traiteur vous permets de déguster vos mets favoris lorque vous le désirez. </p> </div> </div> <div class="spacer col-lg-3"></div> <a href="service.php" class="primary-btn col-lg-6 mt-30 pb-10 pt-10 text-center">Voir tous nos offres de services</a> <div class="spacer col-lg-3"></div> </div> </div> </section> <!-- End services Area --> <!-- Start gallery-area Area --> <section class="gallery-area section-gap" id="teamBistro"> <div class="container"> <div class="row d-flex justify-content-center"> <div class="menu-content pb-70 col-lg-8"> <div class="title text-justify"> <h1 class="mb-10">Notre équipe</h1> <p>Certains nous conscidèrent comme étant une famille ayant les liens tissé sérer, d'autres pensent que nous sommes une équipe à l'épreuve de tous défis. Cependant, lorsque nous définissons qui nous sommes, nous réalisons que nous sommes les deux.</p> </div> </div> </div> <div class="filters-content"> <div class="row grid"> <?php if($action->isLoggedIn()){ foreach ($action->equipes as $e){ ?> <div class="col-lg-4 col-md-6 col-sm-6 all"> <div class="single-gallery"> <div class="itemContent text-center"> <?php echo '<img class="img-fluid imgPerson" src="'.$e[4].'" alt="'.$e[1].'"/>'; ?> <div class="h4 text-center mt-2 nomPerson"><?= $e[1] ?></div> <div class="h6 text-center mb-2 postePerson"><?= $e[2] ?></div> <div class="text-black mb-2 descPerson text-justify"><?= $e[3] ?></div> </div> <button class="btn-info btn-lg h5 text-white col-lg-12 text-uppercase text-center mb-lg-2 mb-md-2 modify">Modifier</button> <form action="restaurant.php" method="post" class="deleteItem"> <input type="hidden" value=<?=$e[0]?> name="id"> <button type="submit" name="remove" class="btn-danger btn-lg h5 text-white col-lg-12 mb-lg-2 mb-md-2 text-uppercase text-center">Supprimer</button> </form> </div> </div> <?php } } else{ foreach ($action->equipes as $e){ ?> <div class="col-lg-4 col-md-6 col-sm-6 all"> <div class="single-gallery"> <?php echo '<img class="img-fluid imgPerson" src="'.$e[4].'" alt="'.$e[1].'"/>'; ?> <div class="h4 text-center mt-2"><?= $e[1] ?></div> <div class="h6 text-center mb-2"><?= $e[2] ?></div> <div class="text-black mb-2"><?= $e[3] ?></div> </div> </div> <?php } } ?> </div> </div> </div> </section> <!-- End gallery-area Area --> <?php require_once("partiel/footer.php");<file_sep><?php require_once("action/CarriereAction.php"); $action = new CarriereAction(); $action->execute(); require_once("partiel/header.php"); ?> <?php if($action->isLoggedIn()){ ?> <script src="js/backend/carriereEditor.js"></script> <?php } ?> <!-- start banner Area --> <section class="about-banner relative"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white">Carrière</h1> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start menu-area Area --> <section class="menu-area section-gap" id="menu"> <div class="container"> <div class="row d-flex justify-content-center"> <div class="menu-content pb-70 col-lg-8"> <div class="title text-justify"> <h1 class="mb-10">Venez rejoindre l'équipe du Bistro le 633</h1> <p>Venir travaillez chez nous c'est accepter de ce lever chaque matin pour venir s'amuser afin de partager sa joie et sa passion pour la cuisine raffiner. Plusieurs de nos travailleurs sont venu joindre nos rangs afin d'y rester pour une courte durée, mais lorsqu'ils ont vu la chimie et l'esprit amicale et famillial de notre restaurant, ils ont tous décider d'y rester</p> </div> </div> </div> <ul class="filter-wrap filters col-lg-12 no-padding"> <li class="active" data-filter="*">Tous les postes</li> <li data-filter=".cuisine">En cuisine</li> <li data-filter=".salle">Dans la salle à manger</li> <li data-filter=".administration">Administration</li> <li data-filter=".autre">Autres postes</li> </ul> <div class="filters-content"> <div class="row grid"> <?php if($action->isLoggedIn()){ foreach ($action->carrieres as $carriere){ ?> <div class="col-md-6 all all <?= $carriere[2] ?>"> <div class="single-menu text-justify"> <div class="itemContent text-center"> <div class="title-wrap d-flex justify-content-between"> <h4 class="nameCarriere"><?= $carriere[1] ?></h4> <h4 class="price"><?= $carriere[3] ?></h4> </div> <div class="descCarriere text-justify"><?= $carriere[4] ?></div> </div> <button class="btn-info btn-lg h5 text-white col-lg-12 text-uppercase text-center mt-lg-2 mt-md-2 mb-lg-2 mb-md-2 modify">Modifier</button> <form action="carriere.php" method="post" class="deleteItem"> <input type="hidden" value=<?=$carriere[0]?> name="id"> <button type="submit" name="remove" class="btn-danger btn-lg h5 text-white col-lg-12 mb-lg-2 mb-md-2 text-uppercase text-center">Supprimer</button> </form> </div> </div> <?php } } else{ foreach ($action->carrieres as $carriere){ ?> <div class="col-md-6 all all <?= $carriere[2] ?>"> <div class="single-menu text-justify"> <div class="title-wrap d-flex justify-content-between"> <h4><?= $carriere[1] ?></h4> <h4 class="price"><?= $carriere[3] ?></h4> </div> <div> <?= $carriere[4] ?> </div> </div> </div> <?php } } ?> </div> </div> </div> </section> <!-- End menu-area Area --> <?php require_once("partiel/footer.php");<file_sep><?php require_once("action/LogoutAction.php"); $action = new LogoutAction(); $action->execute(); ?> <!DOCTYPE html> <html id="pLogout" lang="fr"> <head> <title>Magix - Plant vs Zombies</title> <link href="css/global.css" rel="stylesheet" /> <meta charset="utf-8"/> </head> <body> <?php if ($action->signoutVal) { ?> <div class="error-img"></div> <div class="error-div"><strong>Erreur : </strong>Déconnexion erronée</div> <div class="error-div"><strong>Une erreur s'est produite lors de la connexion...</div> <div class="form-input"> <button type="submit">[<a href="login.php">Retour à la page d'acceuil</a>]</button> </div> <?php } ?> </body> </html> <file_sep><?php define("DB_HOST", "https://webmysql.notes-de-cours.com/phpmyadmin"); define("DB_USER", "chunkysoup"); define("DB_PASS", "<PASSWORD>");<file_sep><?php session_start(); require_once("action/constants.php"); abstract class CommonAction { protected static $VISIBILITY_PUBLIC = 0; protected static $VISIBILITY_MEMBER = 1; protected static $VISIBILITY_MODERATOR = 2; protected static $VISIBILITY_ADMIN = 3; private $pageVisibility; public $infolettreSend = false; public $errorInfolettre = false; public function __construct($pageVisibility) { $this->pageVisibility = $pageVisibility; } public function execute() { if (!empty($_GET["logout"])) { session_unset(); session_destroy(); session_start(); } if (empty($_SESSION["visibility"])) { $_SESSION["visibility"] = CommonAction::$VISIBILITY_PUBLIC; } if ($_SESSION["visibility"] < $this->pageVisibility) { header("location:login.php"); exit; } if(isset($_POST["infoLettreEmail"]) && $this->infolettreSend == false){ $adminEmail = '<EMAIL>'; $personEmail = $_POST["infoLettreEmail"]; $text= "Joyeux Noel et joyeuses fetes!"; $subject= "Des beaux souhaits"; $from = "Bistro le 633"; $headers = "C'est le temps des fetes!"; $messageUser ='From : '.$from.' Subject : '.$subject.' '.$text; $headersAdmin = 'Inscription infolettere'; $textAdmin = "Requete d'inscription a l'infolettre"; $messageAdmin = ''.$textAdmin.' Email : '.$personEmail; if (mail($personEmail, $headers, $messageUser) && mail($adminEmail, $headersAdmin, $messageAdmin)){ $this->infolettreSend = true; }else{ $this->errorInfolettre = true; } } // Template method $this->executeAction(); } protected abstract function executeAction(); public function isLoggedIn() { return $_SESSION["visibility"] > CommonAction::$VISIBILITY_PUBLIC; } public function getUsername() { return empty($_SESSION["username"]) ? "Invité" : $_SESSION["username"]; } }<file_sep><!DOCTYPE html> <html lang="fr" class="no-js"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="shortcut icon" href="img/fav.png"> <meta name="author" content="Charles_Nicolas"> <meta name="description" content=""> <meta name="keywords" content=""> <meta charset="UTF-8"> <title> Oups, désolé! </title> <link href="https://fonts.googleapis.com/css?family=Poppins:100,200,400,300,500,600,700" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.css"> <link rel="stylesheet" href="css/jquery-ui.css"> <link rel="stylesheet" href="css/main.css"> </head> <body> <section class="banner-area"> <div class="container"> <div class="row fullscreen align-items-center justify-content-between"> <div class="editor col-lg-12 banner-content mb-100"> <?php if ($_GET["code"] == 403) { ?> <h1 class="text-white pb-80">Accès refusé.</h1> <div class="text-center"> <img src="img/error/bigEyes.gif" width="800" height="auto" alt="error image not able to load"> </div> <?php } else if ($_GET["code"] == 404) { ?> <h1 class="text-white">La page que vous tentez d'accèder n'existe pas. Retourner au site</h1> <div class="text-center"> <img src="img/error/sadness.gif" width="800" height="auto" alt="error image not able to load"> </div> <?php } else if ($_GET["code"] == 500) { ?> <h1 class="text-white">Problème avec le serveur... Veuillez réessayer votre opération ultérieurement</h1> <div class="text-center"> <img src="img/error/chilliSauce.gif" width="800" height="auto" alt="error image not able to load"> </div> <?php } ?> <div class="text-center mt-40"> <a href="index.php" class="primary-btn text-uppercase mb-100">Retourner en lieux sûr</a> </div> <div class="spacer mt-100 pt-50 pb-50"></div> </div> </div> </section> </body> </html> <file_sep><?php require_once("action/CommonAction.php"); require_once("action/DAO/CarriereDAO.php"); class CarriereAction extends CommonAction { public $carrieres = []; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { if (isset($_POST["remove"])){ CarriereDAO::removeCarriere($_POST["id"]); header("location:carriere.php#menu"); exit; } else if(isset($_POST["submit"]) && isset($_POST["nom"]) && isset($_POST["group"]) && isset($_POST["salary"]) && isset($_POST["desc"])){ CarriereDAO::addCarriere($_POST["nom"], $_POST["group"], $_POST["salary"], $_POST["desc"]); header("location:carriere.php#menu"); exit; } else if(isset($_POST["saveCarriere"]) && isset($_POST["idItem"]) && isset($_POST["newName"]) && isset($_POST["newSalary"]) && isset($_POST["newDesc"])){ CarriereDAO::updateCarriere($_POST["idItem"], $_POST["newName"], $_POST["newSalary"], $_POST["newDesc"]); header("location:carriere.php#menu"); exit; } $this->carrieres = CarriereDAO::getCarrieres(); } }<file_sep><?php require_once("action/GalleryAction.php"); $action = new GalleryAction(); $action->execute(); require_once("partiel/header.php"); ?> <?php if($action->isLoggedIn()){ ?> <script src="js/backend/foodEditor.js"></script> <?php } ?> <!-- start banner Area --> <section class="about-banner relative"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white">Gallerie</h1> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start gallery-area Area1 --> <section id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="3000"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> <li data-target="#carouselExampleIndicators" data-slide-to="3"></li> <li data-target="#carouselExampleIndicators" data-slide-to="4"></li> <li data-target="#carouselExampleIndicators" data-slide-to="5"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-50 mx-auto img-fluid" height="auto" width="auto" src=".\img\nourriture\assiette.jpg" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-50 mx-auto img-fluid" height="lg-675 md-500 sm-20" width="auto" src=".\img\nourriture\repas10.jpg" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-50 mx-auto img-fluid" height="lg-675 md-500 sm-20" width="auto" src=".\img\nourriture\Poutine.jpg" alt="Third slide"> </div> <div class="carousel-item"> <img class="d-block w-50 mx-auto img-fluid" height="lg-675 md-500 sm-20" width="auto" src=".\img\nourriture\repas2.jpg" alt="Four slide"> </div> <div class="carousel-item"> <img class="d-block w-50 mx-auto img-fluid" height="675" width="auto" src=".\img\nourriture\pate.jpg" alt="Five slide"> </div> <div class="carousel-item"> <img class="d-block w-50 mx-auto img-fluid" height="675" width="auto" src=".\img\nourriture\fromage.jpg" alt="Six slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </section> <!-- End gallery-area Area1 --> <!-- Start gallery-area Area --> <section class="gallery-area section-gap" id="gallery"> <div class="container"> <div class="row d-flex justify-content-center"> <div class="menu-content pb-70 col-lg-8"> <div class="title text-justify"> <h1 class="mb-10">Galerie de nos réalisations</h1> <p>À l'affût des saisons et des goûts de nos consommateurs, notre menu de tapas est modifier réguliairement.</p> </div> </div> </div> <ul class="filter-wrap filters col-lg-12 no-padding"> <li class="active" data-filter="*">Tous les menus</li> <li data-filter=".entrees">Nos entrées</li> <li data-filter=".dinner">Les dînners</li> <li data-filter=".souper">Les tapas du soir</li> <li data-filter=".dessert">Les desserts</li> </ul> <div class="filters-content"> <div class="row grid" id="imgGallery"> <?php if($action->isLoggedIn()){ foreach ($action->repas as $item){ ?> <div class="col-lg-4 col-md-6 col-sm-6 all <?= $item[2] ?>"> <div class="single-menu"> <div class="itemContent text-center"> <?php echo '<img class="img-fluid imgPerson" src="'.$item[4].'" alt="'.$item[1].'"/>'; ?> <div class="h4 mt-2 mealName"><?= $item[1] ?></div> <div class="text-justify mt-2 mb-2 mealDesc"><?= $item[3] ?></div> </div> <button class="btn-info btn-lg h5 text-white col-lg-12 text-uppercase text-center mb-lg-2 mb-md-2 modify">Modifier</button> <form action="gallery.php" method="post" class="deleteItem"> <input type="hidden" value=<?=$item[0]?> name="id"> <button type="submit" name="remove" class="btn-danger btn-lg h5 text-white col-lg-12 mb-lg-2 mb-md-2 text-uppercase text-center">Supprimer</button> </form> </div> </div> <?php } } else{ foreach ($action->repas as $item){ ?> <div class="col-lg-4 col-md-6 col-sm-6 all <?= $item[2] ?>"> <div class="single-menu"> <div class="itemContent text-center"> <?php echo '<img class="img-fluid imgPerson" src="'.$item[4].'" alt="'.$item[1].'"/>'; ?> <div class="h4 mt-2"><?= $item[1] ?></div> <div class="text-justify mb-2"><?= $item[3] ?></div> </div> </div> </div> <?php } } ?> </div> </div> </div> </section> <!-- End gallery-area Area --> <?php require_once("partiel/footer.php");<file_sep> let ctx = null; let CANVAS_WIDTH=0; let CANVAS_HEIGHT=0; let spriteList = []; let POS_SANTA_INIT_X = 100; let POS_SANTA_INIT_Y = 100; let SIZE_SANTA = 2; let SPEED = 3; let BTN_LINK = null; let DIV_PARENT = null; let ID_CANVAS = "canvasSanta"; let canvasDeleted = false; window.addEventListener("load", ()=> { BTN_LINK = document.querySelector("li button"); DIV_PARENT = document.querySelector(".footer-bottom-wrap"); BTN_LINK.onclick = () =>{ intisaliseEnvironement(DIV_PARENT); BTN_LINK.disabled=true; } }); const tick = () =>{ ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); for (let i = 0; i < spriteList.length; i++) { const sprite = spriteList[i]; let alive = sprite.tick(); if(!alive){ spriteList.splice(i,1); i--; } } if(spriteList.length == 0 && !canvasDeleted){ DIV_PARENT.removeChild(document.getElementById(ID_CANVAS)); BTN_LINK.disabled=false; canvasDeleted = true; } window.requestAnimationFrame(tick); } const intisaliseEnvironement = (node) =>{ CANVAS_WIDTH = (document.documentElement.clientWidth || window.innerWidth || document.body.clientWidth)-2; CANVAS_HEIGHT = 300; let nodeCanvas = document.createElement("canvas"); nodeCanvas.setAttribute("id", ID_CANVAS); nodeCanvas.setAttribute("width", CANVAS_WIDTH); nodeCanvas.setAttribute("height", CANVAS_HEIGHT); nodeCanvas.style.position = "absolute"; nodeCanvas.style.border = "1px solid"; nodeCanvas.textContent = "Not gonna happen..."; node.appendChild(nodeCanvas); ctx = nodeCanvas.getContext("2d"); spriteList.push(new SantaClaus(POS_SANTA_INIT_X, POS_SANTA_INIT_Y, SIZE_SANTA)); tick(); }<file_sep><!DOCTYPE html> <html lang="zxx" class="no-js"> <head> <!-- Mobile Specific Meta --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Favicon--> <link rel="shortcut icon" href="img/fav.png"> <!-- Author Meta --> <meta name="author" content="Charles_Nicolas"> <!-- Meta Description --> <meta name="description" content=""> <!-- Meta Keyword --> <meta name="keywords" content=""> <!-- meta character set --> <meta charset="UTF-8"> <!-- Site Title --> <title>DKONCEPT</title> <link href="https://fonts.googleapis.com/css?family=Poppins:100,200,400,300,500,600,700" rel="stylesheet"> <!-- CSS ============================================= --> <link rel="stylesheet" href="css/linearicons.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/bootstrap.css"> <link rel="stylesheet" href="css/magnific-popup.css"> <link rel="stylesheet" href="css/jquery-ui.css"> <link rel="stylesheet" href="css/nice-select.css"> <link rel="stylesheet" href="css/animate.min.css"> <link rel="stylesheet" href="css/owl.carousel.css"> <link rel="stylesheet" href="css/main.css"> <!-- Javascript --> <script src="js/vendor/jquery-2.2.4.min.js"></script> <script src="js/popper.min.js"></script> <script src="js/vendor/bootstrap.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBhOdIF3Y9382fqJYt5I_sswSrEw5eihAA"></script> <script src="js/jquery-ui.js"></script> <script src="js/easing.min.js"></script> <script src="js/hoverIntent.js"></script> <script src="js/superfish.min.js"></script> <script src="js/jquery.ajaxchimp.min.js"></script> <script src="js/jquery.magnific-popup.min.js"></script> <script src="js/jquery.nice-select.min.js"></script> <script src="js/owl.carousel.min.js"></script> <script src="js/isotope.pkgd.min.js"></script> <script src="js/mail-script.js"></script> <script src="js/main.js"></script> <script src="js/TiledImage.js"></script> <script src="js/santaAnimation.js"></script> <script src="js/sprite/SantaClaus.js"></script> <?php if ($action->isLoggedIn()){ ?> <script src="https://cdn.ckeditor.com/ckeditor5/15.0.0/classic/ckeditor.js"></script> <?php } ?> </head> <body> <?php if($action->errorInfolettre){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-danger"> <div class="h4 col-lg-8 text-justify">Un problème est survenu dans l'inscription à l'infolettre. Veuillez réessayer plus tard... </div></div> <?php } else if($action->infolettreSend){ ?> <div class="col-lg-12 pt-10 pl-lg-100 pl-md-100 pb-10 text-black text-center bg-success"><div class="h4 col-lg-8 text-justify">Vous êtes maintenant inscrit à l'infolettre du Bistro le 633.</div></div> <?php } ?> <header id="header"> <div class="header-top"> <div class="container"> <div class="row justify-content-center"> <div id="logo"> <a href="index.php"><img src="img/logo.png" width="175px" height="auto" alt="" title="" /></a> </div> </div> </div> </div> <div class="container main-menu"> <div class="row align-items-center justify-content-center d-flex"> <nav id="nav-menu-container"> <ul class="nav-menu"> <li><a href="index.php">Accueil</a></li> <li><a href="restaurant.php">Le restaurant</a> <ul> <li><a href="restaurant.php#teamBistro">L'équipe</a></li> </ul> </li> <li><a href="carriere.php">Carrière</a></li> <li><a href="gallery.php">Galerie photos</a></li> <li><a href="service.php">Service</a></li> <li><a href="contact.php">Contactez-nous</a></li> <?php if ($action->isLoggedIn()){ ?> <li><a href="password.php">Modifier mot de passe</a></li> <li><a href="logout.php">Se déconnecter</a></li> <?php } ?> </ul> </nav><!-- #nav-menu-container --> </div> </div> </header><!-- #header --><file_sep><?php class Connection { private static $connection = null; //https://webmysql.notes-de-cours.com/phpmyadmin/ public static function getConnection() { if (Connection::$connection == null) { Connection::$connection = new PDO("mysql:host=webmysql.notes-de-cours.com;dbname=chunkysoup", "chunkysoup", "AAAaaa111"); Connection::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Connection::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } return Connection::$connection; } }<file_sep><?php require_once("action/DAO/FatherDAO.php"); class UserDAO extends FatherDAO{ public static function authenticate($username, $password) { $user = null; $connection = Connection::getConnection(); $statement = $connection->prepare("SELECT * from users where username = ?"); $statement->bindParam(1, $username); $statement->setFetchMode(PDO::FETCH_ASSOC); $statement->execute(); if ($row = $statement->fetch()) { if (password_verify($password, $row["password"])) { $user = []; $user["username"] = $row["username"]; $user["visibility"] = $row["visibility"]; } } return $user; } public static function newUser($username, $passwors,$visibility){ $connection = Connection::getConnection(); $hash = password_hash($password,PASSWORD_DEFAULT); $statement = $connection->prepare("INSERT INTO `users`(`username`, `password`, `visibility`) VALUES (?,?,?)"); $statement->bindParam(1, $username); $statement->bindParam(2, $hash); $statement->bindParam(3, $visibility); $statement->execute(); } public static function updatePassword($username, $newPassword) { $connection = Connection::getConnection(); $hash = password_hash($newPassword,PASSWORD_DEFAULT); $statement = $connection->prepare("UPDATE `users` SET `password` = ? where `username`=?"); $statement->bindParam(1, $hash); $statement->bindParam(2, $username); $statement->execute(); } }<file_sep><?php require_once("action/CommonAction.php"); require_once("action/DAO/UserDAO.php"); class LoginAction extends CommonAction { public $wrongLogin = false; public $messageSend = false; public $sendingError = false; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { if (isset($_POST["username"])) { $user = UserDAO::authenticate($_POST["username"], $_POST["password"]); if (!empty($user)) { $_SESSION["username"] = $user["username"]; $_SESSION["visibility"] = $user["visibility"]; header("location:index.php"); exit; } else { $this->wrongLogin = true; } } else if(isset($_POST["emailPasswordForgot"]) && $this->messageSend == false){ $emailUser = $_POST["emailPasswordForgot"]; $emailAdmin = '<EMAIL>'; $firstName = $lastName = $text= "DUDE.. come on, sérieux la. What a noob. On va t'envoyer ton mot de passe dans pas long"; $subject= "Cest la periode des fêtes... Attendez que les gars de la TI reviennes de voyage."; $headersUser = 'Mot de passe oublié Bistro le 633'; $messageUser ='From : les gars de la TI du Bistro le 633'.' Subject : '.$subject.' '.$text; $headerAdmin = "Reset de mot de passe"; $messageAdmin = 'Ya un dude qui a oublié son mot de passse'.' Email de la honte: '. $emailUser; if (mail($emailUser, $headersUser, $messageUser) && mail($emailAdmin, $headerAdmin, $messageAdmin)){ $this->messageSend = true; }else{ $this->sendingError = true; } } } } <file_sep><?php require_once("action/CommonAction.php"); require_once("action/DAO/TeamDAO.php"); class RestaurantAction extends CommonAction { public $equipes = []; public $error = []; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { if (isset($_POST["remove"])){ $delete_file = TeamDAO::getFileEquipe($_POST["id"]); unlink($delete_file); TeamDAO::removePersonTeam($_POST["id"]); header("location:restaurant.php#teamBistro"); exit; } else if(isset($_POST["submit"]) && isset($_POST["nom"]) && isset($_POST["poste"]) && isset($_POST["desc"]) && isset($_FILES['image'])){ $extensions= array("jpeg","jpg","png"); $file_name = $_FILES['image']['name']; $file_ext=strtolower(end(explode('.',$file_name))); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } else { $check = getimagesize($_FILES["image"]["tmp_name"]); if($check !== false){ $file_size = $_FILES['image']['size']; $file_tmp = $_FILES['image']['tmp_name']; $file_type = $_FILES['image']['type']; if($file_size > 2097152){ $errors[]='File size must be excately 2 MB'; } if(empty($this->errors)==true){ $compteur = 0; $test = fopen("img/insert/".$compteur.$file_name,'r'); while ($test != FALSE){ $compteur++; $test = fopen("img/insert/".$compteur.$file_name,'r'); } $file = "img/insert/".$compteur.$file_name; move_uploaded_file($file_tmp,$file); TeamDAO::addPersonTeam($_POST["nom"], $_POST["poste"], $_POST["desc"], $file); header("location:restaurant.php#teamBistro"); exit; } } } } else if(isset($_POST["savePerson"]) && isset($_POST["newName"]) && isset($_POST["newPoste"]) && isset($_POST["newDesc"])){ if (isset($_FILES["newImage"])){ $extensions= array("jpeg","jpg","png"); $file_name = $_FILES['newImage']['name']; $file_ext=strtolower(end(explode('.',$file_name))); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } else { $check = getimagesize($_FILES["newImage"]["tmp_name"]); if($check !== false){ $file_size = $_FILES['newImage']['size']; $file_tmp = $_FILES['newImage']['tmp_name']; $file_type = $_FILES['newImage']['type']; if($file_size > 2097152){ $errors[]='File size must be excately 2 MB'; } if(empty($this->errors)==true){ move_uploaded_file($file_tmp,TeamDAO::getFileEquipe($_POST["idItem"])); } } } } TeamDAO::updatePersonTeam($_POST["idItem"], $_POST["newName"], $_POST["newPoste"], $_POST["newDesc"]); header("location:restaurant.php#teamBistro"); exit; } $this->equipes = TeamDAO::getPersonTeam(); } }<file_sep><?php require_once("action/CommonAction.php"); require_once("action/DAO/MealDAO.php"); class IndexAction extends CommonAction { public $repas = []; public $messageSend = false; public $sendingError = false; public function __construct() { parent::__construct(CommonAction::$VISIBILITY_PUBLIC); } protected function executeAction() { if(isset($_POST["firstName"]) && isset($_POST["lastName"]) && isset($_POST["emailReservation"]) && isset($_POST["phone"])&& isset($_POST["dateReservation"]) && isset($_POST["optionReservation"]) && $this->messageSend == false){ $to = '<EMAIL>'; $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $email= $_POST["emailReservation"]; $phone= $_POST["phone"]; $date= $_POST["dateReservation"]; $option= $_POST["optionReservation"]; $headers = 'Reservation au Bistro le 633 pour le '.$date; $message ='From : '.$firstName.' '.$lastName.' Email : '.$email.' Phone : '.$phone.' Date : '.$date.' Option : '.$option; if (mail($to, $headers, $message)){ $this->messageSend = true; }else{ $this->sendingError = true; } } $this->repas = MealDAO::getRepas(); } }<file_sep> -- -------------------------------------------- -- Insertion de données dans la base de donées -- -------------------------------------------- INSERT INTO `users`( `username`, `password`, `visibility`) VALUES ("chunkysoup","AAA<PASSWORD>",1) -- ------------------------- -- Insert Footer -- ------------------------- INSERT INTO `textes` ( --id=1 `texte`) VALUES ("Heure d'ouverture") INSERT INTO `textes` ( --id=2 `texte`) VALUES ("Dimanche - Jeudi 10.00 am - 10.00 pm") INSERT INTO `textes` ( --id=3 `texte`) VALUES ("Vendredi - Samedi 11.30 am - 11.30 pm") INSERT INTO `textes` ( --id=4 `texte`) VALUES ("Contactez-nous") INSERT INTO `textes` ( --id=5 `texte`) VALUES ("633 Rue Shefford, Bromont, Qc, Canada - J2L 2K5") INSERT INTO `textes` ( --id=6 `texte`) VALUES ("(450) 534-0633") INSERT INTO `textes` ( --id=7 `texte`) VALUES ("Infolettre") INSERT INTO `textes` ( --id=8 `texte`) VALUES ("En vous inscrivant à l'infolettre, vous receverez uniquements des offres exclusives.") -- ------------------------- -- Insert page Index -- ------------------------- --Section 1 INSERT INTO `textes` ( --id=9 `texte`) VALUES ("Une expérience inégalable") INSERT INTO `textes` ( --id=10 `texte`) VALUES ("Bistro le 633") INSERT INTO `textes` ( --id=11 `texte`) VALUES ("Un endroit où vous mettez les pieds, et que vous voulez y rester. Ambiance chaleureuse et nourriture qui sait séduire les amateurs de fine gastronomie. Peu nombreux son ceux qui ne tombe pas sous le charme de ce petit restaurant.") INSERT INTO `textes` ( --id=12 `texte`) VALUES ("Consulter le menu gastronomique") --Section 2 INSERT INTO `textes` ( --id=13 `texte`) VALUES ("Un brin d'histoire") INSERT INTO `textes` ( --id=14 `texte`) VALUES ("Situé sur la rue Shefford à Bromont dans une maison des années 1800, le Bistro 633 possède une salle de 80 places qui offre une vue imprenable sur le mont Bromont. Cet endroit est idéal pour vous recevoir des occasions de toutes sortes, tels que des rendez-vous galants, des réunions et des événements corporatifs, en passant par les fêtes de famille, les soirées animées ou autres! Possédant une inventaire de spiritueux composer principalement de Scotch et de Whisky, sans compter l'énorme cave à vin constituer principalement d'importation privée, <NAME> (propriétaire du Bistro 633) a su mettre à profit sa passion, son histoire et ses connaissances afin de faire vivre une expérience inoubliable à chacun des vervants visiteurs de son restaurant.") INSERT INTO `textes` ( --id=15 `texte`) VALUES ("Voir notre équipe") --Section 3 INSERT INTO `textes` ( --id=16 `texte`) VALUES ("Réserver vos places dès aujourd'hui pour une expérience inoubliable.") INSERT INTO `textes` ( --id=17 `texte`) VALUES ("En deux temps trois mouvements, votre réservation sera complété et acheminé dans l'agenda du restaurant. Un message vous sera transmis dans les 48 heures avant la réservation afin de valider votre disponibilité.") --Section 4 INSERT INTO `textes` ( --id=18 `texte`) VALUES ("Galerie de nos réalisations") INSERT INTO `textes` ( --id=19 `texte`) VALUES ("À l'affût des saisons et des goûts de nos consommateurs, notre menu de tapas est modifier réguliairement.") -- ------------------------- -- Insert page Le Restaurant + Equipe -- ------------------------- --Section 1 INSERT INTO `textes` ( --id=20 `texte`) VALUES ("Un brin d'histoire") INSERT INTO `textes` ( --id=21 `texte`) VALUES ("Situé sur la rue Shefford à Bromont dans une maison des années 1800, le Bistro 633 possède une salle de 80 places qui offre une vue imprenable sur le mont Bromont. Cet endroit est idéal pour vous recevoir des occasions de toutes sortes, tels que des rendez-vous galants, des réunions et des évènements corporatives, en passant par les fêtes de famille, les soirées animées ou autres! Possédant une inventaire de spiritueux composer principalement de Scotch et de Wisky, sans compter l'énorme cave à vin constituer principalement d'importation privée, <NAME> (propriétaire du Bistro 633) a su mettre à profit sa passion, son histoire et ses connaissances afin de faire vivre une expérience inoubliable à chacun des vervants visiteurs de son resturant.") --Section 2 INSERT INTO `textes` ( --id=22 `texte`) VALUES ("Quel sont les types de service que nous offrons?") INSERT INTO `textes` ( --id=23 `texte`) VALUES ("Notre vaste variété de service un peu plus personnalisé les uns que les autres sauront vous charmer et combler vos attentes, et ce, peu importe le type d’activité ou d’évènement que vous tentez de réaliser. Bref, vous aurez droit à un évènement sans égale, que vous ne pourrez pas reproduire nulle part ailleurs.") --Section 3 INSERT INTO `textes` ( --id=24 `texte`) VALUES ("Service à table") INSERT INTO `textes` ( --id=25 `texte`) VALUES ("inappropriate behavior is often laughed off as “boys will be boys,” women face higher conduct women face higher conduct.") --Section 4 INSERT INTO `textes` ( --id=26 `texte`) VALUES ("Service évènementiel") INSERT INTO `textes` ( --id=27 `texte`) VALUES ("inappropriate behavior is often laughed off as “boys will be boys,” women face higher conduct women face higher conduct.") --Section 5 INSERT INTO `textes` ( --id=28 `texte`) VALUES ("Notre équipe") INSERT INTO `textes` ( --id=29 `texte`) VALUES ("Certains nous conscidèrent comme étant une famille ayant les liens tissé sérer, d'autres pensent que nous sommes une équipe à l'épreuve de tous défis. Cependant, lorsque nous définissons qui nous sommes, nous réalisons que nous sommes les deux.") -- ------------------------- -- Insert page Carriere -- ------------------------- INSERT INTO `textes` ( --id=30 `texte`) VALUES ("Venez rejoindre l'équipe du Bistro le 633") INSERT INTO `textes` ( --id=31 `texte`) VALUES ("Venir travaillez chez nous c'est accepter de ce lever chaque matin pour venir s'amuser afin de partager sa joie et sa passion pour la cuisine raffiner. Plusieurs de nos travailleurs sont venu joindre nos rangs afin d'y rester pour une courte durée, mais lorsqu'ils ont vu la chimie et l'esprit amicale et famillial de notre restaurant, ils ont tous décider d'y rester") -- ------------------------- -- Insert page Galerie photo -- ------------------------- INSERT INTO `textes` ( --id=32 `texte`) VALUES ("Galerie de nos réalisations") INSERT INTO `textes` ( --id=33 `texte`) VALUES ("À l'affût des saisons et des goûts de nos consommateurs, notre menu de tapas est modifier réguliairement.") -- ------------------------- -- Insert page Galerie photo -- ------------------------- --Section 1 INSERT INTO `textes` ( --id=34 `texte`) VALUES ("Service traiteur") INSERT INTO `textes` ( --id=35 `texte`) VALUES ("Bistro le 633 vous offre la possibilité de commander sous forme de traiteur une multitude de variétés de repas, de tapas et d'entrées du menu. Le restaurant offre la possibilité de commander du service traiteur, afin de réaliser des évènements inégalable chez vous ou ailleurs. Ce service vous permettera donc de commander votre menu gastronomique préférer dans la chaleur et le copmfort de votre maison. Si vous rétissez à commander du service traiteur, vous remarquerez que celui du Bistro 633 n'est pas comparable celui à de null part ailleurs.") --Section 2 INSERT INTO `textes` ( --id=36 `texte`) VALUES ("Évènements spéciaux") INSERT INTO `textes` ( --id=37 `texte`) VALUES ("Présentement en train d'organiser un évènement spécial telqu'un mariage ou un évènement de grand envergure? Le Bistro le 633 se fera un grand plaisir de vous aider à la réalisation de celui-ci. Tout dépendandament la saison, il sera possible d'acceuil un grand nomhbre de personne à l'intérieur, ou à l'extérieur du restaurant. Tous trouveront leur comble et leur bonheur. Sans pouvoir le garantir, nous vous garantissons un évèenement réussi avec du plaisir et de la joie.") --Section 3 INSERT INTO `textes` ( --id=38 `texte`) VALUES ("Souper entre amis et corporatif") INSERT INTO `textes` ( --id=39 `texte`) VALUES ("Avec son ambiance festive, Bistro le 633 est la place parfaite pour pour avoir une soirée inoubliable avce vos collègues de travail, ou encore mêmes vos amis. Réserver d'avance à la venu de groupe de grandes tailles, et réserver un mois à l'avance pour les groupes de plus petites tailes. Dans les périodes estivales, le Bistro le 633 est très prisé pour sa qualiter de service et de nourriture.") --Section 4 INSERT INTO `textes` ( --id=40 `texte`) VALUES ("Dégustation de spiritueux") INSERT INTO `textes` ( --id=41 `texte`) VALUES ("Ayant réaliser plusieurs voyages en Écosse, en Angletterre et en Irlande, <NAME> s'est découvert une passion pour le Whiskey, plus précisément le Scotch. Il est possible de constater l'amour du Whiskey que <NAME> a en comptant le nombre de bouteilles dans son restaurant. Pour transmettre sa passion, ce dernier effectue de nombreuses évènements environ une fois par mois pour faire une dégustation de ses coups de coeurs. Faites attention! Les places de ces évènements s'envolle d'ailleurs comme des petits pains chaud. ") INSERT INTO `textes` ( --id=42 `texte`) VALUES ("Il est possible d'effectuer une dégustation de Whiskey à n'importe quel moment, mais les bouteilles secrètent de Luc ne sortiront pas du placard.") --Section 5 INSERT INTO `textes` ( --id=43 `texte`) VALUES ("Dégustation de vin") INSERT INTO `textes` ( --id=44 `texte`) VALUES ("La passion de Luc ne s'arrête pas seulement qu'à la nourriture et qu'au Whisky. Effectivement, <NAME> est également un grand amamteur de vin provenant du Portugal, de la France, de l'Italy ainsi que de l'Espagne. Écoutant les intérêts de ses clients ainsi que sa passion, <NAME> modernise et raffine sa cave à vin quelques fois par année. Pour une soirée entre amoureux le Samedi soir ou pour une soirée du Dimanche soir, le Bsitro 633 aura la consommation parfaite pour s'armonier avec votre repas et pour style l'occasion. Possédant une cave à vin principalement constituer d'importation privée, <NAME> organise des soirées de dégustation de vin pour ceux qui veulent découvrir les secrets cachés de la cave à vin du Bistro le 633.") -- ------------------------- -- Insert page Galerie photo -- ------------------------- INSERT INTO `textes` ( --id=45 `texte`) VALUES ("Bromont, Québec") INSERT INTO `textes` ( --id=46 `texte`) VALUES ("633 Rue Shefford, QC J2L 2K5") INSERT INTO `textes` ( --id=47 `texte`) VALUES ("(450) 534-0633") INSERT INTO `textes` ( --id=48 `texte`) VALUES ("Appelez-nous sur nos heures d'ouverture et il nous fera un plaisir de vous répondre.") INSERT INTO `textes` ( --id=49 `texte`) VALUES ("<EMAIL>") INSERT INTO `textes` ( --id=50 `texte`) VALUES ("Si vous avez une question ou de l'intérêt dans nos services et nos produits, communiquer nous à n'importe quel moment!")<file_sep><?php require_once("action/DAO/FatherDAO.php"); class TeamDAO extends FatherDAO{ public static function updatePersonTeam($id, $newName, $newPoste, $newDesc) { $connection = Connection::getConnection(); $result = $connection->prepare("SELECT `description` FROM `equipes` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); $idDescription = $result->fetch()[0]; $statementDesc = $connection->prepare("UPDATE `textes` SET `texte`=? WHERE id=?"); $statementDesc->bindParam(1, $newDesc); $statementDesc->bindParam(2, $idDescription); $statementDesc->execute(); $statementNom = $connection->prepare("UPDATE `equipes` SET `nom`=?, `poste`=? where `id`=?"); $statementNom->bindParam(1, $newName); $statementNom->bindParam(2, $newPoste); $statementNom->bindParam(3, $id); $statementNom->execute(); } public static function addPersonTeam($nom, $poste, $description, $image){ $connection = Connection::getConnection(); $statement = $connection->prepare("INSERT INTO `textes` (`texte`) VALUES(?)"); $statement->bindParam(1, $description); $statement->execute(); $result = $connection->query("SELECT LAST_INSERT_ID()"); $idDesc = $result->fetch()[0]; $statement = $connection->prepare("INSERT INTO `equipes` (`nom`,`poste`, `description`,`image`) VALUES (?,?,?,?)"); $statement->bindParam(1, $nom); $statement->bindParam(2, $poste); $statement->bindParam(3, $idDesc); $statement->bindParam(4, $image); $statement->execute(); } public static function getPersonTeam(){ $equipes = []; $connection = Connection::getConnection(); $result = $connection->query("SELECT `id`,`nom`,`poste`, `description`,`image` FROM `equipes`"); while($row = $result->fetch()) { $texte = TeamDAO::getTexte($row["description"]); array_push($equipes, [$row["id"],$row["nom"],$row["poste"], $texte,$row["image"]]); } return $equipes; } public static function removePersonTeam($id){ $connection = Connection::getConnection(); $result = $connection->prepare("SELECT `description` FROM `equipes` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); $idDescription = $result->fetch()[0]; $statement = $connection->prepare("DELETE FROM textes WHERE id=?"); $statement->bindParam(1, $idDescription); $statement->execute(); $statement = $connection->prepare("DELETE FROM equipes WHERE id=?"); $statement->bindParam(1, $id); $statement->execute(); } public static function getFileEquipe($id){ $connection = Connection::getConnection(); $statement = $connection->prepare("SELECT `image` FROM `equipes` WHERE `id`=?"); $statement->bindParam(1, $id); $statement->execute(); $image = $statement->fetch()[0]; return $image; } }<file_sep><?php require_once("action/DAO/FatherDAO.php"); class MealDAO extends FatherDAO{ public static function updateRepas($id, $newName, $newDesc) { $connection = Connection::getConnection(); $result = $connection->prepare("SELECT `description` FROM `repas` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); $idDescription = $result->fetch()[0]; $statementDesc = $connection->prepare("UPDATE `textes` SET `texte`=? WHERE id=?"); $statementDesc->bindParam(1, $newDesc); $statementDesc->bindParam(2, $idDescription); $statementDesc->execute(); $statementNom = $connection->prepare("UPDATE `repas` SET `nom`=? where `id`=?"); $statementNom->bindParam(1, $newName); $statementNom->bindParam(2, $id); $statementNom->execute(); } public static function addRepas($nom, $group, $description, $image){ $connection = Connection::getConnection(); $statement = $connection->prepare("INSERT INTO `textes` (`texte`) VALUES(?)"); $statement->bindParam(1, $description); $statement->execute(); $result = $connection->query("SELECT LAST_INSERT_ID()"); $idDesc = $result->fetch()[0]; $statement = $connection->prepare("INSERT INTO `repas` (`nom`,`group`,`description`,`image`) VALUES (?,?,?,?)"); $statement->bindParam(1, $nom); $statement->bindParam(2, $group); $statement->bindParam(3, $idDesc); $statement->bindParam(4, $image); $statement->execute(); } public static function getRepas(){ $repas = []; $connection = Connection::getConnection(); $result = $connection->query("SELECT `id`,`nom`,`group`,`description`,`image` FROM `repas`"); while($row = $result->fetch()) { $texte = MealDAO::getTexte($row["description"]); array_push($repas, [$row["id"],$row["nom"],$row["group"], $texte, $row["image"]]); } return $repas; } public static function removeRepas($id){ $connection = Connection::getConnection(); $result = $connection->prepare("SELECT `description` FROM `repas` WHERE `id`=?"); $result->bindParam(1, $id); $result->execute(); $idDescription = $result->fetch()[0]; $statement = $connection->prepare("DELETE FROM textes WHERE id=?"); $statement->bindParam(1, $idDescription); $statement->execute(); $statement = $connection->prepare("DELETE FROM repas WHERE id=?"); $statement->bindParam(1, $id); $statement->execute(); } public static function getFileRepas($id){ $connection = Connection::getConnection(); $statement = $connection->prepare("SELECT `image` FROM `repas` WHERE `id`=?"); $statement->bindParam(1, $id); $statement->execute(); $image = $statement->fetch()[0]; return $image; } }
a761efc9372687323a2a03e2dc31610a2b16ad62
[ "JavaScript", "SQL", "Text", "PHP" ]
33
SQL
CLaganiere/DKConcept
f7a87b0acbbcbec9fcde20c5ac0b79335d20318a
4d191ebb359fa878704a0cdda082e3b757532501
refs/heads/master
<repo_name>KaziooWielki/CI-projekt<file_sep>/src/accept/test.sh actualsize=$(wc -c <"../../target/classes/org/mindrot/BCrypt.class") if [ $actualsize -eq 21585 ]; then echo correct size exit 0 else echo size is incorrect: $actualsize exit 1 fi
c9074af4487c46fe1ddaaa3e4950475b8b1e09a2
[ "Shell" ]
1
Shell
KaziooWielki/CI-projekt
72ce57925162d18a5c0b198e29618bf087a327a0
8a63abab0738433772afab2f8483065a00d2addf
refs/heads/master
<file_sep>import { Component } from "@angular/core"; import {LoggedInService} from './logged-in.service'; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"], }) export class AppComponent { title = "RecipeWeb"; loggedIn; constructor(loggedInCheck: LoggedInService ) { loggedInCheck.loggedIn.subscribe(loggedIn => this.loggedIn = loggedIn); } } <file_sep>import { Component, OnInit } from "@angular/core"; import { MatSnackBar } from "@angular/material/snack-bar"; import { RecipeService } from "../recipe.service"; import { UserService } from "../user.service"; @Component({ selector: "app-home", templateUrl: "./home.component.html", styleUrls: ["./home.component.css"], }) export class HomeComponent implements OnInit { userFName; randomRecipes: any[]; constructor( private _userService: UserService, private _recipeService: RecipeService, private snackBar: MatSnackBar ) { if (localStorage.getItem("token") === null) { window.location.href = "/Login"; } } ngOnInit(): void { this._userService.info(localStorage.getItem("token")).subscribe((res) => { if (res.Result === "Success") { localStorage.setItem("fName", res.Message.Info.FirstName); localStorage.setItem("userName", res.Message.Info.Username); this.userFName = res.Message.Info.FirstName; } else { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } }); this._recipeService .getRandomRecipes(localStorage.getItem("token")) .subscribe((res) => { if (res.Result === "Success") { this.randomRecipes = res.Message; } }); } saveRecipe(recipeId, recipeName, recipeSummary) { this._userService .addRecipe( localStorage.getItem("token"), recipeId, recipeName, recipeSummary, "" ) .subscribe((res) => { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); }); } } <file_sep>const path = require('path') require('dotenv').config({ path: path.resolve(__dirname, '../../.env') }) const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize(process.env.DBString); /** * The model representing the CustomRecipes table in the database. * @model * @property {Number} id - The id of the recipe. * @property {Number} UserId - The username of the user. * @property {String} RecipeName - The name of the custom recipe. * @property {String} RecipeIngredients - The ingredients of the custom recipe. * @property {String} RecipeInstructions - The instructions of the custom recipe. * @property {String} RecipeSummary - The summary of the custom recipe. * @property {String} RecipeComments - The comments of the custom recipe. */ const CustomRecipes = sequelize.define('CustomRecipes', { // Model attributes are defined here id: { type: DataTypes.INTEGER, primaryKey: true }, UserId: { type: DataTypes.INTEGER, allowNull: false }, RecipeName: { type: DataTypes.STRING, }, RecipeIngredients: { type: DataTypes.STRING, }, RecipeInstructions: { type: DataTypes.STRING, }, RecipeSummary: { type: DataTypes.STRING }, RecipeComments: { type: DataTypes.STRING } }, { timestamps: false, tableName: 'CustomRecipes' }); module.exports = CustomRecipes;<file_sep>const { query } = require('express'); const external = require('../Config/External'); var recipeFunctions = { /** * Gets 20 recipes by ingredients string. * @function * @param {String} token - The token given by the user. * @param {String} searchQuery - The search query. */ async GetRecipeByIngredients(token, searchQuery) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.api.getRecipeByIngredients(searchQuery) } else { return { Result: "Error", Message: "Invalid User" } } }, /** * Gets 20 recipes by name. * @function * @param {String} token - The token given by the user. * @param {String} searchQuery - The search query. */ async GetRecipeByName(token, searchQuery) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.api.getRecipeByName(searchQuery) } else { return { Result: "Error", Message: "Invalid User" } } }, /** * Gets recipe by id. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The id of the recipe. */ async GetRecipeById(token, recipeId) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.api.getRecipeById(recipeId) } else { return { Result: "Error", Message: "Invalid User" } } }, /** * Gets 5 random recipes. * @function * @param {String} token - The token given by the user. */ async GetRandomRecipes(token) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.api.getRandomRecipes() } else { return { Result: "Error", Message: "Invalid User" } } }, /** * Send an email when the user finds a ingredient missing. * @function * @param {String} token - The token given by the user. * @param {String} ingredient - The missing ingredient. * @param {String} username - The username of the user * @param {String} firstName - the first name of the user. */ async MissingIngredient(token, ingredient, username, firstName){ var isValid = await external.auth.isValidUser(token); if (isValid) { return external.email.AddSuggestion(ingredient,firstName, username) } else { return { Result: "Error", Message: "Invalid User" } } }, /** * Gets all ingredients for the table. * @function * @param {String} token - The token given by the user. */ async GetIngredients(token){ var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.getIngredients() } else { return { Result: "Error", Message: "Invalid User" } } } } module.exports = recipeFunctions;<file_sep>var hash = require('object-hash'); var jwt = require("jsonwebtoken"); const path = require('path'); require('dotenv').config({ path: path.resolve(__dirname, '../.env') }); var secret = process.env.SECRET; var db = require('./JawsDbConnection'); var securityFunctions = { /** * Hashes the password. * @function * @param {String} password - The plain password of the user. */ hasher(password) { return hash({ Password: password }) }, /** * Generates a JWT token with the userId, password, and username. * @function * @param {Number} userId - The username of the user. * @param {String} username - The username of the user. * @param {String} password - The plain <PASSWORD> of the user. */ genJWTCode(userId, username, password) { var hashpass = this.hasher(password); var token = jwt.sign({ "UserId": userId, "Username": username, "Password": <PASSWORD> }, secret) return token; }, /** * Gets the Id from the token. * @function * @param {String} token - The token given by the user. */ getIdFromToken(token) { try { var decoded = jwt.verify(token, secret); } catch{ return { Result: "Error", Message: "Invalid User" } } return decoded.UserId }, /** * Checks if token is for a valid user. * @function * @param {String} token - The token given by the user. */ async isValidUser(token) { try { var decoded = jwt.verify(token, secret); } catch{ return false; } var validUser = await db.isUser(decoded.Username, decoded.Password) return validUser; } }; module.exports = securityFunctions;<file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class LoggedInService { private _loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public loggedIn: Observable<boolean> = this._loggedIn.asObservable(); constructor() { this._loggedIn.next(localStorage.getItem('token') != null) } logOut(){ this._loggedIn.next(false); } logIn(){ this._loggedIn.next(true); } isLoggedIn(){ return this.loggedIn; } } <file_sep>import { Injectable } from "@angular/core"; import { HttpClient, HttpErrorResponse, HttpHeaders, } from "@angular/common/http"; import { throwError, Observable } from "rxjs"; import { catchError } from "rxjs/operators"; @Injectable() export class UserService { private baseUrl = "http://recipeserver.jasondesigns.net/"; //private baseUrl = "http://localhost:8000/"; private httpOptions(token) { if (token) { return { headers: new HttpHeaders({ "Content-Type": "application/json", token, }), }; } return { headers: new HttpHeaders({ "Content-Type": "application/json", }), }; } constructor(private http: HttpClient) {} login(username, password): Observable<any> { const data = this.http .post<any>( this.baseUrl + "login", { username, password, }, this.httpOptions(null) ) .pipe(catchError(this.catcher)); return data; } signup(firstName, username, password): Observable<any> { const data = this.http .post<any>( this.baseUrl + "signup", { firstName, username, password, }, this.httpOptions(null) ) .pipe(catchError(this.catcher)); return data; } info(token): Observable<any> { const data = this.http .get(this.baseUrl + "info", this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } addRecipe( token, recipeId, recipeName, recipeSummary, recipeComments ): Observable<any> { const data = this.http .post<any>( this.baseUrl + "saved", { recipeId, recipeName, recipeSummary, recipeComments, }, this.httpOptions(token) ) .pipe(catchError(this.catcher)); return data; } editRecipeComments(token, recipeId, recipeComments): Observable<any> { const data = this.http .put<any>( this.baseUrl + "saved", { recipeId, recipeComments, }, this.httpOptions(token) ) .pipe(catchError(this.catcher)); return data; } deleteRecipe(token, recipeId): Observable<any> { const data = this.http .delete(this.baseUrl + "saved/" + recipeId, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } getCustomRecipe(token, recipeId): Observable<any> { const data = this.http .get(this.baseUrl + "custom/" + recipeId, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } addCustomRecipe( token, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments ): Observable<any> { const data = this.http .post<any>( this.baseUrl + "custom", { recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments }, this.httpOptions(token) ) .pipe(catchError(this.catcher)); return data; } editCustomRecipe( token, recipeId, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments, ): Observable<any> { const data = this.http .put<any>( this.baseUrl + "custom", { recipeId, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments, }, this.httpOptions(token) ) .pipe(catchError(this.catcher)); return data; } deleteCustomRecipe(token, recipeId): Observable<any> { const data = this.http .delete(this.baseUrl + "custom/" + recipeId, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } forgotPassword(firstName, username, suggestedPassword): Observable<any> { const data = this.http .post<any>( this.baseUrl + "forgot", { firstName, username, suggestedPassword, }, this.httpOptions(null) ) .pipe(catchError(this.catcher)); return data; } updateImage(token, image, customRecipeId): Observable<any> { const data = this.http .put<any>( this.baseUrl + "image", { image, customRecipeId }, this.httpOptions(token) ) .pipe(catchError(this.catcher)); return data; } removeImage(token, customRecipeId): Observable<any> { const data = this.http .delete(this.baseUrl + "image/" + customRecipeId, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } getImage(token, customRecipeId): Observable<any>{ const data = this.http.get(this.baseUrl + "image/" + customRecipeId, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } catcher(error: HttpErrorResponse) { console.log(error.message); return throwError(error.message || "Service Error"); } } <file_sep>const external = require("../Config/External"); var userFunctions = { /** * Signs the user up with a hashed password, username, and first name and sends back the JWT token. It also lets the admin know that there is a new user. * @function * @param {String} firstName - The first name of the user. * @param {String} username - The username of the user. * @param {String} password - The <PASSWORD>. */ async SignUp(firstName, username, password) { var hashedPassword = external.auth.hasher(password); var signUpStatus = await external.db.signup( firstName, username, hashedPassword ); if (signUpStatus.Result == "Success") { external.email.NewUser(firstName, username); var token = external.auth.genJWTCode( signUpStatus.UserId, username, password ); return { Result: "Success", Token: token }; } else { return { Result: "Error", Message: signUpStatus.Message }; } }, /** * Checks if it's a user and if the password and login is valid and sends back the JWT token. * @function * @param {String} username - The username of the user. * @param {String} password - The <PASSWORD>. */ async Login(username, password) { var hashedPassword = external.auth.hasher(password); var loginStatus = await external.db.login(username, hashedPassword); if (loginStatus.Result == "Success") { var token = external.auth.genJWTCode( loginStatus.UserId, username, password ); return { Result: "Success", Token: token }; } else { return { Result: "Error", Message: loginStatus.Message }; } }, /** * Checks if token is for a valid user and if so, send back the user information and saved recipes. * @function * @param {String} token - The token given by the user. */ async Info(token) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.getInfo(external.auth.getIdFromToken(token)); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * Checks if token is for a valid user and if so, adds the recipe to the SavedRecipe table. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The id of the recipe being added. * @param {String} recipeName - The name of the recipe being added. * @param {String} recipeSummary - The summary of the recipe being added. * @param {String} recipeComments - The comments to the recipe being added. */ async AddRecipe(token, recipeName, recipeId, recipeSummary, recipeComments) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.addRecipe( external.auth.getIdFromToken(token), recipeId, recipeName, recipeSummary, recipeComments ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * If the recipe isn't already deleted, this deletes the recipe from the user list as long as the user is valid.. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The id of the recipe being deleted. */ async DeleteRecipe(token, recipeId) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.deleteRecipe( external.auth.getIdFromToken(token), recipeId ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * If the user is valid, this edits their comments on the recipe. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The id of the recipe being deleted. * @param {String} comments - the new comments for the recipe */ async EditRecipe(token, recipeId, comments) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.editRecipeComment( external.auth.getIdFromToken(token), recipeId, comments ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * Checks if token is for a valid user and if so, gets the specific custom recipe. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The name of the recipe being added. */ async GetCustomRecipe(token, recipeId) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.getUserCustomRecipe( external.auth.getIdFromToken(token), recipeId ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * Checks if token is for a valid user and if so, adds the recipe to the CustomRecipes table. * @function * @param {String} token - The token given by the user. * @param {String} recipeName - The name of the recipe being added. * @param {String} recipeIngredients - The ingredients of the recipe being added. * @param {String} recipeInstructions - The instructions of the recipe being added. * @param {String} recipeSummary - The summary of the recipe being added. * @param {String} recipeComments - The comments to the recipe being added. */ async AddCustomRecipe( token, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments, ) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.addCustomRecipe( external.auth.getIdFromToken(token), recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * Checks if token is for a valid user and if so, edit the recipe in the CustomRecipes table. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The id of the recipe * @param {String} recipeName - The name of the recipe being added. * @param {String} recipeSummary - The summary of the recipe being added. * @param {String} recipeIngredients - The ingredients of the recipe being added. * @param {String} recipeInstructions - The instructions of the recipe being added. * @param {String} recipeComments - The comments to the recipe being added. */ async EditCustomRecipe( token, recipeId, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments, ) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.editCustomRecipe( external.auth.getIdFromToken(token), recipeId, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * If the recipe isn't already deleted, this deletes the recipe from the user custom recipe list as long as the user is valid.. * @function * @param {String} token - The token given by the user. * @param {Number} recipeId - The id of the recipe being deleted. */ async DeleteCustomRecipe(token, recipeId) { var isValid = await external.auth.isValidUser(token); if (isValid) { return external.db.deleteCustomRecipe( external.auth.getIdFromToken(token), recipeId ); } else { return { Result: "Error", Message: "Invalid User" }; } }, /** * Sends an email when a user wants to change their password. * @function * @param {String} firstName - The first name of the user. * @param {String} username - The username of the user. * @param {String} suggestedPassword - The suggested password of the user. */ async ForgetPassword(firstName, username, suggestedPassword) { var emailStatus = await external.email.ForgetPassword( firstName, username, suggestedPassword ); console.log(emailStatus); return emailStatus; }, }; module.exports = userFunctions; <file_sep>const path = require('path'); require('dotenv').config({ path: path.resolve(__dirname, '../.env') }); const baseUrl = "https://api.spoonacular.com/recipes/"; const axios = require('axios').default; const apiKey = process.env.SpoonApiKey; const db = require('./JawsDbConnection'); const { api } = require('./External'); /** * Gets recipe information from the api using the recipeId. * @function * @param {Number} recipeId - The id of the recipe. */ function getRecipeInformation(recipeId) { return new Promise(function (resolve) { axios.get(baseUrl + recipeId + "/information?apiKey=" + apiKey + "&includeNutrition=false").then( (res) => { if (res.data) { resolve({ Result: "Success", Message: res.data }) } }, err => { resolve({ Result: "Error", Message: "No recipes found, incorrect id: " + recipeId }) }) }) } /** * Admin Only, Gets the ingredient from autocomplete from searchQuery, using api and adds it to the db if not there aleady. * @function * @param {Number} ingredient - The ingredient. */ function missingIngredient(ingredient) { return new Promise(function (resolve) { axios.get("https://api.spoonacular.com/food/ingredients/autocomplete?apiKey=" + apiKey + "&query=" + ingredient + "&number=20").then( (res) => { for (let ingredient of res.data) { console.log(ingredient) db.addIngredient(ingredient.name) } }, err => { resolve({ Result: "Error", Message: err }) }) }) } var apiFunctions = { /** * Gets 20 recipes from the api, searching by the searchQuery. * @function * @param {String} searchQuery - The Search Query. */ getRecipeByName(searchQuery) { return new Promise(function (resolve) { axios.get(baseUrl + "complexSearch?apiKey=" + apiKey + "&query=" + searchQuery + "&instructionsRequired=true&number=20").then( (res) => { if (res.data.results.length > 0) { resolve({ Result: "Success", Message: res.data.results }) } else { resolve({ Result: "Error", Message: "No recipes found, try a different search term" }) } }, err => { resolve({ Result: "Error", Message: err }) }) }) }, /** * Gets 20 recipes from the api, searching by the ingredients. * @function * @param {String} searchQuery - The Search Query, string of ingredients. */ getRecipeByIngredients(searchQuery) { return new Promise(function (resolve) { axios.get(baseUrl + "findByIngredients?apiKey=" + apiKey + "&ingredients=" + searchQuery + "&number=20").then( (res) => { if (res.data.length > 0) { resolve({ Result: "Success", Message: res.data }) } else { resolve({ Result: "Error", Message: "No recipes found, try a different set of ingredients" }) } }, err => { resolve({ Result: "Error", Message: err }) }) }) }, /** * Gets 5 random recipes. * @function */ getRandomRecipes() { return new Promise(function (resolve) { axios.get(baseUrl + "random?apiKey=" + apiKey + "&number=5").then( (res) => { if (res.data.recipes.length > 0) { resolve({ Result: "Success", Message: res.data.recipes }) } else { resolve({ Result: "Error", Message: "Error getting random recipes" }) } }, err => { resolve({ Result: "Error", Message: err }) }) }) }, /** * Gets the recipe from getRecipeinformation() and getRecipeInstructions() using the recipeId. * @function * @param {Number} recipeId - The id of the recipe. */ async getRecipeById(recipeId) { var info = await getRecipeInformation(recipeId); if (info.Result == "Success") { return { Result: "Success", Message: { Info: info.Message, } } } else { return { Result: "Error", Message: { Info: info.Message, } } } } }; module.exports = apiFunctions; // async function tester() { // var test = await apiFunctions.getRandomRecipes() // console.log(test) // } // tester() <file_sep>import { Component, OnInit, ViewChild } from "@angular/core"; import { MatSnackBar } from "@angular/material/snack-bar"; import { RecipeService } from "../recipe.service"; import { FormControl } from "@angular/forms"; import { UserService } from "../user.service"; import { MatPaginator } from "@angular/material/paginator"; import { MatSort } from "@angular/material/sort"; import { MatTableDataSource } from "@angular/material/table"; import { MatDialog } from "@angular/material/dialog"; import { MissingIngredientDialogComponent } from "./missing-ingredient-dialog/missing-ingredient-dialog.component"; export interface IngredientData { id: number; name: string; checked: boolean; } @Component({ selector: "app-search-recipes", templateUrl: "./search-recipes.component.html", styleUrls: ["./search-recipes.component.css"], }) export class SearchRecipesComponent implements OnInit { recipeNameQuery = new FormControl("", { updateOn: "change" }); displayedColumns: string[] = ["name", "select"]; dataSource: MatTableDataSource<IngredientData>; selectedIngredients: IngredientData[] = []; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; ingredients; recipes; constructor( private _recipeService: RecipeService, private snackBar: MatSnackBar, private _userService: UserService, private dialog: MatDialog ) {} ngOnInit(): void { this._recipeService .getIngredients(localStorage.getItem("token")) .subscribe((res) => { if(res.Result === "Success"){ this.dataSource = new MatTableDataSource( res.Message.map((x) => ({ id: x.id, name: x.Name, checked: false })) ); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } else{ this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } }); } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } missingIngredient() { const dialogRef = this.dialog.open(MissingIngredientDialogComponent, { width: "500px", }); dialogRef.afterClosed().subscribe((response) => { console.log(response); if (response.isSent) { this._recipeService .missingIngredient( localStorage.getItem("token"), response.ingredients, localStorage.getItem("userName"), localStorage.getItem("fName") ) .subscribe((res) => { if (res) { res.Result === "Success" ? this.snackBar.open(res.Message, "", { duration: 3000 }) : this.snackBar.open( "Error sending email, check console for more...", "", { duration: 3000 } ); console.log(res.Message); } }); } }); } searchByRecipeName() { this.recipes = []; this._recipeService .getRecipesByName( localStorage.getItem("token"), this.recipeNameQuery.value ) .subscribe((res) => { if (res.Result === "Success") { this.recipes = res.Message; } else { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } }); } searchByIngredients() { this.recipes = []; this._recipeService .getRecipesByIngredients( localStorage.getItem("token"), this.selectedIngredients.map((x) => x.name).toString() ) .subscribe((res) => { if (res.Result === "Success") { this.recipes = res.Message; } else { this.snackBar.open(res.Message.Info, "", { duration: 3000 }); console.log(res.Message); } }); } selectIngredient(ingredient: IngredientData, add: boolean) { if (add) { this.selectedIngredients.push(ingredient); } else { this.selectedIngredients = this.selectedIngredients.filter( (x) => x !== ingredient ); } } isRowSelected(row: IngredientData): boolean { const existingFormControl = this.selectedIngredients.find( (c) => c.id === row.id ); return existingFormControl !== undefined; } removeFromSelectedIngredients(ingredient: IngredientData) { this.selectedIngredients = this.selectedIngredients.filter( (x) => x !== ingredient ); } saveRecipe(recipeId, recipeName, recipeSummary) { this._userService .addRecipe( localStorage.getItem("token"), recipeId, recipeName, recipeSummary, "" ) .subscribe((res) => { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); }); } } <file_sep>const path = require('path'); require('dotenv').config({ path: path.resolve(__dirname, '../.env') }); var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ host: process.env.Host, port: process.env.Port, secure: false, auth: { user: process.env.Email, pass: process.env.Pass } }); var emailFunctions = { /** * When the password is forgotten, this function is called to email the admin (me) to change it. * @function * @param {String} firstName - The first name of the user. * @param {String} username - The username of the user. * @param {String} suggPassword - The suggested password. */ ForgetPassword(firstName, username, suggPassword) { return new Promise(function (resolve) { const mailOptions = { from: process.env.FromEmail, // sender address to: process.env.ToEmail, // list of receivers subject: 'Forgotten Password', // Subject line html: `<h2>${firstName} has forgetten their password and needs it to be reset, Their username is ${username}.</h2><br><h3>They recommend this to be their new password to be: ${suggPassword}</h3>` } transporter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err) resolve({ Result: "Error", Message: "Error sending mail: " + err }) } else { console.log(info); resolve({ Result: "Success", Message: "Email sent" }) } }); }) }, /** * When a new user is added, this notifies me of them being added. * @function * @param {String} firstName - The first name of the user. * @param {String} username - The username of the user. */ NewUser(firstName, username) { const mailOptions = { from: process.env.FromEmail, // sender address to: process.env.ToEmail, // list of receivers subject: 'New User', // Subject line html: `<h2>${firstName} is a new user, Their username is ${username}.</h2>` } transporter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err) } else { console.log(info); } }); }, /** * When a user find a ingredient that needs to be added. * @function * @param {String} ingredientName - The ingredient missing. * @param {String} firstName - The first name of the user. */ AddSuggestion(ingredientName, firstName, username) { return new Promise(function (resolve) { const mailOptions = { from: process.env.FromEmail, // sender address to: process.env.ToEmail, // list of receivers subject: 'Missing Ingredient', // Subject line html: `<h2>${firstName}, username being ${username}, noticed that an ingredient is missing, The ingredient is ${ingredientName}.</h2>` } transporter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err) resolve({ Result: "Error", Message: "Error sending mail: " + err }) } else { console.log(info); resolve({ Result: "Success", Message: "Email sent" }) } }); }) } }; module.exports = emailFunctions; // async function tester(){ // var test = await emailFunctions.AddSuggestion("Test", "Jason", "jasondamion20"); // console.log(test); // } // tester();<file_sep>import { Component, OnInit } from "@angular/core"; import { FormControl } from "@angular/forms"; import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from "@angular/material/snack-bar"; import { Router } from '@angular/router'; import { UserService } from "../user.service"; import { AddCustomComponent } from './add-custom/add-custom.component'; @Component({ selector: "app-personal-recipes", templateUrl: "./personal-recipes.component.html", styleUrls: ["./personal-recipes.component.css"], }) export class PersonalRecipesComponent implements OnInit { recipeNameFilter = new FormControl("", { updateOn: "change" }); initialSavedRecipes: any[] = []; customNameFilter = new FormControl("", { updateOn: "change" }); initialCustomRecipes: any[] = []; savedRecipes: any[] = []; customRecipes: any[] = []; isRecipeEmpty = false; isCustomEmpty = false; constructor( private _userService: UserService, private snackBar: MatSnackBar, private dialog: MatDialog, private router: Router ) {} ngOnInit(): void { this._userService.info(localStorage.getItem("token")).subscribe((res) => { if (typeof res.Message.SavedRecipes === "string") { this.isRecipeEmpty = true; this.snackBar.open(res.Message.SavedRecipes, "", { duration: 3000 }); } else { this.initialSavedRecipes = this.savedRecipes = res.Message.SavedRecipes; } }); this._userService.info(localStorage.getItem("token")).subscribe((res) => { if (typeof res.Message.CustomRecipes === "string") { this.isCustomEmpty = true; this.snackBar.open(res.Message.CustomRecipes, "", { duration: 3000 }); } else { this.initialCustomRecipes = this.customRecipes = res.Message.CustomRecipes; } }); } addRecipe(){ const dialogRef = this.dialog.open(AddCustomComponent, { width: "500px", }); dialogRef.afterClosed().subscribe((response) => { if (response.confirmed) { this._userService .addCustomRecipe( localStorage.getItem("token"), response.recipeName, response.recipeIngredients, response.recipeInstructions, response.recipeSummary, response.recipeComments, ) .subscribe((res) => { console.log(res); this.snackBar.open(res.Message, " ", { duration: 3000 }); if(res.Result === "Success"){ const currentRoute = this.router.url; this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => { this.router.navigate([currentRoute]); // navigate to same route }); } }); } }); } unSaveRecipe(recipeId) { this._userService .deleteRecipe(localStorage.getItem("token"), recipeId) .subscribe((res) => { this.initialSavedRecipes = this.initialSavedRecipes.filter( (x) => x.RecipeId !== recipeId ); this.savedRecipes = this.savedRecipes.filter( (x) => x.RecipeId !== recipeId ); this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); }); } filterSaved() { this.savedRecipes = this.initialSavedRecipes.filter((x) => x.RecipeName?.includes(this.recipeNameFilter.value) ); } filterCustom(){ this.customRecipes = this.initialCustomRecipes.filter((x) => x.RecipeName?.includes(this.customNameFilter.value) ); } } <file_sep>import { Component, OnInit } from "@angular/core"; import { MatSnackBar } from "@angular/material/snack-bar"; import { FormControl } from "@angular/forms"; import { ActivatedRoute } from "@angular/router"; import { RecipeService } from "../recipe.service"; import { UserService } from "../user.service"; @Component({ selector: "app-individual-recipe", templateUrl: "./individual-recipe.component.html", styleUrls: ["./individual-recipe.component.css"], }) export class IndividualRecipeComponent implements OnInit { recipe; recipeId: string; aisles: any; comments: FormControl; constructor( private _recipeService: RecipeService, private _userService: UserService, private route: ActivatedRoute, private snackBar: MatSnackBar ) {} ngOnInit(): void { this.recipeId = this.route.snapshot.paramMap.get("id"); this._recipeService .getRecipeById(localStorage.getItem("token"), this.recipeId) .subscribe((res) => { if (res.Result === "Success") { this.recipe = res.Message.Info; this.sortIngredientsByAisle(); this.splitInstructions(); } else { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } this.assignCommentsIfSaved(); }); } printRecipe() { window.print(); } goToSource() { window.open(this.recipe.Info.spoonacularSourceUrl); } assignCommentsIfSaved() { this._userService .info(localStorage.getItem("token")) .subscribe((response) => { if (typeof response.Message.SavedRecipes !== "string") { if ( response.Message.SavedRecipes.map((x) => { return { RecipeId: x.RecipeId, RecipeComments: x.RecipeComments, }; }).find((x) => x.RecipeId == this.recipe.id) ) { this.comments = new FormControl( response.Message.SavedRecipes.map((x) => { return { RecipeId: x.RecipeId, RecipeComments: x.RecipeComments, }; }).find((x) => x.RecipeId == this.recipe.id).RecipeComments, { updateOn: "change" } ); } else { this.comments = new FormControl("", { updateOn: "change" }); } } }); } sortIngredientsByAisle() { this.recipe.extendedIngredients.forEach((x) => { if (!x.aisle) { x.aisle = "z"; } }); this.recipe.extendedIngredients = this.recipe.extendedIngredients.sort( (a, b) => a.aisle?.localeCompare(b.aisle) ); } splitInstructions() { this.recipe.instructions = this.recipe.instructions.replace( /(<([^>]+)>)/gi, "" ); if (this.recipe.instructions.includes("↵")) { this.recipe.instructions = this.recipe.instructions.split("↵"); } if (this.recipe.instructions.includes(",")) { this.recipe.instructions = this.recipe.instructions.split(","); } if (this.recipe.instructions.includes(".")) { this.recipe.instructions = this.recipe.instructions.split("."); } } saveRecipe() { this._userService .addRecipe( localStorage.getItem("token"), this.recipeId, this.recipe.title, this.recipe.summary, this.comments.value ) .subscribe((res) => { if (res.Message === "Recipe Already Saved") { this._userService .editRecipeComments( localStorage.getItem("token"), this.recipeId, this.comments.value ) .subscribe((res) => { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); }); } else { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } }); } } <file_sep>import { Component, OnInit } from "@angular/core"; import { FormControl } from "@angular/forms"; import { MatDialog } from "@angular/material/dialog"; import { MatSnackBar } from "@angular/material/snack-bar"; import { ActivatedRoute, Router } from "@angular/router"; import { UserService } from "../user.service"; import { CustomDialogComponent } from "./custom-dialog/custom-dialog.component"; @Component({ selector: "app-individual-custom", templateUrl: "./individual-custom.component.html", styleUrls: ["./individual-custom.component.css"], }) export class IndividualCustomComponent implements OnInit { recipe; recipeId: string; comments; image; constructor( private _userService: UserService, private route: ActivatedRoute, private router: Router, private dialog: MatDialog, private snackBar: MatSnackBar ) {} ngOnInit(): void { this.recipeId = this.route.snapshot.paramMap.get("id"); this._userService .getCustomRecipe(localStorage.getItem("token"), this.recipeId) .subscribe((res) => { if (typeof res.Message === "string") { this.snackBar.open(res.Message, "", { duration: 3000 }); } else { this.recipe = res.Message; this.splitInstructionsAndIngredients(); this.comments = new FormControl(this.recipe.RecipeComments, { updateOn: "change", }); } }); this._userService .getImage(localStorage.getItem("token"), this.recipeId) .subscribe((res) => { if (res) { this.image = res; } }); } printRecipe() { window.print(); } deleteRecipe() { this._userService .deleteCustomRecipe(localStorage.getItem("token"), this.recipeId) .subscribe((res) => { this.snackBar.open(res.Message, "", { duration: 3000 }); this.router.navigate(["Personal"]); }); } splitInstructionsAndIngredients() { this.recipe.RecipeInstructions = this.recipe.RecipeInstructions.replace( /(<([^>]+)>)/gi, "" ); if (this.recipe.RecipeInstructions.includes(".")) { this.recipe.RecipeInstructions = this.recipe.RecipeInstructions.split( "." ); } this.recipe.RecipeIngredients = this.recipe.RecipeIngredients.replace( /(<([^>]+)>)/gi, "" ); if (this.recipe.RecipeIngredients.includes(".")) { this.recipe.RecipeIngredients = this.recipe.RecipeIngredients.split("."); } } editRecipe() { const dialogRef = this.dialog.open(CustomDialogComponent, { width: "500px", data: { recipe: this.recipe, image: this.image }, }); dialogRef.afterClosed().subscribe((response) => { if (response.confirmed) { this._userService .editCustomRecipe( localStorage.getItem("token"), this.recipeId, response.recipeName, response.recipeIngredients, response.recipeInstructions, response.recipeSummary, response.recipeComments ) .subscribe((res) => { this.snackBar.open(res.Message, "", { duration: 3000 }); this.router .navigateByUrl("/", { skipLocationChange: true }) .then(() => { this.router.navigate(["/IndividualCustom", this.recipeId]); }); }); } }); } } <file_sep>const path = require('path') require('dotenv').config({ path: path.resolve(__dirname, '../../.env') }) const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize(process.env.DBString); /** * The model representing the SavedRecipes table in the database. * @model * @property {Number} id - The id of the recipe. * @property {Number} UserId - The username of the user. * @property {Number} RecipeId - The id of the recipe from the API. * @property {String} RecipeName - The name of the recipe from the API. * @property {String} RecipeSummary - The summary of the recipe from the API. * @property {String} RecipeComments - The comment of the recipe added by the user. */ const SavedRecipes = sequelize.define('SavedRecipes', { // Model attributes are defined here id: { type: DataTypes.INTEGER, primaryKey: true }, UserId: { type: DataTypes.INTEGER, allowNull: false }, RecipeId: { type: DataTypes.INTEGER, allowNull: false }, RecipeName: { type: DataTypes.STRING, }, RecipeSummary: { type: DataTypes.STRING }, RecipeComments: { type: DataTypes.STRING } }, { timestamps: false, tableName: 'SavedRecipes' }); module.exports = SavedRecipes;<file_sep>require('dotenv').config(); const express = require("express"); const app = express(); let isDev = process.env.isDev; const PORT = isDev === "true" ? process.env.ServerPort : process.env.PORT; const bodyParser = require('body-parser'); const cors = require('cors'); // Middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.text()); app.use(cors({ origin: '*' })); // Routes app.get("/", function (req, res) { res.send("Working"); }) require("./User/UserRoutes")(app); require("./Recipe/RecipeRoutes")(app); app.listen(PORT); console.log('Server running at port: ' + PORT)<file_sep>import { Component, OnInit } from "@angular/core"; import { MatDialogRef } from "@angular/material/dialog"; import { FormControl } from "@angular/forms"; @Component({ selector: 'app-missing-ingredient-dialog', templateUrl: './missing-ingredient-dialog.component.html', styleUrls: ['./missing-ingredient-dialog.component.css'] }) export class MissingIngredientDialogComponent implements OnInit { ingredients = new FormControl("", { updateOn: "change" }); constructor(public dialogRef: MatDialogRef<MissingIngredientDialogComponent>) { } ngOnInit(): void { } closeDialog(isSent: boolean) { const response = { ingredients: this.ingredients.value, isSent, }; this.dialogRef.close(response); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { throwError, Observable } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class RecipeService { private baseUrl = 'http://recipeserver.jasondesigns.net/'; private httpOptions(token) { return { headers: new HttpHeaders({ 'Content-Type': 'application/json', token }) } } constructor(private http: HttpClient) { } getRecipesByIngredients(token, ingredients): Observable<any> { const data = this.http.get(this.baseUrl + 'recipe/ingredients/' + ingredients, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } getRandomRecipes(token): Observable<any> { const data = this.http.get(this.baseUrl + 'random', this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } getRecipesByName(token, name): Observable<any> { const data = this.http.get(this.baseUrl + 'recipe/name/' + name, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } getRecipeById(token, recipeId): Observable<any> { const data = this.http.get(this.baseUrl + 'recipe/' + recipeId, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } getIngredients(token): Observable<any> { const data = this.http.get(this.baseUrl + 'ingredients/', this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } missingIngredient(token, ingredients, username, firstName): Observable<any> { const data = this.http.post<any>(this.baseUrl + 'ingredients/missing', { ingredients, username, firstName }, this.httpOptions(token)) .pipe(catchError(this.catcher)); return data; } catcher(error: HttpErrorResponse) { console.log(error.message) return throwError(error.message || 'Service Error'); } }<file_sep>import { Component, Inject, OnInit, ElementRef, Input } from "@angular/core"; import { FormControl } from "@angular/forms"; import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog"; @Component({ selector: "app-custom-dialog", templateUrl: "./custom-dialog.component.html", styleUrls: ["./custom-dialog.component.css"], }) export class CustomDialogComponent implements OnInit { recipeName = new FormControl(this.data.recipe.RecipeName, { updateOn: "change", }); recipeIngredients = new FormControl(this.data.recipe.RecipeIngredients, { updateOn: "change", }); recipeInstructions = new FormControl(this.data.recipe.RecipeInstructions, { updateOn: "change", }); recipeSummary = new FormControl(this.data.recipe.RecipeSummary, { updateOn: "change", }); recipeComments = new FormControl(this.data.recipe.RecipeComments, { updateOn: "change", }); constructor( public dialogRef: MatDialogRef<CustomDialogComponent>, @Inject(MAT_DIALOG_DATA) private readonly data, ) {} ngOnInit(): void {console.log(this.data.recipe)} formatArray() { this.recipeIngredients.setValue(this.recipeIngredients.value.toString()); this.recipeInstructions.setValue(this.recipeInstructions.value.toString()); if (this.recipeInstructions.value.includes(",")) { this.recipeInstructions.setValue(this.recipeInstructions.value.replace(/,/g, ".")); } if (this.recipeIngredients.value.includes(",")) { this.recipeIngredients.setValue(this.recipeIngredients.value.replace(/,/g, ".")); } } closeDialog(confirmed){ this.formatArray(); this.dialogRef.close({ confirmed, recipeName: this.recipeName.value, recipeIngredients: this.recipeIngredients.value, recipeInstructions: this.recipeInstructions.value, recipeSummary: this.recipeSummary.value, recipeComments: this.recipeComments.value, }) } } <file_sep>import { Component, OnInit } from "@angular/core"; import { FormControl } from "@angular/forms"; import { UserService } from "../user.service"; import { MatSnackBar } from "@angular/material/snack-bar"; import { Router } from "@angular/router"; import { ForgetPasswordDialogComponent } from "./forget-password-dialog/forget-password-dialog.component"; import { MatDialog } from "@angular/material/dialog"; import { LoggedInService } from '../logged-in.service'; @Component({ selector: "app-login", templateUrl: "./login.component.html", styleUrls: ["./login.component.css"], }) export class LoginComponent implements OnInit { username = new FormControl("", { updateOn: "change" }); password = new FormControl("", { updateOn: "change" }); disableForgetPasswordButton: boolean = false; constructor( private userService: UserService, private dialog: MatDialog, private snackBar: MatSnackBar, private router: Router, private loggedInCheck: LoggedInService ) {} ngOnInit() {} login() { this.userService .login(this.username.value, this.password.value) .subscribe((res) => { if (res) { if (res.Result === "Success") { localStorage.setItem("token", res.Token); this.loggedInCheck.logIn(); this.router.navigate(["/"]); } else { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } } }); } forgetPassword() { const dialogRef = this.dialog.open(ForgetPasswordDialogComponent, { width: '500px', }); dialogRef.afterClosed().subscribe((response) => { if (response.isSent) { this.disableForgetPasswordButton = true; this.userService .forgotPassword( response.firstName, response.username, response.suggestedPassword ) .subscribe((res) => { if (res) { res.Result === 'Success' ? this.snackBar.open(res.Message, '', { duration: 3000 }) : this.snackBar.open( 'Error sending email, check console for more...', '', { duration: 3000 } ); console.log(res.Message); } }); } }); } } <file_sep>const Users = require('./Users'); const SavedRecipes = require('./SavedRecipes'); const Ingredients = require('./Ingredients'); const CustomRecipes = require('./CustomRecipes'); /** * The module provides an one stop, easy access to the models. * @module * @property {Object} Users - The Users Model. * @property {Object} SavedRecipes - The SavedRecipes Model. * @property {Object} CustomRecipes - The CustomRecipes Model. * @property {Object} Ingredients - The Ingredients Model. */ const Tables = { Users, SavedRecipes, CustomRecipes, Ingredients} module.exports = Tables;<file_sep>import { Component, OnInit } from "@angular/core"; import { MatDialogRef } from "@angular/material/dialog"; import { FormControl } from "@angular/forms"; @Component({ selector: "app-forget-password-dialog", templateUrl: "./forget-password-dialog.component.html", styleUrls: ["./forget-password-dialog.component.css"], }) export class ForgetPasswordDialogComponent implements OnInit { username = new FormControl("", { updateOn: "change" }); suggestedPassword = new FormControl("", { updateOn: "change" }); firstName = new FormControl("", { updateOn: "change" }); constructor(public dialogRef: MatDialogRef<ForgetPasswordDialogComponent>) {} ngOnInit() {} closeDialog(isSent: boolean) { const response = { username: this.username.value, suggestedPassword: this.suggested<PASSWORD>.value, firstName: this.firstName.value, isSent, }; this.dialogRef.close(response); } } <file_sep>import { Component, OnInit } from "@angular/core"; import { FormControl } from "@angular/forms"; import { UserService } from "../user.service"; import { MatSnackBar } from "@angular/material/snack-bar"; import { Router } from "@angular/router"; import { LoggedInService } from '../logged-in.service'; @Component({ selector: "app-signup", templateUrl: "./signup.component.html", styleUrls: ["./signup.component.css"], }) export class SignupComponent implements OnInit { username = new FormControl("", { updateOn: "change" }); password = new FormControl("", { updateOn: "change" }); firstName = new FormControl("", { updateOn: "change" }); constructor( private userService: UserService, private snackBar: MatSnackBar, private router: Router, private loggedInCheck: LoggedInService ) {} ngOnInit(): void {} signUp() { this.userService .signup(this.firstName.value, this.username.value, this.password.value) .subscribe((res) => { if (res) { if (res.Result === "Success") { localStorage.setItem("token", res.Token); this.loggedInCheck.logOut(); this.router.navigate(["/"]); } else { this.snackBar.open(res.Message, "", { duration: 3000 }); console.log(res.Message); } } }); } } <file_sep>const path = require('path') require('dotenv').config({ path: path.resolve(__dirname, '../../.env') }) const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize(process.env.DBString); /** * The model representing the Ingredients table in the database. * @model * @property {Number} id - The id of the ingredient. * @property {String} Name - The ingredient name. */ const Ingredients = sequelize.define('Ingredients', { // Model attributes are defined here id: { type: DataTypes.INTEGER, primaryKey: true }, Name: { type: DataTypes.STRING, } }, { timestamps: false, tableName: 'Ingredients' }); module.exports = Ingredients;<file_sep>import { Component, Inject, OnInit } from "@angular/core"; import { FormControl } from "@angular/forms"; import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog"; @Component({ selector: "app-add-custom", templateUrl: "./add-custom.component.html", styleUrls: ["./add-custom.component.css"], }) export class AddCustomComponent implements OnInit { recipeName = new FormControl("", { updateOn: "change", }); recipeIngredients = new FormControl("", { updateOn: "change", }); recipeInstructions = new FormControl("", { updateOn: "change", }); recipeSummary = new FormControl("", { updateOn: "change", }); recipeComments = new FormControl("", { updateOn: "change", }); constructor( public dialogRef: MatDialogRef<AddCustomComponent>, @Inject(MAT_DIALOG_DATA) private readonly data, ) {} ngOnInit(): void {} closeDialog(confirmed){ this.dialogRef.close({ confirmed, recipeName: this.recipeName.value, recipeIngredients: this.recipeIngredients.value, recipeInstructions: this.recipeInstructions.value, recipeSummary: this.recipeSummary.value, recipeComments: this.recipeComments.value, }) } } <file_sep>const db = require("./Models/Tables"); /** * Gets the user's id, first name, and last name from the database. * @function * @param {Number} userId - The id of the user. */ function getUserInfo(userId) { return new Promise(function (resolve) { db.Users.findAll({ attributes: ["id", "FirstName", "Username"], where: { id: userId, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Success", Message: res[0].dataValues }); } else { resolve({ Result: "Error", Message: "No User Found with the id: " + userId, }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { console.log(err); resolve({ Result: "Error", Message: err }); } ); }); } /** * Gets all the user saved recipe's id, name, summary, and comments from the database. * @function * @param {Number} userId - The id of the user that saved the recipe. */ function getUserRecipes(userId) { return new Promise(function (resolve) { db.SavedRecipes.findAll({ attributes: ["RecipeId", "RecipeName", "RecipeSummary", "RecipeComments"], where: { UserId: userId, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Success", Message: res }); } else { resolve({ Result: "Success", Message: "No Recipes Found for the user with id: " + userId, }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { console.log(err); resolve({ Result: "Error", Message: err }); } ); }); } /** * Gets all the user custom recipe's id, name, ingredients, instructions, summary, and comments from the database. * @function * @param {Number} userId - The id of the user. */ function getUserCustomRecipes(userId) { return new Promise(function (resolve) { db.CustomRecipes.findAll({ attributes: [ "id", "RecipeName", "RecipeIngredients", "RecipeInstructions", "RecipeSummary", "RecipeComments", ], where: { UserId: userId, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Success", Message: res }); } else { resolve({ Result: "Success", Message: "No Custom Recipes Found for the user with id: " + userId, }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { console.log(err); resolve({ Result: "Error", Message: err }); } ); }); } var dbFunctions = { /** * Checks to see if the username exists, if not, creats a user, if so, * tells the user to choose another username because it's already used. * @function * @param {String} firstName - The first name of the user. * @param {String} username - The username of the user. * @param {String} hashedPassword - The hashed password of the user. */ async signup(firstName, username, hashedPassword) { console.log(username); return new Promise(function (resolve) { db.Users.findAll({ where: { Username: username, }, }).then( async (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Error", Message: "Username Taken" }); } else { await db.Users.create({ FirstName: firstName, Username: username, HashPass: <PASSWORD>Password, }); db.Users.findAll({ where: { Username: username } }).then( (response) => { resolve({ Result: "Success", UserId: response[0].dataValues.id, }); } ); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * Checks to see if the username and password match in the database. * @function * @param {String} username - The username of the user. * @param {String} hashedPassword - The hashed password of the user. */ login(username, hashedPassword) { return new Promise(function (resolve) { db.Users.findAll({ where: { Username: username, HashPass: hashedPassword, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Success", Message: "Valid User", UserId: res[0].dataValues.id, }); } else { resolve({ Result: "Error", Message: "Invalid User" }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * Uses the getUserInfo and getUserRecipe functions to return information, saved recipes, and customRecipes for the user. * @function * @param {Number} userId - The id of the user. */ async getInfo(userId) { var info = await getUserInfo(userId); var savedRecipes = await getUserRecipes(userId); var customRecipes = await getUserCustomRecipes(userId); if ( info.Result == "Success" && savedRecipes.Result == "Success" && customRecipes.Result == "Success" ) { return { Result: "Success", Message: { Info: info.Message, SavedRecipes: savedRecipes.Message, CustomRecipes: customRecipes.Message, }, }; } else { return { Result: "Error", Message: { Info: info.Message, SavedRecipes: savedRecipes.Message, CustomRecipes: customRecipes.Message, }, }; } }, /** * If the recipe isn't already added, this adds the recipe to the user's saved recipe list. * @function * @param {Number} userId - The id of the user. * @param {Number} recipeId - The id of the recipe being added. * @param {String} recipeName - The name of the recipe being added. * @param {String} recipeSummary - The summary of the recipe being added. * @param {String} recipeComments - The comments to the recipe being added. */ addRecipe(userId, recipeId, recipeName, recipeSummary, recipeComments) { return new Promise(function (resolve) { db.SavedRecipes.findAll({ where: { UserId: userId, RecipeId: recipeId, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Error", Message: "Recipe Already Saved" }); } else { db.SavedRecipes.create({ UserId: userId, RecipeId: recipeId, RecipeName: recipeName, RecipeSummary: recipeSummary, RecipeComments: recipeComments, }); resolve({ Result: "Success", Message: "Recipe Saved" }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * If the recipe isn't already deleted, this deletes the recipe from the user list. * @function * @param {Number} userId - The id of the user. * @param {Number} recipeId - The id of the recipe being deleted. */ deleteRecipe(userId, recipeId) { return new Promise(function (resolve) { db.SavedRecipes.destroy({ where: { UserId: userId, RecipeId: recipeId, }, }).then( (res) => { console.log(res); if (res) { resolve({ Result: "Success", Message: "Recipe deleted" }); } else { resolve({ Result: "Error", Message: "Recipe already deleted or Recipe didn't exist", }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * This edits the recipe comments if it exists. * @function * @param {Number} userId - The id of the user. * @param {Number} recipeId - The id of the recipe being edited. * @param {String} recipeComments - The new comments for the saved recipe. */ editRecipeComment(userId, recipeId, recipeComments) { return new Promise(function (resolve) { db.SavedRecipes.update( { RecipeComments: recipeComments }, { where: { UserId: userId, RecipeId: recipeId, }, } ).then( (res) => { if (res[0] > 0) { resolve({ Result: "Success", Message: "Successfully updated comments", }); } else { resolve({ Result: "Error", Message: "Recipe not found or no changes in the comments", }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * Gets a specific user custom recipe by id. * @function * @param {Number} userId - The id of the user. * @param {Number} recipeId - The id of the recipe. */ getUserCustomRecipe(userId, recipeId) { return new Promise(function (resolve) { db.CustomRecipes.findAll({ attributes: [ "RecipeName", "RecipeIngredients", "RecipeInstructions", "RecipeSummary", "RecipeComments", ], where: { id: recipeId, UserId: userId, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Success", Message: res[0] }); } else { resolve({ Result: "Success", Message: "No Custom Recipe Found with id: " + recipeId, }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * If the recipe isn't already added, this adds the recipe to the user's custom recipe list. * @function * @param {Number} userId - The id of the user. * @param {String} recipeName - The name of the recipe being added. * @param {String} recipeIngredients - The ingredients of the recipe being added. * @param {String} recipeInstructions - The instructions to the recipe being added. * @param {String} recipeSummary - The summary of the recipe being added. * @param {String} recipeComments - The comments to the recipe being added. */ addCustomRecipe( userId, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments ) { return new Promise(function (resolve) { db.CustomRecipes.findAll({ where: { UserId: userId, RecipeName: recipeName, }, }).then( async (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Error", Message: "Custom Recipe Already Saved", }); } else { await db.CustomRecipes.create({ UserId: userId, RecipeName: recipeName, RecipeIngredients: recipeIngredients, RecipeInstructions: recipeInstructions, RecipeSummary: recipeSummary, RecipeComments: recipeComments, }); db.CustomRecipes.findAll({ where: { UserId: userId, RecipeName: recipeName }, }).then((response) => { resolve({ Result: "Success", Message: "Custom Recipe Added", RecipeId: response[0].dataValues.id, }); }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * If the recipe isn't already deleted, this deletes the recipe from the user custom recipe list. * @function * @param {Number} userId - The id of the user. * @param {Number} recipeId - The id of the recipe being deleted. */ deleteCustomRecipe(userId, recipeId) { return new Promise(function (resolve) { db.CustomRecipes.destroy({ where: { id: recipeId, UserId: userId, }, }).then( (res) => { if (res) { resolve({ Result: "Success", Message: "Custom Recipe deleted" }); } else { resolve({ Result: "Error", Message: "Custom Recipe already deleted or Custom Recipe didn't exist", }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * This edits the recipe with the fields provided. * @function * @param {Number} userId - The id of the user. * @param {Number} recipeId - The id of the recipe edited * @param {String} recipeName - The name of the recipe being added. * @param {String} recipeIngredients - The ingredients of the recipe being added. * @param {String} recipeInstructions - The instructions to the recipe being added. * @param {String} recipeSummary - The summary of the recipe being added. * @param {String} recipeComments - The comments to the recipe being added. */ editCustomRecipe( userId, recipeId, recipeName, recipeIngredients, recipeInstructions, recipeSummary, recipeComments ) { return new Promise(function (resolve) { db.CustomRecipes.update( { RecipeName: recipeName, RecipeIngredients: recipeIngredients, RecipeInstructions: recipeInstructions, RecipeSummary: recipeSummary, RecipeComments: recipeComments, }, { where: { id: recipeId, UserId: userId, }, } ).then( (res) => { if (res[0] > 0) { resolve({ Result: "Success", Message: "Successfully updated custom recipe", }); } else { resolve({ Result: "Error", Message: "Custom Recipe not found or no changes in the custom recipe", }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, /** * Checks if they are a user. * @function * @param {String} username - The username of the user. * @param {String} hashPassword - The hashed password of the user. */ isUser(username, hashPassword) { return new Promise(function (resolve) { db.Users.findAll({ where: { Username: username, HashPass: hashPassword, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve(true); } else { resolve(false); } } else { resolve(false); } }, (err) => { resolve(false); } ); }); }, /** * This just returns all ingredients. * @function */ getIngredients() { return new Promise(function (resolve) { db.Ingredients.findAll({}).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Success", Message: res }); } else { resolve({ Result: "Error", Message: "No Ingredients found" }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: "Unknown Error" }); } ); }); }, /** * Admin only, this just adds ingredients to the database if not already there. * @function * @param {String} ingredient - The ingredient to add. */ addIngredient(ingredient) { return new Promise(function (resolve) { db.Ingredients.findAll({ where: { Name: ingredient, }, }).then( (res) => { if (res) { if (res.length > 0) { resolve({ Result: "Error", Message: "Ingredient already there" }); } else { db.Ingredients.create({ Name: ingredient, }); resolve({ Result: "Success" }); } } else { resolve({ Result: "Error", Message: "Unknown Error" }); } }, (err) => { resolve({ Result: "Error", Message: err }); } ); }); }, }; module.exports = dbFunctions; // async function tester() { // var test = await dbFunctions.getIngredients("c") // console.log(test) // } // tester(); <file_sep>import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatCardModule } from '@angular/material/card'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatDialogModule } from '@angular/material/dialog'; import { MatDividerModule } from '@angular/material/divider'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatGridListModule } from '@angular/material/grid-list'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatListModule } from '@angular/material/list'; import { MatMenuModule } from '@angular/material/menu'; import { MatNativeDateModule, MAT_DATE_FORMATS, NativeDateAdapter, DateAdapter } from '@angular/material/core'; import { MatPaginatorModule } from '@angular/material/paginator'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatRadioModule } from '@angular/material/radio'; import { MatSelectModule } from '@angular/material/select'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSortModule } from '@angular/material/sort'; import { MatStepperModule } from '@angular/material/stepper'; import { MatTableModule } from '@angular/material/table'; import { MatTabsModule } from '@angular/material/tabs'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTreeModule } from '@angular/material/tree'; import { NgModule, Injectable } from '@angular/core'; import { DragDropModule } from '@angular/cdk/drag-drop'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { FormsModule } from '@angular/forms'; import { MatBottomSheetModule } from '@angular/material/bottom-sheet'; import { MatChipsModule } from '@angular/material/chips'; const matModules = [ DragDropModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatBottomSheetModule, MatCardModule, MatCheckboxModule, MatDatepickerModule, MatDialogModule, MatDividerModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressSpinnerModule, MatRadioModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatStepperModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, MatTreeModule, FormsModule, MatChipsModule, ]; @Injectable() export class AppDateAdapter extends NativeDateAdapter { format(date: Date, displayFormat: any): string { if (displayFormat === 'input') { const day = date.getDate(); const month = date.getMonth() + 1; const year = date.getFullYear(); return this._to2digit(month) + '/' + this._to2digit(day) + '/' + year; } else { return date.toDateString(); } } private _to2digit(n: number) { return ('00' + n).slice(-2); } } export const MY_DATE_FORMATS = { parse: { dateInput: { month: 'short', year: 'numeric', day: 'numeric' } }, display: { dateInput: 'input', } }; @NgModule({ declarations: [], imports: matModules, exports: matModules, providers: [ { provide: DateAdapter, useClass: AppDateAdapter }, { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS }, ] }) export class AppMatModule {} <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { NavbarComponent } from './navbar/navbar.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ForgetPasswordDialogComponent } from './login/forget-password-dialog/forget-password-dialog.component'; import { ReactiveFormsModule } from '@angular/forms'; import { UserService } from './user.service'; import { RecipeService } from './recipe.service'; import {AppMatModule} from './app-mat'; import { SignupComponent } from './signup/signup.component'; import { HomeComponent } from './home/home.component'; import { LoggedInService } from './logged-in.service'; import { IndividualRecipeComponent } from './individual-recipe/individual-recipe.component'; import { SearchRecipesComponent } from './search-recipes/search-recipes.component'; import { MissingIngredientDialogComponent } from './search-recipes/missing-ingredient-dialog/missing-ingredient-dialog.component'; import { PersonalRecipesComponent } from './personal-recipes/personal-recipes.component'; import { IndividualCustomComponent } from './individual-custom/individual-custom.component'; import { CustomDialogComponent } from './individual-custom/custom-dialog/custom-dialog.component'; import { AddCustomComponent } from './personal-recipes/add-custom/add-custom.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, NavbarComponent, ForgetPasswordDialogComponent, SignupComponent, HomeComponent, IndividualRecipeComponent, SearchRecipesComponent, MissingIngredientDialogComponent, PersonalRecipesComponent, IndividualCustomComponent, CustomDialogComponent, AddCustomComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, ReactiveFormsModule, HttpClientModule, AppMatModule, ], providers: [UserService, RecipeService, LoggedInService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep># RecipeBook This is an application I made using the Spoonacular API, JawsDB, NodeJS, JSDocs, Angular 7+, JWT, and more. The purpose is to be able to search for recipes and save your favorite ones to find later. I made this because I find cooking to be exciting but I always lost the recipes that I plan on making so this way, I can keep track of them and I might as well let the application help others so I hope you enjoy! ## How it works * First you signup or login. * Then from there, you can look up different recipes, see random recipes, create your own, save your favorite ones and revisit them when it's time to chef it up! ### See what its all about: [RecipeBook](http://recipebook.jasondesigns.net)
e29a78be81f98e72ceb87d1a6a39a3fdf717ca93
[ "JavaScript", "TypeScript", "Markdown" ]
29
TypeScript
jasondamion/RecipeBook
34e3458d9dc998074d051d7789853ca511dbc24b
9ed7be20bc15ee89ed900f82d53b68318b91b062
refs/heads/master
<repo_name>hernan-arga/Prueba_Bitarray<file_sep>/bitarray.c #include <stdio.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <commons/bitarray.h> #include <commons/string.h> #include <stdlib.h> #include <unistd.h> #include <string.h> void iniciarMmap(); void actualizarBitArray(); void crearBitArray(); void modificarBitArray(); void modificarBitArray2(); void crearArchivoBitmap(); t_bitarray* bitarray; char *mmapDeBitmap; int main() { //crearArchivoBitmap(); iniciarMmap(); bitarray = bitarray_create(mmapDeBitmap, 512); //modificarBitArray(); modificarBitArray2(); bitarray_destroy(bitarray); //si pierdo memoria averiguar mmunmap } void crearArchivoBitmap() { FILE *f = fopen("bitmap.bin", "w"); //5192 sale de mystat.st_size (tamanio del archivo de bitmap). tengo que escribir en el archivo para mapear la memoria. for (int i = 0; i < 5192; i++) { fputc(0, f); } fclose(f); } /*void crearBitArray() { FILE* bitmap_f = fopen("bitmap.bin", "w"); //en vez de 512 seria tamanioenbytesdebloques() char* bitmap = malloc(512); bitarray = bitarray_create(bitmap, 512); fclose(bitmap_f); }*/ //Preguntar sobre esto void iniciarMmap() { //Open es igual a fopen pero el FD me lo devuelve como un int (que es lo que necesito para fstat) int bitmap = open("bitmap.bin", O_RDWR); struct stat mystat; //fstat rellena un struct con informacion del FD dado if (fstat(bitmap, &mystat) < 0) { close(bitmap); } /* mmap mapea un archivo en memoria y devuelve la direccion de memoria donde esta ese mapeo * MAP_SHARED Comparte este área con todos los otros objetos que señalan a este objeto. Almacenar en la región es equivalente a escribir en el fichero. */ mmapDeBitmap = mmap(NULL, mystat.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, bitmap, 0); close(bitmap); } void modificarBitArray() { int j; for (j = 0; j < bitarray_get_max_bit(bitarray); j++) { bool bit = bitarray_test_bit(bitarray, j); printf("%i", bit); } printf("\n"); for (j = 0; j < bitarray_get_max_bit(bitarray) / 2; j++) { bool bit = bitarray_test_bit(bitarray, j); if (bit == 0) { bitarray_set_bit(bitarray, j); //encontroUnBloque = 1; //bloqueEncontrado = j; //break; } } for (j = 0; j < bitarray_get_max_bit(bitarray); j++) { bool bit = bitarray_test_bit(bitarray, j); printf("%i", bit); } } void modificarBitArray2() { int j; for (j = 0; j < bitarray_get_max_bit(bitarray); j++) { bool bit = bitarray_test_bit(bitarray, j); printf("%i", bit); } printf("\n"); for (j = bitarray_get_max_bit(bitarray) - 1; j > (bitarray_get_max_bit(bitarray) / 2) - 1; j--) { bool bit = bitarray_test_bit(bitarray, j); if (bit == 0) { bitarray_set_bit(bitarray, j); //encontroUnBloque = 1; //bloqueEncontrado = j; //break; } } for (j = 0; j < bitarray_get_max_bit(bitarray); j++) { bool bit = bitarray_test_bit(bitarray, j); printf("%i", bit); } } /* void realizarSelect(char* tabla, char* key) { string_to_upper(tabla); if (existeLaTabla(tabla)) { char* pathMetadata = malloc( strlen( string_from_format("%sTables/", structConfiguracionLFS.PUNTO_MONTAJE)) + strlen(tabla) + strlen("/Metadata") + 1); strcpy(pathMetadata, string_from_format("%sTables/", structConfiguracionLFS.PUNTO_MONTAJE)); strcat(pathMetadata, tabla); strcat(pathMetadata, "/Metadata"); t_config *metadata = config_create(pathMetadata); int cantidadDeParticiones = config_get_int_value(metadata, "PARTITIONS"); int particionQueContieneLaKey = (atoi(key)) % cantidadDeParticiones; printf("La key esta en la particion %i\n", particionQueContieneLaKey); char* stringParticion = malloc(4); stringParticion = string_itoa(particionQueContieneLaKey); char* pathParticionQueContieneKey = malloc( strlen( string_from_format("%sTables/", structConfiguracionLFS.PUNTO_MONTAJE)) + strlen(tabla) + strlen("/") + strlen(stringParticion) + strlen(".bin") + 1); strcpy(pathParticionQueContieneKey, string_from_format("%sTables/", structConfiguracionLFS.PUNTO_MONTAJE)); strcat(pathParticionQueContieneKey, tabla); strcat(pathParticionQueContieneKey, "/"); strcat(pathParticionQueContieneKey, stringParticion); strcat(pathParticionQueContieneKey, ".bin"); t_config *tamanioYBloques = config_create(pathParticionQueContieneKey); char** vectorBloques = config_get_array_value(tamanioYBloques, "BLOCK"); //devuelve vector de STRINGS int m = 0; while (vectorBloques[m] != NULL) { m++; } int timestampActualMayorBloques = -1; char* valueDeTimestampActualMayorBloques; // POR CADA BLOQUE, TENGO QUE ENTRAR A ESTE BLOQUE for (int i = 0; i < m; i++) { char* pathBloque = malloc( strlen( string_from_format("%sBloques/", structConfiguracionLFS.PUNTO_MONTAJE)) + strlen((vectorBloques[i])) + strlen(".bin") + 1); strcpy(pathBloque, "./Bloques/"); strcat(pathBloque, vectorBloques[i]); strcat(pathBloque, ".bin"); FILE *archivoBloque = fopen(pathBloque, "r"); if (archivoBloque == NULL) { printf("no se pudo abrir archivo de bloques"); exit(1); } int cantidadIgualDeKeysEnBloque = 0; t_registro* vectorStructs[100]; obtenerDatosParaKeyDeseada(archivoBloque, (atoi(key)), vectorStructs, &cantidadIgualDeKeysEnBloque); //cual de estos tiene el timestamp mas grande? guardar timestamp y value int temp = 0; char* valor; for (int k = 1; k < cantidadIgualDeKeysEnBloque; k++) { for (int j = 0; j < (cantidadIgualDeKeysEnBloque - k); j++) { if (vectorStructs[j]->timestamp < vectorStructs[j + 1]->timestamp) { temp = vectorStructs[j + 1]->timestamp; valor = malloc(strlen(vectorStructs[j + 1]->value)); strcpy(valor, vectorStructs[j + 1]->value); vectorStructs[j + 1]->timestamp = vectorStructs[j]->timestamp; vectorStructs[j + 1]->value = vectorStructs[j]->value; vectorStructs[j]->timestamp = temp; vectorStructs[j]->value = valor; } } } if (vectorStructs[0]->timestamp > timestampActualMayorBloques) { timestampActualMayorBloques = vectorStructs[0]->timestamp; valueDeTimestampActualMayorBloques = malloc( strlen(vectorStructs[0]->value)); //strcpy(valueDeTimestampActualMayorBloques, vectorStructs[0]->value); valueDeTimestampActualMayorBloques = vectorStructs[0]->value; // ESTO NO DEBERIA SER ASI, Y DEBERIA FUNCIONAR LA LINEA DE ARRIBA } fclose(archivoBloque); free(pathBloque); //free(vectorStructs); } //cierra el for // si encontro alguno, me guarda el timestamp mayor en timestampActualMayorBloques // y guarda el valor en valueDeTimestampActualMayorBloques // si no hay ninguno en vectorBloques (porque por ej, esta en los temporales) // entonces timestampActualMayorBloques = -1 y // valueDeTimestampActualMayorBloques = NULL //------------------------------------------------- // AHORA ABRO ARCHIVOS TEMPORALES. EL PROCEDIMIENTO ES MUY PARECIDO AL ANTERIOR char* pathTemporales = malloc(strlen("./Tables/") + strlen(tabla) + 1); strcpy(pathTemporales, "./Tables/"); strcat(pathTemporales, tabla); DIR *directorioTemporal = opendir(pathTemporales); struct dirent *directorioTemporalALeer; int timestampActualMayorTemporales = -1; char* valueDeTimestampActualMayorTemporales; while((directorioTemporalALeer = readdir(directorioTemporal)) != NULL) { //PARA CADA .TMP if( directorioTemporalALeer termina en .tmp ){ //obtengo el nombre de ese archivo .tmp . Ejemplo obtengo A1.tmp siendo A1 el nombre (tipo char*) char* pathTemporal = malloc(strlen("./Tables/") + strlen(tabla) + strlen("/") + strlen( nombreArchivoTemporal ) + strlen(".tmp") + 1); strcpy(pathTemporal, "./Tables/"); strcat(pathTemporal, tabla); strcat(pathTemporal, "/"); strcat(pathTemporal, nombreArchivoTemporal ); strcat(pathTemporal, ".tmp"); FILE *archivoTemporal = fopen(pathTemporal, "r"); if (archivoTemporal == NULL) { printf("no se pudo abrir archivo de temporales"); exit(1); } int cantidadIgualDeKeysEnTemporal = 0; t_registro* vectorStructsTemporal[100]; obtenerDatosParaKeyDeseada(archivoTemporal, (atoi(key)), vectorStructsTemporal, &cantidadIgualDeKeysEnTemporal); //cual de estos tiene el timestamp mas grande? guardar timestamp y value int tempo = 0; char* valorTemp; for (int k = 1; k < cantidadIgualDeKeysEnTemporal; k++){ for (int j = 0; j < (cantidadIgualDeKeysEnTemporal-k); j++){ if (vectorStructsTemporal[j]->timestamp < vectorStructsTemporal[j+1]->timestamp){ tempo = vectorStructsTemporal[j+1]->timestamp; valorTemp = malloc(strlen(vectorStructsTemporal[j+1]->value)); strcpy(valorTemp,vectorStructsTemporal[j+1]->value); vectorStructsTemporal[j+1]->timestamp = vectorStructsTemporal[j]->timestamp; vectorStructsTemporal[j+1]->value = vectorStructsTemporal[j]->value; vectorStructsTemporal[j]->timestamp = tempo; vectorStructsTemporal[j]->value = valorTemp; } } } if(vectorStructsTemporal[0]->timestamp > timestampActualMayorBloques){ timestampActualMayorTemporales = vectorStructsTemporal[0]->timestamp; valueDeTimestampActualMayorTemporales = malloc(strlen(vectorStructsTemporal[0]->value)); //strcpy(valueDeTimestampActualMayorTemporales, vectorStructsTemporal[0]->value); valueDeTimestampActualMayorTemporales = vectorStructsTemporal[0]->value; // ESTO NO DEBERIA SER ASI, Y DEBERIA FUNCIONAR LA LINEA DE ARRIBA } fclose(archivoTemporal); free(pathTemporal); //free(vectorStructsTemporal) } } //cierra el while // si encontro alguno, me guarda el timestamp mayor en timestampActualMayorTemporales // y guarda el valor en valueDeTimestampActualMayorTemporales // si no hay ninguno en vectorStructsTemporal // entonces timestampActualMayorTemporales = -1 y // valueDeTimestampActualMayorTemporales = NULL closedir(directorioTemporal); // ---------------------------------------------------- // aca iria verificar los datos tamb de la memoria de la tabla //----------------------------------------------------- free(pathMetadata); free(pathParticionQueContieneKey); config_destroy(tamanioYBloques); config_destroy(metadata); // SI NO ENCUENTRA LA TABLA (lo de abajo) } else { char* mensajeALogear = malloc( strlen("Error: no existe una tabla con el nombre ") + strlen(tabla) + 1); strcpy(mensajeALogear, "Error: no existe una tabla con el nombre "); strcat(mensajeALogear, tabla); t_log* g_logger; //Si uso LOG_LEVEL_ERROR no lo imprime ni lo escribe g_logger = log_create("./erroresSelect.log", "LFS", 1, LOG_LEVEL_INFO); log_info(g_logger, mensajeALogear); log_destroy(g_logger); free(mensajeALogear); } } */
ba387b672b89029d3f8f9265407c15537c53bf16
[ "C" ]
1
C
hernan-arga/Prueba_Bitarray
d2ab65f3a412fbe2ba6a5e8248ab26749b98b6ce
64b40e20c315177e39e6eb6c10ffca74b37ce8a2
refs/heads/master
<file_sep>#!/bin/bash DEVICE="" MODEL="artik5" FORMAT="" WRITE="" TARNAME="" FILENAME="" FOLDERNAME="" FOLDERTMP="tizen_boot" BL1="bl1.bin" BL2="bl2.bin" UBOOT="u-boot.bin" TZSW="tzsw.bin" PARAMS="params.bin" INITRD="uInitrd" KERNEL="zImage" DTBARTIK5="exynos3250-artik5.dtb" DTBARTIK10="exynos5422-artik10.dtb" MODULESIMG="modules.img" ROOTFSIMG="rootfs.img" SYSTEMDATAIMG="system-data.img" USERIMG="user.img" MODULESPART=2 ROOTFSPART=3 SYSTEMDATAPART=5 USERPART=6 BL1_OFFSET=1 BL2_OFFSET=31 UBOOT_OFFSET=63 TZSW_OFFSET=719 PARAMS_OFFSET=1031 function show_usage { echo "Usage:" echo " sudo ./mk_sdboot.sh -f /dev/sd[x]" echo " sudo ./mk_sdboot.sh -w /dev/sd[x] <file name>" echo "" echo " Be careful, Just replace the /dev/sd[x] for your device!" } function partition_format { DISK=$DEVICE SIZE=`sfdisk -s $DISK` SIZE_MB=$((SIZE >> 10)) BOOT_SZ=32 MODULE_SZ=32 ROOTFS_SZ=2048 DATA_SZ=256 echo $SIZE_MB let "USER_SZ = $SIZE_MB - $BOOT_SZ - $ROOTFS_SZ - $DATA_SZ - $MODULE_SZ - 4" BOOT=boot ROOTFS=rootfs SYSTEMDATA=system-data USER=user MODULE=modules if [[ $USER_SZ -le 100 ]] then echo "We recommend to use more than 4GB disk" exit 0 fi echo "========================================" echo "Label dev size" echo "========================================" echo $BOOT" " $DISK"1 " $BOOT_SZ "MB" echo $MODULE" " $DISK"2 " $MODULE_SZ "MB" echo $ROOTFS" " $DISK"3 " $ROOTFS_SZ "MB" echo "[Extend]"" " $DISK"4" echo " "$SYSTEMDATA" " $DISK"5 " $DATA_SZ "MB" echo " "$USER" " $DISK"6 " $USER_SZ "MB" MOUNT_LIST=`mount | grep $DISK | awk '{print $1}'` for mnt in $MOUNT_LIST do umount $mnt done echo "Remove partition table..." dd if=/dev/zero of=$DISK bs=512 count=1 conv=notrunc sfdisk --in-order --Linux --unit M $DISK <<-__EOF__ 4,$BOOT_SZ,0xE,* ,$MODULE_SZ,,- ,$ROOTFS_SZ,,- ,,E,- ,$DATA_SZ,,- ,$USER_SZ,,- __EOF__ mkfs.vfat -F 16 ${DISK}1 -n $BOOT mkfs.ext4 -q ${DISK}2 -L $MODULE -F mkfs.ext4 -q ${DISK}3 -L $ROOTFS -F mkfs.ext4 -q ${DISK}5 -L $SYSTEMDATA -F mkfs.ext4 -q ${DISK}6 -L $USER -F } function find_model { TMPNAME=${TARNAME/artik10/found} if [ $TARNAME != $TMPNAME ]; then MODEL="artik10" PARAMS_OFFSET=1031 fi } function write_image { echo "writing $FILENAME ..." if [ $FILENAME == $BL1 ]; then dd if=$FOLDERNAME"/"$BL1 of=$DEVICE bs=512 seek=$BL1_OFFSET conv=notrunc return fi if [ $FILENAME == $BL2 ]; then dd if=$FOLDERNAME"/"$BL2 of=$DEVICE bs=512 seek=$BL2_OFFSET conv=notrunc return fi if [ $FILENAME == $UBOOT ]; then dd if=$FOLDERNAME"/"$UBOOT of=$DEVICE bs=512 seek=$UBOOT_OFFSET conv=notrunc return fi if [ $FILENAME == $TZSW ]; then dd if=$FOLDERNAME"/"$TZSW of=$DEVICE bs=512 seek=$TZSW_OFFSET conv=notrunc return fi if [ $FILENAME == $PARAMS ]; then dd if=$FOLDERNAME"/"$PARAMS of=$DEVICE bs=512 seek=$PARAMS_OFFSET conv=notrunc return fi if [ $FILENAME == $INITRD ] || [ $FILENAME == $KERNEL ] || [ $FILENAME == $DTBARTIK5 ] || [ $FILENAME == $DTBARTIK10 ]; then mkdir $FOLDERTMP mount ${DEVICE}1 $FOLDERTMP cp $FOLDERNAME"/"$FILENAME $FOLDERTMP sync umount $FOLDERTMP rm -rf $FOLDERTMP sync return fi if [ $FILENAME == $MODULESIMG ]; then dd if=$FOLDERNAME"/"$FILENAME of=${DEVICE}${MODULESPART} bs=1M return fi if [ $FILENAME == $ROOTFSIMG ]; then dd if=$FOLDERNAME"/"$FILENAME of=${DEVICE}${ROOTFSPART} bs=1M return fi if [ $FILENAME == $SYSTEMDATAIMG ]; then dd if=$FOLDERNAME"/"$FILENAME of=${DEVICE}${SYSTEMDATAPART} bs=1M return fi if [ $FILENAME == $USERIMG ]; then dd if=$FOLDERNAME"/"$FILENAME of=${DEVICE}${USERPART} bs=1M return fi } function write_images { FOLDERNAME=${TARNAME%%.*} find_model mkdir $FOLDERNAME for FILENAME in `tar xvf $TARNAME -C $FOLDERNAME` do write_image sync done rm -rf $FOLDERNAME } function cmd_run { if [ "$DEVICE" == "/dev/sdX" ]; then echo "Just replace the /dev/sdX for your device!" show_usage exit 0 fi if [ "$WRITE" == "1" ]; then if [ "$DEVICE" == "" ] || [ "$TARNAME" == "" ]; then show_usage exit 0 fi echo " === Start writing $TARNAME images === " write_images echo " === end writing $TARNAME images === " fi if [ "$FORMAT" == "1" ]; then if [ "$DEVICE" == "" ]; then show_usage exit 0 fi echo " === Start $DEVICE format === " partition_format echo " === end $DEVICE format === " fi } function check_args { if [ "$WRITE" == "" ] && [ "$FORMAT" == "" ]; then show_usage exit 0 fi } while test $# -ne 0; do option=$1 shift case $option in -f|--format) FORMAT="1" DEVICE=$1 shift ;; -w|--write) WRITE="1" DEVICE=$1 shift TARNAME=$1 shift ;; *) ;; esac done check_args cmd_run
ebab0e75f7e2fb380b1b42bbaa47006927f9a768
[ "Shell" ]
1
Shell
jinocho00/tizen_on_artik
113b3a67a0ef715ee0089e80db62e5b2cd42bce5
da6e920ed190f198dd0fdcbda464638105af0d07
refs/heads/master
<repo_name>TingTing01/Test3<file_sep>/Tourcan/WebContent/js/member/login.js firebase.initializeApp({ apiKey : "<KEY>", authDomain : "tourcan-1373.firebaseapp.com", databaseURL : "https://tourcan-1373.firebaseio.com", storageBucket : "tourcan-1373.appspot.com", }); $(function() { var doneHandler = function(result) { var credential, user; if (typeof (result.user) === "undefined") { user = result; } else { credential = result.credential; user = result.user; } $(".help-block").text(""); if (typeof (user) === "undefined") { $(".help-login-email").text("Signed out."); } else { $(".help-login-email").text("Welcome back, " + user.displayName); if (typeof (credential) !== "undefined") { console.log("Login with " + credential.provider); } } firebase.auth().currentUser.getToken().then( function(d) { $("<form action='login/continue' method='POST'>").append( $("<input name='token'>").val(d)).submit(); }); } var errorHandler = function(error) { console.log(error.email + ": " + error.code); $(".help-block").text(""); console.log(error); console.log((error.email !== "undefined" ? error.email + ": " + error.code : error.code)); if (typeof (error.credential) !== "undefined") console.log(error.credential.provider); if (error.code === 'auth/invalid-email') $(".help-login-email").text("無效的電子郵件地址"); if (error.code === 'auth/user-disabled') $(".help-login-email").text("帳號已停用,請聯絡管理員"); if (error.code === 'auth/user-not-found') $(".help-login-email").text("帳號不存在"); if (error.code === 'auth/wrong-password') $(".help-login-password").text("您輸入的帳號與密碼不符"); if (error.code === 'auth/operation-not-allowed') $(".help-oauth").text("該登入方式尚未開放"); if (error.code === 'auth/account-exists-with-different-credential') { firebase.auth().fetchProvidersForEmail(error.email).then( function(providers) { if (providers[0] === 'password') { $("#username").val(error.email); console.log("該email已由其他提供者註冊。如果這是您,請使用先前使用的方式登入"); return; } }) } } var popupLogin = function(provider) { firebase.auth().signInWithPopup(provider).then(doneHandler, errorHandler); } $("#signin").click( function(e) { e.preventDefault(); firebase.auth().signInWithEmailAndPassword( $("#username").val(), $("#password").val()).then( doneHandler, errorHandler); }); $(".omb_login .omb_socialButtons .omb_btn-google").click(function(e) { provider = new firebase.auth.GoogleAuthProvider(); provider.addScope('email'); provider.addScope('profile'); popupLogin(provider); }); $(".omb_login .omb_socialButtons .omb_btn-facebook").click(function(e) { provider = new firebase.auth.FacebookAuthProvider(); provider.addScope('email'); provider.addScope('user_friends'); popupLogin(provider); }); $(".omb_login .omb_socialButtons .omb_btn-github").click(function(e) { provider = new firebase.auth.GithubAuthProvider(); provider.addScope('user:email'); popupLogin(provider); }); $(".omb_login .omb_socialButtons .omb_btn-twitter").click(function(e) { provider = new firebase.auth.TwitterAuthProvider(); popupLogin(provider); }); }); $(function() { var doneHandler = function(result) { var credential, user; if (typeof (result.user) === "undefined") { user = result; } else { credential = result.credential; user = result.user; } $(".help-block").text(""); if (typeof (user) === "undefined") { $(".help-reg-email").text("Signed out."); } else { $(".help-login-email").text("Welcome join us, " + user.email); if (typeof (credential) !== "undefined") { //console.log("Login with " + credential.provider); } } $("#username").val(user.email); $("a[href='#login_form']").click(); } var errorHandler = function(error) { console.log(error.email + ": " + error.code); $(".help-block").text(""); console.log(error); console.log((error.email !== "undefined" ? error.email + ": " + error.code : error.code)); if (typeof (error.credential) !== "undefined") console.log(error.credential.provider); if (error.code === 'auth/invalid-email'){ $("#reg_username").parent() .removeClass("has-success has-error").addClass("has-error"); $(".help-reg-email").text("無效的電子郵件地址");} if (error.code === 'auth/email-already-in-use'){ $("#reg_username").parent() .removeClass("has-success has-error").addClass("has-error"); $(".help-reg-email").text("該電子郵件地址已被使用");} if (error.code === 'auth/operation-not-allowed'){ $("#reg_username").parent() .removeClass("has-success has-error").addClass("has-error"); $(".help-reg-email").text("不合法的操作,請洽詢管理員");} if (error.code === 'auth/weak-password'){ $("#reg_password").parent() .removeClass("has-success has-error").addClass("has-error"); $("#reg_password_2").parent() .removeClass("has-success has-error").addClass("has-error"); $(".help-reg-password").text("密碼安全性不足,請使用強式密碼");} } var timer; $("#reg_username").keyup( function() { var email = this.value; $(".help-reg-email").text(""); clearTimeout(timer); timer = setTimeout(function() { firebase.auth().fetchProvidersForEmail(email).then( function(providers) { if (providers.length > 0) { $("#reg_username").parent() .removeClass("has-success has-error").addClass("has-error"); $(".help-reg-email").text("該帳號已被使用"); }else{ $("#reg_username").parent() .removeClass("has-success has-error").addClass("has-success"); $(".help-reg-email").text(""); } }, errorHandler) }, 200); }); $("#reg_password").keyup( function() { $(".help-reg-password").text(""); if (this.value.length >= 8) { // No illegal character allowed if (!/[^A-Za-z0-9!@#$%^&*]/g.test(this.value)) { var point = 1; var msg = "必須包含"; if (/[A-Z]/g.exec(this.value) == null) { point--; msg = msg + "大寫字母、"; } ; if (/[a-z]/g.exec(this.value) == null) { point--; msg = msg + "小寫字母、"; } ; if (/[0-9]/g.exec(this.value) == null) { point--; msg = msg + "數字、"; } ; if (/[!@#$%^&*]/g.exec(this.value) == null) { point--; msg = msg + "特殊符號(!@#$%^&*)、"; } ; if (point < 0) { $("#reg_password").parent().removeClass( "has-success has-error").addClass( "has-error"); $(".help-reg-password").text( msg.substr(0, msg.length - 1)); } else { $("#reg_password").parent().removeClass( "has-success has-error").addClass( "has-success"); $(".help-reg-password").text(""); } } else { $("#reg_password").parent().removeClass( "has-success has-error").addClass("has-error"); $(".help-reg-password").text( "密碼限使用大小寫字母、數字、特殊符號(!@#$%^&*)"); } } else { $("#reg_password").parent().removeClass( "has-success has-error").addClass("has-error"); $(".help-reg-password").text("密碼長度不得低於8位"); } }); $("#reg_password_2").keyup( function() { if ($("#reg_password_2").val() != $("#reg_password").val()) { $("#reg_password_2").parent().removeClass( "has-success has-error").addClass("has-error"); $(".help-reg-password").text("兩次輸入的密碼不一致"); } else { $("#reg_password_2").parent().removeClass( "has-success has-error").addClass("has-success"); $(".help-reg-password").text(""); } }); $("#signup").click( function(e) { e.preventDefault(); firebase.auth().createUserWithEmailAndPassword( $("#reg_username").val(), $("#reg_password").val()).then( doneHandler, errorHandler); }); });<file_sep>/Tourcan/src/com/tourcan/resp/model/RespVO.java package com.tourcan.resp.model; import java.io.Serializable; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; import com.google.gson.annotations.Expose; import com.tourcan.theme.model.ThemeVO; @SuppressWarnings("serial") public class RespVO implements Serializable { @Expose private Integer resp_id; @Expose private String resp_topic; @Expose private String resp_article; @Expose private Timestamp resp_time; @Expose private String mem_uid; @Expose private Integer theme_id; // private Set<ThemeVO> themeno =new HashSet<ThemeVO>(); // // public Set<ThemeVO> getThemeno() { // return themeno; // } // public void setThemeno(Set<ThemeVO> themeno) { // this.themeno = themeno; // } public Integer getResp_id() { return resp_id; } public void setResp_id(Integer resp_id) { this.resp_id = resp_id; } public String getResp_topic() { return resp_topic; } public void setResp_topic(String resp_topic) { this.resp_topic = resp_topic; } public String getResp_article() { return resp_article; } public void setResp_article(String resp_article) { this.resp_article = resp_article; } public Timestamp getResp_time() { return resp_time; } public void setResp_time(Timestamp resp_time) { this.resp_time = resp_time; } public String getMem_uid() { return mem_uid; } public void setMem_uid(String mem_uid) { this.mem_uid = mem_uid; } public Integer getTheme_id() { return theme_id; } public void setTheme_id(Integer theme_id) { this.theme_id = theme_id; } } <file_sep>/Tourcan/src/com/tourcan/trip/controller/TripServlet.java package com.tourcan.trip.controller; import java.io.BufferedReader; import java.io.IOException; import java.sql.Timestamp; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import javax.servlet.RequestDispatcher; 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 org.json.JSONObject; import com.google.gson.Gson; import com.tourcan.mem.model.MemVO; import com.tourcan.trip.model.TripService; import com.tourcan.trip.model.TripVO; import com.tourcan.tripitem.model.TripitemService; @WebServlet(urlPatterns={"/trip/TripServlet","/tripitem/TripServlet"}) public class TripServlet extends HttpServlet { private static final long serialVersionUID = 1L; public TripServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); String method = request.getParameter("method"); // if(method.equals("findByID")){ // String id = request.getParameter("tripId"); // try{ // Integer tripno =null; // try{ // tripno =new Integer(id); // }catch (Exception e) { // throw new Exception(); // } // TripService trsv = new TripService(); // TripVO tripVO =trsv.findById(tripno); // request.setAttribute("tripVO",tripVO); // System.out.println(tripVO.getTrip_id()); // String url = "/trip/???????.jsp"; // RequestDispatcher successView = request.getRequestDispatcher(url); // successView.forward(request, response); // }catch (Exception e) { // RequestDispatcher failureView = request.getRequestDispatcher("/trip/listOneFromMemTrip.jsp"); // failureView.forward(request, response); // } // } if(method.equals("findByMemuid")){ JSONObject chResult = new JSONObject(); List<TripVO> tripVO = null; try{ String uid = request.getParameter("mem_uid"); if(uid==null||uid.trim().length()==0) chResult.append("chResult", "error"); if(chResult.length()>0){ throw new Exception(); }else{ TripService tsv =new TripService(); tripVO = tsv.findByMemuid(uid); if(tripVO.size()!=0){ Gson gson =new Gson(); String strjson = gson.toJson(tripVO); response.getWriter().println(strjson); }else{ chResult.append("chResult", "sreach null"); response.getWriter().println(chResult.toString()); } } }catch (Exception e) { chResult.append("chResult", "sreach error"); response.getWriter().println(chResult.toString()); } } // ----------------findById---------------- if (method.equals("getOneById")) { JSONObject checkResult = new JSONObject(); Integer tripId = null; TripVO tripVO = null; try { String id = request.getParameter("trip_id"); // System.out.println(id); if (id == null || id.trim().length() == 0) { checkResult.append("checkResult", "請輸入行程ID"); } else { try { tripId = new Integer(id); } catch (Exception e) { // e.printStackTrace(); checkResult.append("checkResult", "行程ID格式不正確"); } } TripService tripSvc = new TripService(); tripVO = tripSvc.findById(tripId); if (tripVO != null) { JSONObject obj = new JSONObject(tripVO); response.getWriter().println(obj.toString()); } else { checkResult.append("checkResult", "查無資料"); response.getWriter().println(checkResult.toString()); } } catch (Exception e) { checkResult.append("false", "查詢失敗"); response.getWriter().println(checkResult.toString()); } } // ----------------findByName---------------- String tripName = request.getParameter("tripName"); List<TripVO> tripVO = null; if (method.equals("getByName")) { JSONObject checkResult = new JSONObject(); try { if (tripName == null || tripName.trim().length() == 0) checkResult.append("result", "請輸入行程名稱"); if (checkResult.length() > 0) { throw new Exception(); } else { TripService tripSvc = new TripService(); tripVO = tripSvc.findByName(tripName); if (tripVO.size() != 0) { Gson gson = new Gson(); String jsonG = gson.toJson(tripVO); // System.out.println(jsonG); response.getWriter().println(jsonG); } else { checkResult.append("result", "查無資料"); response.getWriter().println(checkResult.toString()); } } // ***************************其他可能的錯誤處理*************************************//* } catch (Exception e) { checkResult.append("result", "查詢失敗"); System.out.println("err=" + checkResult); response.getWriter().println(checkResult.toString()); } } // ----------------getAll---------------- if (method.equals("getAll")) { JSONObject checkResult = new JSONObject(); try { TripService tripSvc = new TripService(); tripVO = tripSvc.getAll(); if (tripVO.size() != 0) { Gson gson = new Gson(); String jsonG = gson.toJson(tripVO); // System.out.println(jsonG); response.getWriter().println(jsonG); } // ***************************其他可能的錯誤處理*************************************//* } catch (Exception e) { checkResult.append("result", "查詢失敗"); System.out.println("err=" + checkResult); response.getWriter().println(checkResult.toString()); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ----------------INSERT---------------- request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); BufferedReader br = request.getReader(); String tripName = null; Timestamp tripCtime = null; Integer tripPrice = null; String memUid = null; JSONObject checkResult = new JSONObject(); // checking result TripVO tripVO = null; try { tripVO = new Gson().fromJson(br, TripVO.class); tripName = tripVO.getTrip_name(); if (tripName == null || tripName.trim().isEmpty()) { checkResult.append("trip_name", "請輸入旅遊名稱。"); } else if (tripName.trim().length() >= 50) { checkResult.append("trip_name", "旅遊名稱不得超過50個字"); } // 抓出建立當下時間 tripCtime = new Timestamp(System.currentTimeMillis()+8*60*60*1000); tripVO.setTrip_ctime(tripCtime); try{ tripPrice = tripVO.getTrip_price(); }catch(Exception e){ } MemVO memVO = (MemVO) request.getSession().getAttribute("vo"); memUid = memVO.getMem_uid(); tripVO.setMem_uid(memUid); if (checkResult.length() > 0) { throw new Exception(); } else { TripService srv = new TripService(); srv.insertTrip(tripVO); checkResult.append("trip_id", tripVO.getTrip_id()); checkResult.append("result", "新增成功"); response.getWriter().println(checkResult.toString()); } } catch (Exception e) { checkResult.append("result", "新增失敗。"); response.getWriter().println(checkResult.toString()); e.printStackTrace(); } } protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ----------------UPDATE---------------- request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); BufferedReader br = request.getReader(); StringBuffer sb = new StringBuffer(128); String json; while ((json = br.readLine()) != null) sb.append(json); json = sb.toString(); System.out.println(json); String tripName = null; Integer tripId = null; Timestamp tripCtime = null; Integer tripPrice = null; String memUid = null; JSONObject checkResult = new JSONObject(); // checking result try { JSONObject obj = new JSONObject(json); // received and parsed JSON tripName = obj.getString("trip_name"); tripId = obj.getInt("trip_id"); // 抓出修改當下時間 tripCtime = new Timestamp(System.currentTimeMillis()+8*60*60*1000); tripPrice =obj.getInt("trip_price"); memUid = obj.getString("mem_uid"); // 抓出會員Id 且 不能修改 // System.out.println(tripName + "," + tripId + "," + tripCtime + "," + tripPrice + "," + memUid); if (checkResult.length() > 0) { throw new Exception(); } else { TripService srv = new TripService(); srv.updateTrip(tripName, tripId, tripCtime, tripPrice, memUid); checkResult.append("result", "更新成功"); response.getWriter().println(checkResult.toString()); } } catch (Exception e) { checkResult.append("result", "更新失敗。"); response.getWriter().println(checkResult.toString()); // e.printStackTrace(); } } protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ----------------DELETE---------------- request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); Integer tripId = null; /***************************** 刪除一筆資料 ************************************************************************/ Map<String, String> errorMsgs = new HashMap<>(); /**************************** * 1.接收請求參數 - 輸入格式的錯誤處理 **********************/ String id = request.getParameter("tripId"); try { System.out.println(id); if (id == null || (id.trim()).length() == 0) { errorMsgs.put("errMsg", "請輸入行程ID"); } else { try { tripId = new Integer(id); } catch (Exception e) { errorMsgs.put("errMsg", "行程ID格式不正確"); } } /*************************** 2.開始刪除單筆資料 *****************************************/ TripitemService itsvc =new TripitemService(); itsvc.deleteForTripID(tripId); TripService tripSvc = new TripService(); try { tripSvc.deleteTrip(tripId); } catch (Exception e) { errorMsgs.put("errMsg", "查無資料"); } /*************************** 其他可能的錯誤處理 **************************************/ } catch (Exception e) { errorMsgs.put("errMsg", "無法取得資料:" + e.getMessage()); } JSONObject json = new JSONObject(errorMsgs); response.getWriter().println(json.toString()); } } <file_sep>/Tourcan/src/com/tourcan/util/AttRestConfig.java package com.tourcan.util; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; @ApplicationPath("attractions") public class AttRestConfig extends ResourceConfig { public AttRestConfig() { this.packages("com.tourcan.att"); } } <file_sep>/Tourcan/src/com/tourcan/region/model/RegionJdbcDAO.java package com.tourcan.region.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class RegionJdbcDAO implements RegionDAO { // Ver.JDBC private static final String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=Tourcan"; private static final String userid = "sa"; private static final String passwd = "<PASSWORD>"; private static int STMT_SHIFT = 1; // 1 for JDBC, 0 for Hibernate // private boolean manual_mode = false; // private Connection conn = null; // private PreparedStatement pstmt = null; // SQL statements private static final String INSERT_STMT = "INSERT INTO region ( " + "region_name, region_area ) " + "VALUES ( ?, ? )"; private static final String GET_ALL_STMT = "SELECT " + "region_name, region_area, region_id " + "FROM region order by region_id"; private static final String GET_BY_ID_STMT = "SELECT " + "region_name, region_area, region_id " + "FROM region where region_id = ?"; private static final String GET_BY_AREA_STMT = "SELECT " + "region_name, region_area, region_id " + "FROM region where region_area = ?"; private static final String GET_BY_NAME_STMT = "SELECT " + "region_name, region_area, region_id " + "FROM region where region_name like ?"; private static final String DELETE_STMT = "DELETE FROM region where region_id = ?"; private static final String UPDATE_STMT = "UPDATE region set " + "region_name=?, region_area=? " + "where region_id = ?"; @Override public void insert(RegionVO regionVO) { Connection conn = null; PreparedStatement pstmt = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(INSERT_STMT); pstmt.setString(0 + STMT_SHIFT, regionVO.getRegion_name()); pstmt.setInt(1 + STMT_SHIFT, regionVO.getRegion_area()); // pstmt.setInt(2 + STMT_SHIFT, regionVO.getRegion_id()); pstmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void update(RegionVO regionVO) { Connection conn = null; PreparedStatement pstmt = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(UPDATE_STMT); pstmt.setString(0 + STMT_SHIFT, regionVO.getRegion_name()); pstmt.setInt(1 + STMT_SHIFT, regionVO.getRegion_area()); pstmt.setInt(2 + STMT_SHIFT, regionVO.getRegion_id()); pstmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void delete(RegionVO regionVO) { Connection conn = null; PreparedStatement pstmt = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(DELETE_STMT); pstmt.setInt(0 + STMT_SHIFT, regionVO.getRegion_id()); pstmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public RegionVO findById(Integer region_id) { Connection conn = null; PreparedStatement pstmt = null; RegionVO region = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(GET_BY_ID_STMT); pstmt.setInt(0 + STMT_SHIFT, region_id); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { // rs.getMetaData(); region = new RegionVO(); region.setRegion_name(rs.getString("region_name")); region.setRegion_area(rs.getInt("region_area")); ; region.setRegion_id(rs.getInt("region_id")); ; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return region; } @Override public List<RegionVO> findByArea(Integer region_area) { Connection conn = null; PreparedStatement pstmt = null; List<RegionVO> regions = new ArrayList<RegionVO>(); try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(GET_BY_AREA_STMT); pstmt.setInt(0 + STMT_SHIFT, region_area); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { // rs.getMetaData(); RegionVO region = new RegionVO(); region.setRegion_name(rs.getString("region_name")); region.setRegion_area(rs.getInt("region_area")); ; region.setRegion_id(rs.getInt("region_id")); ; regions.add(region); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return regions; } @Override public List<RegionVO> findByName(String region_name) { Connection conn = null; PreparedStatement pstmt = null; List<RegionVO> regions = new ArrayList<RegionVO>(); try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(GET_BY_NAME_STMT); pstmt.setString(0 + STMT_SHIFT, region_name); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { // rs.getMetaData(); RegionVO region = new RegionVO(); region.setRegion_name(rs.getString("region_name")); region.setRegion_area(rs.getInt("region_area")); ; region.setRegion_id(rs.getInt("region_id")); ; regions.add(region); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return regions; } @Override public List<RegionVO> getAll() { Connection conn = null; PreparedStatement pstmt = null; List<RegionVO> regions = new ArrayList<RegionVO>(); try { Class.forName(driver); conn = DriverManager.getConnection(url, userid, passwd); pstmt = conn.prepareStatement(GET_ALL_STMT); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { // rs.getMetaData(); RegionVO region = new RegionVO(); region.setRegion_name(rs.getString("region_name")); region.setRegion_area(rs.getInt("region_area")); ; region.setRegion_id(rs.getInt("region_id")); ; regions.add(region); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return regions; } public static void main(String[] args) { for (RegionVO att : new RegionJdbcDAO().getAll()) { System.out.println(att.getRegion_id() + ": " + att.getRegion_name() + " @ " + att.getRegion_area()); } } }<file_sep>/Tourcan/src/com/tourcan/att/model/AttDAO_interface.java package com.tourcan.att.model; import java.util.List; public interface AttDAO_interface { public Integer insert(AttVO attVO); public void update(AttVO attVO); public void delete(Integer att_id); public AttVO findById(Integer att_id); public List<AttVO> findByName(String att_name); public List<AttVO> getAll(); public List<AttVO> findByRegionId(Integer region_id); } <file_sep>/Tourcan/src/com/tourcan/hotel/model/HotelVO.java package com.tourcan.hotel.model; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.tourcan.region.model.RegionVO; @XmlRootElement(name = "hotel") @JsonIgnoreProperties(ignoreUnknown=true) public class HotelVO implements java.io.Serializable { private static final long serialVersionUID = 1L; // private Integer att_area; private String hotel_name; private Integer hotel_id; // private Integer region_id; private RegionVO regionVO; private String hotel_addr; private Double hotel_price; private String hotel_phone; private Integer hotel_class; private String hotel_url; private Double hotel_lat; private Double hotel_lng; public String getHotel_name() { return hotel_name; } public void setHotel_name(String hotel_name) { this.hotel_name = hotel_name; } public Integer getHotel_id() { return hotel_id; } public void setHotel_id(Integer hotel_id) { this.hotel_id = hotel_id; } // public Integer getRegion_id() { // return region_id; // } // // public void setRegion_id(Integer region_id) { // this.region_id = region_id; // } public String getHotel_addr() { return hotel_addr; } public void setHotel_addr(String hotel_addr) { this.hotel_addr = hotel_addr; } public Double getHotel_price() { return hotel_price; } public void setHotel_price(Double hotel_price) { this.hotel_price = hotel_price; } public String getHotel_phone() { return hotel_phone; } public void setHotel_phone(String hotel_phone) { this.hotel_phone = hotel_phone; } public Integer getHotel_class() { return hotel_class; } public void setHotel_class(Integer hotel_class) { this.hotel_class = hotel_class; } public String getHotel_url() { return hotel_url; } public void setHotel_url(String hotel_url) { this.hotel_url = hotel_url; } public Double getHotel_lat() { return hotel_lat; } public void setHotel_lat(Double hotel_lat) { this.hotel_lat = hotel_lat; } public Double getHotel_lng() { return hotel_lng; } public void setHotel_lng(Double hotel_lng) { this.hotel_lng = hotel_lng; } public RegionVO getRegionVO() { return regionVO; } public void setRegionVO(RegionVO regionVO) { this.regionVO = regionVO; } } <file_sep>/Tourcan/src/com/tourcan/theme/model/ThemeService.java package com.tourcan.theme.model; import java.sql.Timestamp; import java.util.List; public class ThemeService { private Theme_interface dao; public ThemeService() { dao = new ThemeDAO(); } public void update(ThemeVO themeVO) { dao.update(themeVO); } public void delete(Integer theme_id) { dao.delete(theme_id); } public ThemeVO findById(Integer theme_id) { return dao.findById(theme_id); } public List<ThemeVO> findByTopic(String theme_topic) { return dao.findByTopic(theme_topic); } public List<ThemeVO> getAll() { return dao.getAll(); } public List<ThemeVO> findByMemuid(String mem_uid) { return dao.findByMemuid(mem_uid); } public void insert(ThemeVO themeVO) { dao.insert(themeVO); } } <file_sep>/Tourcan/src/com/tourcan/region/controller/RegionServlet.java package com.tourcan.region.controller; import java.io.IOException; import java.io.PrintWriter; 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 org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.google.gson.Gson; import com.tourcan.region.model.RegionDAO; import com.tourcan.region.model.RegionHibernateDAO; @WebServlet("/att/RegionServlet") public class RegionServlet extends HttpServlet { private static final long serialVersionUID = 1L; ApplicationContext context; @Override public void init() throws ServletException { context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); RegionDAO dao = context.getBean(RegionHibernateDAO.class); PrintWriter out = response.getWriter(); // out.println(context.getBean(Gson.class).toJson(dao.getAll())); out.println(context.getBean(Gson.class).toJson(dao.getAll())); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } <file_sep>/Tourcan/src/com/tourcan/mem/model/MemVO.java package com.tourcan.mem.model; import java.util.Date; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.tourcan.region.model.RegionVO; @XmlRootElement(name = "member") @JsonIgnoreProperties(ignoreUnknown=true) public class MemVO implements java.io.Serializable { private static final long serialVersionUID = 1L; // TODO rebuild DB to fit new design: mem_uid as primary key // private Integer mem_id; //replaced with mem_uid private String mem_lname; private String mem_fname; private String mem_nick; // private String mem_account; // replaced with Firebase // private String mem_pwd; // replaced with Firebase private String mem_email; private String mem_mobile; private byte[] mem_photo; private Integer mem_sex; // private Integer region_id; // still necessary? private RegionVO regionVO; private Date mem_bdate; private Date mem_regtime; private String mem_uid; // public Integer getMem_id() { // return mem_id; // } // // public void setMem_id(Integer mem_id) { // this.mem_id = mem_id; // } public String getMem_lname() { return mem_lname; } public void setMem_lname(String mem_lname) { this.mem_lname = mem_lname; } public String getMem_fname() { return mem_fname; } public void setMem_fname(String mem_fname) { this.mem_fname = mem_fname; } public String getMem_nick() { return mem_nick; } public void setMem_nick(String mem_nick) { this.mem_nick = mem_nick; } // public String getMem_account() { // return mem_account; // } // // public void setMem_account(String mem_account) { // this.mem_account = mem_account; // } // // public String getMem_pwd() { // return mem_pwd; // } // // public void setMem_pwd(String mem_pwd) { // this.mem_pwd = mem_pwd; // } public String getMem_email() { return mem_email; } public void setMem_email(String mem_email) { this.mem_email = mem_email; } public String getMem_mobile() { return mem_mobile; } public void setMem_mobile(String mem_mobile) { this.mem_mobile = mem_mobile; } public byte[] getMem_photo() { return mem_photo; } public void setMem_photo(byte[] mem_photo) { this.mem_photo = mem_photo; } public Integer getMem_sex() { return mem_sex; } public void setMem_sex(Integer mem_sex) { this.mem_sex = mem_sex; } // public Integer getRegion_id() { // return region_id; // } // // public void setRegion_id(Integer region_id) { // this.region_id = region_id; // } public Date getMem_bdate() { return mem_bdate; } public void setMem_bdate(Date mem_bdate) { this.mem_bdate = mem_bdate; } public Date getMem_regtime() { return mem_regtime; } public void setMem_regtime(Date mem_regtime) { this.mem_regtime = mem_regtime; } public String getMem_uid() { return mem_uid; } public void setMem_uid(String mem_uid) { this.mem_uid = mem_uid; } public RegionVO getRegionVO() { return regionVO; } public void setRegionVO(RegionVO regionVO) { this.regionVO = regionVO; } } <file_sep>/Tourcan/WebContent/js/common.js /** * */ $.ajax({ url : baseurl + "/att/RegionServlet", method : "GET", contentType : "application/json; charset=UTF-8", dataType : "json" }).done(function(l) { var f = document.createDocumentFragment(); for (var i = 1; i < l.length; i++) f.appendChild(new Option(l[i].region_name, l[i].region_id)); $("#region_id").append(f); }).fail(function(xhr) { console.log("Get region list unsuccessful."); }); $(".datepicker").datepicker({ dateFormat : "yy-mm-dd", //dayNamesMin : [ "日", "月", "火", "水", "木", "金", "土" ], dayNamesMin : [ "日", "一", "二", "三", "四", "五", "六" ], //monthNames: ["睦月", "如月", "彌生", "卯月", "皐月", "水無月", "文月", "葉月", "長月", "神無月", "霜月", "師走" ], //monthNames: ["端月", "花月", "梅月", "桐月", "蒲月", "伏月", "荔月", "桂月", "菊月", "陽月", "葭月", "臘月" ], monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], monthNamesShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], showMonthAfterYear: true, changeYear: true, changeMonth: true, firstDay : 1, onClose : function(){$(this).blur()} });<file_sep>/Tourcan/src/com/tourcan/dashboard/controller/AttList.java package com.tourcan.dashboard.controller; import java.io.IOException; 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 com.tourcan.att.model.AttDAO; import com.tourcan.region.model.RegionDAO; import com.tourcan.util.ApplicationContextUtils; @WebServlet({ "/adridores/att" }) public class AttList extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("attVO", ((AttDAO) ApplicationContextUtils.getContext().getBean("attDAO")).getAll()); req.setAttribute("regionVO", ((RegionDAO) ApplicationContextUtils.getContext().getBean("regionDAO")).getAll()); req.getRequestDispatcher("/WEB-INF/adridores/att.jsp").forward(req, resp); } } <file_sep>/Tourcan/src/com/tourcan/quest/model/QuestDAO_interface.java package com.tourcan.quest.model; import java.util.List; public interface QuestDAO_interface { public void insert(QuestVO questVO); public void update(QuestVO questVO); public void delete(Integer quest_id); public QuestVO findById(Integer quest_id); public List<QuestVO> findByName(String quest_topic); public List<QuestVO> findByUid(String mem_uid); public List<QuestVO> getAll(); } <file_sep>/Tourcan/src/com/tourcan/dashboard/controller/HotelList.java package com.tourcan.dashboard.controller; import java.io.IOException; 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 com.tourcan.hotel.model.HotelDAO; import com.tourcan.region.model.RegionDAO; import com.tourcan.util.ApplicationContextUtils; @WebServlet({ "/adridores/hotel" }) public class HotelList extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("hotelVO", ((HotelDAO) ApplicationContextUtils.getContext().getBean("hotelDAO")).getAll()); req.setAttribute("regionVO", ((RegionDAO) ApplicationContextUtils.getContext().getBean("regionDAO")).getAll()); req.getRequestDispatcher("/WEB-INF/adridores/hotel.jsp").forward(req, resp); } } <file_sep>/Tourcan/src/com/tourcan/hotel/controller/HotelService.java package com.tourcan.hotel.controller; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.tika.Tika; import com.tourcan.hotel.model.HotelDAO; import com.tourcan.hotel.model.HotelVO; import com.tourcan.photo.model.PhotoDAO_interface; import com.tourcan.photo.model.PhotoVO; import com.tourcan.util.ApplicationContextUtils; @Path("/") public class HotelService { @Context HttpServletRequest request; @Context HttpServletResponse response; HotelDAO dao = (HotelDAO) ApplicationContextUtils.getContext().getBean("hotelDAO"); PhotoDAO_interface pdao = (PhotoDAO_interface) ApplicationContextUtils.getContext().getBean("photoDAO"); @GET @Path("{id: [0-9]+}") @Produces({ MediaType.APPLICATION_JSON }) public Response queryById(@PathParam("id") Integer id) { HotelVO vo; if ((vo = dao.findById(id)) == null) { // 404 Not found HashMap<String, String> msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "id not exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { // 200 OK return Response.status(Status.OK).entity(vo).build(); } } @GET @Path("{id: [0-9]+}") @Produces({ MediaType.TEXT_HTML }) public void queryById_static(@PathParam("id") Integer id) { response.setCharacterEncoding("UTF-8"); try { HotelVO vo = dao.findById(id); // 200 OK request.setAttribute("hotelVO", vo); ArrayList<String> imgs = new ArrayList<String>(); for (PhotoVO pvo : pdao.findByHotleId(id)) imgs.add(request.getContextPath() + request.getServletPath() + request.getPathInfo() + "/photos/" + pvo.getPhoto_id()); request.setAttribute("imgs", imgs); request.setAttribute("pageName", "飯店"); request.getRequestDispatcher("/WEB-INF/hotel/fs_listOneAtt.jsp").forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @GET @Path("{id: [0-9]+}/photos") @Produces({ MediaType.APPLICATION_JSON }) public Response queryPhotosById(@PathParam("id") Integer id) { HashMap<String, Object> msg = new HashMap<String, Object>(); if (dao.findById(id) == null) { // 404 Not found msg.put("result", "failure"); msg.put("error", "id not exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { // 200 OK ArrayList<String> imgPath = new ArrayList<String>(); for (PhotoVO pvo : pdao.findByHotleId(id)) imgPath.add(request.getContextPath() + request.getServletPath() + request.getPathInfo() + "/" + pvo.getPhoto_id()); msg.put("result", "success"); msg.put("imgs", imgPath); return Response.status(Status.OK).entity(msg).build(); } } @GET @Path("{id: [0-9]+}/photos/{pid: [0-9]+}") public void queryPhotoById(@PathParam("id") Integer id, @PathParam("pid") Integer pid) { HotelVO vo; PhotoVO pvo; try { OutputStream out = response.getOutputStream(); if ((vo = dao.findById(id)) == null || (pvo = pdao.findById(pid)) == null || vo.getHotel_id() != pvo.getHotel_id()) { // 404 Not found response.sendError(HttpServletResponse.SC_NOT_FOUND); } else if (vo.getHotel_id() != pvo.getHotel_id()) { // 404 Not found response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { // 200 OK byte[] photo = pvo.getPhoto_file(); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Content-Type", ApplicationContextUtils.getContext().getBean(Tika.class).detect(photo)); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "inline"); response.setContentLength(photo.length); out.write(photo); } } catch (IOException e) { // 500 Internal server error e.printStackTrace(); } } @GET @Path("/names/{name}") @Produces({ MediaType.APPLICATION_JSON }) public Response queryByName(@PathParam("name") String name) { List<HotelVO> vos; if ((vos = dao.findByName(name)) == null) { // 404 Not found HashMap<String, String> msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "no matched entry exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { // 200 OK return Response.status(Status.OK).entity(vos).build(); } } @GET @Path("/name/{name}") @Produces({ MediaType.TEXT_HTML }) public void queryByName_static(@PathParam("name") String name) { response.setCharacterEncoding("UTF-8"); try { List<HotelVO> vos = dao.findByName(name); // 200 OK request.setAttribute("hotelVO", vos); request.setAttribute("pageName", "飯店"); request.getRequestDispatcher("/WEB-INF/hotel/fs_List.jsp").forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @GET @Path("/regions/{id}") @Produces({ MediaType.APPLICATION_JSON }) public Response queryByRegion(@PathParam("id") Integer region_id) { List<HotelVO> vos; if ((vos = dao.findByRegionId(region_id)) == null) { // 404 Not found HashMap<String, String> msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "no matched entry exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { // 200 OK return Response.status(Status.OK).entity(vos).build(); } } @GET @Path("/region/{id}") @Produces({ MediaType.TEXT_HTML }) public void queryByRegion_static(@PathParam("id") Integer region_id) { response.setCharacterEncoding("UTF-8"); try { List<HotelVO> vos = dao.findByRegionId(region_id); // 200 OK request.setAttribute("hotelVO", vos); request.setAttribute("pageName", "飯店"); request.getRequestDispatcher("/WEB-INF/hotel/fs_List.jsp").forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @GET @Produces({ MediaType.APPLICATION_JSON }) public Response queryAll() { List<HotelVO> vos = dao.getAll(); if ((vos = dao.getAll()) == null) { // 404 Not found HashMap<String, String> msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "no data."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { // 200 OK return Response.status(Status.OK).entity(vos).build(); } } @GET @Produces({ MediaType.TEXT_HTML }) public void queryAll_static() { response.setCharacterEncoding("UTF-8"); try { List<HotelVO> vos = dao.getAll(); List<String> imgs = new ArrayList<String>(); for (HotelVO hvo : vos) { // System.out.println(request.getPathInfo()); List<PhotoVO> pvo; if ((pvo = pdao.findByHotleId(hvo.getHotel_id())) != null && pvo.size() > 0) { imgs.add(request.getContextPath() + request.getServletPath() + "/" + hvo.getHotel_id() + "/photos/" + pvo.get(0).getPhoto_id()); }else{ imgs.add(request.getContextPath() + "/images/noInfo.jpg"); } } // 200 OK request.setAttribute("imgs", imgs); request.setAttribute("hotelVO", vos); request.setAttribute("pageName", "飯店"); request.getRequestDispatcher("/WEB-INF/hotel/fs_List.jsp").forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public Response insertHotel(HotelVO vo) { HashMap<String, Object> msg = null; // for general message, such as OK, failure HashMap<String, String> err = null; // for column-specific message, such as hotel_name is invalid. if (vo.getHotel_id() != null) { if ((dao.findById(vo.getHotel_id())) == null) { // 404 Not found msg = new HashMap<String, Object>(); msg.put("result", "failure"); msg.put("error", "id not exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { // 409 Conflict msg = new HashMap<String, Object>(); msg.put("result", "failure"); msg.put("error", "id already exist."); return Response.status(Status.CONFLICT).entity(msg).build(); } } err = new HashMap<String, String>(); // hotel_name if (vo.getHotel_name() == null) { err.put("hotel_name", "can't be empty."); } else { if (vo.getHotel_name().trim().length() == 0) err.put("hotel_name", "can't be empty."); if (vo.getHotel_name().trim().length() > 60) err.put("hotel_name", "too long."); } // region_id if (vo.getRegionVO() == null || vo.getRegionVO().getRegion_id() < 0 || vo.getRegionVO().getRegion_id() == 0) err.put("region_id", "must provide."); // phone_addr if (vo.getHotel_addr() == null) { err.put("hotel_addr", "can't be empty."); } else { if (vo.getHotel_addr().trim().length() == 0) err.put("hotel_addr", "can't be empty."); if (vo.getHotel_addr().trim().length() >= 60) err.put("hotel_addr", "too long."); } // hotel_price if (vo.getHotel_price() == null) { vo.setHotel_price(-1.0); } else { if (vo.getHotel_price() <= -1) err.put("hotel_price", "invalid price range."); } // hotel_phone if (vo.getHotel_phone() == null) { vo.setHotel_phone(""); } else { if (vo.getHotel_phone().trim().length() >= 20) err.put("hotel_phone", "too long."); } // hotel_class if (vo.getHotel_class() == null) { vo.setHotel_class(-1); } else { if (vo.getHotel_class() <= -1 || vo.getHotel_class() > 10) err.put("hotel_class", "invalid ranking."); } // hotel_url if (vo.getHotel_url() == null) { vo.setHotel_url(""); } else { if (vo.getHotel_phone().trim().length() >= 60) err.put("hotel_url", "too long."); } // hotel_lat if (vo.getHotel_lat() == null) { err.put("hotel_lat", "invalid coordinate format."); } else { if (vo.getHotel_lat() > 90 || vo.getHotel_lat() < -90) err.put("hotel_lat", "invalid coordinate format."); } // hotel_lng if (vo.getHotel_lng() == null) { err.put("hotel_lng", "invalid coordinate format."); } else { if (vo.getHotel_lng() > 180 || vo.getHotel_lng() < -180) err.put("hotel_lng", "invalid coordinate format."); } // update database if (err.size() > 0) { // 400 Bad request msg = new HashMap<String, Object>(); msg.put("result", "validation-error"); msg.put("error", "invalid user input."); msg.put("validation", err); return Response.status(Status.BAD_REQUEST).entity(msg).build(); } else { try { dao.insert(vo); // 201 Created msg = new HashMap<String, Object>(); msg.put("result", "success"); msg.put("hotel_id", vo.getHotel_id()); return Response.status(Status.CREATED).entity(msg).build(); } catch (Exception e) { e.printStackTrace(); // 500 Internal server error msg = new HashMap<String, Object>(); msg.put("result", "failure"); msg.put("error", "insert unsuccessful."); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } } @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public Response updateHotel(HotelVO vo) { HashMap<String, String> msg = null; // for general message, such as OK, failure HashMap<String, String> err = new HashMap<String, String>(); // for column-specific message, such as hotel_name is invalid. // checking input // hotel_id if (vo.getHotel_id() == null) { err.put("hotel_id", "must provide."); } else { if ((dao.findById(vo.getHotel_id())) == null) { // 404 Not found msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "id not exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } } // hotel_name if (vo.getHotel_name() == null) { err.put("hotel_name", "can't be empty."); } else { if (vo.getHotel_name().trim().length() == 0) err.put("hotel_name", "can't be empty."); if (vo.getHotel_name().trim().length() > 60) err.put("hotel_name", "too long."); } // region_id if (vo.getRegionVO() == null || vo.getRegionVO().getRegion_id() < 0 || vo.getRegionVO().getRegion_id() == 0) err.put("region_id", "must provide."); // phone_addr if (vo.getHotel_addr() == null) { err.put("hotel_addr", "can't be empty."); } else { if (vo.getHotel_addr().trim().length() == 0) err.put("hotel_addr", "can't be empty."); if (vo.getHotel_addr().trim().length() >= 60) err.put("hotel_addr", "too long."); } // hotel_price if (vo.getHotel_price() == null) { vo.setHotel_price(-1.0); } else { if (vo.getHotel_price() <= -1) err.put("hotel_price", "invalid price range."); } // hotel_phone if (vo.getHotel_phone() == null) { vo.setHotel_phone(""); } else { if (vo.getHotel_phone().trim().length() >= 20) err.put("hotel_phone", "too long."); } // hotel_class if (vo.getHotel_class() == null) { vo.setHotel_class(-1); } else { if (vo.getHotel_class() <= -1 || vo.getHotel_class() > 10) err.put("hotel_class", "invalid ranking."); } // hotel_url if (vo.getHotel_url() == null) { vo.setHotel_url(""); } else { if (vo.getHotel_phone().trim().length() >= 60) err.put("hotel_url", "too long."); } // hotel_lat if (vo.getHotel_lat() == null) { err.put("hotel_lat", "invalid coordinate format."); } else { if (vo.getHotel_lat() > 90 || vo.getHotel_lat() < -90) err.put("hotel_lat", "invalid coordinate format."); } // hotel_lng if (vo.getHotel_lng() == null) { err.put("hotel_lng", "invalid coordinate format."); } else { if (vo.getHotel_lng() > 180 || vo.getHotel_lng() < -180) err.put("hotel_lng", "invalid coordinate format."); } // update database if (err.size() > 0) { // 400 Bad request msg = new HashMap<String, String>(); msg.put("result", "validation-error"); msg.put("error", "invalid user input."); msg.put("validation", err.toString()); return Response.status(Status.BAD_REQUEST).entity(msg).build(); } else { try { dao.update(vo); // 200 OK msg = new HashMap<String, String>(); msg.put("result", "success"); return Response.status(Status.OK).entity(msg).build(); } catch (Exception e) { e.printStackTrace(); // 500 Internal server error msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "update unsuccessful."); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } } @DELETE @Path("{id: [0-9]+}") // Be careful, just writing "{id}" will NOT work. // Maybe conflict with GET ?? @Produces({ MediaType.APPLICATION_JSON }) public Response deleteHotel(@PathParam("id") Integer id) { HashMap<String, String> msg = null; HotelVO vo; if ((vo = dao.findById(id)) == null) { // 404 Not found msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "id not exist."); return Response.status(Status.NOT_FOUND).entity(msg).build(); } else { vo = ApplicationContextUtils.getContext().getBean(HotelVO.class); vo.setHotel_id(id); try { List<PhotoVO> photos = pdao.findByHotleId(id); for (PhotoVO photoVO : photos) { pdao.delete(photoVO.getPhoto_id()); } dao.delete(vo); // 200 OK msg = new HashMap<String, String>(); msg.put("result", "success"); return Response.status(Status.OK).entity(msg).build(); } catch (Exception e) { e.printStackTrace(); // 500 Internal server error msg = new HashMap<String, String>(); msg.put("result", "failure"); msg.put("error", "delete unsuccessful."); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } } }<file_sep>/Tourcan/src/com/tourcan/util/ServletContextUtils.java package com.tourcan.util; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.tourcan.admin.model.AdminDAO; import com.tourcan.admin.model.AdminFakeDAO; public class ServletContextUtils implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); AdminDAO dao = new AdminFakeDAO(); // System.out.println("contextPath = " + sc.getContextPath()); sc.setAttribute("contextPath", sc.getContextPath()); sc.setAttribute("siteName", "Tourcan"); sc.setAttribute("admin", dao.findById(0)); } @Override public void contextDestroyed(ServletContextEvent sce) { } } <file_sep>/Tourcan/src/com/tourcan/region/model/RegionDAO.java package com.tourcan.region.model; import java.util.List; public interface RegionDAO { public void insert(RegionVO regionVO); public void update(RegionVO regionVO); public void delete(RegionVO regionVO); public RegionVO findById(Integer region_id); public List<RegionVO> findByArea(Integer region_area); public List<RegionVO> findByName(String region_name); public List<RegionVO> getAll(); } <file_sep>/Tourcan/src/com/tourcan/resp/controller/RespServlet.java package com.tourcan.resp.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.List; 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 org.json.JSONObject; import org.springframework.http.converter.json.GsonBuilderUtils; import com.google.gson.Gson; import com.tourcan.resp.model.RespService; import com.tourcan.resp.model.RespVO; @WebServlet("/resp/RespServlet") public class RespServlet extends HttpServlet{ private static final long serialVersionUID =1L; public RespServlet(){ super(); } @Override protected void doGet(HttpServletRequest req ,HttpServletResponse resp) throws ServletException,IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); // PrintWriter out = response.getWriter(); BufferedReader br = req.getReader(); StringBuffer sb = new StringBuffer(128); String json; while ((json = br.readLine()) != null) sb.append(json); json = sb.toString(); JSONObject err = new JSONObject(); // ----------------Query one by attId---------------- String thstr = req.getParameter("resp_id"); if(thstr!=null){ Integer rsno =null; try { rsno =new Integer(req.getParameter("resp_id")); System.out.println(rsno); } catch (Exception e) { err.append("respId", "編號只能為整數"); resp.getWriter().println(err.toString()); // System.out.println(e.getMessage()); } // ***************************2.開始查詢資料*****************************************//* if(rsno!=null){ RespService rsv =new RespService(); RespVO thVO = rsv.findById(rsno); // System.out.println(thVO); if(thVO !=null){ try{ Gson gson = GsonBuilderUtils.gsonBuilderWithBase64EncodedByteArrays().create(); String themeG = gson.toJson(thVO); // System.out.println(themeG); resp.getWriter().println(themeG); }catch (Exception e) { err.append("respId", "無此編號"); resp.getWriter().println(err.toString()); } } else { err.append("respId", "無此編號"); resp.getWriter().println(err.toString()); } }else{ err.append("respId", "無此編號2"); } return; } String th_name = req.getParameter("resp_topic"); if (th_name != null) { try { try { if (th_name == null || (th_name.trim()).length() == 0) { throw new Exception(); } } catch (Exception e) { err.append("respTopic", "無此Resp"); } // ***************************2.開始查詢資料*****************************************//* RespService asv = new RespService(); List<RespVO> avo = asv.findByTopic(th_name); System.out.println("2="+th_name); Gson gson = new Gson(); String jsonG = gson.toJson(avo); System.out.println(jsonG); if(jsonG.length()<3){ // response.getWriter().write(jsonG); err.append("respTopic", "無此Resp"); resp.getWriter().println(err.toString()); }else{ resp.getWriter().println(jsonG.toString()); } // ***************************其他可能的錯誤處理*************************************//* } catch (Exception e) { err.append("respTopic", "respTopic search error"); resp.getWriter().println(err.toString()); } } // } else if (thstr == null && th_name == null) { // RespService asv = new RespService(); // List<ThemeVO> avo = asv.getAll(); // Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); // String jsonG = gson.toJson(avo); // System.out.println(jsonG); // resp.getWriter().println(jsonG.toString()); // } } @SuppressWarnings("unused") protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); BufferedReader br = req.getReader(); JSONObject checkR =new JSONObject(); Timestamp resptime =null; String memUid =null; Integer themeid=null; RespVO respVO=null; try{ respVO = new Gson().fromJson(br,RespVO.class); String respTopic= respVO.getResp_topic(); // System.out.println(themeTopic); if(respTopic==null||respTopic.trim().isEmpty()||respTopic.trim().length()==0){ checkR.append("resp_topic","請輸入回覆主題"); } String resparticle = respVO.getResp_article(); // System.out.println("themearticle:"+themearticle); if(resparticle==null||resparticle.trim().isEmpty()||resparticle.trim().length()==0){ checkR.append("resp_article", "請輸入回覆內容"); } resptime=new Timestamp(System.currentTimeMillis()+8*60*60*1000); // System.out.println("themetime:"+themetime); respVO.setResp_time(resptime); themeid=respVO.getTheme_id(); memUid= respVO.getMem_uid();//抓出已建立的id if(checkR.length()>0){ throw new Exception(); }else{ RespService srv =new RespService(); srv.insert(respVO); //(respTopic, resparticle, resptime, memId); checkR.append("result", "success"); resp.getWriter().println(checkR.toString()); } }catch (Exception e) { checkR.append("result", "faill"); resp.getWriter().println(checkR.toString()); e.printStackTrace(); } } @SuppressWarnings("unused") protected void doPut(HttpServletRequest req,HttpServletResponse resp)throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); BufferedReader br = req.getReader(); Timestamp resptime =null; Integer respid=null; Integer themeid=null; String memUid =null; RespVO respVO=null; JSONObject checkR =new JSONObject(); try{ respVO = new Gson().fromJson(br,RespVO.class); String respTopic= respVO.getResp_topic(); // System.out.println(themeTopic); if(respTopic==null||respTopic.trim().isEmpty()||respTopic.trim().length()==0){ checkR.append("theme_topic","plz into topic"); } String resparticle = respVO.getResp_article(); // System.out.println("themearticle:"+themearticle); if(resparticle==null||resparticle.trim().isEmpty()||resparticle.trim().length()==0){ checkR.append("theme_article", "plz into article"); } // System.out.println("themetime:"+themetime); resptime=new Timestamp(System.currentTimeMillis()+8*60*60*1000); respVO.setResp_time(resptime); themeid=respVO.getTheme_id(); respid=respVO.getResp_id(); memUid= respVO.getMem_uid();//抓出已建立的id if(checkR.length()>0){ throw new Exception(); }else{ RespService srv =new RespService(); srv.update(respVO); // srv.insert(themeTopic, themecatalog, themearticle, themetime, memId); checkR.append("result", "修改成功"); resp.getWriter().println(checkR.toString()); } }catch (Exception e) { checkR.append("result", "修改失敗"); resp.getWriter().println(checkR.toString()); e.printStackTrace(); } } protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); JSONObject err = new JSONObject(); String respstr = req.getParameter("resp_id"); if(respstr!=null){ Integer rsno =null; try { rsno =new Integer(req.getParameter("resp_id")); System.out.println(rsno); } catch (Exception e) { err.append("respInt", "編號只能為整數"); // resp.getWriter().println(err.toString()); System.out.println(e.getMessage()); } if(rsno!=null){ RespService rsv =new RespService(); try{ rsv.delete(rsno); }catch (Exception e) { err.append("respId", "無此編號"); System.out.println(e.getMessage()); // resp.getWriter().println(err.toString()); } }else{ err.append("respId", "無此編號"); // System.out.println(e.getMessage()); } } PrintWriter out = resp.getWriter(); out.println(err.append("respSu","success")); } }<file_sep>/Tourcan/src/com/tourcan/eat/model/EatDAO.java package com.tourcan.eat.model; import java.util.List; import com.tourcan.att.model.AttVO; public interface EatDAO { public AttVO findById(Integer att_id); public List<AttVO> findByName(String att_name); public List<AttVO> getAll(); public List<AttVO> findByRegionId(Integer region_id); } <file_sep>/Tourcan/src/com/tourcan/resp/model/RespDAO.java package com.tourcan.resp.model; import java.util.List; import java.util.Set; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.tourcan.theme.model.ThemeVO; import hibernate.util.HibernateUtil; public class RespDAO implements Resp_interface { @Override public void insert(RespVO respVO) { Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); sion.saveOrUpdate(respVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } } @Override public void update(RespVO respVO) { Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); sion.saveOrUpdate(respVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } } @Override public void delete(Integer resp_id) { Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ System.out.println("i2="+resp_id); sion.beginTransaction(); RespVO respVO= new RespVO(); respVO.setResp_id(resp_id); sion.delete(respVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } } @Override public RespVO findById(Integer resp_id) { RespVO respVO =null; Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); respVO = (RespVO) sion.get(RespVO.class,resp_id ); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } return respVO; } @Override public List<RespVO> findByThID(Integer theme_id) { List<RespVO> respVO =null; Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tc =sion.beginTransaction(); Integer t1= theme_id; try{ // sion.beginTransaction(); // sion.getTransaction().commit(); Query query =sion.createQuery("FROM RespVO WHERE theme_id=:theme_id"); System.out.println("rethid="+query); query.setParameter("theme_id",t1); respVO=query.list(); tc.commit(); }catch (RuntimeException e) { tc.rollback(); throw e; } return respVO; } @Override public List<RespVO> findByTopic(String resp_topic) { List<RespVO> rtopic = null; Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tc= sion.beginTransaction(); String topic3 ="%" +resp_topic+ "%"; // System.out.println(topic2); try{ // sion.beginTransaction(); String QueryTopic ="FROM RespVO WHERE resp_topic like :resp_topic"; // System.out.println(QueryTopic); Query query =sion.createQuery(QueryTopic); query.setParameter("resp_topic",topic3); // System.out.println(query); rtopic=query.list(); tc.commit(); // sion.getTransaction().commit();; }catch (RuntimeException e) { // sion.getTransaction().rollback(); tc.rollback(); throw e; } return rtopic; } // @Override // public Set<ThemeVO> getThemesByID(Integer theme_id) { // Set<ThemeVO> set =findById(resp_id). // return set; // } } <file_sep>/Tourcan/src/com/tourcan/trip/model/TripDAO_interface.java package com.tourcan.trip.model; import java.util.List; public interface TripDAO_interface { public Integer insert(TripVO tripVO); public void update(TripVO tripVO); public void delete(Integer trip_id); public TripVO findById(Integer trip_id); public List<TripVO> findByName(String trip_name); public List<TripVO> findByMemuid(String mem_uid); public List<TripVO> getAll(); } <file_sep>/Tourcan/src/com/tourcan/theme/model/ThemeDAO.java package com.tourcan.theme.model; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import hibernate.util.HibernateUtil; @SuppressWarnings("unused") public class ThemeDAO implements Theme_interface { @Override public void insert(ThemeVO themeVO) { Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); sion.saveOrUpdate(themeVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); e.printStackTrace(); throw e; } } @Override public void update(ThemeVO themeVO) { Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); sion.saveOrUpdate(themeVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } } @Override public void delete(Integer theme_id) { Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); ThemeVO themeVO= new ThemeVO(); themeVO.setTheme_id(theme_id); sion.delete(themeVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } } @Override public ThemeVO findById(Integer theme_id) { ThemeVO themeVO =null; // System.out.println("111=="+theme_id); Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); try{ sion.beginTransaction(); themeVO = (ThemeVO) sion.get(ThemeVO.class,theme_id ); // System.out.println(themeVO); sion.getTransaction().commit();; }catch (RuntimeException e) { sion.getTransaction().rollback(); throw e; } return themeVO; } @Override public List<ThemeVO> findByTopic(String theme_topic) { List<ThemeVO> topic = null; Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = sion.beginTransaction(); String topic2 ="%" +theme_topic+ "%"; try{ // sion.beginTransaction(); String QueryTopic ="FROM ThemeVO WHERE theme_topic like :theme_topic"; Query query =sion.createQuery(QueryTopic); query.setParameter("theme_topic",topic2); topic=query.list(); // sion.getTransaction().commit(); tx.commit(); }catch (RuntimeException e) { // sion.getTransaction().rollback(); tx.rollback(); throw e; } return topic; } @Override public List<ThemeVO> getAll() { List<ThemeVO> list =null; Session session=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); try { // session.beginTransaction(); Query query =session.createQuery("from ThemeVO order by theme_id DESC"); list=query.list(); tx.commit(); // session.beginTransaction().commit(); } catch (RuntimeException e) { tx.rollback(); // session.beginTransaction().rollback(); throw e; } return list; } @Override public List<ThemeVO> findByMemuid(String mem_uid) { List<ThemeVO> memuid = null; Session sion = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = sion.beginTransaction(); String mid ="%" +mem_uid+ "%"; try{ // sion.beginTransaction(); String QueryTopic ="FROM ThemeVO WHERE mem_uid like :mem_uid"; Query query =sion.createQuery(QueryTopic); query.setParameter("mem_uid",mid); memuid=query.list(); // sion.getTransaction().commit(); tx.commit(); }catch (RuntimeException e) { // sion.getTransaction().rollback(); tx.rollback(); throw e; } return memuid; } } <file_sep>/Tourcan/src/com/tourcan/mem/model/MemHibernateDAO.java package com.tourcan.mem.model; import java.sql.Date; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tourcan.region.model.RegionVO; public class MemHibernateDAO implements MemDAO { private SessionFactory factory; public void setSessionFactory(SessionFactory factory) { this.factory = factory; } @Override public void insert(MemVO memVO) { Session session = factory.getCurrentSession(); Transaction tx = session.beginTransaction(); session.save(memVO); session.flush(); tx.commit(); } @Override public void update(MemVO memVO) { Session session = factory.getCurrentSession(); Transaction tx = session.beginTransaction(); session.update(memVO); session.flush(); tx.commit(); } @Override public void delete(MemVO memVO) { Session session = factory.getCurrentSession(); Transaction tx = session.beginTransaction(); session.delete(memVO); session.flush(); tx.commit(); } // @Override // public MemVO findById(Integer mem_id) { // Session session = factory.getCurrentSession(); // Transaction tx = session.beginTransaction(); // MemVO vo = (MemVO) session.get(MemVO.class, mem_id); // session.flush(); // tx.commit(); // return vo; // } @Override public MemVO findByUid(String mem_uid) { Session session = factory.getCurrentSession(); Transaction tx = session.beginTransaction(); //MemVO vo = (MemVO) session.createCriteria(MemVO.class).add(Restrictions.eq("mem_uid", mem_uid)).uniqueResult(); MemVO vo = (MemVO) session.get(MemVO.class, mem_uid); session.flush(); tx.commit(); return vo; } @SuppressWarnings("unchecked") @Override public List<MemVO> findByName(String mem_name) { Session session = factory.getCurrentSession(); Transaction tx = session.beginTransaction(); Query query = session.createQuery("from MemVO where mem_fname||mem_lname like :mem_name"); query.setParameter("mem_name", "%" + mem_name + "%"); List<MemVO> vo = query.list(); session.flush(); tx.commit(); return vo; } @SuppressWarnings("unchecked") @Override public List<MemVO> getAll() { Session session = factory.getCurrentSession(); Transaction tx = session.beginTransaction(); Query query = session.createQuery("from MemVO"); List<MemVO> vo = query.list(); session.flush(); tx.commit(); return vo; } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); String uid = "99999999999999999997"; MemVO vo = null; List<MemVO> vos = null; MemDAO dao = context.getBean(MemHibernateDAO.class); System.out.println("------ INSERT ------"); vo = context.getBean(MemVO.class); // vo.setMem_account("tomcatuser"); vo.setMem_bdate(new Date(new java.util.Date().getTime() - 12 * 365 * 86400 * 1000)); vo.setMem_regtime(new Date(new java.util.Date().getTime())); vo.setMem_email("<EMAIL>"); vo.setMem_fname("T0mcat"); vo.setMem_lname("Apache"); vo.setMem_mobile("+12185654096"); vo.setMem_nick("neko"); // vo.setMem_pwd("<PASSWORD>"); vo.setMem_sex(2); RegionVO regionVO = new RegionVO(); regionVO.setRegion_id(0); vo.setRegionVO(new RegionVO()); vo.setMem_uid(uid); dao.insert(vo); vo = null; System.out.println("------ FINDBYUSERID ------"); vo = dao.findByUid(uid); if (vo != null) { System.out.println(vo.getMem_uid() + vo.getMem_lname() + vo.getMem_fname() + vo.getMem_email()); } else System.out.println("User not exist."); System.out.println("------ UPDATE ------"); vo.setMem_email("<EMAIL>"); vo.setMem_fname("Tomcat"); dao.update(vo); vo = null; System.out.println("------ GETALL ------"); vos = dao.getAll(); if (vos.size() > 0) for (MemVO vo0 : vos) System.out.println(vo0.getMem_uid() + vo0.getMem_lname() + vo0.getMem_fname() + vo0.getMem_email()); else System.out.println("Ain't Nobody Here but Us Chickens."); vos = null; System.out.println("------ FINDBYUSERID ------"); vo = dao.findByUid(uid); if (vo != null) { System.out.println(vo.getMem_uid() + vo.getMem_lname() + vo.getMem_fname() + vo.getMem_email()); // dao.delete(vo); // System.out.println("------ DELETE ------"); } else System.out.println("User not exist."); System.out.println("------ FINDBYNAME ------"); vos = dao.findByName("pac"); if (vos.size() > 0) for (MemVO vo0 : vos) System.out.println(vo0.getMem_uid() + vo0.getMem_lname() + vo0.getMem_fname() + vo0.getMem_email()); else System.out.println("Ain't Nobody Here but Us Chickens."); vos = null; System.out.println("------ CLOSE ------"); ((ConfigurableApplicationContext) context).close(); } } <file_sep>/Tourcan/src/com/tourcan/admin/controller/AdminAuthService.java package com.tourcan.admin.controller; import java.io.IOException; 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 com.tourcan.admin.model.AdminDAO; import com.tourcan.admin.model.AdminVO; import com.tourcan.util.ApplicationContextUtils; @WebServlet("/adridores/login") public class AdminAuthService extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/WEB-INF/adridores/login.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AdminDAO dao = (AdminDAO) ApplicationContextUtils.getContext().getBean("adminDAO"); AdminVO vo = dao.findByAccount(req.getParameter("admin_account")); if (!vo.getAdmin_pwd().equals(req.getParameter("admin_pwd"))) { req.getRequestDispatcher("/WEB-INF/adridores/login.jsp").forward(req, resp); } else { req.getSession().setAttribute("admin", vo); resp.sendRedirect(req.getContextPath() + "/adridores/att"); } } } <file_sep>/Tourcan/src/com/tourcan/mem/controller/MemListServlet.java package com.tourcan.mem.controller; import java.io.IOException; import java.util.List; 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.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.tourcan.mem.model.MemVO; import com.tourcan.region.model.RegionDAO; import com.tourcan.region.model.RegionHibernateDAO; import com.tourcan.region.model.RegionVO; import com.tourcan.util.ApplicationContextUtils; @WebServlet("/mem/listuser") public class MemListServlet extends HttpServlet { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); Response rm = new MemService().queryAll(); List<MemVO> vos = null; RegionDAO regionDAO = ApplicationContextUtils.getContext().getBean(RegionHibernateDAO.class); List<RegionVO> regions = regionDAO.getAll(); if (rm.getStatusInfo().equals(Status.OK)) { vos = (List<MemVO>) rm.getEntity(); req.setAttribute("members", vos); req.setAttribute("regions", regions); req.getRequestDispatcher("/WEB-INF/mem/listuser.jsp").forward(req, resp); } } } <file_sep>/Tourcan/src/com/tourcan/resp/model/Resp_interface.java package com.tourcan.resp.model; import java.util.List; import java.util.Set; import com.tourcan.theme.model.ThemeVO; public interface Resp_interface { public void insert(RespVO respVO); public void update(RespVO respVO); public void delete(Integer resp_id); public RespVO findById(Integer resp_id); public List<RespVO> findByThID(Integer theme_id); public List<RespVO> findByTopic(String resp_topic); } <file_sep>/Tourcan/src/com/tourcan/resp/model/RespService.java package com.tourcan.resp.model; import java.util.List; public class RespService { private Resp_interface dao; public RespService() { dao = new RespDAO(); } public void insert(RespVO respVO) { dao.insert(respVO); } public void update(RespVO respVO) { dao.update(respVO); } public List<RespVO> findByTopic(String resp_topic) { return dao.findByTopic(resp_topic); } public void delete(Integer resp_id) { dao.delete(resp_id); } public List<RespVO> findByThID(Integer theme_id) { return dao.findByThID(theme_id); } public RespVO findById(Integer resp_id) { return dao.findById(resp_id); } public boolean deleteByThemeID(Integer theme_id) { List<RespVO> reslist = null; try { reslist = dao.findByThID(theme_id); for (RespVO respVO : reslist) { Integer respID = respVO.getResp_id(); dao.delete(respID); } return true; } catch (Exception e) { return false; } } } <file_sep>/Tourcan/src/com/tourcan/util/EatRestConfig.java package com.tourcan.util; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; @ApplicationPath("restaurants") public class EatRestConfig extends ResourceConfig { public EatRestConfig() { this.packages("com.tourcan.eat"); } } <file_sep>/Tourcan/src/com/tourcan/photo/model/PhotoVO.java package com.tourcan.photo.model; import java.io.Serializable; public class PhotoVO implements Serializable { private Integer photo_id; private byte[] photo_file; private Integer att_id; private Integer hotel_id; public Integer getPhoto_id() { return photo_id; } public void setPhoto_id(Integer photo_id) { this.photo_id = photo_id; } public byte[] getPhoto_file() { return photo_file; } public void setPhoto_file(byte[] photo_file) { this.photo_file = photo_file; } public Integer getAtt_id() { return att_id; } public void setAtt_id(Integer att_id) { this.att_id = att_id; } public Integer getHotel_id() { return hotel_id; } public void setHotel_id(Integer hotel_id) { this.hotel_id = hotel_id; } } <file_sep>/Tourcan/src/com/tourcan/quest/model/QuestVO.java package com.tourcan.quest.model; import java.sql.Timestamp; public class QuestVO implements java.io.Serializable { private static final long serialVersionUID = 1L; private Integer quest_catalog; private String quest_topic; private Integer quest_id; private String mem_uid; private String quest_quiz; private Integer admin_id; private String quest_reply; private Timestamp quest_qtime; private Timestamp quest_rtime; public QuestVO() { } public Integer getQuest_catalog() { return quest_catalog; } public void setQuest_catalog(Integer quest_catalog) { this.quest_catalog = quest_catalog; } public String getQuest_topic() { return quest_topic; } public void setQuest_topic(String quest_topic) { this.quest_topic = quest_topic; } public Integer getQuest_id() { return quest_id; } public void setQuest_id(Integer quest_id) { this.quest_id = quest_id; } public String getMem_uid() { return mem_uid; } public void setMem_uid(String mem_uid) { this.mem_uid = mem_uid; } public String getQuest_quiz() { return quest_quiz; } public void setQuest_quiz(String quest_quiz) { this.quest_quiz = quest_quiz; } public Integer getAdmin_id() { return admin_id; } public void setAdmin_id(Integer admin_id) { this.admin_id = admin_id; } public String getQuest_reply() { return quest_reply; } public void setQuest_reply(String quest_reply) { this.quest_reply = quest_reply; } public Timestamp getQuest_qtime() { return quest_qtime; } public void setQuest_qtime(Timestamp quest_qtime) { this.quest_qtime = quest_qtime; } public Timestamp getQuest_rtime() { return quest_rtime; } public void setQuest_rtime(Timestamp quest_rtime) { this.quest_rtime = quest_rtime; } } <file_sep>/Tourcan/src/experimental/CronJob.java package experimental; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class CronJob implements ServletContextListener { private Thread t = null; private ServletContext context; private Integer flag = 0; @Override public void contextInitialized(ServletContextEvent sce) { t = new Thread() { // task public void run() { try { while (true) { // System.out.println("Thread running every second"); CronJob.this.setFlag(); Thread.sleep(1000); } } catch (InterruptedException e) { } } }; t.start(); context = sce.getServletContext(); // you can set a context variable just like this context.setAttribute("AccessPoint", this); } @Override public void contextDestroyed(ServletContextEvent sce) { t.interrupt(); } public Integer getFlag() { return flag; } public void setFlag() { this.flag++; } } <file_sep>/Tourcan/src/com/tourcan/hotel/controller/HotelServlet.java package com.tourcan.hotel.controller; import java.io.IOException; import java.util.List; 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 org.json.JSONObject; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.tourcan.hotel.model.HotelDAO; import com.tourcan.hotel.model.HotelHibernateDAO; import com.tourcan.hotel.model.HotelVO; @WebServlet("/HotelServlet/*") public class HotelServlet extends HttpServlet { private static final long serialVersionUID = 1L; ApplicationContext context; @Override public void init() throws ServletException { context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); String[] parameters; if (req.getPathInfo() != null && (parameters = req.getPathInfo().split("/")).length > 0 && parameters[1].length() > 0) { req.setAttribute("pathParam", parameters); if (parameters[1].trim().length() > 0) { try { req.setAttribute("queryId", Integer.parseInt(parameters[1].trim())); } catch (NumberFormatException e) { req.setAttribute("queryString", parameters[1].trim()); } } } super.service(req, resp); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HotelDAO dao = context.getBean(HotelHibernateDAO.class); String name = (String) request.getAttribute("queryString"); Integer id = (Integer) request.getAttribute("queryId"); if (id != null) { // Query by Id HotelVO vo = context.getBean(HotelVO.class); if ((vo = dao.findById(id)) == null) { // 404 Not found response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { // 200 OK response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(context.getBean(Gson.class).toJson(vo)); } } else if (name != null) { // Query by String/Name List<HotelVO> vos = dao.findByName(name); if (vos == null || vos.size() == 0) { // 404 Not found response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { // 200 OK response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(context.getBean(Gson.class).toJson(vos)); } } else { // Query all List<HotelVO> vos = dao.getAll(); // if (vos == null || vos.size() == 0) { // // 404 Not found // response.setStatus(HttpServletResponse.SC_NOT_FOUND); // } else { // } // 200 OK response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(context.getBean(Gson.class).toJson(vos)); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Query that had either Id or String. if (request.getAttribute("queryString") != null || request.getAttribute("queryId") != null) { // 405 Method not allowed response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } HotelVO vo = null; JSONObject err = new JSONObject(); // mapping json to vo try { vo = context.getBean(Gson.class).fromJson(request.getReader(), HotelVO.class); } catch (JsonSyntaxException e) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println(new JSONObject().put("result", "error: JsonSyntaxException.").toString()); e.printStackTrace(); return; } // checking input // hotel_id if (vo.getHotel_id() != null) { if ((context.getBean(HotelHibernateDAO.class).findById(vo.getHotel_id())) == null) { // 404 Not found response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { // 409 Conflict response.setStatus(HttpServletResponse.SC_CONFLICT); } return; } // hotel_name if (vo.getHotel_name() == null) { err.put("hotelName", "can't be empty."); } else { if (vo.getHotel_name().trim().length() == 0) err.put("hotelName", "can't be empty."); if (vo.getHotel_name().trim().length() > 60) err.put("hotelName", "too long."); } // region_id if (vo.getRegionVO() == null || vo.getRegionVO().getRegion_id() < 0 || vo.getRegionVO().getRegion_id() == 0) err.put("regionId", "must provide."); // phone_addr if (vo.getHotel_addr() == null) { err.put("hotelAddr", "can't be empty."); } else { if (vo.getHotel_addr().trim().length() == 0) err.put("hotelAddr", "can't be empty."); if (vo.getHotel_addr().trim().length() >= 60) err.put("hotelAddr", "too long."); } // hotel_price if (vo.getHotel_price() == null) { vo.setHotel_price(-1.0); } else { if (vo.getHotel_price() <= -1) err.put("hotelPrice", "invalid price range."); } // hotel_phone if (vo.getHotel_phone() == null) { vo.setHotel_phone(""); } else { if (vo.getHotel_phone().trim().length() >= 20) err.put("hotelPhone", "too long."); } // hotel_class if (vo.getHotel_class() == null) { vo.setHotel_class(-1); } else { if (vo.getHotel_class() <= -1 || vo.getHotel_class() > 10) err.put("hotelClass", "invalid ranking."); } // hotel_url if (vo.getHotel_url() == null) { vo.setHotel_url(""); } else { if (vo.getHotel_phone().trim().length() >= 60) err.put("hotelUrl", "too long."); } // hotel_lat if (vo.getHotel_lat() == null) { err.put("hotelLat", "invalid coordinate format."); } else { if (vo.getHotel_lat() > 90 || vo.getHotel_lat() < -90) err.put("hotelLat", "invalid coordinate format."); } // hotel_lng if (vo.getHotel_lng() == null) { err.put("hotelLat", "invalid coordinate format."); } else { if (vo.getHotel_lng() > 180 || vo.getHotel_lng() < -180) err.put("hotelLat", "invalid coordinate format."); } // update database if (err.length() > 0) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter() .println(new JSONObject().put("result", "validation-error").put("message", err).toString()); } else { try { context.getBean(HotelHibernateDAO.class).insert(vo); // 201 Created response.setStatus(HttpServletResponse.SC_CREATED); response.getWriter().println(new JSONObject().put("result", "success").toString()); } catch (Exception e) { // 500 Internal server error response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().println(new JSONObject().put("result", "error: insert unsuccessful.").toString()); e.printStackTrace(); } } } protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Query that had either Id or String. if (request.getAttribute("queryString") != null) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } HotelVO vo = null; JSONObject err = new JSONObject(); // mapping json to vo try { vo = context.getBean(Gson.class).fromJson(request.getReader(), HotelVO.class); } catch (JsonSyntaxException e) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println(new JSONObject().put("result", "error: JsonSyntaxException.").toString()); e.printStackTrace(); return; } // checking input // hotel_id if (request.getAttribute("queryId") != null && (Integer) request.getAttribute("queryId") != vo.getHotel_id()) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println(new JSONObject().put("result", "error: resource Id not match.").toString()); return; } if (vo.getHotel_id() == null) { err.put("hotelId", "must provide."); } else { if ((context.getBean(HotelHibernateDAO.class).findById(vo.getHotel_id())) == null) { // 404 Not found response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } // hotel_name if (vo.getHotel_name() == null) { err.put("hotelName", "can't be empty."); } else { if (vo.getHotel_name().trim().length() == 0) err.put("hotelName", "can't be empty."); if (vo.getHotel_name().trim().length() > 60) err.put("hotelName", "too long."); } // region_id if (vo.getRegionVO() == null || vo.getRegionVO().getRegion_id() < 0 || vo.getRegionVO().getRegion_id() == 0) err.put("regionId", "must provide."); // phone_addr if (vo.getHotel_addr() == null) { err.put("hotelAddr", "can't be empty."); } else { if (vo.getHotel_addr().trim().length() == 0) err.put("hotelAddr", "can't be empty."); if (vo.getHotel_addr().trim().length() >= 60) err.put("hotelAddr", "too long."); } // hotel_price if (vo.getHotel_price() == null) { vo.setHotel_price(-1.0); } else { if (vo.getHotel_price() <= -1) err.put("hotelPrice", "invalid price range."); } // hotel_phone if (vo.getHotel_phone() == null) { vo.setHotel_phone(""); } else { if (vo.getHotel_phone().trim().length() >= 20) err.put("hotelPhone", "too long."); } // hotel_class if (vo.getHotel_class() == null) { vo.setHotel_class(-1); } else { if (vo.getHotel_class() <= -1 || vo.getHotel_class() > 10) err.put("hotelClass", "invalid ranking."); } // hotel_url if (vo.getHotel_url() == null) { vo.setHotel_url(""); } else { if (vo.getHotel_phone().trim().length() >= 60) err.put("hotelUrl", "too long."); } // hotel_lat if (vo.getHotel_lat() == null) { err.put("hotelLat", "invalid coordinate format."); } else { if (vo.getHotel_lat() > 90 || vo.getHotel_lat() < -90) err.put("hotelLat", "invalid coordinate format."); } // hotel_lng if (vo.getHotel_lng() == null) { err.put("hotelLat", "invalid coordinate format."); } else { if (vo.getHotel_lng() > 180 || vo.getHotel_lng() < -180) err.put("hotelLat", "invalid coordinate format."); } // update database if (err.length() > 0) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter() .println(new JSONObject().put("result", "validation-error").put("message", err).toString()); } else { try { context.getBean(HotelHibernateDAO.class).update(vo); // 200 OK response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(new JSONObject().put("result", "success").toString()); } catch (Exception e) { // 500 Internal server error response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().println(new JSONObject().put("result", "error: update unsuccessful.").toString()); e.printStackTrace(); } } } protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HotelDAO dao = context.getBean(HotelHibernateDAO.class); HotelVO vo = null; String name = (String) request.getAttribute("queryString"); Integer id = (Integer) request.getAttribute("queryId"); if (id != null) { if ((vo = dao.findById(id)) == null) { // 404 Not found response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().println(new JSONObject().put("result", "error: id not exist.").toString()); return; } else { vo = context.getBean(HotelVO.class); vo.setHotel_id(id); try { dao.delete(vo); // 200 OK response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(new JSONObject().put("result", "success").toString()); } catch (Exception e) { // 500 Internal server error response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter() .println(new JSONObject().put("result", "error: delete unsuccessful.").toString()); e.printStackTrace(); return; } } } else if (name != null) { // 400 Bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { // 405 Method not allowed response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } } <file_sep>/Tourcan/src/com/tourcan/tripitem/model/TripitemService.java package com.tourcan.tripitem.model; import java.util.List; public class TripitemService { private TripitemDAO_interface dao; public TripitemService() { dao = new TripitemDAO(); } public TripitemVO insert(TripitemVO tripitemVO) { dao.insert(tripitemVO); return tripitemVO; } public TripitemVO update(TripitemVO tripitemVO) { dao.update(tripitemVO); return tripitemVO; } public void delete(Integer tripitem_id) { dao.delete(tripitem_id); } public TripitemVO findById(Integer tripitem_id) { return dao.findById(tripitem_id); } public List<TripitemVO> getAll() { return dao.getAll(); } public List<TripitemVO> findByTripID(Integer trip_id) { return dao.findByTripID(trip_id); } public boolean deleteForTripID(Integer trip_id) { List<TripitemVO> itemlist = null; try { itemlist = dao.findByTripID(trip_id); for (TripitemVO tVO : itemlist) { Integer id = tVO.getTripitem_id(); dao.delete(id); } return true; } catch (Exception e) { return false; } } }
a53fb94e987742f8a2202375f3c9f6711d40eca4
[ "JavaScript", "Java" ]
33
JavaScript
TingTing01/Test3
87a55c9310dca8e2240a436f9f9927200afa84dd
4ebffb34e28f1ee648369f511c02308f3faa8865
refs/heads/master
<repo_name>DavidBM/test-accounting<file_sep>/src/account.rs use decimal_rs::Decimal; use serde::{ ser::{SerializeStruct, Serializer}, Serialize, }; use std::collections::HashMap; /// Representes all 5 transaction types #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub enum AccountOperationType { Deposit, Withdrawal, Dispute, Resolve, Chargeback, } /// Represents a transaction to be applied to an account. #[derive(Debug, serde::Deserialize)] pub struct AccountOperation { r#type: AccountOperationType, client: u16, tx: u32, amount: Option<Decimal>, } impl AccountOperation { #[inline] pub fn get_type(&self) -> &AccountOperationType { &self.r#type } #[inline] pub fn get_amount(&self) -> &Option<Decimal> { &self.amount } #[inline] pub fn get_tx(&self) -> &u32 { &self.tx } #[inline] pub fn get_client(&self) -> &u16 { &self.client } } /// Represents an account where transactions can be applied. /// It has a custome serializer so it can be rendered only /// with the human-expected arguments. #[derive(Debug)] pub struct Account { client: u16, locked: bool, available: Decimal, held: Decimal, active_disputes: HashMap<u32, Decimal>, } impl Serialize for Account { #[inline] fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut output = ser.serialize_struct("Account", 5)?; output.serialize_field("client", &self.client)?; output.serialize_field("available", &self.available)?; output.serialize_field("held", &self.held)?; output.serialize_field("locked", &self.locked)?; output.serialize_field("total", &self.get_total())?; output.end() } } impl Account { #[inline] pub fn new(client: u16) -> Account { Account { client, locked: false, available: Decimal::from(0), held: Decimal::from(0), active_disputes: HashMap::new(), } } #[inline] pub fn get_total(&self) -> Decimal { self.available + self.held } #[inline] pub fn is_locked(&self) -> bool { self.locked } #[inline] pub fn lock(&mut self) { self.locked = true; } #[inline] pub fn deposit(&mut self, amount: &Option<Decimal>) { if self.is_locked() { return; } if let Some(amount) = amount { self.available += amount; } } #[inline] pub fn withdraw(&mut self, amount: &Option<Decimal>) { if self.is_locked() { return; } if let Some(amount) = amount { if self.available < amount { return; } self.available -= amount; } } #[inline] pub fn dispute(&mut self, amount: &Option<Decimal>, tx_id: &u32) { if self.is_locked() { return; } if let Some(amount) = amount { self.available -= amount; self.held += amount; self.active_disputes.insert(*tx_id, *amount); } } #[inline] pub fn resolve(&mut self, tx_id: &u32) { if self.is_locked() { return; } let amount = self.active_disputes.remove(&tx_id); if let Some(amount) = amount { self.available += amount; self.held -= amount; } } #[inline] pub fn chargeback(&mut self, tx_id: &u32) { if self.is_locked() { return; } // We keep the dispute for later research of why // the account was locked let amount = self.active_disputes.get(&tx_id); if amount.is_none() { return; } self.lock(); } } <file_sep>/src/lib.rs mod account; mod processor; use crate::account::AccountOperation; use crate::processor::AccountProcessor; use eyre::Result; use std::io::{Read, Write}; const QUEUE_CACHE_MB: usize = 25; /// Processes the transafer in a CSV Reader and outputs /// the accounts state into a Writer as CSV. /// /// This method is generic over a reader and a writer in /// order to allow easier testing. It is a nice thing to /// have too as you can use the code in other libraries /// and executables too. pub fn process_csv<R: Read, W: Write>(reader: R, writer: &mut W) -> Result<()> { let mut csv_reader = csv::ReaderBuilder::new() .flexible(true) .trim(csv::Trim::All) .from_reader(reader); // This uses a different thread for the operations // in order to allow the reader to be as sequential // as possible. In the case of the CSV, this allows // to have a thread decoding and other processing // transactions. The max_queue is a cache of how // many messages should be stores before stopping // the reader. In my tests I found that 25MB is the // ideal, as more can harm the overall time just // because the allocation time for the crossbeam-channel // initialization. let processor = AccountProcessor::new(calculate_mem_cache(QUEUE_CACHE_MB)); for result in csv_reader.deserialize() { let operation: AccountOperation = result?; // Each operate call sends a message through a // crossbeam channel, so this loop is very thigh // and allows the thread to be decoding as much // time as possible. processor.operate(operation)?; } // Report sends back the other thread account storage // which is in a BTreeMap<u16, Account> (the one that // performed better in my testings). let result = processor.report()?; let mut csv_writer = csv::Writer::from_writer(writer); let _ = result .into_iter() // the main.rs provided a BufWriter with a huge buffer // size, so many calls to the serialize method won't // hurt the write performance .for_each(|(_, account)| csv_writer.serialize(account).unwrap()); Ok(()) } /// Calculates how many messages will take to fill the given /// memory space taking in account the message size sent in /// the crossbeam channel. fn calculate_mem_cache(megabytes: usize) -> usize { let message_size = std::mem::size_of::<AccountOperation>(); get_mb_in_bytes(megabytes) / message_size } pub fn get_mb_in_bytes(mb: usize) -> usize { mb * 1024 * 1024 } <file_sep>/README.md # Test Accounting This project showcases a transaction processor which takes its input from a CSV and outputs another CSV with the resulting accounts state. ## TL;DR Run `cargo test` to execute a varied set of tests. You can check `tests/tests.rs` to see several usages of the library version of the crate. You can use `cargo run -- transactions.csv > accounts.csv` to run the executable. I advise to use the `--release` flat to test the executable. ## Design Decisions I've tried several designs. Mostly related with parallelization. You can see the different approaches in the commits that start with "poc" (ex: "poc 4: rayon". In which I tried rayon in order to parallelize transaction processing). ### Parallelization I tried several designs in order to parallelize the process. The main problem with CSV is that its parsing cannot be parallelized, so the ideal situation for parsing a CSV is having a thread only parsing the CSV and sending work to other thread/s. The operations in itself aren't complex, and it is hard that they are going to suppose a bigger processing cost than the CSV row parsing itself, as they are usually simple additions and subtractions. During the development I tried several ways to try to parallelize the work, but they all showed to be slower than just having 2 threads, one reading/parsing and other processing transfers. As a summary for fast comparative when processing a CSV with 21 million entries (without white-spaces handling): - 1 thread parsing and processing: 6.5 seconds. - 1 thread parsing + rayon (with Dashmap) for processing: 12 seconds - 1 thread parsing + thread pool (with data sharding) for processing: 9 seconds - 1 thread parsing + 1 thread processing: 4.8 seconds The 1+1 design works best compared to others 1+>1 due to these reasons: - *With data sharding*: Multi thread solutions require to reorder the input. This is due to the dependency between messages. Ex: You can only resolve a dispute if the dispute is already processed. So each thread keeps a shard/chunk of the accounts (like Kafka multi consumers) and handles all operations belonging to their accounts. - *With Dashmap or similar*: Having more than 1 thread incurs in synchronization primitives as `Arc`s and, in the worse case (rayon), `Mutex`es. Which in this case, given that the operation in itself is so small, hurts more than benefits. - *In general*: 1+1 allows each thread to have a tighter loop that only do one thing, which I suspect that helps the CPU branch predictor to be more efficient. ### Parallelization Correctness For keeping the correctness of the system, the most important thing when thinking on the concurrency part is that **message processing must be serializable (as in serializable isolation level) per account**. Messages from different account can be processed in parallel. Initially I thought to just use rayon to parallelize the processing, but this point made impossible to "just use rayon TM" because it requires some ordering before processing. ### Parallelization Design and Data Structures Chosen Finally, I chose the *1 thread parsing + 1 thread processing* solution as it performs better and it isn't so much more complicated compared to the *1 thread parsing and processing*. For the thread communication I use `crossbeam-channel` with a 25 MB buffer (in my experiments, it was the best performant size). For the account *"storage"* in ram, I use a `BTreeMap<u16, Account>` as it performed better than a HashMap. I didn't change the hasher when using the HashMap because choosing a hasher is something that needs to be done depending on the execution context and the default Rust hasher is a safe bet for all cases. For the deserialization, I implemented a custom deserialization of account to match the desired output. It is very simple, and it can be seen in `<crate::account::Account as Serialize>`. For the numeric handling, I'm using `decimal-rs` in order to avoid IEEE-754 floating-point calculation errors. As a thing to consider, if the program is going to handle astronomically absurd huge quantities (like, as many dollars as atoms are in the galaxy or something like it) then I would use `bigdecimal` or keep `decimal-rs` and use `.checked_add`/`.checked_sub`/etc method family rather than `+` and `-` operators. ### Error Handling In this project there are two types of errors mainly. Errors that can be ignored, and errors that need to abort the execution. For the later I use `eyre`, so I just bubble up with `?` all errors. There is usually a third family of errors, the ones that can be handled. Mostly in servers and long-running programs. For the current problem and execution context (shell binary) I didn't find any errors of that family. In the case this executable needs to be extended to handle errors (ex: report error on stderr) we will need to use `thiserror` to be able to differentiate the errors to be handled and the ones that cannot be handled and need to abort the program. Mostly in a shape like: ```rust #[derive(thiserror::Error)] pub enum MyError{ #[error("Error context. {0}")] MyBusinessError(OtherErrorType), //... other error types ... #[error("Error context. {0}")] Unexpected(#[from] eyre::Report), } ``` ## Code Design I've separated the application in a `main.rs` and a `lib.rs`. The `lib.rs` provides an interface as ```rust fn process_csv<R: Read, W: Write>(reader: R, writer: &mut W) -> Result<()> ``` which doesn't care of how input and output comes, as long as it can be `.read()` and `.write()`. The main.rs file makes sure to create and wrap the `File` in a `BufRead` and the output in a `BufWrite` for performance. The testing becomes much simpler when having a generic interface in the `lib.rs` as you can provide simple string to test the code. Example: ```rust #[test] fn chargeback_dispute() { let input = r#"type,client,tx,amount deposit,14,1,57097.49 dispute,14,2,16397.12 chargeback,14,2, deposit,14,1,57097.49 "#; let expected_output = r#"client,available,held,locked,total 14,40700.37,16397.12,true,57097.49 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } ``` Beyond that, all the *"business logic"* is encapsulated in the `account.rs`. And finally, the `processor.rs` encapsulates the processing strategy (AKA, multi-thread, +1 thread, same thread, etc). This is the main file that changed when trying different parallelization strategies. ## Business Logic Implementation Decisions For the implementation, I took these decisions: - Locked accounts don't process anything. This includes other `dispute` and `resolve` transactions. It is reasonable to require other disputes to be processed in order to have the most updated available/held funds in the output. That would be a very easy change in the `crate::account::Account::dispute` and `crate::account::Account::resolve` methods. - Each account tracks its opened disputes. When processing a resolve transaction, the opened dispute is removed. In the case of a chargeback, the account is locked and the dispute is not removed. This works well with the previous point. If the previous point was required to change as exposed, the `chargeback` transaction will remove the dispute from the account. Again, easy change in the `crate::account::Account::chargeback` method. ## Things I Didn't Dry I didn't try to use any executor as `async-std` or `tokio` as this code has no network dependencies. The IO is with the filesystem and can easily be solved with `BufRead` and `BufWrite` and no async solution will be able to outperform that in the current context (executable binary). Now, this is a binary to be executed in a local shell and that reads a CSV in the local filesystem. In the case of using this code in a HTTP server or to have required saving the accounts in a database like QLDB or PostgreSQL, I would have used an executor. Provably async-std, as it is simpler to use for small utilities. That would have changed the whole game. In such case, the transaction serialization per account is still required, but that can be easily solved with `dashmap` or similar and/or a task-pool (not thread pool). Also, I had the idea of trying to just parse the csv row as string and then try to deserialize it in parallel. But that has the problem that then they need to be reordered after the parallel deserialization in order to not have `resolve` transactions before the `dispute` transaction. I suspect that that reordering will make the parallelization non-effective. ## Performance Numbers Best case for 21 Million (597 MB file) transactions read from the CSV, processed and saved to a CSV: 12.5 seconds in my i7-9750H with SSD. There is an important thing to be noted. When disabling the `.trim(csv::Trim::All)` on the `csv` library, the processing time goes down to **4.8 seconds**. I left it with the trim enabled, as that is a hard requirement. If performance is paramount, I would create a custom parser using `nom` or similar crate for the specific CSV format used in production. I've done parsers in the past (https://github.com/Couragium/ion-binary-rs and https://github.com/Couragium/qldb-rs) and it is an accessible thing to do safely in Rust. ## Dependencies - clap: executable arguments parsing - crossbeam-channel: channel between main thread and worker thread - csv: csv parsing / encoding - decimal: decimal handling - eyre: error handling library (like anyhow, but a bit more ergonomic) - serde: generic serialization/deserialization `cargo audit` is clean. `cargo geiger` shows that the library `csv` and `decimal-rs` directly use unsafe. I don't like that. I trust `eyre`, `clap` and `crossbeam-channel`, but I would question is unsafe is really needed in a csv parser and a decimal handling library. `cargo clippy` is clean `cargo test` is clean `cargo build` is clean <file_sep>/src/main.rs use clap::{App, Arg, ArgMatches}; use eyre::Result; use std::{ fs::File, io::{BufReader, BufWriter}, }; use test_accounting::{get_mb_in_bytes, process_csv}; fn main() -> Result<()> { let source_reader = get_source_reader_from_args()?; let mut output_writer = BufWriter::with_capacity(get_mb_in_bytes(1024), std::io::stdout()); process_csv(source_reader, &mut output_writer)?; Ok(()) } /// Return a reader from a file given from the shell /// first argument fn get_source_reader_from_args() -> Result<BufReader<File>> { let matches = get_exec_args(); let source_csv_path = matches .value_of("source") .expect("No source csv path provided"); let source_csv = std::fs::File::open(source_csv_path)?; Ok(BufReader::new(source_csv)) } /// Declares the binary executable parameters and help fn get_exec_args() -> ArgMatches<'static> { App::new("CSV Transactions Processor") .version("1.0") .author("<NAME>. <<EMAIL>>") .arg( Arg::with_name("source") .help("Relative path to the source csv file") .required(true) .index(1), ) .get_matches() } <file_sep>/tests/tests.rs use test_accounting::process_csv; #[test] fn chargeback_dispute() { let input = r#"type,client,tx,amount deposit,14,1,57097.49 dispute,14,2,16397.12 chargeback,14,2, deposit,14,1,57097.49 "#; let expected_output = r#"client,available,held,locked,total 14,40700.37,16397.12,true,57097.49 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn unresolved_dispute() { let input = r#"type,client,tx,amount deposit,14,1,57097.49 dispute,14,2,16397.12 deposit,14,1,57097.49 "#; let expected_output = r#"client,available,held,locked,total 14,97797.86,16397.12,false,114194.98 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn resolved_dispute() { let input = r#"type,client,tx,amount deposit,14,1,57097.49 dispute,14,2,16397.12 resolve,14,2, deposit,14,1,57097.49 "#; let expected_output = r#"client,available,held,locked,total 14,114194.98,0,false,114194.98 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn provided_case() { let input = r#"type,client,tx,amount deposit,1,1,1.0 deposit,2,2,2.0 deposit,1,3,2.0 withdrawal,1,4,1.5 withdrawal,2,5,3.0 "#; let expected_output = r#"client,available,held,locked,total 1,1.5,0,false,1.5 2,2,0,false,2 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn no_newline_eof() { let input = r#"type,client,tx,amount deposit,1,1,1.0"#; let expected_output = r#"client,available,held,locked,total 1,1,0,false,1 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn newline_start_input() { let input = r#" type,client,tx,amount deposit,1,1,1.0 "#; let expected_output = r#"client,available,held,locked,total 1,1,0,false,1 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn weird_spacing() { let input = r#" type, client, tx, amount deposit ,1 , 1 , 1.0 "#; let expected_output = r#"client,available,held,locked,total 1,1,0,false,1 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn missing_trailing_comma_on_missing_param() { let input = r#"type,client,tx,amount deposit,14,1,57097.49 dispute,14,2,16397.12 chargeback,14,2, deposit,14,1,57097.49 "#; let expected_output = r#"client,available,held,locked,total 14,40700.37,16397.12,true,57097.49 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } #[test] fn too_many_trailing_commas() { let input = r#"type,client,tx,amount deposit,14,1,57097.49,,,, dispute,14,2,16397.12 chargeback,14,2,, deposit,14,1,57097.49 "#; let expected_output = r#"client,available,held,locked,total 14,40700.37,16397.12,true,57097.49 "#; let mut output: Vec<u8> = vec![]; process_csv(input.as_bytes(), &mut output).unwrap(); assert_eq!(expected_output, &String::from_utf8(output).unwrap()) } <file_sep>/Cargo.toml [package] name = "test-accounting" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] clap = "2.33.3" crossbeam-channel = "0.5.1" csv = "1.1.6" decimal-rs = {version = "0.1.12", features = ["serde"]} eyre = "0.6.5" serde = {version = "1.0.126", features = ["serde_derive"]} <file_sep>/src/processor.rs use crate::account::{Account, AccountOperation, AccountOperationType}; use crossbeam_channel::{bounded, Sender}; use eyre::Result; use std::collections::BTreeMap; /// Each transaction is represented with a AccountCommand::Operate. /// The Report variant is used to gather the results /// at the end of the program. #[derive(Debug)] pub enum AccountCommand { Report(Sender<BTreeMap<u16, Account>>), Operate(AccountOperation), } /// Handles all the accounts transactions and keeps /// the state pub struct AccountProcessor { sender: Sender<AccountCommand>, } impl AccountProcessor { #[inline] pub fn new(max_queue: usize) -> AccountProcessor { let sender = create_worker(max_queue); AccountProcessor { sender } } /// Executed a transaction. It sends the transaction /// operation command to the processing thread via a /// channel. #[inline] pub fn operate(&self, operation: AccountOperation) -> Result<()> { self.sender.send(AccountCommand::Operate(operation))?; Ok(()) } /// Ends the execution and returns the current state /// of all accounts. #[inline] pub fn report(&self) -> Result<BTreeMap<u16, Account>> { let (report_sender, report_receiver) = bounded::<BTreeMap<u16, Account>>(0); self.sender.send(AccountCommand::Report(report_sender))?; Ok(report_receiver.recv()?) } } /// Creates a thread to process all command. Including /// transactions operations and reports #[inline] fn create_worker(max_queue: usize) -> Sender<AccountCommand> { let (sender, receiver) = bounded::<AccountCommand>(max_queue); std::thread::spawn(move || { let mut accounts: BTreeMap<u16, Account> = BTreeMap::new(); while let Ok(command) = receiver.recv() { match command { AccountCommand::Operate(operation) => { apply_operate_command(&mut accounts, operation) } AccountCommand::Report(sender) => { let _ = sender.send(accounts); break; } } } }); sender } /// Applies the operation to the accounts. If there isn't /// an account with the provided ID, it will create a new /// one. #[inline] fn apply_operate_command(accounts: &mut BTreeMap<u16, Account>, operation: AccountOperation) { if let Some(account) = accounts.get_mut(operation.get_client()) { process_operation(account, operation); } else { let mut account = Account::new(*operation.get_client()); let client = *operation.get_client(); process_operation(&mut account, operation); accounts.insert(client, account); } } /// Given an account and an operation, applies the operation /// to the account #[inline] fn process_operation(account: &mut Account, operation: AccountOperation) { match operation.get_type() { AccountOperationType::Deposit => account.deposit(operation.get_amount()), AccountOperationType::Withdrawal => account.withdraw(operation.get_amount()), AccountOperationType::Dispute => { account.dispute(operation.get_amount(), operation.get_tx()) } AccountOperationType::Resolve => account.resolve(operation.get_tx()), AccountOperationType::Chargeback => account.chargeback(operation.get_tx()), } }
b239e03bfbbaf0dfed86b081727fee89e3eae853
[ "Markdown", "Rust", "TOML" ]
7
Rust
DavidBM/test-accounting
abd26f3d3876e6a93cdfb17918115ccf7b77bcd2
76cefd0612aa7c3920dcd419c705daf415993acd
refs/heads/main
<repo_name>vinhlp32aptech/Portfolio<file_sep>/app/Http/Controllers/Frontend/SignupController.php <?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class SignupController extends Controller { public function index(){ return view('client.signup'); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; //client Route::get('/', 'Frontend\IndexController@index'); Route::get('/index', 'Frontend\IndexController@index')->name('frontend.index'); Route::get('/about-us', 'Frontend\AboutController@index')->name('about'); Route::get('/contact-us', 'Frontend\ContactController@index')->name('contact'); Route::get('/our-service', 'Frontend\ServiceController@index')->name('service'); Route::get('/sign-in', 'Frontend\SigninController@index')->name('signin'); Route::get('/sign-up', 'Frontend\SignupController@index')->name('signup'); Route::get('/profie', 'Frontend\ProfieController@index')->name('profie'); ///admin Route::get('/admin', 'Backend\AdminController@index')->name('admin'); Route::get('/inbox', 'Backend\InboxController@index')->name('inbox'); Route::get('/compose', 'Backend\ComposeController@index')->name('compose'); Route::get('/read', 'Backend\ReadController@index')->name('read'); Route::get('/account', 'Backend\AccountController@index')->name('account'); Route::get('/hashtag', 'Backend\HashtagController@index')->name('hashtag'); Route::get('/profile', 'Backend\ProfileController@index')->name('profile'); Route::get('/social-network', 'Backend\SocialNetWorkController@index')->name('social-network'); Route::get('/rating', 'Backend\RatingController@index')->name('rating'); Route::get('/view', 'Backend\ViewController@index')->name('view'); Route::get('/follow', 'Backend\FollowController@index')->name('follow'); Route::get('/create', [ 'as' => 'backend.manage-web.menus.create', 'uses' => 'MenuController@create' ]); Route::post('/store', [ 'as' => 'backend.manage-web.menus.store', 'uses' => 'MenuController@store' ]); /* Social web */ Route::prefix('socials')->group(function (){ Route::get('/', [ 'as' => 'socials.social', 'uses' => 'SocialController@social' ]); Route::get('/create', [ 'as' => 'backend.manage-web.socials.create', 'uses' => 'SocialController@create' ]); Route::post('/store', [ 'as' => 'backend.manage-web.socials.store', 'uses' => 'SocialController@store' ]); }); /* footer */ Route::prefix('footers')->group(function (){ Route::get('/', [ 'as' => 'footers.footer', 'uses' => 'FooterController@footer' ]); Route::get('/create', [ 'as' => 'backend.manage-web.footers.create', 'uses' => 'FooterController@create' ]); Route::post('/store', [ 'as' => 'backend.manage-web.footers.store', 'uses' => 'FooterController@store' ]); }); Route::get('/sendemail', 'SendEmailController@index'); Route::post('/sendemail/send', 'SendEmailController@send'); Route::prefix('categories')->group(function (){ Route::get('/create', [ 'as' => 'categories.create', 'uses' => 'CategoryController@create' ]); }); /* menu */ Route::prefix('menus')->group(function () { Route::get('/', [ 'as' => 'menus.menu', 'uses' => 'MenuController@menu' ]); }); <file_sep>/README.md # Portfolio this is Fisrt comment <file_sep>/app/Http/Controllers/FooterController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class FooterController extends Controller { public function footer(){ return view('backend.manage-web.footers.footer'); } public function create(){ return view('backend.manage-web.footers.add'); } } <file_sep>/app/Http/Controllers/MenuController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class MenuController extends Controller { public function create(){ return view('backend.manage-web.menus.add'); } public function menu(){ return view('backend.manage-web.menus.menu'); } }
d3516adc7076c6cff9274c1813514c6f3fa9954c
[ "Markdown", "PHP" ]
5
PHP
vinhlp32aptech/Portfolio
418e9547f1121c24dfebf61f1541f25f986b9b98
4746248a302ad587b83992850e81c450de9c150c
refs/heads/master
<repo_name>vesnikos/wpLAN<file_sep>/LAN_Productor.py from collections import defaultdict import pathlib import ftplib import argparse import click import rasterio import numpy as np try: from local_config import wp_ftp, WORKFOLDER except ImportError: # please make a local_config.py in the same directory as this file, and copy paste the following, # changing where appropriate: # import pathlib # output_folder = r"MY OUTPUT FOLDER" # WORKFOLDER = pathlib.Path(output_folder) # wp_ftp = { # 'ftp_server': 'ftp.worldpop.org.uk', # 'user': "user", # wp_username # 'password': "<PASSWORD>", # wp_password # } wp_ftp = { 'ftp_server': 'ftp.worldpop.org.uk', 'user': 'user', 'password': '<PASSWORD>', } WORKFOLDER = pathlib.Path(__file__).parent GDAL_CACHEMAX = 512 # mb wp_ftp['root'] = '/WP515640_Global/Covariates/{iso}/{product}' class IllegalArgumentError(ValueError): pass class DataBroker(object): def __init__(self): self.data = defaultdict(lambda: [+3e10, -3e10]) # zones start with default 0 min/max def get_min(self, zone): return self.data[zone][0] def get_max(self, zone): return self.data[zone][1] def set_min(self, zone, value): if not self.data[zone][0] < value: self.data[zone][0] = value def set_max(self, zone, value): if not self.data[zone][1] > value: self.data[zone][1] = value def get_range(self, zone): # abs(max - min) return np.absolute(self.get_max(zone) - self.get_min(zone)) def main(iso, year1, year2): years = [year for year in range(year1, year2) if year != 2011] ISO_FOLDER = WORKFOLDER / iso.upper() LAN_FOLDER = ISO_FOLDER / 'LAN' OUTFOLDER = LAN_FOLDER / 'derived' if not OUTFOLDER.exists(): OUTFOLDER.mkdir(parents=True, exist_ok=True) def footer(iso=iso): print(end='\n' * 3) print('Production of Weighted LAN for country {iso} Finished!'.format(iso=iso.upper())) print('\nThe product can be found in the folder: \n{folder}'.format(folder=LAN_FOLDER.absolute())) def header(): print( 'Welcome to the Weighted LAN producing Program. This program is going to derive the Lights-At-Night Product ' 'for: \n {iso} \n and years: \n{years}'.format(iso=iso, years=years)) def download_ccid_product(): with ftplib.FTP(wp_ftp['ftp_server'], user=wp_ftp['user'], passwd=wp_ftp['password']) as ftp: ccid_ftp_folder = '/WP515640_Global/Covariates/{iso}/Mastergrid'.format(iso=iso.upper()) ftp.cwd(ccid_ftp_folder) with ccidadminl1_file.open('wb') as f: ftp.retrbinary('RETR ' + ccidadminl1_file.name, f.write) def get_lan_filenames(year1: int, iso: str) -> (str, str): prod1_template = "{iso}_grid_100m_dmsp_{year}.tif" prod2_template = "{iso}_grid_100m_viirs_{year}.tif" if year1 > 2016 or year1 < 2000: return None, None if year1 == 2011: return prod1_template.format(year=year1, iso=iso) if year1 < 2011: return prod1_template.format(year=year1, iso=iso), prod1_template.format(year=year1 + 1, iso=iso) if year1 > 2011: return prod2_template.format(year=year1, iso=iso), prod2_template.format(year=year1 + 1, iso=iso) def get_lan_outname(year: int, iso): template = '{iso}_{prod}_{year_target}_normlag_{year_plus1}-{year_target}' if year < 2011: return template.format( product='dmsp', iso=iso, year_target=year, year_plus1=year + 1 ) if year > 2011: return template.format( product='viirs', iso=iso, year_target=year, year_plus1=year + 1 ) def download_lan_product(year): with ftplib.FTP(wp_ftp['ftp_server'], user=wp_ftp['user'], passwd=wp_ftp['password']) as ftp: if year < 2012: ftp.cwd(wp_ftp['root'].format(iso=iso.upper(), product='DMSP')) if year > 2011: ftp.cwd(wp_ftp['root'].format(iso=iso.upper(), product='VIIRS')) for FILENAME in get_lan_filenames(year, iso=iso): outfile = LAN_FOLDER.joinpath(FILENAME) if outfile.exists(): continue with open(outfile, 'wb') as f: ftp.retrbinary('RETR ' + FILENAME, f.write) header() ccidadminl1_file = '{iso}_grid_100m_ccidadminl1.tif'.format(iso=iso) ccidadminl1_file = LAN_FOLDER.joinpath(ccidadminl1_file) if not ccidadminl1_file.exists(): download_ccid_product() for year in years: LAN_1, LAN_2 = [LAN_FOLDER.joinpath(x) for x in get_lan_filenames(year, iso=iso)] if year < 2011: outfile = '{iso}_dmsp_{year1}_normlag_{year1}-{year2}.tif'.format( iso=iso.upper(), year1=year, year2=year + 1 ) outfile = OUTFOLDER.joinpath(outfile) else: outfile = '{iso}_viirs_{year1}_normlag_{year1}-{year2}.tif'.format( iso=iso.upper(), year1=year, year2=year + 1 ) outfile = OUTFOLDER.joinpath(outfile) # realise the LAN's if don't exist if not LAN_1.exists() or not LAN_2.exists(): download_lan_product(year) databroker = DataBroker() with rasterio.Env(GDAL_CACHEMAX=GDAL_CACHEMAX) as env, rasterio.open( ccidadminl1_file.as_posix()) as ccid_raster, \ rasterio.open(LAN_2.as_posix()) as lan_2_raster, \ rasterio.open(LAN_1.as_posix()) as lan_1_raster: ccid_nodata = ccid_raster.nodata def normalize(dstack, nodata): def normalize_value(zone, value): if zone == nodata: return nodata # special case for the water == 0 if zone == 0: return 0.0 min = databroker.get_min(zone) max = databroker.get_max(zone) # range = databroker.get_range(zone) if max - min == 0: return 0.0 result = 1.0 / (max - min) * (value - max) + 1.0 return result gen = [normalize_value(zone, value) for zone, value in dstack] result = np.fromiter(gen, dtype=rasterio.float32, ) return result vnorm = np.vectorize(normalize, otypes=[rasterio.float32], signature='(m_2,n),()->(i)') # Iter1 get zonal stats with click.progressbar([window for _, window in ccid_raster.block_windows(1)]) as windows: for window in windows: windows.label = 'Calculating Zonal Statistics' ccid_block = ccid_raster.read(1, window=window) lan1_block = lan_1_raster.read(1, window=window) lan2_block = lan_2_raster.read(1, window=window) lan_block = lan2_block - lan1_block del lan2_block, lan1_block datablock = np.stack((ccid_block, lan_block)) del lan_block q = np.where(datablock[0] != ccid_nodata) zones = np.unique(datablock[0][q]) for z in zones: qq = np.where(datablock[0][q] == z) min = np.min(datablock[1][q][qq]) max = np.max(datablock[1][q][qq]) databroker.set_max(zone=z, value=max) databroker.set_min(zone=z, value=min) # Iter2 apply and normalize raster profile = ccid_raster.profile profile.update(dtype=rasterio.float32, count=1, compress='lzw', nodata=8888) with rasterio.open(outfile.as_posix(), 'w', **profile) as dst: with click.progressbar([window for _, window in ccid_raster.block_windows(1)]) as windows: for window in windows: windows.label = 'Writing Normalized LAN' ccid_block = ccid_raster.read(1, window=window) lan1_block = lan_1_raster.read(1, window=window) lan2_block = lan_2_raster.read(1, window=window) lan_block = lan2_block - lan1_block del lan2_block, lan1_block buffer = np.dstack((ccid_block, lan_block)) datastack = vnorm(buffer, profile['nodata']) dst.write(datastack, indexes=1, window=window) footer() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('args', nargs='*') parsed_arguments = parser.parse_args() text_arguments = [arg for arg in parsed_arguments.args if not arg.isnumeric()] numeric_arguments = sorted(map(int, [arg for arg in parsed_arguments.args if arg.isnumeric()])) if len(numeric_arguments) != 2: print('Please provide the starting year and the ending year: YYYY YYYY') raise IllegalArgumentError iso = text_arguments[0] year1, year2 = numeric_arguments[0], numeric_arguments[1] # start the main routine main(iso, year1, year2)
88b0820b77070827e03162c4ecf416f1437f4fcf
[ "Python" ]
1
Python
vesnikos/wpLAN
dc56eb7b3d0204cc99e407c421798d5ec3564e37
8347aba01410088a6b0d46209d90d3e2dcd6ba4d
refs/heads/master
<repo_name>the-sooners/LibraryManagement<file_sep>/LibraryManagement_final/src/Librarymanagement/ChangePassword_121.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.sql.*; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.*; /** * * @author 26625 */ public class ChangePassword_121 extends javax.swing.JFrame { /** * Creates new form ChangePassword_121 */ Connection con=DBClass.getConnection();//连接数据库 public ChangePassword_121() { initComponents(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); userid = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); originalpassword = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); new1 = new javax.swing.JPasswordField(); new2 = new javax.swing.JPasswordField(); uesrtype = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); cancel = new javax.swing.JButton(); ok = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Change Password"); setResizable(false); getContentPane().setLayout(new java.awt.GridBagLayout()); jPanel1.setBackground(new java.awt.Color(165, 223, 224)); jLabel1.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel1.setText("Original Password"); userid.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel2.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel2.setText("New Password"); jLabel5.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel5.setText("Uesr Type"); originalpassword.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel3.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel3.setText("New Password"); new1.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N new2.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N uesrtype.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N uesrtype.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrator", "User" })); jLabel4.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel4.setText("UserID"); cancel.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N cancel.setText("Cancel"); cancel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cancelMouseClicked(evt); } }); ok.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N ok.setText("OK"); ok.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { okMouseClicked(evt); } }); ok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(111, 111, 111) .addComponent(uesrtype, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(141, 141, 141) .addComponent(userid, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(31, 31, 31) .addComponent(originalpassword, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(81, 81, 81) .addComponent(new1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(81, 81, 81) .addComponent(new2, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(58, 58, 58)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(65, 65, 65) .addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(75, 75, 75)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(uesrtype, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(userid, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(originalpassword, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(new1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(new2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) .addComponent(ok, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(48, 48, 48)) ); getContentPane().add(jPanel1, new java.awt.GridBagConstraints()); pack(); }// </editor-fold>//GEN-END:initComponents private void okMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okMouseClicked // TODO add your handling code here: }//GEN-LAST:event_okMouseClicked private void cancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelMouseClicked // TODO add your handling code here: dispose(); }//GEN-LAST:event_cancelMouseClicked private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed // TODO add your handling code here: PreparedStatement pst,pst1,pst2; ResultSet rs; String sql; //通过组合框进行选择 if (uesrtype.getSelectedIndex() == 0)//Administrator { String sql1 = "select * from admindata where id=? and password=?"; try { pst = con.prepareStatement(sql1); pst.setString(1, userid.getText()); pst.setString(2, originalpassword.getText());//originalpassword是password rs = pst.executeQuery();//执行语句 Pattern p = Pattern.compile("^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,16})$"); Matcher m1 = p.matcher(new1.getText()); if (userid.getText().length() == 0) { JOptionPane.showMessageDialog(this, "Empty UserID", "Warning", JOptionPane.WARNING_MESSAGE); } else if (originalpassword.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty OriginalPassword", "Warning", JOptionPane.WARNING_MESSAGE); } else if(m1.matches()==false){ JOptionPane.showMessageDialog(this, "Please both number and lower letter in your password,length 8-16 ", "Error", JOptionPane.ERROR_MESSAGE); } else if (rs.next()) { if (new1.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty newpassword!", "Warning", JOptionPane.WARNING_MESSAGE); } else if (new2.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Please enter your new password again!", "Warning", JOptionPane.WARNING_MESSAGE); } else if (Arrays.equals(new1.getPassword(), new2.getPassword())) { sql = "update admindata set password=? where id=?"; pst1 = con.prepareStatement(sql); pst1.setString(1, new2.getText()); pst1.setString(2, userid.getText()); pst1.executeUpdate();//执行语句 this.dispose(); JOptionPane.showMessageDialog(this, "Password changed successfully!", "OK", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Please confirm that the passwords entered twice are the same!", "Warning", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Incorrect UserID or Password", "Error", JOptionPane.ERROR_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(ChangePassword_121.class.getName()).log(Level.SEVERE, null, ex); } } else//User { String sql2 = "select * from userdata where id=? and password=?"; try { pst = con.prepareStatement(sql2); pst.setString(1, userid.getText()); pst.setString(2, originalpassword.getText());//originalpassword是password rs = pst.executeQuery();//执行语句 if (userid.getText().length() == 0) { JOptionPane.showMessageDialog(this, "Empty UserID", "Warning", JOptionPane.WARNING_MESSAGE); } else if (originalpassword.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty OriginalPassword", "Warning", JOptionPane.WARNING_MESSAGE); } else if (rs.next()) { if (new1.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty newpassword!", "Warning", JOptionPane.WARNING_MESSAGE); } else if (new2.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Please enter your new password again!", "Warning", JOptionPane.WARNING_MESSAGE); } else if (Arrays.equals(new1.getPassword(), new2.getPassword())) //(new1.getPassword()).equals(new2.getPassword()) { sql = "update userdata set password=? where id=?"; pst2 = con.prepareStatement(sql); pst2.setString(1, new2.getText()); pst2.setString(2, userid.getText()); pst2.executeUpdate();//执行语句 JOptionPane.showMessageDialog(this, "Password changed successfully!", "OK", JOptionPane.INFORMATION_MESSAGE); this.dispose(); } else { JOptionPane.showMessageDialog(this, "Please confirm that the passwords entered twice are the same!", "Warning", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Incorrect UserID or Password", "Error", JOptionPane.ERROR_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(ChangePassword_121.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_okActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField new1; private javax.swing.JPasswordField new2; private javax.swing.JButton ok; private javax.swing.JPasswordField originalpassword; private javax.swing.JComboBox uesrtype; private javax.swing.JTextField userid; // End of variables declaration//GEN-END:variables }<file_sep>/Database.sql create database if not exists library; use library; create table if not exists admindata( id int(5) not null primary key auto_increment, name varchar(20) not null, phonenumber varchar(15), state varchar(10) default 'normal', address varchar(50), password varchar(18) not null )charset utf8 engine myisam; alter table admindata auto_increment=90001; create table if not exists userdata( id int(5) not null primary key auto_increment, name varchar(20) not null, phonenumber varchar(15), state varchar(10) default 'normal', address varchar(50), password varchar(18) not null )charset utf8 engine myisam; alter table userdata auto_increment=10001; create table if not exists bookdata( id int(5) not null primary key auto_increment, title varchar(30) not null, author varchar(30) not null, type varchar(50) not null, publishing_house varchar(50) not null, publicationdate varchar(15), book_borrowing_state varchar(20) default 'Not lent', borrower_id int(5), BorrowDate date )charset utf8 engine myisam; alter table bookdata auto_increment=50001; create table if not exists bookreport( BookID int(5), BookName varchar(30), UserAction varchar(15), UserID int(5), ActionTime timestamp #primary key )charset utf8 engine myisam; create table if not exists userreport( userID int(5), UserName varchar(20), UserAction varchar(15), ActionTime timestamp #primary key )charset utf8 engine myisam; insert into userdata(name,password,phonenumber,address) values ('user','niit1234','15234526352','Renmin Road 58th'); insert into admindata(name,password,phonenumber,address) values ('root','niit1234','13732134321','hbrd'); insert into bookdata(title,author,publishing_house,book_borrowing_state,borrower_id,type) values ('Brief History of Time','<NAME>','OnePublishingHouse', 'lent','10001','Science and Technology');<file_sep>/LibraryManagement_final/src/Librarymanagement/Welcome_131.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.sql.*; /** * * @author 123 */ public class Welcome_131 extends javax.swing.JFrame { String str,strr,strrr,str1,sql1,sql2,sql3,sql4,sql5; PreparedStatement pst; Connection con; ResultSet rs; /** * Creates new form Welcome_131 * @throws java.sql.SQLException */ public Welcome_131() throws SQLException { sql2 = RegistrationPage_130.usernamespace.getText(); sql3 = RegistrationPage_130.passwordspace1.getText(); sql4 = RegistrationPage_130.phonespace.getText(); sql5 = RegistrationPage_130.addressspace.getText(); con = DBClass.getConnection(); sql1 = "select id from userdata where name=? and password = ? and phonenumber = ? and address = ?"; pst = con.prepareStatement(sql1); pst.setString(1, sql2); pst.setString(2, sql3); pst.setString(3, sql4); pst.setString(4, sql5); rs = pst.executeQuery(); rs.next(); str1=rs.getString(1); str = "Your ID number is: "+str1+"."; strr="Please remember that."; strrr="You'll use it to sign in."; initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); statement = new javax.swing.JLabel(); OKButton = new javax.swing.JButton(); statement1 = new javax.swing.JLabel(); statement2 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setLayout(null); jPanel2.setOpaque(false); jLabel1.setFont(new java.awt.Font("宋体", 0, 36)); // NOI18N jLabel1.setText("Welcome to HNU Library"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(33, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(22, 22, 22)) ); jPanel1.add(jPanel2); jPanel2.setBounds(0, 0, 440, 97); jPanel3.setOpaque(false); statement.setText(str); statement.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); OKButton.setText("OK"); OKButton.setOpaque(false); OKButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { OKButtonActionPerformed(evt); } }); statement1.setText(strr); statement1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); statement2.setText(strrr); statement2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(82, 82, 82) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statement1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(statement, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(statement2, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(58, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(OKButton, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(185, 185, 185)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(statement, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(statement1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(14, 14, 14) .addComponent(statement2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE) .addComponent(OKButton) .addGap(31, 31, 31)) ); jPanel1.add(jPanel3); jPanel3.setBounds(0, 100, 440, 230); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/创造性的学校图书馆-荡桨在蓝色背景的白色空白的书-回到与拷贝空间的学校背景-121723381.jpg"))); // NOI18N jPanel1.add(jLabel2); jLabel2.setBounds(-10, -10, 610, 530); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 440, 330)); pack(); }// </editor-fold>//GEN-END:initComponents private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed // TODO add your handling code here: this.dispose(); LoginMenu_100.rp.dispose(); Main.lm.setVisible(true); }//GEN-LAST:event_OKButtonActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton OKButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JLabel statement; private javax.swing.JLabel statement1; private javax.swing.JLabel statement2; // End of variables declaration//GEN-END:variables } <file_sep>/LibraryManagement_final/src/Librarymanagement/RegistrationPage_130.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.*; /** * * @author 123 */ public class RegistrationPage_130 extends javax.swing.JFrame { public RegistrationPage_130() throws ClassNotFoundException, SQLException { con = DBClass.getConnection(); if(con==null){ System.out.println("Failed to connect;"); }else{ System.out.println("Successfully."); } initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); Password1 = new javax.swing.JLabel(); phonespace = new javax.swing.JTextField(); Phone = new javax.swing.JLabel(); UserName = new javax.swing.JLabel(); cancel = new javax.swing.JButton(); submit = new javax.swing.JButton(); passwordspace1 = new javax.swing.JPasswordField(); notice2 = new javax.swing.JLabel(); Password2 = new javax.swing.JLabel(); Address = new javax.swing.JLabel(); passwordspace2 = new javax.swing.JPasswordField(); jScrollPane1 = new javax.swing.JScrollPane(); addressspace = new javax.swing.JTextArea(); usernamespace = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); Picture = new javax.swing.JLabel(); Title = new javax.swing.JLabel(); background = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBounds(new java.awt.Rectangle(0, 0, 400, 300)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); jPanel3.setLayout(null); Password1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); Password1.setText("<PASSWORD>"); jPanel3.add(Password1); Password1.setBounds(250, 160, 90, 15); jPanel3.add(phonespace); phonespace.setBounds(360, 240, 150, 21); Phone.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); Phone.setText("Phone Number"); jPanel3.add(Phone); Phone.setBounds(240, 240, 100, 15); UserName.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); UserName.setText("<NAME>"); jPanel3.add(UserName); UserName.setBounds(260, 120, 80, 15); cancel.setText("Cancel"); cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelActionPerformed(evt); } }); jPanel3.add(cancel); cancel.setBounds(310, 390, 80, 23); submit.setText("Submit"); submit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitActionPerformed(evt); } }); jPanel3.add(submit); submit.setBounds(170, 390, 80, 23); passwordspace1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { passwordspace1MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { passwordspace1MouseExited(evt); } }); jPanel3.add(passwordspace1); passwordspace1.setBounds(360, 160, 150, 21); notice2.setText("Both number and letters,length 8-16"); jPanel3.add(notice2); notice2.setBounds(340, 180, 220, 20); Password2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); Password2.setText("<PASSWORD>"); jPanel3.add(Password2); Password2.setBounds(230, 200, 110, 15); Address.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); Address.setText("Address"); jPanel3.add(Address); Address.setBounds(260, 280, 80, 15); passwordspace2.setAutoscrolls(false); jPanel3.add(passwordspace2); passwordspace2.setBounds(360, 200, 150, 21); addressspace.setColumns(20); addressspace.setRows(5); jScrollPane1.setViewportView(addressspace); jPanel3.add(jScrollPane1); jScrollPane1.setBounds(360, 270, 150, 61); usernamespace.setToolTipText(""); usernamespace.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { usernamespaceMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { usernamespaceMouseExited(evt); } }); usernamespace.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { usernamespaceActionPerformed(evt); } }); jPanel3.add(usernamespace); usernamespace.setBounds(360, 120, 150, 20); usernamespace.getAccessibleContext().setAccessibleName(""); jPanel1.setOpaque(false); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 450, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 45, Short.MAX_VALUE) ); jPanel3.add(jPanel1); jPanel1.setBounds(50, 20, 450, 45); jPanel2.setOpaque(false); Picture.setFont(new java.awt.Font("宋体", 0, 14)); // NOI18N Picture.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/hnu130.jpg"))); // NOI18N Picture.setToolTipText("null"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(Picture) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 38, Short.MAX_VALUE) .addComponent(Picture, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel3.add(jPanel2); jPanel2.setBounds(18, 65, 210, 290); Title.setFont(new java.awt.Font("宋体", 0, 48)); // NOI18N Title.setText("User Registration"); jPanel3.add(Title); Title.setBounds(80, 40, 408, 45); background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/pbqe4xb5ptf.jpg"))); // NOI18N jPanel3.add(background); background.setBounds(0, -10, 580, 440); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 574, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 427, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed // TODO add your handling code here: this.dispose(); Main.lm.setVisible(true); }//GEN-LAST:event_cancelActionPerformed private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed // TODO add your handling code here: DBClass.getConnection(); try { sql1=usernamespace.getText(); sql2=passwordspace1.getText(); sql3=phonespace.getText(); sql4=addressspace.getText(); sql = "insert into userdata(name,password,phonenumber,address) values (?,?,?,?)"; Pattern p = Pattern.compile("^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,16})$"); Pattern p1 = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$"); Matcher m1 = p.matcher(passwordspace1.getText()); Matcher m2 = p1.matcher(phonespace.getText()); //用户名为空,报错 if (usernamespace.getText().length() == 0) { JOptionPane.showMessageDialog(this, "Empty User Name", "Warning", JOptionPane.WARNING_MESSAGE); } //密码为空,报错 else if (passwordspace1.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty Password", "Warning", JOptionPane.WARNING_MESSAGE); } //密码为空,报错 else if (passwordspace2.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Please Confirm your password", "Warning", JOptionPane.WARNING_MESSAGE); }else if(m1.matches()==false){ JOptionPane.showMessageDialog(this, "Please use both number and letter in your password,length 8-16 ", "Error", JOptionPane.ERROR_MESSAGE); }else if(m2.matches()==false){ JOptionPane.showMessageDialog(this, "Please enter the right phone number", "Error", JOptionPane.ERROR_MESSAGE); } //两次密码一致,欢迎界面弹出 else if (Arrays.equals(passwordspace1.getPassword(), passwordspace2.getPassword())) { pst = con.prepareStatement(sql); pst.setString(1,usernamespace.getText()); pst.setString(2,passwordspace1.getText()); pst.setString(3,phonespace.getText()); pst.setString(4,addressspace.getText()); pst.executeUpdate(); Welcome_131 w = new Welcome_131(); w.setLocationRelativeTo(null); w.setVisible(true); this.dispose(); } else { JOptionPane.showMessageDialog(this, "Please Enter your password again", "Warning", JOptionPane.WARNING_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(RegistrationPage_130.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_submitActionPerformed private void usernamespaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernamespaceActionPerformed // TODO add your handling code here: }//GEN-LAST:event_usernamespaceActionPerformed private void usernamespaceMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_usernamespaceMouseEntered // TODO add your handling code here: }//GEN-LAST:event_usernamespaceMouseEntered private void usernamespaceMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_usernamespaceMouseExited // TODO add your handling code here: }//GEN-LAST:event_usernamespaceMouseExited private void passwordspace1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_passwordspace1MouseEntered // TODO add your handling code here: if(evt.getSource()==passwordspace1) { notice2.setVisible(true); } }//GEN-LAST:event_passwordspace1MouseEntered private void passwordspace1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_passwordspace1MouseExited // TODO add your handling code here: if(evt.getSource()==passwordspace1) { notice2.setVisible(false); } }//GEN-LAST:event_passwordspace1MouseExited // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Address; private javax.swing.JLabel Password1; private javax.swing.JLabel Password2; private javax.swing.JLabel Phone; private javax.swing.JLabel Picture; private javax.swing.JLabel Title; private javax.swing.JLabel UserName; protected static javax.swing.JTextArea addressspace; private javax.swing.JLabel background; private javax.swing.JButton cancel; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel notice2; protected static javax.swing.JPasswordField passwordspace1; private javax.swing.JPasswordField passwordspace2; protected static javax.swing.JTextField phonespace; private javax.swing.JButton submit; protected static javax.swing.JTextField usernamespace; // End of variables declaration//GEN-END:variables String sql; String sql1; String sql2; String sql3; String sql4; String p2 = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$"; PreparedStatement pst = null; Statement stmt = null; ResultSet rs = null; Connection con = null; } <file_sep>/LibraryManagement_final/src/Librarymanagement/AdminManageSystem_114.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.awt.HeadlessException; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author asus */ public class AdminManageSystem_114 extends javax.swing.JFrame { /** * Creates new form AdminManageUser_111 */ String [] a; String str; Statement stmt; Connection con=DBClass.getConnection();//连接数据库 ResultSet rs; DefaultTableModel tm; PreparedStatement preparedStatement; PreparedStatement pst1,pst2,pst3,pst4; ChangePassword_121 cp =new ChangePassword_121(); public AdminManageSystem_114() { initComponents(); thaw.setVisible(false); this.setDefaultCloseOperation(0x1); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); freeze_users = new javax.swing.JLabel(); change = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); thaw = new javax.swing.JPanel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); searchusertxt = new javax.swing.JTextField(); searchuser = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); usertable = new javax.swing.JTable(); freeze = new javax.swing.JButton(); StatusReset = new javax.swing.JButton(); thawExit = new javax.swing.JButton(); jSeparator3 = new javax.swing.JSeparator(); exit = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6.setText("jLabel6"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("System maganemnt"); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setLayout(null); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 192, -1, -1)); freeze_users.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N freeze_users.setText(" Freeze user"); freeze_users.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { freeze_usersMouseClicked(evt); } }); getContentPane().add(freeze_users, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 260, -1, -1)); change.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N change.setText("Change the password"); change.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { changeMouseClicked(evt); } }); getContentPane().add(change, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 210, -1, -1)); jLabel2.setFont(new java.awt.Font("宋体", 1, 36)); // NOI18N jLabel2.setText("System Management"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, -10, 390, 84)); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); getContentPane().add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 0, 20, 650)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/HUNI.png"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 170, 190)); getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); thaw.setOpaque(false); thaw.setLayout(null); jLabel17.setFont(new java.awt.Font("宋体", 1, 24)); // NOI18N jLabel17.setText("Thaw the users"); thaw.add(jLabel17); jLabel17.setBounds(230, 20, 176, 28); jLabel18.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel18.setText("User ID "); thaw.add(jLabel18); jLabel18.setBounds(100, 60, 80, 20); searchusertxt.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N searchusertxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchusertxtActionPerformed(evt); } }); thaw.add(searchusertxt); searchusertxt.setBounds(190, 53, 310, 41); searchuser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/search2.png"))); // NOI18N searchuser.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { searchuserMouseClicked(evt); } }); thaw.add(searchuser); searchuser.setBounds(510, 50, 66, 40); usertable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null} }, new String [] { "User Number", "<NAME>", "Tele", "Status" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); usertable.getTableHeader().setReorderingAllowed(false); jScrollPane2.setViewportView(usertable); thaw.add(jScrollPane2); jScrollPane2.setBounds(170, 137, 386, 60); freeze.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N freeze.setText("Freeze"); freeze.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { freezeMouseClicked(evt); } }); freeze.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { freezeActionPerformed(evt); } }); thaw.add(freeze); freeze.setBounds(130, 230, 100, 31); StatusReset.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N StatusReset.setText("Reset"); StatusReset.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { StatusResetMouseClicked(evt); } }); StatusReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StatusResetActionPerformed(evt); } }); thaw.add(StatusReset); StatusReset.setBounds(300, 230, 100, 31); thawExit.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N thawExit.setText("Exit"); thawExit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { thawExitMouseClicked(evt); } }); thaw.add(thawExit); thawExit.setBounds(490, 230, 90, 31); getContentPane().add(thaw, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 60, 650, 270)); getContentPane().add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 50, 810, 30)); exit.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N exit.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); exit.setText("Back"); exit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { exitMouseClicked(evt); } }); getContentPane().add(exit, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 310, 80, -1)); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/背景(几何)1.jpg"))); // NOI18N getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(-20, 0, 1120, 670)); pack(); }// </editor-fold>//GEN-END:initComponents private void searchusertxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchusertxtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_searchusertxtActionPerformed private void searchuserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchuserMouseClicked // TODO add your handling code here: try{ String sql; sql = "select * from userdata where id=?"; pst1 = con.prepareStatement(sql); pst1.setString(1, this.searchusertxt.getText()); rs = pst1.executeQuery();//执行语句 ResultSetMetaData rsmd = rs.getMetaData();//获取原数据,数据的数据,比如行数列数,列名 int ColumnCount = rsmd.getColumnCount();//获取表格列数 tm = (DefaultTableModel)usertable.getModel();//建立表格模型,editbooktable表格变量名 tm.setRowCount(0);//更新行数据,使表格清空 while (rs.next())//结果不为空,执行,以行进行循环,一次提取一条结果 { for (int i = 1; i <= ColumnCount; i++)//小于列数循环 { // tm.addColumn(rsmd.getColumnName(i));//添加列头 a=new String[ColumnCount];//获取列头名字 for (int s =0; s < ColumnCount; s++)//小于行循环 { a[s]=rs.getString(s+1);//获取列数据 } } tm.addRow(a);//将行和列的数据整合,进行输出 } //当文本字段为空时弹出Warning窗口 if(searchusertxt.getText().length()==0) { JOptionPane.showMessageDialog(this, "Empty!","Warning",JOptionPane.WARNING_MESSAGE); } tm.fireTableDataChanged(); // rs.close(); // stmt.close(); // con.close();//关闭 } catch (SQLException e) { JOptionPane.showMessageDialog(this, e, e.getMessage(), WIDTH, null); }//数据库报错 catch (HeadlessException ex) { JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null); }//整体报错 }//GEN-LAST:event_searchuserMouseClicked private void changeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_changeMouseClicked cp.setLocationRelativeTo(null); cp.setVisible(true); }//GEN-LAST:event_changeMouseClicked private void freeze_usersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_freeze_usersMouseClicked thaw.setVisible(true); }//GEN-LAST:event_freeze_usersMouseClicked private void freezeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_freezeMouseClicked }//GEN-LAST:event_freezeMouseClicked private void thawExitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_thawExitMouseClicked // TODO add your handling code here: thaw.setVisible(false); }//GEN-LAST:event_thawExitMouseClicked private void StatusResetMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_StatusResetMouseClicked // TODO add your handling code here: }//GEN-LAST:event_StatusResetMouseClicked private void StatusResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StatusResetActionPerformed // TODO add your handling code here: try { if(searchusertxt.getText().length()==0){ JOptionPane.showMessageDialog(this, "Please enter User ID first!","Warning",JOptionPane.WARNING_MESSAGE); }else{ String sql = "update userdata set state='Normal' where id=?"; pst2= con.prepareStatement(sql); pst2.setString(1,searchusertxt.getText()); pst2.executeUpdate();//执行语句 JOptionPane.showMessageDialog(this, "Execute Successfully!","Reset",JOptionPane.INFORMATION_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(AdminManageSystem_114.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_StatusResetActionPerformed private void freezeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_freezeActionPerformed // TODO add your handling code here: try { if(searchusertxt.getText().length()==0) { JOptionPane.showMessageDialog(this, "Empty!","Warning",JOptionPane.WARNING_MESSAGE); } else{ String sql; sql = "update userdata set state='Abnormal' where id= ?";//冻结用户 pst3= con.prepareStatement(sql); pst3.setString(1,searchusertxt.getText()); pst3.executeUpdate();//执行语句 JOptionPane.showMessageDialog(this, "Execute Successfully!","Freeze",JOptionPane.INFORMATION_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(AdminManageSystem_114.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_freezeActionPerformed private void exitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitMouseClicked // TODO add your handling code here: this.dispose(); cp.dispose(); }//GEN-LAST:event_exitMouseClicked /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton StatusReset; private javax.swing.JLabel change; private javax.swing.JLabel exit; private javax.swing.JButton freeze; private javax.swing.JLabel freeze_users; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JLabel searchuser; private javax.swing.JTextField searchusertxt; private javax.swing.JPanel thaw; private javax.swing.JButton thawExit; private javax.swing.JTable usertable; // End of variables declaration//GEN-END:variables } <file_sep>/LibraryManagement_final/src/Librarymanagement/ChangeAddress_122.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author 123 */ public class ChangeAddress_122 extends javax.swing.JFrame { /** * Creates new form ChangeAddress */ public ChangeAddress_122() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); confirmpassword = new javax.swing.JPasswordField(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); newaddress = new javax.swing.JTextArea(); OKButon = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel1.setText("Conform password:"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(32, 99, -1, -1)); jPanel1.add(confirmpassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(219, 101, 170, -1)); jLabel2.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel2.setText("Enter new address:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(22, 149, -1, -1)); newaddress.setColumns(20); newaddress.setRows(5); jScrollPane1.setViewportView(newaddress); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(219, 149, 170, 89)); OKButon.setText("OK"); OKButon.setOpaque(false); OKButon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { OKButonActionPerformed(evt); } }); jPanel1.add(OKButon, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 260, 80, -1)); jLabel3.setFont(new java.awt.Font("宋体", 1, 24)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Change Your Address"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(57, 32, 306, -1)); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/背景(几何)1.jpg"))); // NOI18N jLabel4.setText("jLabel4"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 440, 300)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void OKButonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButonActionPerformed // TODO add your handling code here: PreparedStatement pst,pst1,pst2; ResultSet rs; String sql; boolean a; Connection con = DBClass.getConnection(); String sql1 = "select * from userdata where id=? and password=?"; try { pst = con.prepareStatement(sql1); pst.setString(1, LoginMenu_100.idinput.getText()); pst.setString(2, confirmpassword.getText()); rs = pst.executeQuery();//执行语句 a = rs.next(); if (confirmpassword.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty Password", "Warning", JOptionPane.WARNING_MESSAGE); } else if(a == false){ JOptionPane.showMessageDialog(this, "Wrong Password", "Warning", JOptionPane.WARNING_MESSAGE); } else if (a == true) { sql = "update userdata set address=? where id=?"; pst1 = con.prepareStatement(sql); pst1.setString(1, newaddress.getText()); pst1.setString(2, LoginMenu_100.idinput.getText()); pst1.executeUpdate();//执行语句 JOptionPane.showMessageDialog(this, "Address changed successfully!", "OK", JOptionPane.INFORMATION_MESSAGE); this.dispose(); } } catch (SQLException ex) { Logger.getLogger(ChangePassword_121.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_OKButonActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton OKButon; private javax.swing.JPasswordField confirmpassword; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea newaddress; // End of variables declaration//GEN-END:variables } <file_sep>/LibraryManagement_final/nbproject/private/private.properties compile.on.save=true file.reference.mysql-connector-java-5.1.13-bin.jar-1=D:\\JAVA\u6587\u4ef6\\NetBeans 7.1\\ide\\modules\\ext\\mysql-connector-java-5.1.13-bin.jar user.properties.file=C:\\Users\\123\\AppData\\Roaming\\NetBeans\\10.0\\build.properties <file_sep>/LibraryManagement_final/src/Librarymanagement/ChangeUserName_123.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author 123 */ public class ChangeUserName_123 extends javax.swing.JFrame { /** * Creates new form ChangeUserName */ public ChangeUserName_123() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); passwordconfirm1 = new javax.swing.JPasswordField(); jLabel4 = new javax.swing.JLabel(); newusername = new javax.swing.JTextField(); OKButton = new javax.swing.JButton(); bgp = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setOpaque(false); jLabel1.setFont(new java.awt.Font("宋体", 1, 24)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Change Your UserName"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(45, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(40, 40, 40)) ); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, -1)); jPanel3.setOpaque(false); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Please verify your identity"); jLabel3.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel3.setText("Password"); jLabel4.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel4.setText("New UserName"); OKButton.setText("OK"); OKButton.setOpaque(false); OKButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { OKButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(passwordconfirm1) .addComponent(newusername, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE))))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(158, 158, 158) .addComponent(OKButton, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(50, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(passwordconfirm1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(newusername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addComponent(OKButton) .addContainerGap(32, Short.MAX_VALUE)) ); jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 100, 400, 200)); bgp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/背景(几何)1.jpg"))); // NOI18N jPanel1.add(bgp, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300)); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed // TODO add your handling code here: PreparedStatement pst,pst1,pst2; ResultSet rs; String sql; boolean a; Connection con = DBClass.getConnection(); //通过组合框进行选择 String sql1 = "select * from userdata where id=? and password=?"; try { pst = con.prepareStatement(sql1); pst.setString(1, LoginMenu_100.idinput.getText()); pst.setString(2, passwordconfirm1.getText()); rs = pst.executeQuery();//执行语句 a = rs.next(); if (passwordconfirm1.getPassword().length == 0) { JOptionPane.showMessageDialog(this, "Empty Password", "Warning", JOptionPane.WARNING_MESSAGE); } else if (a == true) { sql = "update userdata set name=? where id=?"; pst1 = con.prepareStatement(sql); pst1.setString(1, newusername.getText()); pst1.setString(2, LoginMenu_100.idinput.getText()); pst1.executeUpdate();//执行语句 JOptionPane.showMessageDialog(this, "UserName changed successfully!", "OK", JOptionPane.INFORMATION_MESSAGE); this.dispose(); }else if(a == false){ JOptionPane.showMessageDialog(this, "Wrong Password", "Warning", JOptionPane.WARNING_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(ChangePassword_121.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_OKButtonActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton OKButton; private javax.swing.JLabel bgp; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JTextField newusername; private javax.swing.JPasswordField passwordconfirm1; // End of variables declaration//GEN-END:variables } <file_sep>/LibraryManagement_final/src/Librarymanagement/AdminReport_113.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.awt.HeadlessException; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author 26625 */ public class AdminReport_113 extends javax.swing.JFrame { /** * Creates new form AdminReport_113 */ String [] a; String str11; Statement stmt; PreparedStatement pst; Connection con=DBClass.getConnection();//连接数据库 ResultSet rs; DefaultTableModel tm; PreparedStatement preparedStatement; public AdminReport_113() { initComponents(); bookreportpanel.setVisible(false); this.setDefaultCloseOperation(0x1); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); top = new javax.swing.JLabel(); bookbutton = new javax.swing.JLabel(); bookreportpanel = new javax.swing.JPanel(); searchbooktxt = new javax.swing.JTextField(); searchbutton2 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); booktable = new javax.swing.JTable(); jLabel3 = new javax.swing.JLabel(); booktype = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); top.setFont(new java.awt.Font("宋体", 1, 36)); // NOI18N top.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); top.setText("Report"); jPanel1.add(top, new org.netbeans.lib.awtextra.AbsoluteConstraints(199, 20, 680, 52)); bookbutton.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N bookbutton.setText("Book&User Report"); bookbutton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { bookbuttonMouseClicked(evt); } }); jPanel1.add(bookbutton, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 170, 44)); bookreportpanel.setOpaque(false); bookreportpanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); searchbooktxt.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N bookreportpanel.add(searchbooktxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 60, 287, 44)); searchbutton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/search2.png"))); // NOI18N searchbutton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { searchbutton2MouseClicked(evt); } }); bookreportpanel.add(searchbutton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 60, -1, -1)); jScrollPane2.setOpaque(false); booktable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "BookID", "BookName", "UserAction", "UserID", "ActionTime" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); booktable.setOpaque(false); booktable.getTableHeader().setReorderingAllowed(false); jScrollPane2.setViewportView(booktable); bookreportpanel.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, 680, 120)); jLabel3.setFont(new java.awt.Font("宋体", 1, 24)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Book&User Report"); bookreportpanel.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 0, 230, 33)); booktype.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N booktype.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "BookID", "Title" })); booktype.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { booktypeActionPerformed(evt); } }); bookreportpanel.add(booktype, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 60, -1, 44)); jPanel1.add(bookreportpanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 120, 730, 290)); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/HUNI.png"))); // NOI18N jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, -1, -1)); jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(192, 82, 759, 13)); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); jPanel1.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(192, 7, 21, 410)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/背景(几何)1.jpg"))); // NOI18N jLabel1.setText("jLabel1"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 910, 420)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 911, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void bookbuttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bookbuttonMouseClicked bookreportpanel.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_bookbuttonMouseClicked private void searchbutton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchbutton2MouseClicked // TODO add your handling code here: try{ String sql=null; str11 = this.searchbooktxt.getText(); //通过组合框进行选择 if(booktype.getSelectedIndex()==0){ sql = "select * from bookreport where BookID= ?"; } else if(booktype.getSelectedIndex()==1){ sql = "select * from bookreport where BookName= ?"; } con = DBClass.getConnection(); pst = con.prepareStatement(sql);//查询 pst.setString(1, str11); rs = pst.executeQuery();//执行语句 ResultSetMetaData rsmd = rs.getMetaData();//获取原数据,数据的数据,比如行数列数,列名 int ColumnCount = rsmd.getColumnCount();//获取表格列数 tm = (DefaultTableModel) booktable.getModel();//建立表格模型,editbooktable表格变量名 tm.setRowCount(0);//更新行数据,使表格清空 while (rs.next())//结果不为空,执行,以行进行循环,一次提取一条结果 { for (int i = 1; i <= ColumnCount; i++)//小于列数循环 { // tm.addColumn(rsmd.getColumnName(i));//添加列头 a=new String[ColumnCount];//获取列头名字 for (int s =0; s < ColumnCount; s++)//小于行循环 { a[s]=rs.getString(s+1);//获取列数据 } } tm.addRow(a);//将行和列的数据整合,进行输出 } //当文本字段为空时弹出Warming窗口 if(searchbooktxt.getText().length()==0) { JOptionPane.showMessageDialog(this, "Empty!","Warning",JOptionPane.WARNING_MESSAGE); } tm.fireTableDataChanged(); } catch (SQLException e) { JOptionPane.showMessageDialog(this, e, e.getMessage(), WIDTH, null); }//数据库报错 catch (Exception ex) { JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null); }//整体报错 }//GEN-LAST:event_searchbutton2MouseClicked private void booktypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_booktypeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_booktypeActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bookbutton; private javax.swing.JPanel bookreportpanel; private javax.swing.JTable booktable; private javax.swing.JComboBox booktype; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTextField searchbooktxt; private javax.swing.JLabel searchbutton2; private javax.swing.JLabel top; // End of variables declaration//GEN-END:variables } <file_sep>/LibraryManagement_final/src/Librarymanagement/ChangePhoneNumber_124.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Librarymanagement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; /** * * @author 123 */ public class ChangePhoneNumber_124 extends javax.swing.JFrame { /** Creates new form ChangePhoneNumber_124 */ public ChangePhoneNumber_124() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); confirm_pswd = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); new_ph_number = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); background = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(440, 300)); setResizable(false); jPanel1.setLayout(null); jPanel2.setOpaque(false); jLabel1.setFont(new java.awt.Font("宋体", 1, 24)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Change Phone Number"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel1) .addContainerGap(25, Short.MAX_VALUE)) ); jPanel1.add(jPanel2); jPanel2.setBounds(0, 0, 410, 90); jPanel3.setOpaque(false); jLabel2.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel2.setText("password"); jLabel3.setFont(new java.awt.Font("宋体", 1, 14)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel3.setText("new phone number"); jButton1.setText("ok"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(confirm_pswd, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(new_ph_number, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(155, 155, 155) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(82, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(confirm_pswd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(new_ph_number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1) .addGap(26, 26, 26)) ); jPanel1.add(jPanel3); jPanel3.setBounds(0, 80, 410, 170); background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Picture/背景(几何)1.jpg"))); // NOI18N background.setPreferredSize(new java.awt.Dimension(440, 300)); jPanel1.add(background); background.setBounds(-11, -2, 440, 270); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { // TODO add your handling code here: Pattern p1 = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$"); Matcher m1 = p1.matcher(new_ph_number.getText()); if(confirm_pswd.getText().length() == 0){ JOptionPane.showMessageDialog(this, "Empty Password", "Warning", JOptionPane.WARNING_MESSAGE); }else if(new_ph_number.getText().length() == 0){ JOptionPane.showMessageDialog(this, "Empty Phone Number", "Warning", JOptionPane.WARNING_MESSAGE); } else if(m1.matches() == false){ JOptionPane.showMessageDialog(this, "Please enter the right phone number", "Error", JOptionPane.ERROR_MESSAGE); }else{ Connection con; PreparedStatement pst; con = DBClass.getConnection(); String s = "select * from userdata where id = ? and password = ?"; pst = con.prepareStatement(s); pst.setString(1,LoginMenu_100.idinput.getText()); pst.setString(2, confirm_pswd.getText()); ResultSet rs = pst.executeQuery(); if(rs.next() == false){ JOptionPane.showMessageDialog(this, "Wrong password", "Error",JOptionPane.ERROR_MESSAGE); }else{ String str = "update userdata set phonenumber = ? where id = ?"; pst = con.prepareStatement(str); pst.setString(1,new_ph_number.getText()); pst.setString(2,LoginMenu_100.idinput.getText()); pst.executeUpdate(); JOptionPane.showMessageDialog(this, "Phone Number Changed Successfully", "OK",JOptionPane.INFORMATION_MESSAGE); this.dispose(); } rs.close(); pst.close(); con.close(); } } catch (SQLException ex) { Logger.getLogger(ChangePhoneNumber_124.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel background; private javax.swing.JPasswordField confirm_pswd; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JTextField new_ph_number; // End of variables declaration//GEN-END:variables }
4f74e70dfb378da2a1f9173ff9715a1ad3625d3b
[ "Java", "SQL", "INI" ]
10
Java
the-sooners/LibraryManagement
6d0ce9073ce4688aea4cfcd7c6fe8eb8642bb0fe
3b7604a7f07dd7efe27605f59b0d08d97d7d8808
refs/heads/master
<repo_name>Eduardo32/blog<file_sep>/requirements-dev.txt dj-database-url==0.5.0 dj-static==0.0.6 Django==2.2.5 django-classy-tags==0.9.0 django-taggit==1.1.0 django-taggit-templatetags2==1.6.1 Pillow==6.1.0 python-decouple==3.1 pytz==2019.2 sqlparse==0.3.0 static3==0.7.0 <file_sep>/posts/views.py from django.urls import reverse_lazy from .models import Post from .forms import SalvaPostForm from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from datetime import datetime class PostListView(ListView): template_name = 'posts/lista.html' model = Post context_object_name = 'Posts' class PostDetailView(DetailView): template_name = 'posts/detalhe.html' model = Post context_object_name = 'Post' class PostCreateView(CreateView): template_name = 'posts/novo.html' model = Post form_class = SalvaPostForm success_url = reverse_lazy('posts:lista') def form_valid(self, form): form.instance.autor = self.request.user return super(PostCreateView, self).form_valid(form) class PostUpdateView(UpdateView): template_name = 'posts/edita.html' model = Post fields = [ 'titulo', 'sub_titulo', 'thumb', 'descricao', 'slug', 'tags', ] success_url = reverse_lazy('posts:lista') def form_valid(self, form): form.instance.data_atualizacao = datetime.now() return super(PostUpdateView, self).form_valid(form) class PostDeleteView(DeleteView): template_name = 'posts/exclui.html' model = Post context_object_name = 'Post' success_url = reverse_lazy('posts:lista') <file_sep>/posts/urls.py from django.urls import path from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView from django.conf.urls.static import static from django.conf import settings app_name = 'posts' urlpatterns = [ path('', PostListView.as_view(), name='lista'), path('novo/', PostCreateView.as_view(), name='novo'), path('<str:slug>/', PostDetailView.as_view(), name='detalhe'), path('edita/<str:slug>/', PostUpdateView.as_view(), name='edita'), path('exclui/<str:slug>', PostDeleteView.as_view(), name='exclui'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>/posts/models.py import os from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager from django.dispatch import receiver class Post(models.Model): titulo = models.CharField( max_length=27, blank=False, null=False, ) sub_titulo = models.CharField( max_length=27, ) thumb = models.ImageField(upload_to='thumbs/%Y/%m/%d') thumb_descricao = models.CharField( max_length=20, blank=False, null=False, ) descricao = models.TextField( blank=False, null=False, ) slug = models.SlugField( max_length=20, blank=False, null=False ) data_postagem = models.DateTimeField( auto_now_add=True, blank=False, null=False, ) data_atualizacao = models.DateTimeField( blank=True, null=True, ) autor = models.ForeignKey(User, on_delete=models.CASCADE) tags = TaggableManager() class Meta: verbose_name, verbose_name_plural = u"Post", u"Posts" def __str__(self): return "%s" % self.titulo objects = models.Manager() @receiver(models.signals.post_delete, sender=Post) def auto_delete_file_on_delete(sender, instance, **kwargs): """ Remove o arquivo quando o objeto Post correspondente for deletado """ if instance.thumb: if os.path.isfile(instance.thumb.path): os.remove(instance.thumb.path) @receiver(models.signals.pre_save, sender=Post) def auto_delete_file_on_change(sender, instance, **kwargs): """ Remove o arquivo antigo quando o objeto Post correspondente for atualizado com uma nova imagem """ if not instance.pk: return False try: old_file = Post.objects.get(pk=instance.pk).thumb except Post.DoesNotExist: return False new_file = instance.thumb if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) <file_sep>/posts/forms.py from django import forms from .models import Post class SalvaPostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' exclude = [ 'data_atualizacao', 'autor', ]
eed991f5ebf8b76504cab0b6c20df55ec2757f82
[ "Python", "Text" ]
5
Text
Eduardo32/blog
223b43ca7e46849b25a50291f361f530e23d5bce
2439b686fe9d0087e5e2fa6e202f790ffa354092
refs/heads/main
<repo_name>NIEPS-Water-Program/water-affordability<file_sep>/www/scripts/global_variables.js /*####################################################################################################### LOAD LARGE DATASETS ######################################################################################################-*/ //read in datasets var utilityScores; var utilityDetails; var demData; var blsData; var selCSV; //filter once in drawMap() and call repeatedly... except not working var selFeature; var select_url; var oldSystem = "none"; function getSystemData() { return $.getJSON("data/simple_water_systems.geojson", function (siteData) { gisSystemData = siteData; }); } getSystemData(); // because asynchronous, have to call after function runs //when javascript loads function loadData(){ d3.csv("data/utility_afford_scores.csv").then(function (dataCSV) { dataCSV.forEach(function (d) { d.HBI = +d.HBI; d.PPI = +d.PPI; d.TRAD = +d.TRAD; d.hh_use = +d.hh_use; d.LaborHrs = +d.LaborHrs; d.low = +d.low; d.low_mod = +d.low_mod; d.mod_high = +d.mod_high; d.high = +d.high; d.very_high = +d.very_high; }); utilityScores = dataCSV; //console.log(utilityScores) return utilityScores; }); //end D3 d3.csv("data/utility_descriptions.csv").then(function (detailsCSV) { utilityDetails = detailsCSV; selCSV = utilityDetails; setDropdownValues(); //console.log(utilityDetails) return utilityDetails; }); // DEMOGRAPHIC DATA NEXT //read in csv d3.csv("data/census_summary.csv").then(function (demCSV) { demCSV.forEach(function (d) { d.pop1990 = +d.pop1990; d.pop2000 = +d.pop2000; d.pop2010 = +d.pop2010; d.pop2018 = +d.cwsPop; //THIS ONE NEEDS TO HAVE LAST DATE UPDATED EACH YEAR d.under18 = +d.under18; d.age18to34 = +d.age18to34; d.age35to59 = +d.age35to59; d.age60to64 = +d.age60to64; d.over65 = +d.over65; d.Asian = +d.Asian; d.Black = +d.Black; d.Native = +d.Native; d.Other = +d.Other; d.Hispanic = +d.Hispanic; d.White = +d.White; d.d0to24k = +d.d0to24k; d.d25to49k = +d.d25to49k; d.d50to74k = +d.d50to74k; d.d75to100k = +d.d75to100k; d.d100to125k = +d.d100to125k; d.d125to150k = +d.d125to150k; d.d150kmore = +d.d150kmore; d.built_2010later = +d.built_2010later; d.built_2000to2009 = +d.built_2000to2009; d.built_1990to1999 = +d.built_1990to1999; d.built_1980to1989 = +d.built_1980to1989; d.built_1970to1979 = +d.built_1970to1979; d.built_1960to1969 = +d.built_1960to1969; d.built_1950to1959 = +d.built_1950to1959; d.built_1940to1949 = +d.built_1940to1949; d.built_1939early = +d.built_1939early; }); demData = demCSV; return demCSV; }); //end d3 d3.csv("data/bls_summary.csv").then(function (blsCSV) { blsCSV.forEach(function (d) { d.year = +d.year; d.unemploy_rate = +d.unemploy_rate; }); blsData = blsCSV; return blsData; }); //console.log(blsData) setTimeout(() => { plotDemographics(selectSystem) }, 500); }//end load data function loadData() <file_sep>/rcode/use1_calculate_rates.R ####################################################################################################################################################### # # This script estimates the bills households will pay for different volumes of water use by service type (drinking water, wastewater, or stormwater), # and based on inside and outside rates. The mean bill is calculated for all other spatially distinct rates within a service area # Created by <NAME>, 2021 # ######################################################################################################################################################## ###################################################################################################################################################################### # # Load data and set variables # ###################################################################################################################################################################### #set variables for stormwater calculations res.ft <- 2500; #will replace if vol_base is present... otherwise assume residential household size is 2500 for stormwater res.bedrooms = 2; #again, this variable can be changed res.person = 3; tax.based = 200000; #assume property value = 200000 percent.impervious = 50; #assume half of lot is impervious #read in rates rates <- read_excel(paste0(swd_data, "rates_data\\rates_", state.list[1], ".xlsx"), sheet="rateTable") %>% mutate(state = state.list[1]) for (i in 2:length(state.list)){ zt <- read_excel(paste0(swd_data, "rates_data\\rates_", state.list[i], ".xlsx"), sheet="rateTable") %>% mutate(state = state.list[i]) if (state.list[i] == "nc"){ zt <- zt %>% mutate(pwsid = paste0("NC",str_remove_all(pwsid, "[-]"))) %>% filter(rate_type != "drought_surcharge" & rate_type != "drought_mandatory_surcharge" & rate_type != "drought_voluntary_surcharge" & rate_type != "conservation_surcharge") %>% filter(nchar(pwsid) == 9) %>% filter(pwsid != "NC Aqua NC") %>% filter(pwsid != "NCBayboro") } rates <- rbind(rates, zt); rm(zt) } table(rates$state); #check to make sure have data res.rates <- rates; #do this if you want to update all data OR #Only calculate for those that have been updated-------------------------------------------------------------------------------------- update.list <- rates %>% filter(update_bill != "no") %>% select(pwsid) %>% distinct() #always add this pwsid to have an outside rates keep.pwsid <- as.data.frame(c("NC0363020","NC0136035", "NC0190010")); colnames(keep.pwsid) <- "pwsid" update.list <- rbind(update.list, keep.pwsid) %>% unique() table(substr(update.list$pwsid,0,2)) res.rates <- rates %>% filter(pwsid %in% update.list$pwsid) #------------------------------------------------------------------------------------------------------------------------------------ res.rates <- res.rates %>% mutate_at(c("meter_size", 'value_from', 'value_to', "vol_base", "cost"), as.numeric); #convert to numeric #data check table(res.rates$bill_frequency, useNA="ifany"); #res.rates <- res.rates %>% mutate(rate_type = tolower(rate_type)) table(res.rates$rate_type, useNA="ifany"); #chck for commodity_charge misspellings and service_charge misspellings... also make sure all others have a "surcharge" table(res.rates$vol_unit) #Keep only most recent rate years res.rates <- res.rates %>% mutate(class_category = ifelse(class_category=="NA", "inside", class_category)) %>% mutate(service = sub("\\_.*","", rate_code)) #at this point this only changes "sewer_septic" to sewer... if want to distinguish or omit in future versions - do so here. #res.rates <- res.rates %>% mutate(class_category = ifelse(class_category != "outside", "inside", "outside")); #to early to do for averaging... need to do after average and before sum. res.rates <- res.rates %>% group_by(pwsid, service_area, city_name, utility_name, service) %>% filter(effective_date == max(effective_date)) %>% as.data.frame() #remove stormwater and add back later if desire storm.rates <- res.rates %>% filter(service == "stormwater") %>% rename(category = class_category) res.rates <- res.rates %>% filter(service != "stormwater") %>% rename(category = class_category) ###################################################################################################################################################################### # # CALCULATE RATES # ###################################################################################################################################################################### #For this version we will eventually summarize the costs. IMPORTANT TO DO SUMMARY BY UTILITY_NAME AND CITY ANT END #calculate base or minimum charge---------------------------------------------- fixed.charge <- res.rates %>% filter(volumetric =="no") %>% group_by(pwsid, service_area, city_name, utility_name, rate_type, service, bill_frequency, category) %>% mutate(month_base_cost = ifelse(bill_frequency == "quarterly", round(cost/3,2), ifelse(bill_frequency == "bi-monthly", round(cost/2, 2), ifelse(bill_frequency == "semi-annually", round(cost/6, 2), ifelse(bill_frequency=="annually", round(cost/12,2), cost))))) #rename those that are not inside outside to be inside only; fixed.charge <- fixed.charge %>% mutate(category = ifelse(category != "outside", "inside", "outside")) #summarize by multiple types of categories fixed.charge <- fixed.charge %>% group_by(pwsid, service_area, city_name, rate_type, service, category) %>% summarise(base_cost = round(mean(month_base_cost, na.rm=TRUE),2), .groups = "drop") %>% as.data.frame() fixed.charge <- fixed.charge %>% mutate(rate_type = ifelse(rate_type=="service_charge", "service", "surcharge")) #summarize by multiple types of surcharges fixed.charge <- fixed.charge %>% group_by(pwsid, service_area, city_name, rate_type, service, category) %>% summarise(base_cost = round(sum(base_cost, na.rm=TRUE),2), .groups = "drop") %>% as.data.frame() table(fixed.charge$service, fixed.charge$category) #for those that had inside / outside rates for one service, apply the inside rate to the outside for the missing service... assumption that service is applied outside fx <- fixed.charge%>% pivot_wider(id_cols = c("pwsid", "service_area", "city_name", "rate_type"), names_from = c("service", "category"), values_from = base_cost) #fix if inside rates but not outside rates... not vice versa for NC because shapefile set to outside if only outside fx <- fx %>% mutate(sewer_outside = ifelse(is.na(water_outside)==FALSE & is.na(sewer_outside)==TRUE, sewer_inside, sewer_outside), water_outside = ifelse(is.na(water_outside)==TRUE & is.na(sewer_outside)==FALSE, water_inside, water_outside)) #recombine fx2 <- fx %>% gather(var, base_cost, -c("pwsid", "service_area", "city_name", "rate_type")) %>% mutate(service = substr(var, 0, 5), category = substr(var, 7, nchar(var))) %>% select(-var) #divide service and surcharge into separate columns service.only <- fx2 %>% filter(rate_type == "service") %>% select(-rate_type) flat.surcharge <- fx2 %>% filter(rate_type == "surcharge") %>% select(-rate_type) %>% rename(fixed_surcharge = base_cost) fixed.charge <- merge(service.only, flat.surcharge, by.x=c("pwsid", "service_area", "city_name", "service", "category"), by.y=c("pwsid","service_area","city_name", "service", "category"), all=TRUE) summary(fixed.charge); #check values for obvious data entry errors ##################################################################################################################################### #Calculate the volumetric charge--------------------------------------------------------------------------------------------------------------------------------------- gal.month <- c(0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000) #calculate volumetric charges --------------------------------------------------------------------------------------------------------------------------------------- ws.volume <- res.rates %>% filter(volumetric=="yes") #%>% mutate(rate_type = ifelse(rate_type=="commodity_charge_tier" | rate_type=="commodity_charge_flat", "commodity", "surcharge")) #convert everything to mgal ws.volume <- ws.volume %>% mutate(value_from = ifelse(vol_unit=="gallons", value_from, value_from*7.48052), value_to = ifelse(vol_unit=="gallons", value_to, value_to*7.48052), vol_base = ifelse(vol_unit=="gallons", vol_base, vol_base*7.48052)) %>% as.data.frame() #unique pwsid - pull all of them for merging later unique.pwsid <- unique(res.rates$pwsid) #build in pwsid for those without commodity charge #create dataframe for tiers volume <- as.data.frame(matrix(nrow=0, ncol=9)); colnames(volume) <- c("pwsid","service_area","city_name","service","rate_type","hh_use","category", "unit_price", "vol_cost") for(i in 1:length(unique.pwsid)){ #for(i in 1:400){ zt <- subset(ws.volume, pwsid==as.character(unique.pwsid[i])); zt2 = NA; zt3 = NA; #how many values should there be? nval = res.rates %>% filter(pwsid==as.character(unique.pwsid[i])) %>% select(pwsid, service_area, city_name) %>% distinct() nval = dim(nval)[1] for (j in 1:length(gal.month)){ if(dim(zt)[1]>0){ zt$hh_use <- gal.month[j]; #adjust for bill frequency zt2 <- zt %>% mutate(hh_use_adj = hh_use * adjustment) %>% mutate(value_from = ifelse(bill_frequency == "quarterly", value_from/3, ifelse(bill_frequency == "bi-monthly", value_from/2, ifelse(bill_frequency == "semi-annually", value_from/6, ifelse(bill_frequency=="annually", value_from/12, value_from))))) %>% mutate(value_to = ifelse(bill_frequency == "quarterly", value_to/3, ifelse(bill_frequency == "bi-monthly", value_to/2,ifelse(bill_frequency == "semi-annually", value_to/6, ifelse(bill_frequency=="annually", value_to/12, value_to))))) #subset to appropriate tier and calcualte cost zt2 <- zt2 %>% filter(value_from <= hh_use_adj) %>% mutate(vol_cost = ifelse(value_to <= hh_use_adj, round((value_to - value_from)*cost/vol_base,2), round((hh_use_adj - value_from)*cost/vol_base, 2))) #for those with the same class but multiple categories zt2 <- zt2 %>% group_by(pwsid, service_area, city_name, utility_name, service, bill_frequency, category, rate_type, hh_use) %>% summarize(vol_cost = sum(vol_cost, na.rm=TRUE), .groups="drop") #now mutate to inside outside category only for adding zt2 = zt2 %>% mutate(category = ifelse(category != "outside", "inside", "outside")) #summarize tiers into a single cost zt2 <- zt2 %>% group_by(pwsid, service_area, city_name, service, bill_frequency, category, rate_type, hh_use) %>% summarize(vol_cost = mean(vol_cost, na.rm=TRUE), .groups="drop") #zt2 <- zt2 %>% mutate(category = ifelse(category != "outside", "inside", "outside")) zt2 <- zt2 %>% select(pwsid, service_area, city_name, rate_type, service, category, hh_use, vol_cost) %>% group_by(pwsid, service_area, city_name, rate_type, service, category, hh_use) %>% summarize(vol_cost=round(mean(vol_cost, na.rm=TRUE),2), .groups="drop") %>% mutate(unit_price = round(vol_cost/hh_use*1000,2)) #sumarize by adding cost zt2 <- zt2 %>% mutate(rate_type = ifelse(rate_type=="commodity_charge_tier" | rate_type=="commodity_charge_flat", "commodity", "surcharge")) zt2 <- zt2 %>% select(pwsid, service_area, city_name, rate_type, service, category, hh_use, vol_cost) %>% group_by(pwsid, service_area, city_name, rate_type, service, category, hh_use) %>% summarize(vol_cost=round(sum(vol_cost, na.rm=TRUE),2), .groups="drop") %>% mutate(unit_price = round(vol_cost/hh_use*1000,2)) #if have only one service if (length(unique(zt2$service)) == 1){ miss_serv = NA if(zt2$service == "water") { miss_serv = "sewer" } if(zt2$service == "sewer") { miss_serv = "water" } zt3 <- zt2 %>% select(pwsid, service_area, city_name, rate_type, service, category, hh_use) %>% distinct() %>% mutate(vol_cost = 0, unit_price=0, service = miss_serv) zt2 <- rbind(zt2, zt3) } #if missing a city or if only volume charge partially still need to create parts of the dataframe if (length(unique(zt2$city_name)) < nval){ zt4 <- res.rates %>% filter(pwsid==as.character(unique.pwsid[i])) %>% select(pwsid, service_area, city_name) %>% distinct() #if missing a city, create two values for each service if(length(unique(zt2$city_name)) < length(unique(zt4$city_name))){ zt3 <- zt4 %>% filter(city_name %notin% zt2$city_name) %>% mutate(rate_type = "commodity", service = "water", category = "inside", hh_use = gal.month[j], vol_cost=0, unit_price=0) zt5 <- zt3 %>% mutate(service = "sewer"); zt2 <- rbind(zt2, zt3, zt5) } } }# end if volumetric #if not volumetric if(dim(zt)[1] == 0){ zt3 <- subset(res.rates, pwsid==as.character(unique.pwsid[i])) %>% mutate(rate_type = "commodity") %>% mutate(category = ifelse(category != "outside", "inside", "outside")) %>% select(pwsid, service_area, city_name, rate_type, service, category) %>% distinct() zt2 <- zt3 %>% mutate(hh_use = gal.month[j], vol_cost = 0, unit_price = 0) } volume <- rbind(volume, zt2) } print(paste0(i, ": ", unique.pwsid[i])); } summary(volume); #check for data entry errors bk.up <- volume; #foo <- (table(volume$pwsid)) volume <- volume %>% distinct() table(volume$hh_use) #check for data entry errors table(volume$service, volume$category) #check for data entry errors #for those that had inside / outside rates for one service, apply the inside rate to the outside for the missing service... assumption that service is applied outside fx <- volume %>% select(-unit_price) %>% pivot_wider(id_cols = c("pwsid", "service_area", "city_name", "rate_type","hh_use"), names_from = c("service", "category"), values_from = vol_cost) #fix if inside rates but not outside rates... not vice versa for NC because shapefile set to outside if only outside if("water_outside" %in% colnames(fx)){}else{fx$water_outside = NA; } if("sewer_outside" %in% colnames(fx)){}else{fx$sewer_outside = NA; } fx <- fx %>% mutate(sewer_outside = ifelse(is.na(water_outside)==FALSE & is.na(sewer_outside)==TRUE & is.na(sewer_inside)==FALSE, sewer_inside, sewer_outside), water_outside = ifelse(is.na(water_outside)==TRUE & is.na(sewer_outside)==FALSE & is.na(water_inside)==FALSE, water_inside, water_outside)) fx3 <- volume %>% pivot_wider(id_cols = c("pwsid", "service_area", "city_name", "rate_type","hh_use"), names_from = c("service", "category"), values_from = unit_price) if("water_outside" %in% colnames(fx3)){}else{fx3$water_outside = NA; } if("sewer_outside" %in% colnames(fx3)){}else{fx3$sewer_outside = NA; } #fix if inside rates but not outside rates... not vice versa for NC because shapefile set to outside if only outside fx3 <- fx3 %>% mutate(sewer_outside = ifelse(is.na(water_outside)==FALSE & is.na(sewer_outside)==TRUE & is.na(sewer_inside)==FALSE, sewer_inside, sewer_outside), water_outside = ifelse(is.na(water_outside)==TRUE & is.na(sewer_outside)==FALSE & is.na(water_inside)==FALSE, water_inside, water_outside)) #recombine fx2 <- fx %>% gather(var, vol_cost, -c("pwsid", "service_area", "city_name", "rate_type", "hh_use")) %>% mutate(service = substr(var, 0, 5), category = substr(var, 7, nchar(var))) %>% select(-var) fx3 <- fx3 %>% gather(var, unit_price, -c("pwsid", "service_area", "city_name", "rate_type", "hh_use")) %>% mutate(service = substr(var, 0, 5), category = substr(var, 7, nchar(var))) %>% select(-var) fx2 <- merge(fx2, fx3, by.x=c("pwsid", "service_area", "city_name", "rate_type", "hh_use", "service", "category"), by.y=c("pwsid", "service_area", "city_name", "rate_type", "hh_use", "service", "category"), all=TRUE) commod.volume <- fx2 %>% filter(rate_type=="commodity") %>% select(-rate_type) %>% rename(commodity_unit_price = unit_price) surcharge.volume <- fx2 %>% filter(rate_type=="surcharge") %>% select(-rate_type) %>% rename(vol_surcharge = vol_cost) %>% select(-unit_price) volume <- merge(commod.volume, surcharge.volume, by.x=c("pwsid", "service_area", "city_name", "service", "hh_use", "category"), by.y=c("pwsid","service_area","city_name", "service", "hh_use", "category"), all=TRUE) #Miguel Water has a person surcharge... manually add for now... $12.72 per person... assuming 3 persons volume <- volume %>% mutate(vol_surcharge = ifelse(pwsid=="CA3010073" & service=="sewer" & category=="inside", 3*12.72, vol_surcharge)) foo <- merge(fixed.charge, volume, by.x=c("pwsid", "service_area", "city_name", "service","category"), by.y=c("pwsid","service_area","city_name", "service","category"), all=TRUE) %>% arrange(pwsid, service, category, hh_use) summary(foo) # calculate zone commodity charges --------------------------------------------------------------------------------------------------------------------------------- #volumetric charges - flat - some utilities charge a flat amount if you fall within a tier ws.zone <- res.rates %>% filter(volumetric=="zone") %>% mutate(value_from = ifelse(vol_unit=="gallons", value_from, value_from*7.48052), value_to = ifelse(vol_unit=="gallons", value_to, value_to*7.48052)) ws.zone <- ws.zone %>% mutate(zone_type = ifelse(rate_type=="commodity_charge_zone", "commodity", "surcharge")) #create dataframe zone <- as.data.frame(matrix(nrow=0, ncol=9)); colnames(zone) <- c("pwsid","service_area","city_name", "service","category", "zone_type","hh_use","zone_cost") unique.pwsid <- unique(ws.zone$pwsid) for(i in 1:length(unique.pwsid)){ zt <- subset(ws.zone, pwsid==as.character(unique.pwsid[i])); zt2 = NA; for (j in 1:length(gal.month)){ zt$hh_use <- ifelse(zt$vol_unit=="person", 3, gal.month[j]); zt$hh_use <- ifelse(zt$vol_unit=="tax-based", tax.based, gal.month[j]); zt$hh_use <- ifelse(zt$vol_unit=="percent impervious surface", percent.impervious, gal.month[j]); #hh use should be multiplied based on bill frequency to get cost... then divide #except for zones will charge x number of times each year zt2 <- zt %>% mutate(hh_use_adj = hh_use * adjustment) %>% mutate(bill2months = ifelse(bill_frequency == "quarterly", 4, ifelse(bill_frequency == "bi-monthly", 2, ifelse(bill_frequency == "semi-annually", 6, ifelse(bill_frequency=="annually", 12, 1))))) #zt2 <- zt %>% mutate(hh_use_adj = hh_use * adjustment) %>% mutate(value_from = ifelse(bill_frequency == "quarterly", value_from/3, ifelse(bill_frequency == "bi-monthly", value_from/2, # ifelse(bill_frequency == "semi-annually", value_from/6, ifelse(bill_frequency=="annually", value_from/12, value_from))))) %>% # mutate(value_to = ifelse(bill_frequency == "quarterly", value_to/3, ifelse(bill_frequency == "bi-monthly", value_to/2,ifelse(bill_frequency == "semi-annually", value_to/6, # ifelse(bill_frequency=="annually", value_to/12, value_to))))) zt2 <- zt2 %>% filter(value_from <= hh_use_adj & value_to >= hh_use_adj) %>% group_by(pwsid, service_area, service, city_name, utility_name, category, zone_type, bill_frequency, hh_use, bill2months) %>% summarise(zone_cost = round(mean(cost, na.rm=TRUE),2), .groups="drop") %>% mutate(zone_cost = zone_cost/bill2months) zt2 <- zt2 %>% mutate(category = ifelse(category != "outside", "inside", "outside")) zt2 <- zt2 %>% select(pwsid, service_area, city_name, zone_type, service, category, hh_use, zone_cost) %>% group_by(pwsid, service_area, city_name, zone_type, service, category, hh_use) %>% summarize(zone_cost=round(mean(zone_cost, na.rm=TRUE),2), .groups="drop") zt2 <- zt2 %>% select(pwsid, service_area, city_name, service, category, zone_type, hh_use, zone_cost) #if only volume charge partially still need to create dataframe if (dim(zt2)[1]==0){ zt2 <- zt %>% select(pwsid, service_area, city_name, service, category, zone_type, hh_use) %>% distinct() %>% mutate(zone_cost = 0) } #bind onto volume dataframe zone <- rbind(zone, zt2) } print(paste0(i, ": ", unique.pwsid[i])); } zone <- zone %>% distinct() summary(zone) table(zone$service, zone$category) #for those that had inside / outside rates for one service, apply the inside rate to the outside for the missing service... assumption that service is applied outside fx <- zone %>% pivot_wider(id_cols = c("pwsid", "service_area", "city_name", "zone_type","hh_use"), names_from = c("service", "category"), values_from = zone_cost) #fix if inside rates but not outside rates... not vice versa for NC because shapefile set to outside if only outside fx <- fx %>% mutate(sewer_outside = ifelse(is.na(water_outside)==FALSE & is.na(sewer_outside)==TRUE & is.na(sewer_inside)==FALSE, sewer_inside, sewer_outside), water_outside = ifelse(is.na(water_outside)==TRUE & is.na(sewer_outside)==FALSE & is.na(water_inside)==FALSE, water_inside, water_outside)) #recombine fx2 <- fx %>% gather(var, zone_cost, -c("pwsid", "service_area", "city_name", "zone_type", "hh_use")) %>% mutate(service = substr(var, 0, 5), category = substr(var, 7, nchar(var))) %>% select(-var) commod.zone <- fx2 %>% filter(zone_type=="commodity") %>% select(-zone_type) surcharge.zone <- fx2 %>% filter(zone_type=="surcharge") %>% select(-zone_type) %>% rename(zone_surcharge = zone_cost) zone <- merge(commod.zone, surcharge.zone, by.x=c("pwsid", "service_area", "city_name", "service", "category", "hh_use"), by.y=c("pwsid","service_area","city_name", "service", "category", "hh_use"), all=TRUE) df <- merge(foo, zone, by.x=c("pwsid", "service_area", "service", "city_name", "category", "hh_use"), by.y=c("pwsid", "service_area", "service", "city_name", "category", "hh_use"), all=TRUE) df <- unique(df) #Fixes for specific systems with difficult rates zt <- df %>% filter(pwsid=="NC0229025"); #service area has two names df <- df %>% mutate(service_area = ifelse(pwsid=="NC0229025", "Davidson Water", service_area)) %>% filter(is.na(hh_use)==FALSE) df <- df %>% mutate(service_area = ifelse(pwsid=="NC0472015", "Perquimans County/Winfall", service_area)) %>% mutate(service_area = ifelse(pwsid=="NC1014001", "Caldwell County/Gamewell", service_area)) df <- df %>% mutate(base_cost = ifelse((pwsid=="CA3110003" & service == "water" & category == "inside"), 90.54, base_cost)) #df %>% filter(pwsid=="CA3110003" & category=="inside") df[is.na(df)] <- 0; df <- df %>% mutate(total = base_cost + fixed_surcharge + vol_cost + vol_surcharge + zone_cost + zone_surcharge) #set NA to zero for averaging df <- df %>% mutate(total = na_if(total, 0), base_cost = na_if(base_cost, 0), vol_cost = na_if(vol_cost, 0), commodity_unit_price = na_if(commodity_unit_price, 0), zone_cost = na_if(zone_cost, 0)) df2 <- df %>% group_by(pwsid, service_area, service, category, hh_use) %>% summarize(base_cost = round(mean(base_cost, na.rm=TRUE),2), fixed_surcharge = round(mean(fixed_surcharge, na.rm=TRUE),2), commodity_unit_price = round(mean(commodity_unit_price, na.rm=TRUE),2), vol_cost = round(mean(vol_cost, na.rm=TRUE),2), vol_surcharge = round(mean(vol_surcharge, na.rm=TRUE),2), zone_cost = round(mean(zone_cost, na.rm=TRUE),2), zone_surcharge = round(mean(zone_surcharge, na.rm=TRUE),2), total = round(mean(total, na.rm=TRUE),2), .groups="drop") #TOTAL HERE MAKES A BIG DIFFERENCE FOR PA df2 <- df2 %>% distinct() summary(df2) zt <- as.data.frame(table(df2$pwsid)) subset(zt, Freq>72) #Now lets add a third column for those that are both water and sewer to get teh total price df.ws <- df2 %>% pivot_wider(id_cols = c("pwsid", "service_area", "hh_use", "category"), names_from = service, values_from = c("base_cost", "vol_cost","zone_cost","fixed_surcharge","vol_surcharge", "zone_surcharge", "total", "commodity_unit_price")) #fill NA's with previous value in group df.ws <- df.ws %>% group_by(pwsid, service_area, category) %>% fill(base_cost_sewer, base_cost_water, vol_cost_sewer, vol_cost_water, zone_cost_sewer, zone_cost_water, fixed_surcharge_sewer, fixed_surcharge_water, vol_surcharge_sewer, vol_surcharge_water, zone_surcharge_sewer, zone_surcharge_water, total_sewer, total_water, .direction = "down") #now add a flag for water and sew df.ws <- df.ws %>% mutate(nwat = ifelse(is.na(total_water)==FALSE, 1, 0), nsew = ifelse(is.na(total_sewer)==FALSE, 1, 0)) %>% mutate(n_services = nwat+nsew) %>% select(-nwat, -nsew) #add total df.ws <- df.ws %>% mutate(base_cost_total = base_cost_water + base_cost_sewer, vol_cost_total = vol_cost_water + vol_cost_sewer, zone_cost_total = zone_cost_water + zone_cost_sewer, fixed_surcharge_total = fixed_surcharge_sewer + fixed_surcharge_water, vol_surcharge_total = vol_surcharge_water + vol_surcharge_sewer, zone_surcharge_total = zone_surcharge_water + zone_surcharge_sewer, total_total = total_sewer + total_water) #make long again df.ws2 <- df.ws %>% gather(var, val, -c("pwsid", "service_area", "category", "hh_use", "n_services")) %>% mutate(service = substr(var, nchar(var)-4, nchar(var)), var = substr(var, 0, nchar(var)-6)) %>% spread(var, val) summary(df.ws2) table(df.ws2$n_services, useNA="ifany") df.ws2[is.na(df.ws2)] <- 0; #LETS ADD IN STORMWATER #calculate base or minimum charge---------------------------------------------- fixed.charge <- storm.rates %>% mutate(rate_type = ifelse(rate_type=="service_charge", "service", "surcharge")) fixed.charge <- fixed.charge %>% filter(volumetric =="no") %>% group_by(pwsid, service_area, rate_type, service, bill_frequency, category) %>% mutate(base_cost = ifelse(bill_frequency == "quarterly", round(cost/3,2), ifelse(bill_frequency == "bi-monthly", round(cost/2, 2), ifelse(bill_frequency == "semi-annually", round(cost/6, 2), ifelse(bill_frequency=="annually", round(cost/12,2), cost))))) #assume always inside rates #fixed.charge <- fixed.charge %>% mutate(category = "inside") fixed.charge <- fixed.charge %>% group_by(pwsid, service_area, service, category) %>% summarise(base_cost = round(mean(base_cost, na.rm=TRUE),2), .groups = "drop") %>% as.data.frame() #take average cost by category fixed.charge <- fixed.charge %>% mutate(category = ifelse(category=="outside", "outside", "inside")) %>% group_by(pwsid, service_area, service, category) %>% summarise(base_cost = round(mean(base_cost, na.rm=TRUE),2), .groups = "drop") %>% as.data.frame() #For stormwater - set anticipated tier storm.volume <- storm.rates %>% filter(rate_type=="commodity_charge_flat" | rate_type=="commodity_charge_tier") %>% filter(volumetric=="yes") %>% mutate(hh_use = ifelse(vol_unit=="ERU", 1, ifelse(vol_unit=="square feet", res.ft, NA))) storm.volume <- storm.volume %>% mutate(hh_use = ifelse(vol_base==1 & vol_unit == "square feet", res.ft, hh_use)) storm.volume <- storm.volume %>% filter(value_from <= hh_use) %>% mutate(volCost = ifelse(value_to <= hh_use, round((value_to - value_from)*cost/vol_base,2), round((hh_use - value_from)*cost/vol_base, 2))) storm.volume <- storm.volume %>% mutate(category = ifelse(category=="outside", "outside", "inside")) storm.volume <- storm.volume %>% group_by(pwsid, service_area, service, category, bill_frequency) %>% summarize(volCost = sum(volCost, na.rm=TRUE), .groups="drop") %>% mutate(vol_cost = ifelse(bill_frequency == "quarterly", round(volCost/3,2), ifelse(bill_frequency == "bi-monthly", round(volCost/2, 2), ifelse(bill_frequency == "semi-annually", round(volCost/6, 2), ifelse(bill_frequency=="annually", round(volCost/12,2), volCost))))) %>% as.data.frame() storm.zone <- storm.rates %>% filter(volumetric=="zone") %>% mutate(category = ifelse(category=="outside", "outside", "inside")) %>% mutate(hh_use = ifelse(vol_unit=="ERU", 1, ifelse(vol_unit=="square feet", res.ft, ifelse(vol_unit=="percent impervious surface", percent.impervious, ifelse(vol_unit=="tax-based", tax.based, NA))))) storm.zone <- storm.zone %>% filter(value_from <= hh_use & value_to >= hh_use) %>% group_by(pwsid, service_area, service, category, bill_frequency) %>% summarise(zoneCost = mean(cost, na.rm=TRUE), .groups='drop') %>% mutate(zone_cost = ifelse(bill_frequency == "quarterly", round(zoneCost/3,2), ifelse(bill_frequency == "bi-monthly", round(zoneCost/2, 2), ifelse(bill_frequency == "semi-annually", round(zoneCost/6, 2), ifelse(bill_frequency=="annually", round(zoneCost/12,2), zoneCost))))) %>% as.data.frame() #combine into a single stormwater fee for all volumes df.storm <- merge(fixed.charge, storm.volume, by.x=c("pwsid","service_area","service","category"), by.y=c("pwsid","service_area","service","category"), all=TRUE) %>% select(-bill_frequency, -volCost) df.storm <- merge(df.storm, storm.zone, by.x=c("pwsid","service_area","service","category"), by.y=c("pwsid","service_area","service","category"), all=TRUE) %>% select(-bill_frequency, -zoneCost) df.storm[is.na(df.storm)] <- 0 df.storm <- df.storm %>% mutate(total_storm = base_cost + vol_cost + zone_cost) %>% select(-base_cost, -vol_cost, -zone_cost, -service) %>% group_by(pwsid, service_area, category) %>% summarize(total_storm = mean(total_storm, na.rm=TRUE), .groups="drop") #add last column to df.ws2 df.all <- merge(df.ws, df.storm, by.x=c("pwsid","service_area","category"), by.y=c("pwsid","service_area","category"), all.x=TRUE) df.all[is.na(df.all)] <- 0 df.all <- df.all %>% gather(var, val, -c("pwsid", "service_area", "category", "hh_use", "n_services")) %>% mutate(service = substr(var, nchar(var)-4, nchar(var)), var = substr(var, 0, nchar(var)-6)) %>% spread(var, val) #notice that the total does NOT include stormwater... will need to be added later... I think keep separate since such a hard one to find and so different summary(df.all) #Read in the full table. Remove those with pwsid in this list. Add new rates here. if(exists("update.list")){ orig.data <- read.csv(paste0(swd_results, "estimated_bills.csv")) '%!in%' <- function(x,y)!('%in%'(x,y)); #create function to remove bills that need to be updated orig.data <- orig.data %>% filter(pwsid %!in% df.all$pwsid) orig.data <- rbind(orig.data, df.all) write.csv(orig.data, paste0(swd_results, "estimated_bills.csv"), row.names=FALSE); #if you redid part of the file } else { write.csv(df.all, paste0(swd_results, "estimated_bills.csv"), row.names=FALSE); #if you redid the full file } rm(storm.rates, storm.volume, storm.zone, orig.data, rates, res.rates, service.only, fx, fx2, fx3, keep.pwsid, flat.surcharge, fixed.charge, df2, df.ws2, df.ws, df.storm, df.all, bk.up, commod.volume, commod.zone, df) rm(surcharge.volume, surcharge.zone, update.list, volume, ws.volume, zt2, zt3, ws.zone, zone, zt, i, j, gal.month, unique.pwsid) <file_sep>/README.md # Living Data and Code for the Water Affordability Dashboard operated by the Nicholas Institute for Environmental Policy Solutions Dashboard (desktop): https://nicholasinstitute.duke.edu/water-affordability/water-affordability-dashboard Don't Panic Labs assisted in creating mapbox tiles: https://dontpaniclabs.com/ Information about Project: https://nicholasinstitute.duke.edu/water-affordability/ Paper explaining methods: http://dx.doi.org/10.1002/aws2.1260 Current release version and doi: <a href="https://zenodo.org/badge/latestdoi/385713868"><img src="https://zenodo.org/badge/385713868.svg" alt="DOI"></a> ## Folders 1. **data** folder contains the raw service area boundaries, census, and rates data needed to create the dashboard. Many of the census files are pulled dynamically from the r script and are not provided here. The **rates_data** are provided in csv format for each state in the dashboard. The metadata and templates are provided as well for those who wish to create a database for a state not yet represented. The **census_time** folder contains two spreadsheets needed for the dashboard to display population and unemployment change over time. These data are not needed for the affordability analysis. 2. **rcode** folder contains all the r code needed to obtain the data, estimate bills, calculate affordability metrics, and create files for the dashboard. The rscripts are numbered in the order they must be run for the code to work. Please refer to the workflow document provided. 3. **results** folder contains the results from the rscript. We do not include those files here because they are large. However, we provide the simplified versions used to develop the dashboard in the www folder. We provide the folder since it is necessary for the rcode to run correctly. 4. **www** folder contains the data used to create the dashboard. The dashboard was built using html, css, and javascript. We also used mapbox tilesets and apis. Users will need to obtain their own API keys and create their own tilesets for use. ## Versions 1. v2021-1.0: Data that matches our <a href="http://dx.doi.org/10.1002/aws2.1260">paper</a>. Includes: CA, PA, NC, part of TX, and 9 utilities in OR. There are 1,800 utilities in the data. 2. v2021-2.0: Added remaining utilities in TX, NJ, and NM. There are 2,349 utilities in the data. 3. v2021-3.2: Added utilities in CT, KS, and WA. There are 3,038 utilities represented here. Methods were updated to allow for the inclusion of local minimum wages based on Version 3.0 and 3.1 are nearly identical but were removed due to syncing challenges with Zenodo. ## Terms of Use The copyrights of the Water Affordability Dashboard software and website are owned by Duke University. Developed by <NAME> and <NAME> at the Duke Nicholas Institute for Environmental Policy Solutions. Use of this software and dataset is allowed for noncommercial purposes only. The Water Affordability Dashboard project relies on four components: 1. The data/rates/ are shared under a Creative Commons CC-BY-NC-ND-4.0 license. License: https://creativecommons.org/licenses/by-nc-nd/4.0/ <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png" /></a> 2. The R algorithm /rcode/, shared under a GPLv3 license: License: https://www.gnu.org/licenses/gpl-3.0.en.html 3. The visualization website /www/, shared under the HTML5 Boilerplate license for noncommercial use only under the MIT license. For commercial purposes or inquiries regarding licensing, please contact the Digital Innovations department at the Duke Office for Translation & Commercialization (OTC) (https://olv.duke.edu/software/) at <EMAIL> with reference to ‘OTC File No. 7797’. Please note that this software is distributed AS IS, WITHOUT ANY WARRANTY; and without the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 4. Attribute the data, code, and dashboard as "Patterson, Lauren, <NAME>, <NAME>, and <NAME>. 2021. Water Affordability Data Repository. Nicholas Institute for Environmental Policy Solutions at Duke University. https://github.com/NIEPS-Water-Program/water-affordability" or "NIEPS Water Affordability Data" for short, and the url: https://github.com/NIEPS-Water-Program/water-affordability. You can cite all versions using the doi: 10.5281/zenodo.5156654. The doi for the current version is: <a href="https://zenodo.org/badge/latestdoi/385713868"><img src="https://zenodo.org/badge/385713868.svg" alt="DOI"></a> 5. Attribute the concept of this approach and our findings to: Patterson, LA and <NAME>. 2021 Measuring water affordability and the financial capability of utilities. AWWA Water Science (e1260). 25pp. doi: http://dx.doi.org/10.1002/aws2.1260. ## Workflow The process of creating the dashboard is detaield in the pdf: "Workflow for Creating Water Affordability Dashboard". Briefly, we manually collected rates data and used Rcran to access census and water service area boundaries. We combined the rates and census data with the service area boundaries to calculate affordability metrics in Rcran. The data are visualized using html and javascript. The process is illustrated in the figure below. ![process-overview](https://user-images.githubusercontent.com/15807329/126791513-2b65c0f9-956f-4aca-9dae-c2ae87e3cd6f.png) <file_sep>/www/scripts/selectFunctions.js /////////////////////////////////////////////////////////////////////////////////////////////////// // // AFFORDABILITY DROP DOWN MENUS /////////////// //// /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // This function fills county drop down menu when a state is selected /////////////////////////////////////////////////////////////////////////////////////////////////// function setStateThis(target) { //Change variable selectState = document.getElementById('setState').value; if (selectState === "ca") { map.fitBounds([-124.4, 32.5, -114.2, 42.1]); } if (selectState === "nc") { map.fitBounds([-85.2, 34, -74.2, 36.8]); } if (selectState === "pa") { map.fitBounds([-80.3, 39.2, -73.8, 42.8]); } //left, bottom, right, top if (selectState === "tx") { map.fitBounds([-106.6, 25.8, -93.5, 36.5]); } if (selectState === "or") { map.fitBounds([-124.6, 41.9, -116.5, 46.3]); } if (selectState === "none") { map.fitBounds([-124, 25, -74, 48]); } //selectSystem = "none"; //I just set to none here because of zoom drawMap(); return selectState; //, selectSystem}; } // end setStateThis function /////////////////////////////////////////////////////////////////////////////////////////////////// // This function filters by size of system /////////////////////////////////////////////////////////////////////////////////////////////////// function setSizeThis(target) { //Change variable selectSize = document.getElementById('setSize').value; drawMap(); return selectSize;//, selectSystem}; } // end setStateThis function /////////////////////////////////////////////////////////////////////////////////////////////////// // This function filters by owner type /////////////////////////////////////////////////////////////////////////////////////////////////// function setOwnerThis(target) { //Change variable selectOwner = document.getElementById('setOwner').value; drawMap(); return selectOwner;//, selectSystem}; } // end setStateThis function /////////////////////////////////////////////////////////////////////////////////////////////////// // This function filters volume /////////////////////////////////////////////////////////////////////////////////////////////////// function updateNVol(val) { selectVolume = Number(val); var ccfVol = Math.round(selectVolume / 7.48052); document.getElementById('volTitle').innerHTML = "<p style='font-size: 16px;'><b>Select Monthly Usage: " + "<span style='color: rgb(26,131,130); font-size: 13px;'>" + numberWithCommas(val) + " gallons<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;(~" + numberWithCommas(ccfVol) + " cubic feet)</span></b></p>"; //remove map layers //if (map.getLayer('select-utility-layer')) { map.removeLayer('select-utility-layer'); } var utilitiesLayer = map.getLayer('select-utility-layer'); console.log(utilitiesLayer); if (typeof utilitiesLayer !== 'undefined') { map.removeLayer('select-utility-layer'); console.log("removed select utility layer"); } map.removeLayer('utilities-layer'); map.removeSource('utilities'); //map source only changes when volume changes var select_url; if (selectVolume <= 4000){ select_url = 'mapbox://water-afford-project.a4n8hxrh'; } if (selectVolume >= 5000 & selectVolume <= 8000){ select_url = 'mapbox://water-afford-project.cberqmxq'; } if (selectVolume >= 9000 & selectVolume <= 12000){ select_url = 'mapbox://water-afford-project.5vk4to4o'; } if (selectVolume >= 13000 & selectVolume <= 16000){ select_url = 'mapbox://water-afford-project.8moavisi'; } console.log(select_url); // load map layer based on volume selected map.addSource('utilities', { type: 'vector', url: select_url }); drawMap(); //highlightUtility(selectSystem); return selectVolume; } /////////////////////////////////////////////////////////////////////////////////////////////////// // When a system is selected this function calls plots to load depending on tab /////////////////////////////////////////////////////////////////////////////////////////////////// function setSystemThis(target) { selectSystem = document.getElementById('setSystem').value; highlightUtility(selectSystem); return selectSystem; } function setMatrixLegendThis(target) { matrixLegend = document.getElementById('setMatrixLegend').value; createMatrix(selectSystem, matrixLegend); return matrixLegend; } <file_sep>/rcode/access1_census_data.R ####################################################################################################################################################### # # This script is run once a year to find and update data for the affordability dashboard. # Crated by <NAME>, 2021 # ######################################################################################################################################################## ################################################################################################################################################################### # # UPDATE CENSUS SPATIAL DATA. Will need municipal boundaries to create inside and outside service areas # #################################################################################################################################################################### ################################## # (1) MUNICIPALITIES / PLACES ################################# #call census api muni <- read_sf("https://opendata.arcgis.com/datasets/d8e6e822e6b44d80b4d3b5fe7538576d_0.geojson"); #reduce to states of interest muni <- muni %>% filter(STFIPS %in% state.fips) %>% select(NAME, CLASS, STFIPS, PLACEFIPS, SQMI, geometry) %>% rename(city_name = NAME) %>% st_transform(crs = 4326) muni <- muni %>% mutate(state = ifelse(STFIPS == "06", "ca", ifelse(STFIPS == "41", "or", ifelse(STFIPS == "35", "nm", ifelse(STFIPS == "20", "ks", ifelse(STFIPS == "53", "wa","hold")))))) #or systems are based on municipality muni.or <- muni %>% filter(state=="or") muni.nm <- muni %>% filter(state=="nm") muni.ks <- muni %>% filter(state=="ks") muni.wa <- muni %>% filter(state=="wa") geojson_write(muni.or, file = paste0(swd_data, folder.year, "\\or_systems.geojson")) #look to see if CA, PA, TX, or NC have their own municipal boundaries datasets. Prefer to use states when can. #CA ca.muni <- read_sf("https://opendata.arcgis.com/datasets/35487e8c86644229bffdb5b0a4164d85_0.geojson"); #dataset is gone ... only found TIGER files so use above #remove unincorporated areas #ca.muni <- ca.muni %>% filter(CITY != "Unincorporated") %>% st_transform(crs = 4326) %>% select(CITY, geometry) %>% rename(city_name = CITY) %>% mutate(state="ca") ca.muni <- muni %>% filter(state=="ca") mapview::mapview(ca.muni) #PA, the url works but geojson_read and sf_read do not work directly. Therefore need to temporarily download and read in tmp <- tempfile() curl_download("https://www.pasda.psu.edu/json/PaMunicipalities2020_01.geojson", tmp); pa.muni <- read_sf(tmp) %>% st_transform(crs = 4326) %>% select(MUNICIPAL1, geometry) %>% rename(city_name = MUNICIPAL1) %>% mutate(state="pa") mapview::mapview(pa.muni) #NC nc.muni <- read_sf("https://opendata.arcgis.com/datasets/ee098aeaf28d44138d63446fbdaac1ee_0.geojson") %>% st_transform(crs = 4326) %>% select(MunicipalBoundaryName, geometry) %>% rename(city_name = MunicipalBoundaryName) %>% mutate(state="nc") mapview::mapview(nc.muni) #TX tx.muni <- read_sf("https://opendata.arcgis.com/datasets/09cd5b6811c54857bd3856b5549e34f0_0.geojson") %>% st_transform(crs = 4326) %>% select(CITY_NM, geometry) %>% rename(city_name = CITY_NM) %>% mutate(state="tx") mapview::mapview(tx.muni) #NJ nj.muni <- read_sf("https://opendata.arcgis.com/datasets/3d5d1db8a1b34b418c331f4ce1fd0fef_2.geojson") %>% st_transform(crs = 4326) %>% select(NAME, geometry) %>% rename(city_name = NAME) %>% mutate(state="nj") mapview::mapview(nj.muni) #CT - https://ct-deep-gis-open-data-website-ctdeep.hub.arcgis.com/datasets/CTDEEP::town-polygon/about ct.muni <- read_sf("https://opendata.arcgis.com/datasets/df1f6d681b7e41dca8bdd03fc9ae0dd6_1.geojson") %>% st_transform(crs = 4326) %>% select(TOWN, geometry) %>% rename(city_name = TOWN) %>% mutate(state="ct") mapview::mapview(ct.muni) #KS - did not see anything recent #WA - provide cities... not towns, ect. so using municipal boundaries for now #bind state munis together and save into affordability data folder muni <- muni %>% filter(state != "hold" ) %>% select(city_name, geometry, state) #only keep those states where another spatial file for municipal boundaries was not found muni <- rbind(muni, pa.muni, nc.muni, tx.muni, nj.muni, ct.muni); table(muni$state) mapview::mapview(muni) all.muni <- muni %>% ms_simplify(keep=0.5, keep_shapes=TRUE); #simplify shapefiles a little (helps st_intersetion to work better) geojson_write(all.muni, file = paste0(swd_data, "muni.geojson")) #chck to find a good balance of simplifying polygons... 0.08 for munis is pretty good... miss some tiny pokey parts. I think more simplified for dashboard, but 0.5 start to lose too much. leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = all.muni %>% filter(state=="nj"), fillOpacity= 0.6, fillColor = "gray", color="black", weight=5) %>% addPolygons(data = muni %>% filter(state=="nj"), fillOpacity= 0.3, fillColor = "white", color="red", weight=1) ################################## # (2) COUNTIES & STATES ################################# county <- get_acs(geography = "county", variables = "B01001_001E", state = state.fips, year = selected.year, geometry = TRUE) %>% st_transform(crs = 4326); #pulls county variable #pull out state variables county <- county %>% mutate(state_fips = substr(GEOID,0,2)) %>% select(GEOID, NAME, state_fips, geometry) #create name - remove anything before "County"... or before "," county <- county %>% mutate(name = gsub("(.*),.*", "\\1", NAME)) %>% mutate(name = substr(name,0,(nchar(name)-7))) county <- merge(county, state.df, by.x="state_fips", by.y="state.fips") %>% select(-NAME, -state_fips) %>% rename(state = state.list) table(county$state) #county <- county %>% ms_simplify(keep=0.45, keep_shapes=TRUE) geojson_write(county, file = paste0(swd_data, "county.geojson")) #check to find a good balance of simplifying polygons leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = county, fillOpacity= 0.6, fillColor = "gray", color="black", weight=3) state <- get_acs(geography = "state", variables = "B01001_001E", year = selected.year, geometry=TRUE) %>% st_transform(crs= 4326) state <- state %>% select(GEOID, NAME, geometry) %>% rename(geoid = GEOID, name = NAME) state <- state %>% mutate(data = ifelse(geoid %in% state.fips, "yes", "no")) %>% mutate(data = ifelse(name %in% c("Oregon"), "muni", data)) table(state$data) geojson_write(state, file = paste0(swd_data, "state.geojson")) ################################## # (3) CENSUS TRACTS ################################# #grab data for census tracts - can go back to 2010 with acs - only do one variable with geometry or it creates a massive shapefile fips = unique(substr(county$GEOID,3,5)); #list of unique county fips codes that we want census tract and block group data for tract.sf <- get_acs(geography = "tract", variables = "B19080_001E", state = state.fips, county = fips, year = selected.year, geometry = TRUE); #set geometry as true to get spatial file for intersecting later bk.up <- tract.sf; tract.sf <- tract.sf %>% select(GEOID, geometry) %>% mutate(state_fips = substr(GEOID,0,2)) tract.sf <- merge(tract.sf, state.df, by.x="state_fips", by.y="state.fips") tract.sf <- tract.sf %>% select(-state_fips) %>% rename(state = state.list) #tract.sf <- tract.sf %>% ms_simplify(keep=0.45, keep_shapes=TRUE); #don't simplify right now - keep full size for analysis. Simplify for dashboard. geojson_write(tract.sf, file = paste0(swd_data, "tract_", selected.year,".geojson")) ################################## # (4) CENSUS BLOCK GROUPS ################################# #grab data for census block groups - super slow to do all at once. Do one at a time i=1; bkgroup.sf <- get_acs(geography = "block group", variables = "B19080_001E", state = state.fips[i], year = selected.year, geometry = TRUE); #set geometry as true to get spatial file for intersecting later for (i in 2:length(state.fips)){ bk.up <- get_acs(geography = "block group", variables = "B19080_001E", state = state.fips[i], year = selected.year, geometry = TRUE); #set geometry as true to get spatial file for intersecting later bkgroup.sf <- rbind(bkgroup.sf, bk.up); print(state.fips[i]); } bk.up <- bkgroup.sf; bkgroup.sf <- bkgroup.sf %>% select(GEOID, geometry) %>% mutate(state_fips = substr(GEOID,0,2)) bkgroup.sf <- merge(bkgroup.sf, state.df, by.x="state_fips", by.y="state.fips") %>% select(-state_fips) %>% rename(state = state.list) geojson_write(bkgroup.sf, file = paste0(swd_data,"block_groups_",selected.year,".geojson")) ############################################################################################################################################################################################################### # # (5) UPDATE CENSUS TIME SERIES DATA NEEDED FOR ANALYSIS # ############################################################################################################################################################################################################### ####################################################### # TRACT CENSUS DATA FOR AFFORDABILITY ANALYSIS ######################################################## vars <- c('B19080_001E','B19013_001E',"B01001_001E","B08201_001E") #grab data for census tracts - can go back to 2010 with acs census.tract <- get_acs(geography = "tract", variables = vars, state = state.fips, county = fips, year = selected.year, geometry = FALSE) foo <- get_acs(geography = "tract", variables = c("S0101_C01_001E", "S1701_C01_042E"), state= state.fips, county=fips, year = selected.year, geometry = FALSE) census.tract <- rbind(census.tract, foo) write.csv(census.tract, paste0(swd_data, "census_time\\census_tract_",selected.year,".csv"), row.names=FALSE) ######################################################### # ACCESS BLOCK GROUP DATA FOR AFFORDABILITY ANALYSIS ######################################################### i = 1; block.data <- get_acs(geography = "block group", variables=c("B01001_001E","B19001_001E", "B19001_002E", "B19001_003E", "B19001_004E", "B19001_005E", "B19001_006E", "B19001_007E", "B19001_008E", "B19001_009E", "B19001_010E", "B19001_011E", "B19001_012E", "B19001_013E", "B19001_014E", "B19001_015E", "B19001_016E", "B19001_017E", "B19013_001E"), state=state.fips[i], year=selected.year, geometry = FALSE) for (i in 2:length(state.fips)){ bk.up <- get_acs(geography = "block group", variables=c("B01001_001E","B19001_001E", "B19001_002E", "B19001_003E", "B19001_004E", "B19001_005E", "B19001_006E", "B19001_007E", "B19001_008E", "B19001_009E", "B19001_010E", "B19001_011E", "B19001_012E", "B19001_013E", "B19001_014E", "B19001_015E", "B19001_016E", "B19001_017E", "B19013_001E"), state=state.fips[i], year=selected.year, geometry = FALSE) block.data <- rbind(block.data, bk.up) print(state.fips[i]); } write.csv(block.data, paste0(swd_data,"census_time\\block_group_",selected.year,".csv"), row.names=FALSE) ###################################################################################################################################################################### ## CENSUS TAB OF DASHBOARD ####################################################################################################################################################################### ######################################################## ## Population Change Over Time by Block Group ######################################################## #since block groups change over time - we pull from IPUMS Data... #IPUMS NHGIS... block group... time series... JUST PULL FROM CURRENT AND ADD TO IT pop.time <- read.csv(paste0(swd_data, "census_time/nhgis0033_ts_geog2010_blck_grp.csv")) #create GEOID pop.time <- pop.time %>% mutate(GEOID_state = ifelse(nchar(STATEA)==1, paste0("0",STATEA), STATEA)) %>% mutate(GEOID_county = ifelse(nchar(COUNTYA)==1, paste0("00",COUNTYA), ifelse(nchar(COUNTYA)==2, paste0("0", COUNTYA), COUNTYA))) %>% #county add zeros to front mutate(GEOID_tract = ifelse(nchar(TRACTA)==3, paste0("000",TRACTA), ifelse(nchar(TRACTA)==4, paste0("00",TRACTA), ifelse(nchar(TRACTA)==5, paste0("0",TRACTA), TRACTA)))) pop.time <- pop.time %>% mutate(GEOID = paste0(GEOID_state, GEOID_county, GEOID_tract, BLCK_GRPA)) %>% select(GISJOIN, GEOID, STATE, COUNTY, CL8AA1990, CL8AA2000, CL8AA2010) colnames(pop.time) <- c("GISJOIN", "GEOID", "state", "county", "pop1990", "pop2000", "pop2010") pop.time <- pop.time %>% mutate(pop1990 = round(pop1990,0), pop2000 = round(pop2000, 0)) %>% mutate(GISJOIN = as.character(GISJOIN)) #grab current 5 year summary from above and create variable to match their unique ID pop.now <- block.data %>% filter(variable=="B01001_001") %>% select(GEOID, estimate) %>% mutate(GEOID = ifelse(nchar(GEOID) == 11, paste0("0",GEOID), GEOID)) %>% rename(popNow = estimate) pop.time <- merge(pop.time, pop.now, by.x="GEOID", by.y="GEOID", all.y=TRUE) #write to file write.csv(pop.time, paste0(swd_data,"census_time\\bkgroup_pop_time.csv"), row.names=FALSE) ########################################################### # Population below 18, 18 - 65, and over 65 ########################################################### age.vars <- c("B06001_001E", "B06001_002E","B06001_003E","B06001_004E","B06001_005E","B06001_006E","B06001_007E","B06001_008E","B06001_009E","B06001_010E","B06001_011E","B06001_012E") #no data at block group scale... go to tracts age.pop <- get_acs(geography = "tract", variables = age.vars, state = state.fips, county = fips, year = selected.year, geometry = FALSE) #age.pop <- get_acs(geography = "block group", variables = age.vars, state = state.fips, year = selected.year, geometry = FALSE) head(age.pop) #rename variable age.pop <- age.pop %>% mutate(age = ifelse(variable=="B06001_001", "Total", ifelse(variable=="B06001_002", "Ages<5", ifelse(variable=="B06001_003", "Ages5-17", ifelse(variable=="B06001_004","Ages18-24", ifelse(variable=="B06001_005", "Ages25-34", ifelse(variable=="B06001_006", "Ages35-44", ifelse(variable=="B06001_007","Ages45-54", ifelse(variable=="B06001_008","Ages55-59", ifelse(variable=="B06001_009", "Ages60-61", ifelse(variable=="B06001_010", "Ages62-64", ifelse(variable=="B06001_011","Ages65-74", "Ages>75")))))))))))) #group by category age.pop <- age.pop %>% mutate(ageGroup = ifelse((age=="Ages<5" | age=="Ages5-17"), "under18", ifelse((age=="Ages18-24" | age=="Ages25-34"), "age18to34", ifelse((age=="Ages35-44" | age=="Ages45-54" | age=="Ages55-59"), "age35to59", ifelse((age=="Ages60-61" | age=="Ages62-64"), "age60to64", ifelse((age=="Ages65-74" | age=="Ages>75"), "over65", "total")))))) age.pop2 <- age.pop %>% group_by(GEOID, ageGroup) %>% summarize(population = sum(estimate, na.rm=TRUE), .groups="drop") #spread out age.pop2 <- age.pop2 %>% group_by(GEOID) %>% spread(ageGroup, population) %>% as.data.frame() #write to file write.csv(age.pop2, paste0(swd_data, "census_time\\tract_age.csv"), row.names=FALSE) ########################################################### # Racial Characterization ########################################################### race.vars <- c("B02001_001E", "B02001_002E", "B02001_003E", "B02001_004E", "B02001_005E", "B02001_006E", "B02001_007E", "B02001_008E" ); race.pop <- get_acs(geography = "tract", variables = race.vars, state = state.fips, county = fips, year = selected.year, geometry = FALSE) head(race.pop) #rename variable race.pop2 <- race.pop %>% mutate(race = ifelse(variable=="B02001_001", "Total", ifelse(variable=="B02001_002", "white", ifelse(variable=="B02001_003", "Black", ifelse(variable=="B02001_004", "Native", ifelse(variable=="B02001_005", "Asian", ifelse(variable=="B02001_006","Pacific Islander", ifelse(variable=="B02001_007", "Other", "Multiple Races")))))))) table(race.pop2$race) race.pop2 <- race.pop2 %>% mutate(raceGroup = ifelse(race=="Pacific Islander" | race=="Other" | race=="Multiple Races", "other", race)) race.pop2 <- race.pop2 %>% group_by(GEOID, raceGroup) %>% summarize(population = sum(estimate, na.rm=TRUE), .groups="drop") #spread out race.pop2 <- race.pop2 %>% group_by(GEOID) %>% spread(raceGroup, population) %>% as.data.frame() hispanic.vars <- c("B03001_001E", "B03001_002E", "B03001_003E"); #not at block group, only tract level. his.pop <- get_acs(geography = "tract", variables = hispanic.vars, state = state.fips, county = fips, year = selected.year, geometry = FALSE) %>% as.data.frame() #rename variable his.pop <- his.pop %>% mutate(hispanic = ifelse(variable=="B03001_001", "Total", ifelse(variable=="B03001_002", "NotHispanic", ifelse(variable=="B03001_003", "Hispanic", NA)))) table(his.pop$hispanic) #spread out his.pop2 <- his.pop %>% select(GEOID, hispanic, estimate) %>% group_by(GEOID) %>% spread(hispanic, estimate) %>% select(-Total) %>% as.data.frame() #merge to race and save out race.pop2 <- merge(race.pop2, his.pop2, by.x="GEOID", by.y="GEOID", all=TRUE) #write to file write.csv(race.pop2, paste0(swd_data, "census_time\\tract_race.csv"), row.names=FALSE) ############################################################## ## Income Characterizations ############################################################## hh.by.income <- block.data %>% filter(variable %in% c("B19001_001", "B19001_002", "B19001_003", "B19001_004", "B19001_005", "B19001_006", "B19001_007", "B19001_008", "B19001_009", "B19001_010", "B19001_011", "B19001_012", "B19001_013", "B19001_014", "B19001_015", "B19001_016", "B19001_017")) hh.income <- hh.by.income %>% select(GEOID, variable, estimate) %>% spread(variable, estimate) colnames(hh.income) <- c("GEOID", "totalhh", "hh10","hh15","hh20","hh25","hh30","hh35","hh40","hh45","hh50","hh60","hh75","hh100","hh125","hh150","hh200","hh200more") #calculate percent of homes and remove total households... group by $25 buckets to be consistent across hh.income$d0to24k <- round((hh.income$hh10 + hh.income$hh15 + hh.income$hh20 + hh.income$hh25))#/hh.income$totalhh*100,2) hh.income$d25to49k <- round((hh.income$hh30 + hh.income$hh35 + hh.income$hh40 + hh.income$hh45 + hh.income$hh50))#/hh.income$totalhh*100, 2) hh.income$d50to74k <- round((hh.income$hh60 + hh.income$hh75))#/hh.income$totalhh*100, 2) hh.income$d75to100k <- round(hh.income$hh100)#/hh.income$totalhh*100, 2) hh.income$d100to125k <- round(hh.income$hh125)#/hh.income$totalhh*100, 2) hh.income$d125to150k <- round(hh.income$hh150)#/hh.income$totalhh*100, 2) hh.income$d150kmore <- round((hh.income$hh200 + hh.income$hh200more))#/hh.income$totalhh*100, 2) #reduce dataset hh.income <- hh.income %>% select(GEOID, totalhh, d0to24k, d25to49k, d50to74k, d75to100k, d100to125k, d125to150k, d150kmore) #write to file write.csv(hh.income, paste0(swd_data, "census_time\\block_group_income.csv"), row.names=FALSE) ###################################################################################################################################################################### ## HH AGE CHARACTERISTICS ####################################################################################################################################################################### hh.age <- get_acs(geography = "block group", variables=c("B25034_001E","B25034_002E","B25034_003E","B25034_004E","B25034_005E","B25034_006E","B25034_007E", "B25034_008E", "B25034_009E", "B25034_010E", "B25034_011E"), state=state.fips, year=selected.year, geometry = FALSE) bk.up <- hh.age table(substr(hh.age$GEOID, 0,2), useNA="ifany") hh.age <- hh.age %>% select(GEOID, variable, estimate) %>% spread(variable, estimate) colnames(hh.age) <- c("GEOID", "totalhh", "built_2014later", "built_2010to2013", "built_2000to2009", "built_1990to1999", "built_1980to1989", "built_1970to1979", "built_1960to1969", "built_1950to1959", "built_1940to1949", "built_1939early") hh.age <- hh.age %>% mutate(built_2010later = built_2014later+built_2010to2013) %>% select(GEOID, totalhh, built_2010later, built_2000to2009, built_1990to1999, built_1980to1989, built_1970to1979, built_1960to1969, built_1950to1959, built_1940to1949, built_1939early) #save out full amount because will add over service area write.csv(hh.age, paste0(swd_data, "census_time\\bg_house_age.csv"), row.names=FALSE) <file_sep>/rcode/access2_utility_data.R ####################################################################################################################################################### # # # This script is run as needed to create inside/outside boundaries for analysis. It should be run whenever new rates data are added. # Created by <NAME> for the Affordability Dashboard in 2021 # # ######################################################################################################################################################## #read in municipal file to create inside and outside rate areas muni <- read_sf(paste0(swd_data, "muni.geojson")) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: CA # #################################################################################################################################################################### # California -- will need to find new api ca.sys <- read_sf("https://opendata.arcgis.com/datasets/fbba842bf134497c9d611ad506ec48cc_0.geojson"); ca.sys <- ca.sys %>% st_transform(crs = 4326) %>% rename(pwsid = WATER_SYSTEM_NUMBER, gis_name = WATER_SYSTEM_NAME) %>% mutate(state = "ca") %>% filter(STATE_CLASSIFICATION != "NON-TRANSIENT NON-COMMUNITY") %>% filter(STATE_CLASSIFICATION != "TRANSIENT NON-COMMUNITY") %>% select(pwsid, gis_name, POPULATION, SERVICE_CONNECTIONS) %>% rename(population = POPULATION, connections = SERVICE_CONNECTIONS) geojson_write(ca.sys, file = paste0(swd_data ,"ca_systems.geojson")) ################################################################################################################################################################### ## INSIDE AND OUTSIDE BOUNDARIES - ##################################################################################################################################################################### #Intersect the municipal boundaries with the state to create inside and outside #simplify a little to avoid a bunch of errors ca.rates <- read_excel(paste0(swd_data, "rates_data\\rates_ca.xlsx"), sheet="rateTable") %>% filter(other_class == "inside_outside") ca.rates <- ca.rates %>% filter(pwsid %in% ca.sys$pwsid); #only keep those that are in the shapefiel ca.muni <- muni %>% filter(state=="ca") #%>% ms_simplify(keep=0.5, keep_shapes=TRUE); simplified earlier to 0.5 in saved file ca.sys <- ca.sys %>% ms_simplify(keep=0.5, keep_shapes=TRUE) #fix any corrupt shapefiles if (FALSE %in% st_is_valid(ca.muni)) {ca.muni <- suppressWarnings(st_buffer(ca.muni[!is.na(st_is_valid(ca.muni)),], 0.0)); print("fixed")}#fix corrupt shapefiles if (FALSE %in% st_is_valid(ca.sys)) {ca.sys <- suppressWarnings(st_buffer(ca.sys[!is.na(st_is_valid(ca.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles #ca muni is to big to union with ca.sys... therefore will loop through and try to do that way. ca.pwsid <- unique(ca.rates$pwsid) #all.in.out <- ca.sys %>% filter(pwsid==ca.pwsid[1]) %>% mutate(category = "delete") %>% select(pwsid, gis_name, category, geometry) all.in.out <- ca.sys %>% filter(pwsid %notin% ca.pwsid) %>% mutate(category = "inside") %>% select(pwsid, gis_name, category, geometry) for (i in 1:length(ca.pwsid)){ st_erase = all.in.out %>% filter(category == "blank") ca.sel <- ca.sys %>% filter(pwsid==ca.pwsid[i]) intmunis <- st_intersection(ca.sel, ca.muni) if(dim(intmunis)[1] > 0){ intmunis$muniArea = st_area(intmunis$geometry) inside <- st_union(intmunis) %>% st_sf() st_erase = st_difference(ca.sel, inside) %>% mutate(category = "outside") %>% select(pwsid, gis_name, category, geometry) st_erase$area = st_area(st_erase$geometry) if(dim(st_erase)[1] > 0) { st_union <- inside %>% mutate(pwsid = ca.pwsid[i], gis_name = ca.sel$gis_name[1], category = "inside") %>% select(pwsid, gis_name, category, geometry) st_union$area = st_area(st_union$geometry) in.out = rbind(st_erase, st_union) %>% select(pwsid, gis_name, category, geometry) perOut = 100*(as.numeric(st_erase$area)/(as.numeric(st_erase$area) + as.numeric(st_union$area))) #if outside area is less than 1%, just make all insdie if(perOut <= 1){ in.out = ca.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } } } if(dim(st_erase)[1] == 0) { in.out = ca.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } if(dim(intmunis)[1] == 0){ in.out = ca.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } #rbind to a full database all.in.out <- rbind(all.in.out, in.out) print(i) } table(all.in.out$category) geojson_write(all.in.out, file = paste0(swd_data,"ca_in_out_systems.geojson")) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = all.in.out %>% filter(pwsid %in% ca.pwsid), fillOpacity= 0.6, fillColor = ifelse(subset(all.in.out, pwsid %in% ca.pwsid)$category=="inside", "blue", "red"), #make sure matches data color="blue", weight=1, popup=~paste0("pwsid: ", pwsid)) %>% addPolygons(data = muni %>% filter(state=="ca"), fillOpacity= 0.3, fillColor = "white", color="black", weight=3) rm(all.in.out, ca.sel, ca.sys, intmunis, st_erase, st_union, ca.muni, ca.rates, ca.pwsid, in.out, perOut) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: NC # #################################################################################################################################################################### nc.sys <- read_sf("https://aboutus.internetofwater.dev/geoserver/ows?service=WFS&version=1.0.0&request=GetFeature&typename=geonode%3Anc_statewide_CWS&outputFormat=json&srs=EPSG%3A2264&srsName=EPSG%3A2264") nc.sys <- nc.sys %>% st_transform(crs = 4326) %>% rename(pwsid = PWSID, gis_name = SystemName) %>% mutate(state = "nc") %>% mutate(pwsid = paste0("NC", str_remove_all(pwsid, "[-]"))) %>% select(pwsid, gis_name, geometry, state) nc.sys <- nc.sys %>% ms_simplify(keep=0.5, keep_shapes=TRUE); #file is huge if (FALSE %in% st_is_valid(nc.sys)) {nc.sys <- suppressWarnings(st_buffer(nc.sys[!is.na(st_is_valid(nc.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles nc.sys <- nc.sys %>% mutate(pwsid = ifelse(pwsid == "NC03_63_108", "NC0363108", pwsid)) geojson_write(nc.sys, file = paste0(swd_data, "nc_systems.geojson")) ################################################################################################################################################################### ## INSIDE AND OUTSIDE BOUNDARIES - ##################################################################################################################################################################### #Intersect the municipal boundaries with the state to create inside and outside #simplify a little to avoid a bunch of errors nc.muni <- muni %>% filter(state=="nc") #%>% ms_simplify(keep=0.5, keep_shapes=TRUE); simplified earlier to 0.5 in saved file nc.rates <- read_excel(paste0(swd_data, "\\rates_data\\rates_nc.xlsx"), sheet="rateTable") %>% mutate(adjustment = 1, state = "nc") %>% select(-notes) %>% filter(rate_type != "drought_surcharge" & rate_type != "drought_mandatory_surcharge" & rate_type != "drought_voluntary_surcharge" & rate_type != "conservation_surcharge") %>% mutate(pwsid = paste0("NC",str_remove_all(pwsid, "[-]"))) %>% filter(other_class=="inside_outside") %>% filter(pwsid != "NC0392010Wendell") %>% filter(pwsid != "NC0392010Zebulon") %>% filter(pwsid != "NC0276035Highway22") #Spruce pine is an empty shapefile #fix corrupt shapfiles nc.sys <- nc.sys %>% ms_simplify(keep=0.8, keep_shapes=TRUE); #file is still huge and super slow. gets bogged down on pwsid 127 if (FALSE %in% st_is_valid(nc.muni)) {nc.muni <- suppressWarnings(st_buffer(nc.muni[!is.na(st_is_valid(nc.muni)),], 0.0)); print("fixed")}#fix corrupt shapefiles #ca muni is to big to union with ca.sys... therefore will loop through and try to do that way. nc.rates <- nc.rates %>% filter(pwsid %in% nc.sys$pwsid); #only keep those that are in the shapefiel nc.pwsid <- unique(nc.rates$pwsid) `%notin%` = function(x,y) !(x %in% y); #function to get what is not in the list all.in.out <- nc.sys %>% filter(pwsid %notin% nc.pwsid) %>% mutate(category = "inside") %>% select(pwsid, gis_name, category, geometry) for (i in 312:length(nc.pwsid)){; #highpoint is very slow to run st_erase = all.in.out %>% filter(category == "blank") nc.sel <- nc.sys %>% filter(pwsid==nc.pwsid[i]) #nc.sel <- nc.sys %>% filter(pwsid==nc.pwsid[i]) %>% ms_simplify(keep=0.5, keep_shapes=TRUE); #use when errors emerge if(nc.sel$pwsid != "NC0241020") { intmunis <- st_intersection(nc.sel, nc.muni) %>% ms_simplify(keep = 0.9, keep_shapes=TRUE) if(dim(intmunis)[1] > 0){ intmunis$muniArea = st_area(intmunis$geometry) inside <- st_union(intmunis) %>% st_sf() st_erase = st_difference(nc.sel, inside) %>% mutate(category = "outside") %>% select(pwsid, gis_name, category, geometry) st_erase$area = st_area(st_erase$geometry) if(dim(st_erase)[1] > 0) { st_union <- inside %>% mutate(pwsid = nc.pwsid[i], gis_name = nc.sel$gis_name[1], category = "inside") %>% select(pwsid, gis_name, category, geometry) st_union$area = st_area(st_union$geometry) in.out = rbind(st_erase, st_union) %>% select(pwsid, gis_name, category, geometry) perOut = 100*(as.numeric(st_erase$area)/(as.numeric(st_erase$area) + as.numeric(st_union$area))) #if outside area is less than 1%, just make all insdie if(perOut <= 1){ in.out = nc.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } } } } #end if statement for High Point because breaks R if(dim(st_erase)[1] == 0) { in.out = nc.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } if(dim(intmunis)[1] == 0){ in.out = nc.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } #rbind to a full database all.in.out <- rbind(all.in.out, in.out) print(i) } table(all.in.out$category) all.in.out <- all.in.out %>% filter(category != "delete") geojson_write(all.in.out, file = paste0(swd_data, "nc_in_out_systems.geojson")) zt <- all.in.out %>% mutate(colorCategory = ifelse(category=="inside", "blue", "red")) %>% filter(pwsid %in% nc.pwsid) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = zt, fillOpacity= 0.5, fillColor = zt$colorCategory, #make sure matches data color="blue", weight=1, popup=~paste0("pwsid: ", pwsid))# %>% #addPolygons(data = muni %>% filter(state=="nc"), # fillOpacity= 0.3, fillColor = "white", color="black", weight=3) rm(all.in.out, nc.sel, nc.sys, intmunis, st_erase, st_union, nc.muni, nc.rates, nc.pwsid, in.out, perOut) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: TX # #################################################################################################################################################################### #THe shapefile has to be manually downloaded from here and unzipped: https://www3.twdb.texas.gov/apps/WaterServiceBoundaries tx.sys <- readOGR("C:\\Users\\lap19\\Downloads\\PWS_shapefile", "PWS_Export") tx.sys <- tx.sys %>% st_as_sf %>% st_transform(crs = 4326) %>% rename(pwsid = PWSId, gis_name = pwsName) %>% mutate(state = "tx") %>% select(pwsid, gis_name, geometry, state) if (FALSE %in% st_is_valid(tx.sys)) {tx.sys <- suppressWarnings(st_buffer(tx.sys[!is.na(st_is_valid(tx.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles geojson_write(tx.sys, file = paste0(swd_data, "tx_systems.geojson")) ################################################################################################################################################################### ## INSIDE AND OUTSIDE BOUNDARIES - ##################################################################################################################################################################### #Intersect the municipal boundaries with the state to create inside and outside #simplify a little to avoid a bunch of errors tx.muni <- muni %>% filter(state=="tx") #%>% ms_simplify(keep=0.5, keep_shapes=TRUE); simplified earlier to 0.5 in saved file tx.rates <- read_excel(paste0(swd_data, "rates_data//rates_tx.xlsx"), sheet="rateTable") %>% filter(other_class=="inside_outside") #fix corrupt shapfiles #New SF package is breaking this: tx.muni$geometry <- tx.muni$geometry %>% s2::s2_rebuild() %>% sf::st_as_sfc() sf::sf_use_s2(FALSE) if (FALSE %in% st_is_valid(tx.muni)) {tx.muni <- suppressWarnings(st_buffer(tx.muni[!is.na(st_is_valid(tx.muni)),], 0.0)); print("fixed")}#fix corrupt shapefiles #for (i in 1:dim(tx.muni)[1]){ # if(st_is_valid(tx.muni[i,])){ # tx.muni[i,] = st_make_valid(tx.muni[i,]) # print(paste0(i, ": ", st_is_valid(tx.muni[i,]))) # } # if(i %in% seq(0,2000,50)) # print(paste0(i, ": ", round(i/dim(tx.muni)[1]*100,2), " done")) #} tx.rates <- tx.rates %>% filter(pwsid %in% tx.sys$pwsid); #only keep those that are in the shapefiel tx.pwsid <- unique(tx.rates$pwsid) `%notin%` = function(x,y) !(x %in% y); #function to get what is not in the list all.in.out <- tx.sys %>% filter(pwsid %notin% tx.pwsid) %>% mutate(category = "inside") %>% select(pwsid, gis_name, category, geometry) for (i in 1:length(tx.pwsid)){ #for (i in 101:110){ st_erase = all.in.out %>% filter(category == "blank") tx.sel <- tx.sys %>% filter(pwsid==tx.pwsid[i]) intmunis <- st_intersection(tx.sel, tx.muni) if(dim(intmunis)[1] > 0){ intmunis$muniArea = st_area(intmunis$geometry) inside <- st_union(intmunis) %>% st_sf() st_erase = st_difference(tx.sel, inside) %>% mutate(category = "outside") %>% select(pwsid, gis_name, category, geometry) st_erase$area = st_area(st_erase$geometry) st_erase <- st_cast(st_erase); #TX2270033 wants to be a GEOMETRYCOLLECTION if(dim(st_erase)[1] > 0) { st_union <- inside %>% mutate(pwsid = tx.pwsid[i], gis_name = tx.sel$gis_name[1], category = "inside") %>% select(pwsid, gis_name, category, geometry) st_union$area = st_area(st_union$geometry) in.out = rbind(st_erase, st_union) %>% select(pwsid, gis_name, category, geometry) perOut = 100*(as.numeric(st_erase$area)/(as.numeric(st_erase$area) + as.numeric(st_union$area))) #if outside area is less than 1%, just make all inside if(perOut <= 1){ in.out = tx.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } } } if(dim(st_erase)[1] == 0) { in.out = tx.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } if(dim(intmunis)[1] == 0){ in.out = tx.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } #rbind to a full database #print(summary(in.out)) all.in.out <- rbind(all.in.out, in.out) print(i) } table(all.in.out$category) summary(all.in.out) bk.up <- all.in.out geojson_write(all.in.out, file = paste0(swd_data, "tx_in_out_systems.geojson")) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = all.in.out %>% filter(pwsid %in% tx.pwsid), fillOpacity= 0.6, fillColor = ifelse(subset(all.in.out, pwsid %in% tx.pwsid)$category=="inside", "blue", "red"), #make sure matches data color="blue", weight=1, popup=~paste0("pwsid: ", pwsid)) rm(all.in.out, tx.sel, tx.sys, intmunis, st_erase, st_union, tx.muni, tx.rates, ca.pwsid, in.out, perOut, inside, muni) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: NM # #################################################################################################################################################################### ##nm.sys2 <- read_sf("https://catalog.newmexicowaterdata.org/dataset/5d069bbb-1bfe-4c83-bbf7-3582a42fce6e/resource/ccb9f5ce-aed4-4896-a2f1-aba39953e7bb/download/pws_nm.geojson") #points - had to manually download polygon file nm.sys <- readOGR("C:\\Users\\lap19\\Downloads","nm_pws") nm.sys <- spTransform(nm.sys, CRS("+init=epsg:4326")) %>% st_as_sf() nm.sys <- nm.sys %>% select(Wt_S_ID, PblcSyN) %>% rename(pwsid = Wt_S_ID, gis_name = PblcSyN) %>% mutate(state = "nm") %>% select(pwsid, gis_name, geometry, state) if (FALSE %in% st_is_valid(nm.sys)) {nm.sys <- suppressWarnings(st_buffer(nm.sys[!is.na(st_is_valid(nm.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles #nm has some additional letters in their pwsid and a couple that don't match EPA subset(nm.sys, nchar(pwsid) != 9) nm.sys <- nm.sys %>% mutate(pwsid = substr(pwsid, 1,9)) nm.sys <- nm.sys %>% mutate(pwsid = ifelse(gis_name == "SANTA FE SOUTH WATER COOP", "NM3500826", pwsid)) geojson_write(nm.sys, file = paste0(swd_data, "nm_systems.geojson")) ################################################################################################################################################################### ## INSIDE AND OUTSIDE BOUNDARIES - ##################################################################################################################################################################### #Intersect the municipal boundaries with the state to create inside and outside #simplify a little to avoid a bunch of errors nm.muni <- muni %>% filter(state=="nm") #%>% ms_simplify(keep=0.5, keep_shapes=TRUE); simplified earlier to 0.5 in saved file nm.rates <- read_excel(paste0(swd_data, "rates_data//rates_nm.xlsx"), sheet="rateTable") %>% filter(other_class=="inside_outside") #fix corrupt shapfiles #New SF package is breaking this: nm.muni$geometry <- nm.muni$geometry %>% s2::s2_rebuild() %>% sf::st_as_sfc() sf::sf_use_s2(FALSE) if (FALSE %in% st_is_valid(nm.muni)) {nm.muni <- suppressWarnings(st_buffer(nm.muni[!is.na(st_is_valid(nm.muni)),], 0.0)); print("fixed")}#fix corrupt shapefiles #set up loop nm.rates <- nm.rates %>% filter(pwsid %in% nm.sys$pwsid); #only keep those that are in the shapefiel nm.pwsid <- unique(nm.rates$pwsid) all.in.out <- nm.sys %>% filter(pwsid %notin% nm.pwsid) %>% mutate(category = "inside") %>% select(pwsid, gis_name, category, geometry) for (i in 1:length(nm.pwsid)){ #for (i in 101:110){ st_erase = all.in.out %>% filter(category == "blank") nm.sel <- nm.sys %>% filter(pwsid==nm.pwsid[i]) intmunis <- st_intersection(nm.sel, nm.muni) if(dim(intmunis)[1] > 0){ intmunis$muniArea = st_area(intmunis$geometry) inside <- st_union(intmunis) %>% st_sf() st_erase = st_difference(nm.sel, inside) %>% mutate(category = "outside") %>% select(pwsid, gis_name, category, geometry) st_erase$area = st_area(st_erase$geometry) st_erase <- st_cast(st_erase); #TX2270033 wants to be a GEOMETRYCOLLECTION if(dim(st_erase)[1] > 0) { st_union <- inside %>% mutate(pwsid = nm.pwsid[i], gis_name = nm.sel$gis_name[1], category = "inside") %>% select(pwsid, gis_name, category, geometry) st_union$area = st_area(st_union$geometry) in.out = rbind(st_erase, st_union) %>% select(pwsid, gis_name, category, geometry) perOut = 100*(as.numeric(st_erase$area)/(as.numeric(st_erase$area) + as.numeric(st_union$area))) #if outside area is less than 1%, just make all inside if(perOut <= 1){ in.out = nm.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } } } if(dim(st_erase)[1] == 0) { in.out = nm.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } if(dim(intmunis)[1] == 0){ in.out = nm.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } #rbind to a full database all.in.out <- rbind(all.in.out, in.out) print(i) } table(all.in.out$category) summary(all.in.out) geojson_write(all.in.out, file = paste0(swd_data, "nm_in_out_systems.geojson")) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = all.in.out %>% filter(pwsid %in% nm.pwsid), fillOpacity= 0.6, fillColor = ifelse(subset(all.in.out, pwsid %in% nm.pwsid)$category=="inside", "blue", "red"), #make sure matches data color="blue", weight=1, popup=~paste0("pwsid: ", pwsid)) rm(all.in.out, nm.sel, nm.sys, intmunis, st_erase, st_union, nm.muni, nm.rates, nm.pwsid, in.out, perOut, inside) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: NJ # #################################################################################################################################################################### nj.sys <- read_sf("https://opendata.arcgis.com/datasets/00e7ff046ddb4302abe7b49b2ddee07e_13.geojson") %>% st_transform(crs = 4326) nj.sys <- nj.sys %>% select(PWID, SYS_NAME, geometry) %>% rename(pwsid = PWID, gis_name = SYS_NAME) %>% mutate(state = "nj") %>% select(pwsid, gis_name, geometry, state) if (FALSE %in% st_is_valid(nj.sys)) {nj.sys <- suppressWarnings(st_buffer(nj.sys[!is.na(st_is_valid(nj.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles geojson_write(nj.sys, file = paste0(swd_data, "nj_systems.geojson")) #All of NJ is a municipality so no inside / outside rates ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: CT # #################################################################################################################################################################### #All of CT is a municipality so no inside/outside rates #CT systems - https://portal.ct.gov/DPH/Drinking-Water/DWS/Public-Water-Supply-Map ct.sys <- readOGR("C:\\Users\\lap19\\Downloads\\Buffered_Community_PWS_Service_Areas", "Buffered_Community_PWS_Service_Areas") %>% spTransform(ct.sys, CRS("+init=epsg:4326")) %>% st_as_sf() ct.sys <- read_sf("new_states/ct_systems.geojson") ct.sys <- ct.sys %>% select(pwsid, pws_name) %>% rename(gis_name = pws_name) if (FALSE %in% st_is_valid(ct.sys)) {ct.sys <- suppressWarnings(st_buffer(ct.sys[!is.na(st_is_valid(ct.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles #CT merged several pswid together aquarion <- c("CT1350011", "CT0150011", "CT1370011", "CT1240011", "CT1280021", "CT0900011", "CT0570011", "CT0350011", "CT0960011", "CT1180011", "CT0970011", "CT0180071", "CT0180141", "CT0189961", "CT1220011", "CT1000011", "CT1180021", "CT0980011", "CT0098011", "CT1390021", "CT1680011", "CT0910011", "CT0680011", "CT0740011", "CT0378011", "CT1180081", "CT0189791") #Greenwhich, Stanford, Ridgefield and New Canaan are all merged together ct.muni <- muni %>% filter(state=="CT") main.aq <- ct.sys %>% filter(pwsid=="CT0150011"); mapview::mapview(main.aq) int.sel <- st_intersection(main.aq, ct.muni); mapview::mapview(int.sel) green <- int.sel %>% filter(city_name=="Greenwich") %>% mutate(pwsid="CT0570011", gis_name="AQUARION WATER CO - GREENWICH") %>% select(pwsid, gis_name) %>% group_by(pwsid, gis_name) %>% summarize(n=n(), .groups="drop") %>% select(-n); mapview::mapview(green) stam <- int.sel %>% filter(city_name=="Stamford") %>% mutate(pwsid="CT1350011", gis_name="AQUARION WATER CO - STAMFORD") %>% select(pwsid, gis_name) %>% group_by(pwsid, gis_name) %>% summarize(n=n(), .groups="drop") %>% select(-n); mapview::mapview(stam) new.can <- int.sel %>% filter(city_name=="New Canaan") %>% mutate(pwsid="CT0900011", gis_name="AQURAION WATER CO - NEW CANAAN") %>% select(pwsid, gis_name) %>% group_by(pwsid, gis_name) %>% summarize(n=n(), .groups="drop") %>% select(-n); mapview::mapview(new.can) main <- int.sel %>% filter(city_name %notin% c("Greenwich", "Stamford", "New Canaan", "Ridgefield")) %>% select(pwsid, gis_name) %>% group_by(pwsid, gis_name) %>% summarize(n=n(), .groups="drop") %>% select(-n); mapview::mapview(main) ct.sys = ct.sys %>% filter(pwsid != "CT0150011") %>% group_by(pwsid, gis_name) %>% summarize(n=n(), .groups="drop") %>% select(-n) ct.sys <- rbind(ct.sys, main, green, stam, new.can) mapview::mapview(ct.sys) geojson_write(ct.sys, file=paste0(swd_data, "ct_systems.geojson")) rm(ct.sys) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: PA & OR --> NO INSIDE OR OUTSIDE # #################################################################################################################################################################### # Pennsyvlania -- will need to find new api tmp <- tempfile() curl_download("https://www.pasda.psu.edu/json/PublicWaterSupply2020_04.geojson", tmp); #mapview::mapview(pa.sys) pa.sys <- read_sf(tmp) pa.sys <- pa.sys %>% st_transform(crs = 4326) %>% rename(pwsid =PWS_ID, gis_name = NAME, owner = OWNERSHIP) %>% mutate(state = "pa", pwsid = paste0("PA", pwsid)) %>% mutate(category = "inside") %>% select(pwsid, gis_name, owner, category, geometry) geojson_write(pa.sys, file = paste0(swd_data, "pa_systems.geojson")) unlink(tmp) # Oregon or.sys <- read_sf(paste0(swd_data, folder.year, "\\or_systems.geojson")) #A spreadsheet must be created that links the utility pwsid to the GEOID of the city. This is a manual process or.rates <- read_excel(paste0(swd_data, folder.year, "\\rates_data\\rates_or.xlsx"), sheet="ratesMetadata") %>% select(GEOID, pwsid, service_area) %>% distinct() or.sys <- merge(or.sys, or.rates, by.x="GEOID", by.y="GEOID") %>% rename(gis_name = service_area) %>% select(pwsid, gis_name, geometry, state, GISJOIN, GEOID, city_name, STATEFP) geojson_write(or.sys, file = paste0(swd_data, "or_systems.geojson")) rm(tmp, pa.sys, or.sys, or.rates) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: KS # #################################################################################################################################################################### #ks.sys <- read_sf("https://services.kansasgis.org/arcgis15/rest/services/admin_boundaries/KS_RuralWaterDistricts/MapServer") ks.sys <- readOGR("C://Users//lap19//Documents//GIS//Utilities//KS","PWS_bnd_2021_0430") ks.sys <- spTransform(ks.sys, CRS("+init=epsg:4326")) %>% st_as_sf() ks.sys <- ks.sys %>% select(FED_ID, NAMEWCPSTA) %>% rename(pwsid = FED_ID, gis_name = NAMEWCPSTA) if (FALSE %in% st_is_valid(ks.sys)) {ks.sys <- suppressWarnings(st_buffer(ks.sys[!is.na(st_is_valid(ks.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles geojson_write(ks.sys, file=paste0(swd_data, "ks_systems.geojson")) #simplify a little to avoid a bunch of errors ks.muni <- muni %>% filter(state=="ks") #%>% ms_simplify(keep=0.5, keep_shapes=TRUE); simplified earlier to 0.5 in saved file ks.rates <- read_excel(paste0(swd_data, "rates_data//rates_ks.xlsx"), sheet="rateTable") %>% filter(other_class=="inside_outside") #fix corrupt shapfiles ks.muni$geometry <- ks.muni$geometry %>% s2::s2_rebuild() %>% sf::st_as_sfc() sf::sf_use_s2(FALSE) if (FALSE %in% st_is_valid(ks.muni)) {ks.muni <- suppressWarnings(st_buffer(ks.muni[!is.na(st_is_valid(ks.muni)),], 0.0)); print("fixed")}#fix corrupt shapefiles #set up loop ks.rates <- ks.rates %>% filter(pwsid %in% ks.sys$pwsid); #only keep those that are in the shapefiel ks.pwsid <- unique(ks.rates$pwsid) all.in.out <- ks.sys %>% filter(pwsid %notin% ks.pwsid) %>% mutate(category = "inside") %>% select(pwsid, gis_name, category, geometry) for (i in 1:length(ks.pwsid)){ #for (i in 101:110){ st_erase = all.in.out %>% filter(category == "blank") ks.sel <- ks.sys %>% filter(pwsid==ks.pwsid[i]) intmunis <- st_intersection(ks.sel, ks.muni) if(dim(intmunis)[1] > 0){ intmunis$muniArea = st_area(intmunis$geometry) inside <- st_union(intmunis) %>% st_sf() st_erase = st_difference(ks.sel, inside) %>% mutate(category = "outside") %>% select(pwsid, gis_name, category, geometry) st_erase$area = st_area(st_erase$geometry) st_erase <- st_cast(st_erase); if(dim(st_erase)[1] > 0) { st_union <- inside %>% mutate(pwsid = ks.pwsid[i], gis_name = ks.sel$gis_name[1], category = "inside") %>% select(pwsid, gis_name, category, geometry) st_union$area = st_area(st_union$geometry) in.out = rbind(st_erase, st_union) %>% select(pwsid, gis_name, category, geometry) perOut = 100*(as.numeric(st_erase$area)/(as.numeric(st_erase$area) + as.numeric(st_union$area))) #if outside area is less than 1%, just make all inside if(perOut <= 1){ in.out = ks.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } } } if(dim(st_erase)[1] == 0) { in.out = ks.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } if(dim(intmunis)[1] == 0){ in.out = ks.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } #rbind to a full database all.in.out <- rbind(all.in.out, in.out) print(i) } table(all.in.out$category) summary(all.in.out) geojson_write(all.in.out, file = paste0(swd_data, "ks_in_out_systems.geojson")) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = all.in.out %>% filter(pwsid %in% ks.pwsid), fillOpacity= 0.6, fillColor = ifelse(subset(all.in.out, pwsid %in% ks.pwsid)$category=="inside", "blue", "red"), #make sure matches data color="blue", weight=1, popup=~paste0("pwsid: ", pwsid)) rm(all.in.out, ks.sel, ks.sys, intmunis, st_erase, st_union, ks.muni, ks.rates, ks.pwsid, in.out, perOut, inside) ################################################################################################################################################################### # # (1) UPDATE UTILITY SPATIAL BOUNDARIES OR ADD NEW STATES: WA # #################################################################################################################################################################### #https://www.doh.wa.gov/DataandStatisticalReports/DataSystems/GeographicInformationSystem/DownloadableDataSets #https://fortress.wa.gov/doh/base/gis/ServiceAreas.zip # Download the shapefile. (note that I store it in a folder called DATA. You have to change that if needed.) download.file("https://fortress.wa.gov/doh/base/gis/ServiceAreas.zip" , destfile="C://Users//lap19//Downloads//ServiceAreas.zip") # You now have it in your current working directory, have a look! # Unzip this file. You can do it with R (as below), or clicking on the object you downloaded. wa.sys <- readOGR("C://Users//lap19//Documents//WaterUtilities//UtilityData//WA", "wa_systems") wa.sys <- spTransform(wa.sys, CRS("+init=epsg:4326")) %>% st_as_sf() wa.sys <- wa.sys %>% select(WS_Name, WS_ID, OwnerID, Total_Conn, WS_Status, WS_Type) #st_geometry(wa.sys) <- NULL; #write.csv(wa.sys, "new_states/wa_systems_match_all.csv") #washington does not have pwsid's. Manually linked rates pwsid to values in this shapefile and municipal shapefile. Then merged together. wa.muni <- muni %>% filter(state=="wa") wa.rates <- read_excel(paste0(swd_data, "rates_data\\rates_wa.xlsx"), sheet="PWSID_to_Shapefile") wa.sys2 <- merge(wa.sys, wa.rates, by.x="WS_ID", by.y="WS_ID") %>% select(pwsid, service_area, geometry) wa.sys3 <- merge(wa.muni, wa.rates, by.x="city_name", by.y="MUNI_Name") %>% select(pwsid, service_area, geometry) wa.sys <- rbind(wa.sys2, wa.sys3) #group duplicates wa.sys <- wa.sys %>% group_by(pwsid, service_area) %>% summarize(n=n()) #clark public utilities is duplicated with Clark Public - Utilities - Amboy wa.sys <- wa.sys %>% select(-n) %>% filter(pwsid != "WA5304625") %>% rename(gis_name = service_area) if (FALSE %in% st_is_valid(wa.sys)) {wa.sys <- suppressWarnings(st_buffer(wa.sys[!is.na(st_is_valid(wa.sys)),], 0.0)); print("fixed")}#fix corrupt shapefiles geojson_write(wa.sys, file=paste0(swd_data, "wa_systems.geojson")) #fix corrupt shapfiles wa.muni$geometry <- wa.muni$geometry %>% s2::s2_rebuild() %>% sf::st_as_sfc() if (FALSE %in% st_is_valid(wa.muni)) {wa.muni <- suppressWarnings(st_buffer(wa.muni[!is.na(st_is_valid(wa.muni)),], 0.0)); print("fixed")}#fix corrupt shapefiles wa.rates <- read_excel(paste0(swd_data, "rates_data//rates_wa.xlsx"), sheet="rateTable") %>% filter(other_class=="inside_outside") #set up loop wa.rates <- wa.rates %>% filter(pwsid %in% wa.sys$pwsid); #only keep those that are in the shapefiel wa.pwsid <- unique(wa.rates$pwsid) all.in.out <- wa.sys %>% filter(pwsid %notin% wa.pwsid) %>% mutate(category = "inside") %>% select(pwsid, gis_name, category, geometry) for (i in 1:length(wa.pwsid)){ #for (i in 101:110){ st_erase = all.in.out %>% filter(category == "blank") wa.sel <- wa.sys %>% filter(pwsid==wa.pwsid[i]) intmunis <- st_intersection(wa.sel, wa.muni) if(dim(intmunis)[1] > 0){ intmunis$muniArea = st_area(intmunis$geometry) inside <- st_union(intmunis) %>% st_sf() st_erase = st_difference(wa.sel, inside) %>% mutate(category = "outside") %>% select(pwsid, gis_name, category, geometry) st_erase$area = st_area(st_erase$geometry) st_erase <- st_cast(st_erase); if(dim(st_erase)[1] > 0) { st_union <- inside %>% mutate(pwsid = wa.pwsid[i], gis_name = wa.sel$gis_name[1], category = "inside") %>% select(pwsid, gis_name, category, geometry) st_union$area = st_area(st_union$geometry) in.out = rbind(st_erase, st_union) %>% select(pwsid, gis_name, category, geometry) perOut = 100*(as.numeric(st_erase$area)/(as.numeric(st_erase$area) + as.numeric(st_union$area))) #if outside area is less than 1%, just make all inside if(perOut <= 1){ in.out = wa.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } } } if(dim(st_erase)[1] == 0) { in.out = wa.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } if(dim(intmunis)[1] == 0){ in.out = wa.sel %>% mutate(category="inside") %>% select(pwsid, gis_name, category, geometry) } #rbind to a full database all.in.out <- rbind(all.in.out, in.out) print(i) } table(all.in.out$category) summary(all.in.out) st_geometry_type(all.in.out) #drop line geometry all.in.out <- all.in.out %>% filter(st_geometry_type(all.in.out) != "LINESTRING") geojson_write(all.in.out, file = paste0(swd_data, "wa_in_out_systems.geojson")) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = all.in.out %>% filter(pwsid %in% wa.pwsid), fillOpacity= 0.6, fillColor = ifelse(subset(all.in.out, pwsid %in% wa.pwsid)$category=="inside", "blue", "red"), #make sure matches data color="blue", weight=1, popup=~paste0("pwsid: ", pwsid)) rm(all.in.out, wa.sel, wa.sys, intmunis, st_erase, st_union, wa.muni, wa.rates, wa.pwsid, wa.sys2, wa.sys3, in.out, perOut, inside) <file_sep>/rcode/access3_bls_data.R ####################################################################################################################################################### # # # (c) Copyright Affordability Dashboard by <NAME>, 2021 # This script is run as needed to update data from the bureau of labor statistics # Recommended update frequency: monthly to bi-monthly # # ######################################################################################################################################################## ###################################################################################################################################################################### # # READ IN HISTORIC DATA # ###################################################################################################################################################################### bls.recent <- read.csv(paste0(swd_data, "\\census_time\\current_unemploy.csv")) %>% as.data.frame() ###################################################################################################################################################################### # # READ IN RECENT DATA # ###################################################################################################################################################################### temp = tempfile(); download.file("https://www.bls.gov/web/metro/laucntycur14.zip",temp, mode="wb") zt <- read_excel(unzip(temp, "laucntycur14.xlsx"), sheet="laucntycur14", skip = 6, col_names=FALSE) colnames(zt) <- colnames(bls.recent) # remove the provisional "p" on data in the year column zt <- zt %>% mutate(year = str_remove_all(year, " p")) %>% filter(is.na(stateFips)==FALSE) #remove missing data zt <- zt %>% filter(is.na(stateFips)==FALSE) #only add new data to bls.recent #check format of date check.form <- bls.recent$year[dim(bls.recent)[1]] if(is.na(as.numeric(substr(check.form,1,1))) == TRUE){ str_format="%b-%y-%d"; #sometimes format changes } else { str_format="%y-%b-%d"; #sometimes format changes } last.date <- as.Date(paste0(bls.recent$year[dim(bls.recent)[1]],"-01"), format=str_format); #sometimes format changes last.date check.form <- zt$year[dim(zt)[1]] if(is.na(as.numeric(substr(check.form,1,1))) == TRUE){ str_format="%b-%y-%d"; #sometimes format changes } else { str_format="%y-%b-%d"; #sometimes format changes } zt2 <- zt %>% mutate(format = str_format, date = as.Date(paste0(year,"-01"), format=str_format)) %>% filter(date > as.Date(last.date, format=str_format)) table(zt2$year) bls.recent <- rbind(bls.recent, zt2) #reformat a standard date bls.recent <- bls.recent %>% mutate(format = ifelse(is.na(as.numeric(substr(year,1,1)))==TRUE, "%b-%y-%d", "%y-%b-%d"), date=as.Date(paste0(year,"-01"), format)) bls.recent <- bls.recent %>% mutate(year = as.character(date, format="%y-%b")) #save file write.csv(bls.recent, paste0(swd_data, "\\census_time\\current_unemploy.csv"), row.names=FALSE) unlink(temp) rm(temp, zt, last.date, bls.recent, zt2) <file_sep>/rcode/use2_calculate_afford_metrics.R ############################################################################################################################################################################### # # Calculates affordability metrics at block group and utility scale - this creates one metric for the utility and block group (mean of bills if differ within service area) # Created by <NAME>, 2021 # ##################################################################################################################################################################################### ###################################################################################################################################################################### # # VARIABLES THAT NEED TO BE CHANGED OVER TIME # ###################################################################################################################################################################### #set up by state wages min.wage <- read_excel(paste0(swd_data, "rates_data\\rates_", state.list[1], ".xlsx"), sheet="ratesMetadata") for (i in 2:length(state.list)){ zt <- read_excel(paste0(swd_data, "rates_data\\rates_", state.list[i], ".xlsx"), sheet="ratesMetadata") if(state.list[i] == "or"){ zt <- zt %>% select(-GEOID) } if (state.list[i] == "nc"){ zt <- zt %>% mutate(pwsid = paste0("NC",str_remove_all(pwsid, "[-]"))) %>% filter(nchar(pwsid) == 9) %>% filter(pwsid != "NC Aqua NC") %>% filter(pwsid != "NCBayboro") } zt <- zt[,c(1:16)] min.wage <- rbind(min.wage, zt); rm(zt) } min.wage <- min.wage %>% select(pwsid, service_area, service_type, last_updated, min_wage, min_year) %>% group_by(pwsid, service_area) %>% filter(service_type == "water") %>% filter(last_updated == max(last_updated)) %>% select(-service_type, -last_updated) %>% distinct() table(substr(min.wage$pwsid,1,2)) # block intersection variables percent.area.threshold <- 0.1; #set very low to make sure block group seleted moe.threshold = 250; #For block group data we need to set high or much of it becomes NA ###################################################################################################################################################################### # # LOAD DATA # ###################################################################################################################################################################### #rates data by volume are calculated in "calculate_rates_by_usage_catogery.R res.rates <- read.csv(paste0(swd_results, "estimated_bills.csv")) %>% mutate(state=tolower(substr(pwsid,0,2))) ############## # Load Spatial Data ############## #load tract data ----------------------------------------------------------------------------------------------------------------------------------------------------- tract.data <- read.csv(paste0(swd_data, "census_time\\census_tract_",selected.year,".csv"), colClasses=c("GEOID" = "character")) tract.data <- tract.data %>% mutate(state_fips = substr(GEOID,0,2)) tract.data <- merge(tract.data, state.df, by.x="state_fips", by.y="state.fips") %>% select(-state_fips) %>% rename(state = state.list) table(tract.data$state, useNA = "ifany") #reshape file tract.data <- tract.data %>% mutate(perError = ifelse(estimate==0, 0, round(moe/estimate*100,2))) %>% select(GEOID, state, variable, estimate) %>% spread(variable, estimate) %>% #reshape the dataset mutate(PPI = round(S1701_C01_042/S0101_C01_001*100,2)) #calculate PPI indicator colnames(tract.data) <- c("tractID", "state", "tractPop","tractHH","tractMedIncome","tractQ20","nhhSurvey200", "nhhPov200","PPI") table(tract.data$state, useNA="ifany") #load census block data --------------------------------------------------------------------------------------------------------------------------------- block.group.all <- read.csv(paste0(swd_data, "census_time\\block_group_",selected.year,".csv"), colClasses=c("GEOID" = "character")) block.group.all <- block.group.all %>% mutate(state_fips = substr(GEOID,0,2)) block.group.all <- merge(block.group.all, state.df, by.x="state_fips", by.y="state.fips") %>% select(-state_fips) %>% rename(state = state.list) table(block.group.all$state, useNA="ifany") #load shapefile data ------------------------------------------------------------------------------------------------------------------------------------------------------------------ #NOTE WE WANT TO LOAD IN THE INSIDE AND OUTSIDE VERSIONS WHERE POSSIBLE ca.systems <- read_sf(paste0(swd_data, "ca_in_out_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(state="ca") nc.systems <- read_sf(paste0(swd_data, "nc_in_out_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(state="nc") pa.systems <- read_sf(paste0(swd_data, "pa_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% select(-owner) %>% mutate(state="pa") tx.systems <- read_sf(paste0(swd_data, "tx_in_out_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(state="tx") or.systems <- read_sf(paste0(swd_data, "or_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(category = "inside", state="or") %>% select(pwsid, gis_name, category, geometry, systemarea, state) nm.systems <- read_sf(paste0(swd_data, "nm_in_out_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(state="nm") nj.systems <- read_sf(paste0(swd_data, "nj_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(category = "inside", state="nj") %>% select(pwsid, gis_name, category, geometry, systemarea, state); #not inside/outside because all municipal ct.systems <- read_sf(paste0(swd_data, "ct_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(category = "inside", state="ct") %>% select(pwsid, gis_name, category, geometry, systemarea, state); #not inside/outside because all municipal ks.systems <- read_sf(paste0(swd_data, "ks_in_out_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(state="ks") wa.systems <- read_sf(paste0(swd_data, "wa_in_out_systems.geojson")) %>% mutate(systemarea = st_area(geometry)) %>% mutate(state="wa") gis.systems <- rbind(ca.systems, nc.systems, pa.systems, tx.systems, or.systems, nm.systems, nj.systems, ct.systems, ks.systems, wa.systems) rm(ca.systems, nc.systems, pa.systems, tx.systems, or.systems, nm.systems, nj.systems, ct.systems, ks.systems, wa.systems) #load census block group shapefiles ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- bk.group <- read_sf(paste0(swd_data, "block_groups_", selected.year,".geojson")) %>% mutate(area = st_area(geometry)) if (FALSE %in% st_is_valid(bk.group)) {bk.group <- suppressWarnings(st_buffer(bk.group[!is.na(st_is_valid(bk.group)),], 0.0)); print("fixed")}#fix corrupt shapefiles for block group... takes awhile can try to skip ########################################################################################################################################################################## # # FUNCTIONS TO DO THINGS # ############################################################################################################################################################################ #######################################--------------------------------------------------------------------------------------------------------------------------------- # INTERSECTION FUNCTION #######################################--------------------------------------------------------------------------------------------------------------------------------- intersect_features <- function(system, census){ if (FALSE %in% st_is_valid(system)) {system <- suppressWarnings(st_buffer(system[!is.na(st_is_valid(system)),], 0.0)); print("fixed")}#fix corrupt shapefiles census.int <- st_intersection(system, census); census.int$newArea <- st_area(census.int$geometry) census.int$perArea <- as.numeric(round(census.int$newArea/census.int$area*100,2)) #Keep those covering more area than the percent threshold set up top if(max(census.int$perArea > percent.area.threshold)){ census.int <- subset(census.int, perArea >= percent.area.threshold); #remove areas with less than threshold coverage } return(census.int) } # ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ################################################################################################################################################ # # CALCULATE AFFORDABILITY METRICS AT SERVICE LEVEL # ################################################################################################################################################ #ESTIMATE BLOCK GROUP METRICS FOLLOWING RECOMMENDATIONS FROM AWWA 2019 REPORT #The population-weighted average LQI can be calculated by multiplying the ratio of the population for a given geographic area to the total geographic area by the LQI upper limit #for the geographic area before summing these products across geographies, or using a refined approach based on census track matching to respective utility service areas. service_area_method <- function(block.data){ #weight the population of each tract by the total population in the service area and weight the income ratio based on population weighting weight.block.data <- block.data %>% mutate(popArea = round(totalpop * (perArea/100),4)) %>% group_by(pwsid, service_area, hh_use) %>% mutate(totalPopArea = round(sum(popArea, na.rm=TRUE),2), popRatio = popArea/totalPopArea, HBIratio = HBI*popRatio, tradRatio = TRAD*popRatio) #have to group by hh_use or counts all foo <- weight.block.data %>% group_by(hh_use) %>% summarize(HBI = round(sum(HBIratio, na.rm=TRUE),2), TRAD = round(sum(tradRatio, na.rm=TRUE),2), .groups="drop") %>% mutate(hh_use = as.numeric(as.character(hh_use))) %>% arrange(hh_use) %>% as.data.frame(); foo #weighted PPI for service area weight.block.data <- weight.block.data %>% ungroup() %>% distinct() %>% mutate(totalPov = round(nhhSurvey200*popRatio,0), pov200 = round(nhhPov200*popRatio,0)) %>% summarize(pov200 = sum(pov200, na.rm=TRUE), totalPov = sum(totalPov, na.rm=TRUE)) %>% mutate(PPI_method1 = round(pov200/totalPov*100,2)) #bind these together to return single result service.area.results <- foo %>% mutate(pwsid = as.character(selected.pwsid), service_area = as.character(sel.cost$service_area[1])) %>% mutate(PPI = weight.block.data$PPI_method1) %>% select(pwsid, service_area, hh_use, HBI, TRAD, PPI) #LETS ALSO CALCULATE IDWS AND GET DISTRIBUTIONS READY #convert to percent area hh.per <- block.data %>% select(GEOID, hh10, hh15, hh20, hh25, hh30, hh35, hh40, hh45, hh50, hh60, hh75, hh100, hh125, hh150, hh200, hh200more, perArea, category, totalhh) %>% distinct() hh.per[,c(2:17)] <- round(hh.per[,c(2:17)]*(hh.per$perArea/100),2) #sum total number of hh in each bracket unique.category <- unique(hh.per$category) hh.total <- subset(hh.per, category==as.character(unique.category[1])) hh.total <- colSums(hh.total[,c(2:17)], na.rm=TRUE) %>% as.data.frame() %>% setNames(paste0("nhh_",as.character(unique.category[1]))) %>% rownames_to_column(var="names") if(length(unique.category) >=2 ){ for (u in 2:length(unique.category)){ zt.total <- subset(hh.per, category==as.character(unique.category[u])) zt.total <- colSums(zt.total[,c(2:17)], na.rm=TRUE) %>% as.data.frame() %>% setNames(paste0("nhh_",as.character(unique.category[u]))) %>% rownames_to_column(var="names") zt.total <- zt.total %>% select(-names) hh.total <- cbind(hh.total, zt.total) } } hh.total #create dataframe hh.quintile <- as.data.frame(matrix(nrow=0,ncol=4)); colnames(hh.quintile) <- c("category", "nhh", "inc20", "inc50") dist.entire <- NA; dist.inside <- NA; dist.outside <- NA; #generate random numbers within a range then combine into a single list for (u in 1:length(unique.category)){ hh.total$nhh <- ceiling(hh.total[,u+1]) hh10 <- sample(1:10000, subset(hh.total, names=="hh10")$nhh, replace=T); hh15 <- sample(10001:15000, subset(hh.total, names=="hh15")$nhh, replace=T); hh20 <- sample(15001:20000, subset(hh.total, names=="hh20")$nhh, replace=T); hh25 <- sample(20001:25000, subset(hh.total, names=="hh25")$nhh, replace=T); hh30 <- sample(25001:30000, subset(hh.total, names=="hh30")$nhh, replace=T); hh35 <- sample(30001:35000, subset(hh.total, names=="hh35")$nhh, replace=T); hh40 <- sample(35001:40000, subset(hh.total, names=="hh40")$nhh, replace=T); hh45 <- sample(40001:45000, subset(hh.total, names=="hh45")$nhh, replace=T); hh50 <- sample(45001:50000, subset(hh.total, names=="hh50")$nhh, replace=T); hh60 <- sample(50001:60000, subset(hh.total, names=="hh60")$nhh, replace=T); hh75 <- sample(60001:75000, subset(hh.total, names=="hh75")$nhh, replace=T); hh100 <- sample(75001:100000, subset(hh.total, names=="hh100")$nhh, replace=T); hh125 <- sample(100001:125000, subset(hh.total, names=="hh125")$nhh, replace=T); hh150 <- sample(125001:150000, subset(hh.total, names=="hh150")$nhh, replace=T); hh200 <- sample(150001:200000, subset(hh.total, names=="hh200")$nhh, replace=T); hh250 <- sample(200001:250000, subset(hh.total, names=="hh200more")$nhh, replace=T); dist <- c(hh10, hh15, hh20, hh25, hh30, hh35, hh40, hh45, hh50, hh60, hh75, hh100, hh125, hh150, hh200, hh250) #save out for cost_to_bill or call function here if(as.character(unique.category[u]=="inside")){ dist.inside = dist;} if(as.character(unique.category[u]=="outside")){ dist.outside = dist;} } #for some systems, the outside block dominates... here dist inside to dist outside #if (length(dist.inside) == 1 & length(dist.outside) > 1) { dist.inside = dist.outside; } #to return multiple times in a list newList <- list("results" = service.area.results, "dist.inside" = dist.inside, "dist.outside" = dist.outside) rm(weight.block.data, hh.per, hh.total, foo, hh.quintile, dist.inside, dist.outside, service.area.results) return(newList) } # END FUNCTION ## ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ################################################################################################################################################ # # VISUALIZE FUNCTIONS # ################################################################################################################################################ #PLOT MAP OF WATER SYSTEM SELECTED TRACTS, SELECTED BLOCK GROUPS########################################################################################################## plot_system_map <- function(){ leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = water.system, fillOpacity= 0.8, fillColor = water.system$categoryCol, color="black", weight=0) %>% addPolygons(data = selected.bk, fillOpacity= 0.0, fillColor = "red", color="darkred", weight=2, popup = paste0("GEOID: ", selected.bk$GEOID)) %>% addLegend("bottomright", colors = c("darkgray", "black", "darkred"), labels= c("Water System (entire or inside rates)", "Water System (outside rates)", "Selected Block Groups"), title= paste0("Selected Tracts for ", sel.cost$utility_name[1]), opacity = 1) } #end plot_system_map ################################################################################################################################################ #plot cost to bill ########################################################################################################## plot_cost_to_bill <- function(){ cost.zt <- cost_to_bill %>% select(category, hh_use, percent_income, percent_pays_more) %>% filter(hh_use == 4000) %>% spread(category, percent_pays_more) if(sum(cost.zt$outside)==0){ cost.zt <- cost.zt %>% select(-outside) } p <- plot_ly(cost.zt, x=~percent_income, y = ~inside, name="inside", type="scatter", mode="lines+markers", marker = list(size=4, color="#008b8b"), line = list(color = '#008b8b', width = 3)) %>% layout(margin = list(l = 50, r = 50, b = 50, t = 50, pad = 2), yaxis = list(title = 'Percent of households paying more than x% annual income', range=c(0,100)), title = paste0(sel.cost$utility_name[1], " Annual Bill"), xaxis=list(title="Percent of annual income spent on water/wastewater/stormwater"), shapes = list(list(type = "line", y0 = 0, y1 = 100, x0 = 4.5, x1 = 4.5, line = list(color = "black", dash = 'dash', width=0.75)), list(type = "line", y0 = 0, y1 = 100, x0 = 7, x1 = 7, line = list(color = "black", dash = 'dash', width=0.75)), list(type = "line", y0 = 0, y1 = 100, x0 = 10, x1 = 10, line = list(color = "black", dash = 'dash', width=0.75)), list(type = "line", y0 = 0, y1 = 100, x0 = 20, x1 = 20, line = list(color = "black", dash = 'dash', width=0.75)) ), annotations = list(list(xref = 'x', yref = 'y', x = 4.5, y = 98, xanchor = 'left', yanchor = 'middle', text = "TRAD Threshold", font = list(family = 'Arial', size = 14), showarrow = FALSE), list(xref = 'x', yref = 'y', x = 7.0, y = 95, xanchor = 'left', yanchor = 'middle', text = "HBI Moderate Threshold", font = list(family = 'Arial', size = 14), showarrow = FALSE), list(xref = 'x', yref = 'y', x = 10.0, y = 92, xanchor = 'left', yanchor = 'middle', text = "HBI High Threshold", font = list(family = 'Arial', size = 14), showarrow = FALSE) ), legend = list(x=0.80, y=0.95) ) if("outside" %in% colnames(cost.zt)){ p <- p %>% add_trace(cost.zt, y = ~outside, name="outside", type="scatter", mode="lines+markers", marker = list(size=4, color="darkred"), line = list(color = 'darkred', width = 3)) } return (p) } ################################################################################################################################################ #plot burden by tract ########################################################################################################## plot_burden_by_tract <- function(){ block.scores <- block.data %>% select(GEOID, category, hh_use, totalpop, totalhh, medianIncome, quintile20, hhsize, HBI, PPI, burden, TRAD) %>% filter(hh_use==4000); # Map Burden Matrix ------------------------------------------------------------------------------------------------------------------------------------------ block.map <- sp::merge(selected.bk[,c("GEOID", "geometry")], block.scores, by.x="GEOID", by.y="GEOID", all.x=TRUE) block.map <- block.map %>% mutate(burdenCol = ifelse(burden=="Low", "#3680cd", ifelse(burden=="Low-Moderate", "#36bdcd", ifelse(burden=="Moderate-High", "#cd8536", ifelse(burden=="High","#ea3119", ifelse(burden=="Very High", "#71261c", "white")))))) block.map$burdenCol <- ifelse(is.na(block.map$burden) ==TRUE, "white", block.map$burdenCol) ; table(block.map$burdenCol, useNA="ifany") #make outside colors less opaque block.map$opacityLevel <- ifelse(block.map$category == "outside", 0.3, 0.6) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = water.system, fillOpacity= 0.8, fillColor = water.system$categoryCol, color="black", weight=0) %>% addPolygons(data = block.map, fillOpacity= block.map$opacityLevel, fillColor = block.map$burdenCol, #make sure matches data color="black", weight=1, popup=~paste0("GEOID: ", GEOID, "<br>Rate Category: ", category, "<br>HBI: ", HBI, "<br>PPI: ", PPI, "<br>TRAD: ", TRAD, "<br>Burden: ", burden)) %>% addLegend("bottomright", colors = c("#3680cd","#36bdcd","#cd8536","#ea3119","#71261c","white"), labels= c("Low", "Low-Moderate", "Moderate-High", "High", "Very High", "Poor Data"), title = paste0("Affordability Burden: ", sel.cost$city_name[1]), opacity = 1) } #end plot_burden_by_tract() ################################################################################################################################################ ######################################################################################################################################################################################################### # # LOOP THROUGH ALL UTILITIES AND SAVE FILE # ######################################################################################################################################################################################################### #state <- var.state <- "nc"; #lower list to those with rates data and with shapefile combo <- res.rates %>% filter(state==state) %>% select(pwsid, service_area) %>% distinct() #gis.systems <- get(paste0(state,".systems")); #dynamically calls state data rates.pwsid <- merge(combo, gis.systems, by.x="pwsid", by.y="pwsid", all=FALSE); rates.pwsid <- rates.pwsid %>% select(pwsid, state) %>% distinct(); table(rates.pwsid$state) rates.pwsid <- unique(rates.pwsid) ########################################################################################################################### # # IF YOU ONLY WANT TO UPDATE A PORTION OF THE DATA.... SHORTEN THE LIST # ############################################################################################################################ ca.meta <- read_excel(paste0(swd_data, "rates_data\\rates_ca.xlsx"), sheet="rateTable") %>% mutate(state = "ca") or.meta <- read_excel(paste0(swd_data, "rates_data\\rates_or.xlsx"), sheet="rateTable") %>% mutate(state = "or") pa.meta <- read_excel(paste0(swd_data, "rates_data\\rates_pa.xlsx"), sheet="rateTable") %>% mutate(state = "pa") nc.meta <- read_excel(paste0(swd_data, "rates_data\\rates_nc.xlsx"), sheet="rateTable") %>% mutate(state = "nc") %>% mutate(pwsid = paste0("NC",str_remove_all(pwsid, "[-]"))) tx.meta <- read_excel(paste0(swd_data, "rates_data\\rates_tx.xlsx"), sheet="rateTable") %>% mutate(state = "tx") nm.meta <- read_excel(paste0(swd_data, "rates_data\\rates_nm.xlsx"), sheet="rateTable") %>% mutate(state = "nm") nj.meta <- read_excel(paste0(swd_data, "rates_data\\rates_nj.xlsx"), sheet="rateTable") %>% mutate(state = "nj") ct.meta <- read_excel(paste0(swd_data, "rates_data\\rates_ct.xlsx"), sheet="rateTable") %>% mutate(state = "ct") ks.meta <- read_excel(paste0(swd_data, "rates_data\\rates_ks.xlsx"), sheet="rateTable") %>% mutate(state = "ks") wa.meta <- read_excel(paste0(swd_data, "rates_data\\rates_wa.xlsx"), sheet="rateTable") %>% mutate(state = "wa") rates.meta <- rbind(or.meta, ca.meta, pa.meta, nc.meta, tx.meta, nm.meta, nj.meta, ct.meta, ks.meta, wa.meta) %>% filter(update_bill == "yes") %>% select(pwsid) %>% distinct() ; #filter is optional rates.pwsid <- rates.meta$pwsid update.list <- rates.pwsid rm(ca.meta, or.meta, pa.meta, nc.meta, tx.meta, nm.meta, nj.meta, ct.meta, ks.meta, wa.meta) ############################################################################################################################## #shapefile problems for the following nc: NC0161010 shapefile problem, rates.pwsid <- rates.pwsid[rates.pwsid != c("NC0161010")]; rates.pwsid <- rates.pwsid[rates.pwsid != c("CA3301428")]; rates.pwsid <- rates.pwsid[rates.pwsid != c("CA3010023")]; #city of Newport Beach has an empty geometry... still true June 2021 rates.pwsid <- unique(rates.pwsid) #set hbi levels for burden hbi_mod = 4.6; #4.6% is ~ 1 day of work. AWWA recommended 7%. EPA is considering lower. hbi_high = hbi_mod*2; #AWWA recommended 10% #set up data frames all.block.scores <- as.data.frame(matrix(nrow=0, ncol=14)); colnames(all.block.scores) <- c("GEOID","pwsid", "service_area", "hh_use", "totalpop", "totalhh","perArea", "hhsize", "medianIncome", "income20", "HBI","PPI","burden","TRAD") all.service.scores <- as.data.frame(matrix(nrow=0, ncol=11)); colnames(all.service.scores) = c("pwsid","service_area", "hh_use","HBI", "PPI","TRAD", "min_wage", "min_year", "LaborHrsMin","LaborHrsMax","burden") all.cost.to.bill <- as.data.frame(matrix(nrow=0, ncol=8)); colnames(all.cost.to.bill) <- c("pwsid", "service_area", "category", "hh_use","percent_income", "annual_cost", "annual_income", "percent_pays_more") for (i in 1:length(rates.pwsid)){ #for (i in 2801:3000){ #select utility selected.pwsid = as.character(rates.pwsid[i]); #get estimated bill sel.cost <- res.rates %>% filter(pwsid == as.character(selected.pwsid)) #Calculate an annual household bill - total bill (adds stormwater to water and wastewater (which is current total)) annual.hh.cost <- sel.cost %>% filter(service != "total") %>% group_by(pwsid, service_area, category, hh_use) %>% summarize(annual_cost = sum(total, na.rm=TRUE)*12, .groups="drop") #zt <- annual.hh.cost %>% filter(category=="inside") #plot_ly(zt, x= ~hh_use, y= ~annual_cost/12, name = "", type='scatter', mode = 'lines+markers', marker = list(size=4, color="rgb(0,0,0,0.8)"), line = list(color = 'black', width = 1)) %>% # layout(margin = list(l = 50, r = 50, b = 50, t = 50, pad = 2), yaxis = list(title = 'Monthly Bill ($)', range=c(0,400)), xaxis=list(title="Volume of Water (gallons)")) ######################################## #clip census data to selected pwsid --------------------------------------------------------------------------------------------------- water.system <- gis.systems %>% filter(pwsid==selected.pwsid) %>% mutate(categoryCol = ifelse(category=="outside", "black", "#5a5a5a")) #if no shapefile then skip. If no geometry then skip if (dim(water.system)[1] == 0){ print(paste0("No shapefile for ", selected.pwsid)); next } if(is.na(st_dimension(water.system))){ print(paste0("No geometry in shapefile for ", selected.pwsid)); next } #run intersection function- bk.int <- intersect_features(water.system, bk.group); #double counts if inside/outside - weight later #ensure geometry is multipolygon as.data.frame(table(st_geometry_type(bk.int))) if(st_geometry_type(bk.int) == "GEOMETRYCOLLECTION"){ bk.int <- st_collection_extract(bk.int, "POLYGON") } bk.int <- st_cast(bk.int, "MULTIPOLYGON") selected.bk <- bk.group[bk.group$GEOID %in% bk.int$GEOID,] #grabs anything that intersects #plot_system_map(); #for very small systems with inside and outside rates (but no muni) - set to inside rates if(dim(subset(bk.int, category == "inside"))[1] == 0 & dim(subset(bk.int, category == "outside"))[1] > 0){ bk.int <- bk.int %>% mutate(category = "inside"); } #grab census data and calculate metrics ---------------------------------------------------------------------------------------------------- block.data <- block.group.all %>% filter(GEOID %in% selected.bk$GEOID) block.data <- merge(block.data, bk.int[,c("GEOID","perArea")], by.x="GEOID", by.y="GEOID", all.x=TRUE) %>% mutate(geometry = NA) %>% distinct() #method recommends excluding those census tracts with a large margin of error block.data <- block.data %>% mutate(perError = ifelse(estimate==0, 0, round(moe/estimate*100,2))) %>% mutate(keepEst=ifelse(perError <= moe.threshold, estimate, NA)) #reshape dataframe block.data <- block.data %>% select(GEOID, variable, perArea, keepEst) %>% spread(variable, keepEst) %>% as.data.frame(); #reshape the dataset colnames(block.data) <- c("GEOID", "perArea", "totalpop", "totalhh", "hh10","hh15","hh20","hh25","hh30","hh35","hh40","hh45","hh50","hh60","hh75","hh100","hh125","hh150","hh200","hh200more","medianIncome") #calculate hh size - to look for odd blocks (universities, airports, prisons, etc) block.data <- block.data %>% mutate(hhsize = ifelse(totalhh>0, round(totalpop/totalhh,2), NA)) %>% mutate(hhsize = ifelse(hhsize > 8, NA, hhsize), tractID = substr(GEOID, 0, 11)) #For this method... lots of high percent error. Need to keep all to do calculate block.data$quintile20 = NA; block.data$quintile50 = NA; # block.data$nhhFed200 = NA #estimate 20th quintile for (j in 1:dim(block.data)[1]){ #generate random numbers within a range then combine into a single list hh.total <- block.data[j,]; #if estimate is NA - set to zero; hh.total[is.na(hh.total)] <- 0 hh10 <- sample(1:10000, hh.total$hh10, replace=T); hh15 <- sample(10001:15000, hh.total$hh15, replace=T); hh20 <- sample(15001:20000, hh.total$hh20, replace=T); hh25 <- sample(20001:25000, hh.total$hh25, replace=T); hh30 <- sample(25001:30000, hh.total$hh30, replace=T); hh35 <- sample(30001:35000, hh.total$hh35, replace=T); hh40 <- sample(35001:40000, hh.total$hh40, replace=T); hh45 <- sample(40001:45000, hh.total$hh45, replace=T); hh50 <- sample(45001:50000, hh.total$hh50, replace=T); hh60 <- sample(50001:60000, hh.total$hh60, replace=T); hh75 <- sample(60001:75000, hh.total$hh75, replace=T); hh100 <- sample(75001:100000, hh.total$hh100, replace=T); hh125 <- sample(100001:125000, hh.total$hh125, replace=T); hh150 <- sample(125001:150000, hh.total$hh150, replace=T); hh200 <- sample(150001:200000, hh.total$hh200, replace=T); hh250 <- sample(200001:250000, hh.total$hh200more, replace=T); dist <- c(hh10, hh15, hh20, hh25, hh30, hh35, hh40, hh45, hh50, hh60, hh75, hh100, hh125, hh150, hh200, hh250) block.data$quintile20[j] <- round(as.numeric(quantile(dist, 0.20)),0); block.data$quintile50[j] <- round(as.numeric(quantile(dist, 0.50)),0); } #merge in the PPI value from tract data block.data <- merge(block.data, tract.data[,c("tractID", "nhhSurvey200", "nhhPov200", "PPI")], by.x="tractID", by.y="tractID", all.x=TRUE) block.data <- block.data %>% mutate(medianIncome = ifelse(is.na(medianIncome)==TRUE, quintile50, medianIncome)) #head(block.data) #Calculate metrics #add service area calculation back in block.data <- merge(block.data, bk.int[,c("GEOID","category","perArea")], by.x=c("GEOID","perArea"), by.y=c("GEOID","perArea"), all.x=TRUE) all.cost <- annual.hh.cost %>% mutate(hh_use = paste0("vol_", hh_use)) %>% pivot_wider(names_from = hh_use, values_from = annual_cost) block.data <- merge(block.data, all.cost, by.x=c("category"), by.y=c("category"), all.x=TRUE) #reshape back to long block.data <- block.data %>% pivot_longer(cols = starts_with("vol"), names_to = "hh_use", names_prefix = "vol", values_to = "annual_cost", values_drop_na = FALSE) %>% mutate(hh_use = substr(hh_use, 2, nchar(hh_use))) #calculate metrics block.data <- block.data %>% mutate(HBI = ifelse(is.na(hhsize)==TRUE, NA, round(annual_cost/quintile20*100,2)), TRAD = ifelse(is.na(hhsize)==TRUE, NA, round(annual_cost/medianIncome*100,2))) %>% #Traditional has lots of missing values for median mutate(burden = ifelse(PPI >= 35 & HBI >= hbi_high, "Very High", ifelse(PPI >=35 & HBI < hbi_high & HBI >= hbi_mod, "High", ifelse(PPI >= 35 & HBI < hbi_mod, "Moderate-High", ifelse(PPI >= 20 & PPI < 35 & HBI >= hbi_high, "High", ifelse(PPI >=20 & PPI < 35 & HBI >= hbi_mod & HBI < hbi_high, "Moderate-High", ifelse(PPI >=20 & PPI < 35 & HBI < hbi_mod, "Low-Moderate", ifelse(PPI < 20 & HBI >= hbi_high, "Moderate-High", ifelse(PPI < 20 & HBI >= hbi_mod & HBI < hbi_high, "Low-Moderate", ifelse(PPI < 20 & HBI < hbi_mod, "Low", "Unknown")))))))))) %>% mutate(burden = ifelse(is.na(burden)==TRUE, "unknown", burden)) #table(block.data$hh_use, block.data$burden, useNA="ifany") # plot_burden_by_tract(); ################################################################################################################################################ #Calculate service area metrics - call functions list.results <- service_area_method(block.data); service.area.results <- list.results$results; summary(service.area.results) dist.inside <- list.results$dist.inside; dist.outside <- list.results$dist.outside rm(list.results) #calculate labor hrs state.var <- tolower(substr(service.area.results$pwsid[1],0,2)) min.df <- min.wage %>% filter(pwsid==selected.pwsid) %>% group_by(pwsid, service_area) %>% summarize(min_wage = mean(min_wage, na.rm=TRUE), min_year = mean(min_year, na.rm=TRUE), .groups="drop") service.area.results <- service.area.results %>% mutate(min_wage = min.df$min_wage, min_year = min.df$min_year) wage.cost <- annual.hh.cost %>% spread(category, annual_cost) %>% select(hh_use, inside, outside) %>% mutate(outside = ifelse(outside==0, inside, outside)) %>% mutate(cheap = ifelse(inside <= outside, inside, outside), expense = ifelse(inside <= outside, outside, inside)) %>% select(hh_use, cheap, expense) service.area.results <- merge(service.area.results, wage.cost, by.x="hh_use", by.y="hh_use", all.x=TRUE) service.area.results <- service.area.results %>% mutate(LaborHrsMin = round(cheap/12/min_wage,2), LaborHrsMax = round(expense/12/min_wage,2)) %>% select(-cheap, -expense,) #calculate the cost to bill---------------------------------------------------------------------------------------------------------------------------------------------------------- rep.per.cost <- length(unique(annual.hh.cost$hh_use))*length(unique(annual.hh.cost$category)) cost_to_bill <- bind_rows(replicate(21, annual.hh.cost, simplify = FALSE)) cost_to_bill <- cost_to_bill %>% mutate(percent_income = c(rep(0,rep.per.cost), rep(1,rep.per.cost), rep(2, rep.per.cost), rep(3, rep.per.cost), rep(4, rep.per.cost), rep(5, rep.per.cost), rep(6, rep.per.cost), rep(7, rep.per.cost), rep(8, rep.per.cost), rep(9, rep.per.cost), rep(10, rep.per.cost), rep(11, rep.per.cost), rep(12, rep.per.cost), rep(13, rep.per.cost), rep(14, rep.per.cost), rep(15, rep.per.cost), rep(16, rep.per.cost), rep(17, rep.per.cost), rep(18, rep.per.cost), rep(19, rep.per.cost), rep(20, rep.per.cost))) cost_to_bill <- cost_to_bill %>% mutate(annual_income = round(annual_cost/(percent_income/100),0)) %>% mutate(annual_income = ifelse(percent_income==0, annual_cost/0.001, annual_income), percent_pays_more = NA); for (k in 1:dim(cost_to_bill)[1]){ foo.zt <- cost_to_bill[k,] #select correct dist if(as.character(foo.zt$category=="inside")){ foo = dist.inside; zt.length = length(dist.inside); } if(as.character(foo.zt$category=="outside")){ foo = dist.outside; zt.length = length(dist.outside); } zt <- foo %>% as.data.frame() %>% filter(. <= foo.zt$annual_income); cost_to_bill$percent_pays_more[k] <- round(dim(zt)[1]/zt.length*100,2); }#end category loop head(cost_to_bill) %>% as.data.frame(); # plot_cost_to_bill(); ############################################################################################################################################################################################################################################# # # #FILL DATA FRAMES TO SAVE OUT OF LOOP # ############################################################################################################################################################################################################################################# #Block Scores Table #Calculate a single score for each block #remove geometry #st_geometry(block.data) <- NULL block.data <- block.data %>% select(-geometry) block.scores <- block.data %>% mutate(popArea = round(totalpop * (perArea/100),2)) %>% group_by(GEOID, pwsid, service_area, hh_use) %>% mutate(totalPopArea = round(sum(popArea, na.rm=TRUE),0), popRatio = popArea/totalPopArea, HBIratio = HBI*popRatio, tradRatio = TRAD*popRatio) %>% ungroup() block.scores <- block.scores %>% group_by(pwsid, GEOID, service_area, hh_use, totalpop, totalhh, hhsize, PPI) %>% summarize(HBI = round(sum(HBIratio, na.rm=TRUE),2), TRAD = round(sum(tradRatio, na.rm=TRUE),2), perArea = sum(perArea, na.rm=TRUE), income20 = round(mean(quintile20, na.rm=TRUE),0), medianIncome = round(mean(medianIncome, na.rm=TRUE),0), .groups="drop") %>% mutate(hh_use = as.numeric(as.character(hh_use))) %>% arrange(hh_use) #reset NAs to zero if needed block.scores <- block.scores %>% mutate(HBI = ifelse(HBI==0, NA, HBI), PPI = ifelse(PPI==0, NA, PPI), TRAD = ifelse(TRAD==0, NA, TRAD), perArea = ifelse(perArea>100, 100, perArea)) block.scores <- block.scores %>% mutate(burden = ifelse(PPI >= 35 & HBI >= hbi_high, "Very High", ifelse(PPI >=35 & HBI < hbi_high & HBI >= hbi_mod, "High", ifelse(PPI >= 35 & HBI < hbi_mod, "Moderate-High", ifelse(PPI >= 20 & PPI < 35 & HBI >= hbi_high, "High", ifelse(PPI >=20 & PPI < 35 & HBI >= hbi_mod & HBI < hbi_high, "Moderate-High", ifelse(PPI >=20 & PPI < 35 & HBI < hbi_mod, "Low-Moderate", ifelse(PPI < 20 & HBI >= hbi_high, "Moderate-High", ifelse(PPI < 20 & HBI >= hbi_mod & HBI < hbi_high, "Low-Moderate", ifelse(PPI < 20 & HBI < hbi_mod, "Low", "Unknown")))))))))) block.scores <- block.scores %>% mutate(burden = ifelse(is.na(burden)==TRUE, "unknown", burden)) %>% select(GEOID, pwsid, service_area, hh_use, totalpop, totalhh, perArea, hhsize, medianIncome, income20, HBI, PPI, burden, TRAD) all.block.scores <- rbind(all.block.scores, block.scores) #Service Scores service.area.results <- service.area.results %>% arrange(as.numeric(as.character(hh_use))) %>% mutate(burden = ifelse(PPI >= 35 & HBI >= hbi_high, "Very High", ifelse(PPI >=35 & HBI < hbi_high & HBI >= hbi_mod, "High", ifelse(PPI >= 35 & HBI < hbi_mod, "Moderate-High", ifelse(PPI >= 20 & PPI < 35 & HBI >= hbi_high, "High", ifelse(PPI >=20 & PPI < 35 & HBI >= hbi_mod & HBI < hbi_high, "Moderate-High", ifelse(PPI >=20 & PPI < 35 & HBI < hbi_mod, "Low-Moderate", ifelse(PPI < 20 & HBI >= hbi_high, "Moderate-High", ifelse(PPI < 20 & HBI >= hbi_mod & HBI < hbi_high, "Low-Moderate", ifelse(PPI < 20 & HBI < hbi_mod, "Low", "Unknown")))))))))) %>% mutate(burden = ifelse(is.na(burden)==TRUE, "Unknown", burden)) all.service.scores <- rbind(all.service.scores, service.area.results) #cost to bill Scores all.cost.to.bill <- rbind(all.cost.to.bill, cost_to_bill) print(paste0(i, ": ", sel.cost$service_area[1], ", ", substr(sel.cost$pwsid[1],0,2))) } #end master loop bk.up1 <- all.service.scores; bk.up2 <- all.block.scores; bk.up3 <- all.cost.to.bill summary(all.service.scores); #summary(all.cost.to.bill); table(as.numeric(as.character(all.service.scores$hh_use)), all.service.scores$burden, useNA="ifany"); #NC2036024 Dallas NC ... suburb section? has a problem with rates or no rates data --> remove for now #all.service.scores %>% filter(pwsid=="NC2036024") all.service.scores <- all.service.scores %>% filter(pwsid != "NC2036024") all.block.scores <- all.block.scores %>% filter(pwsid != "NC2036024") #for block scores where incomes are NA - set HBI to NA and burden to NA summary(all.block.scores); all.block.scores <- all.block.scores %>% mutate(HBI = ifelse(is.infinite(HBI), NA, HBI), TRAD = ifelse(is.infinite(TRAD), NA, TRAD)) table(as.numeric(as.character(all.block.scores$hh_use)), all.block.scores$burden, useNA="ifany"); #check to make sure no duplicate block/pwsid combos... duplication was occuring in block groups where census did not provide a median income. Changed grouping above to address. xt <- all.block.scores %>% filter(hh_use==4000) xt <- xt %>% mutate(duplicate = duplicated(xt[,1:2])) xt %>% filter(duplicate==TRUE) #two utilities duplicating because of income_20 - almost identical answers... group_by and recalculate burden all.block.scores <- all.block.scores %>% group_by(GEOID, pwsid, service_area, hh_use, totalpop, totalhh, perArea, hhsize, medianIncome) %>% summarize(income20 = round(mean(income20, na.rm=TRUE),0), HBI = round(mean(HBI, na.rm=TRUE),2), PPI = mean(PPI), TRAD = round(mean(TRAD, na.rm=TRUE),2), .groups="drop") all.block.scores <- all.block.scores %>% mutate(burden = ifelse(PPI >= 35 & HBI >= hbi_high, "Very High", ifelse(PPI >=35 & HBI < hbi_high & HBI >= hbi_mod, "High", ifelse(PPI >= 35 & HBI < hbi_mod, "Moderate-High", ifelse(PPI >= 20 & PPI < 35 & HBI >= hbi_high, "High", ifelse(PPI >=20 & PPI < 35 & HBI >= hbi_mod & HBI < hbi_high, "Moderate-High", ifelse(PPI >=20 & PPI < 35 & HBI < hbi_mod, "Low-Moderate", ifelse(PPI < 20 & HBI >= hbi_high, "Moderate-High", ifelse(PPI < 20 & HBI >= hbi_mod & HBI < hbi_high, "Low-Moderate", ifelse(PPI < 20 & HBI < hbi_mod, "Low", "Unknown")))))))))) all.block.scores <- all.block.scores %>% mutate(burden = ifelse(is.na(burden)==TRUE, "unknown", burden)) %>% select(GEOID, pwsid, service_area, hh_use, totalpop, totalhh, perArea, hhsize, medianIncome, income20, HBI, PPI, burden, TRAD) #NOW IF WE WANT TO ONLY UPDATE OR ADD NEW FILES - DO THE FOLLOWING...##################################################################################################################################### #spread resrates data (do outside of loop) rates.table <- res.rates %>% mutate(variable_cost = vol_cost + zone_cost, surcharge_cost = vol_surcharge + zone_surcharge + fixed_surcharge) %>% filter(service != "total") %>% pivot_wider(id_cols = c("pwsid", "service_area", "category", "hh_use"), names_from = service, values_from = c("base_cost", "variable_cost", "surcharge_cost", "total")) rates.table <- rates.table %>% mutate(percent_fixed_sewer = round(base_cost_sewer/total_sewer*100,2), percent_fixed_water = round(base_cost_water/total_water*100,2), percent_variable_sewer = round(variable_cost_sewer/total_sewer*100,2), percent_variable_water = round(variable_cost_water/total_water*100,2), percent_surcharge_sewer = round(surcharge_cost_sewer/total_sewer*100, 2), percent_surcharge_water = round(surcharge_cost_water/total_water*100,2)) rates.table[is.na(rates.table)] <- 0; #set rates that are NA to zero #Read in the full table. Remove those with pwsid in this list. Add new rates here. if(exists("update.list")){ orig.scores <- read.csv(paste0(swd_results,"utility_service_scores_",selected.year,".csv")) %>% filter(pwsid %notin% rates.pwsid) orig.blocks <- read.csv(paste0(swd_results,"utility_block_scores_",selected.year,".csv")) %>% filter(pwsid %notin% rates.pwsid) orig.cost.bill <- read.csv(paste0(swd_results,"utility_idws.csv")) %>% filter(pwsid %notin% rates.pwsid) orig.scores <- rbind(orig.scores, all.service.scores) orig.blocks <- rbind(orig.blocks, all.block.scores) orig.cost.bill <- rbind(orig.cost.bill, all.cost.to.bill) rates.table <- rates.table %>% filter(pwsid %in% orig.scores$pwsid) write.csv(rates.table, paste0(swd_results, "utility_rates_table.csv"), row.names=FALSE) write.csv(orig.scores, paste0(swd_results,"utility_service_scores_",selected.year,".csv"), row.names=FALSE) write.csv(orig.blocks, paste0(swd_results,"utility_block_scores_", selected.year, ".csv"), row.names=FALSE) write.csv(orig.cost.bill, paste0(swd_results, "utility_idws.csv"), row.names=FALSE) } else { #SAVE OUT FILES #Write These out################################################## write.csv(all.service.scores, paste0(swd_results,"utility_service_scores_",selected.year,".csv"), row.names=FALSE) write.csv(all.block.scores, paste0(swd_results,"utility_block_scores_", selected.year, ".csv"), row.names=FALSE) write.csv(all.cost.to.bill, paste0(swd_results, "utility_idws.csv"), row.names=FALSE) rates.table <- rates.table %>% filter(pwsid %in% all.service.scores$pwsid) write.csv(rates.table, paste0(swd_results, "utility_rates_table.csv"), row.names=FALSE) } rm(rates.meta, rates.table, sel.cost, selected.bk, orig.cost.bill, orig.scores, orig.blocks, all.service.scores, all.block.scores, all.cost.to.bill, gis.systems, hh.total, min.wage) rm(dist, dist.inside, dist.outside, hh10, hh100, hh125, foo, service.area.results, tract.data, wage.cost, water.system, block.scores, combo, res.rates, gis.systems, bk.group, bk.int) rm(all.cost, annual.hh.cost, block.data, block.group.all, cost_to_bill, foo.zt, zt, hh15, hh150, hh20, hh200, hh25, hh250, hh30, hh35, hh40, hh45,hh50, hh60, hh75, moe.threshold, i, j, k, percent.area.threshold) rm(update.list, hh75, rates.pwsid, rep.per.cost, selected.pwsid, state.var) rm(bk.up1, bk.up2, bk.up3) <file_sep>/rcode/READ_ME_R.MD # Details about R Environment for Code Development The libraries and files here work for certain versions of R and libraries. As R and libraries update, the scripts may break. If the code is not working, you may try changing the package version. R Version: 4.0 - geojsonio package version 0.9.2 - httr version 1.4.2 - jsonlite version 1.7.2 - lubridate version 1.7.9 - purrr version 0.3.4 - raster version 3.1-5 - readxl version 1.3.1 - rgdal version 1.5-16 - rmapshaper version 0.4.4 - rstudioapi version 0.13 - rvest version 0.3.5 - sf package version 0.9-8 - spData package version 0.3.5 - stringr version 1.4.0 - tidycensus version 0.9.9.5 - tidyverse version 1.3.0 ### Additional Notes Mac users may need to change the file paths to `/` rather than `\\`. <file_sep>/rcode/use3_calculate_demographics.R ################################################################################################################################################################################# # # CODE FOR CENSUS DATA IN AFFORDABILITY DASHBOARD # CREATED by <NAME>, 2021 # ################################################################################################################################################################################# ###################################################################################################################################################################### # # MERGE CENSUS DATA WITH PWSID AND CALCULATE VALUES # ###################################################################################################################################################################### #read files pop <- read.csv(paste0(swd_data, "census_time\\bkgroup_pop_time.csv"), colClasses=c("GEOID" = "character")) %>% select(-GISJOIN, -state, -county) %>% mutate(GEOID = ifelse(nchar(GEOID) ==11, paste0("0",GEOID), GEOID)) age <- read.csv(paste0(swd_data, "census_time\\tract_age.csv"), colClasses=c("GEOID" = "character")) %>% mutate(GEOID = ifelse(nchar(GEOID) ==10, paste0("0",GEOID), GEOID)) race <- read.csv(paste0(swd_data, "census_time\\tract_race.csv"), colClasses=c("GEOID" = "character")) %>% mutate(GEOID = ifelse(nchar(GEOID) ==10, paste0("0",GEOID), GEOID)) hh.income <- read.csv(paste0(swd_data,"census_time\\block_group_income.csv"), colClasses=c("GEOID" = "character")) build.age <- read.csv(paste0(swd_data, "census_time\\bg_house_age.csv"), colClasses=c("GEOID" = "character")) cws <- read.csv(paste0(swd_data, "sdwis\\cws_systems.csv")) %>% select(PWSID, POPULATION_SERVED_COUNT) %>% group_by(PWSID) %>% summarize(POPULATION_SERVED_COUNT = median(POPULATION_SERVED_COUNT, na.rm=TRUE), .groups="drop") %>% distinct(); #for some reason many duplicates in NJ #read in all.block.scores to link GEOID with PWSID all.block.scores <- read.csv(paste0(swd_results, "utility_block_scores_", selected.year, ".csv"), colClasses=c("GEOID" = "character")); all.block.scores <- all.block.scores %>% mutate(GEOID = ifelse(nchar(GEOID) ==11, paste0("0",GEOID), GEOID)) %>% #sometimes the 0 is still being left out mutate(tracts = substr(GEOID,0,11), county = substr(GEOID,1,5)) %>% select(pwsid, service_area, GEOID, tracts, county, perArea) %>% distinct() #very small systems cannot be weighted. Change to NA.... it seems 15% makes most of the metrics fairly close. Some still are over 100% tooSmall <- all.block.scores %>% group_by(pwsid, service_area) %>% summarize(n = n(), totalArea = sum(perArea, na.rm=TRUE), .groups="drop") %>% mutate(keep = ifelse(totalArea >= 15, "keep", "too small")) table(tooSmall$keep); head(tooSmall %>% filter(keep=="too small" & totalArea>14)) #Now summarize by groups pop <- merge(all.block.scores, pop, by.x="GEOID", by.y="GEOID", all.x=TRUE) %>% distinct() #pop <- pop %>% mutate(pop1990 = ceiling(pop1990*perArea/100), pop2000 = ceiling(pop2000*perArea/100), pop2010 = ceiling(pop2010*perArea/100), popNow = ceiling(popNow*perArea/100)); pop <- pop %>% group_by(pwsid, service_area) %>% summarize(pop1990 = sum(pop1990, na.rm=TRUE), pop2000 = sum(pop2000, na.rm=TRUE), pop2010 = sum(pop2010, na.rm=TRUE), popNow = sum(popNow, na.rm=TRUE), .groups="keep") pop2 <- merge(pop, cws, by.x="pwsid", by.y="PWSID", all.x=TRUE) pop2 <- pop2 %>% mutate(cwsPop = ifelse(is.na(POPULATION_SERVED_COUNT), popNow, POPULATION_SERVED_COUNT)) %>% select(-POPULATION_SERVED_COUNT) #weight popNow by cwsPop and adjust earlier years accordingly pop2 <- pop2 %>% mutate(perCWS = cwsPop/popNow, pop1990a = ceiling(pop1990*perCWS), pop2000a = ceiling(pop2000*perCWS), pop2010a = ceiling(pop2010*perCWS)) pop <- pop2 %>% select(pwsid, service_area, pop1990a, pop2000a, pop2010a, cwsPop) %>% rename(pop1990 = pop1990a, pop2000 = pop2000a, pop2010 = pop2010a) #names(pop)[names(pop) == 'popNow'] <- paste0("pop",selected.year); leave cwsPop because makes easier in scripts #age all.tract.scores <- all.block.scores %>% select(pwsid, service_area, tracts, perArea) %>% distinct() age <-merge(all.tract.scores, age, by.x="tracts", by.y="GEOID", all.x=TRUE) #if only one census tract... do not need to weight... if more than 5, weight age, otherwise just use basic proportions age <- age %>% group_by(pwsid) %>% mutate(count=n()) %>% mutate(age18to34 = ifelse(count>5, ceiling(age18to34*perArea/100), age18to34), age35to59 = ifelse(count>5, ceiling(age35to59*perArea/100), age35to59), age60to64 = ifelse(count>5, ceiling(age60to64*perArea/100), age60to64), over65 = ifelse(count>5, ceiling(over65*perArea/100), over65), under18 = ifelse(count>5, ceiling(under18*perArea/100), under18)) age <- age %>% group_by(pwsid) %>% summarize(under18 = sum(under18, na.rm=TRUE), age18to34 = sum(age18to34, na.rm=TRUE), age35to59 = sum(age35to59, na.rm=TRUE), age60to64 = sum(age60to64, na.rm=TRUE), over65 = sum(over65, na.rm=TRUE), .groups="drop") age <- age %>% mutate(total = under18+age18to34+age35to59+age60to64+over65) #sums are much higher because census tracts instead of block group so only want percent of population age <- age %>% mutate(under18 = round(under18/total*100,2), age18to34 = round(age18to34/total*100,2), age35to59 = round(age35to59/total*100,2), age60to64 = round(age60to64/total*100,2), over65 = round(over65/total*100,2)) age <- age %>% mutate(total = under18+age18to34+age35to59+age60to64+over65) age <- age %>% select(-total) census.data <- merge(pop, age, by.x="pwsid", by.y="pwsid", all=TRUE) #add race race <- merge(all.tract.scores, race, by.x="tracts", by.y="GEOID", all.x=TRUE) #if few census tracts... do not weight... if more than 5, weight age, otherwise just use basic proportions race <- race %>% group_by(pwsid) %>% mutate(count=n()) %>% mutate(Asian = ifelse(count>5, ceiling(Asian*perArea/100), Asian), Black = ifelse(count>5, ceiling(Black*perArea/100), Black), Native = ifelse(count>5, ceiling(Native*perArea/100), Native), other = ifelse(count>5, ceiling(other*perArea/100), other), white = ifelse(count>5, ceiling(white*perArea/100), white), Hispanic = ifelse(count>5, ceiling(Hispanic*perArea/100), Hispanic)) %>% select(-NotHispanic) race <- race %>% group_by(pwsid) %>% summarize(Asian = sum(Asian, na.rm=TRUE), Black = sum(Black, na.rm=TRUE), Native = sum(Native, na.rm=TRUE), Other = sum(other, na.rm=TRUE), White = sum(white, na.rm=TRUE), Hispanic = sum(Hispanic, na.rm=TRUE), .groups="drop") race <- race %>% mutate(Total = Asian+Black+Native+White+Other) race <- race %>% mutate(Asian = round(Asian/Total*100,2), Black = round(Black/Total*100,2), Native = round(Native/Total*100,2), Other = round(Other/Total*100,2), White = round(White/Total*100,2), Hispanic = round(Hispanic/Total*100,2)) race <- race %>% mutate(Total = Asian+Black+Native+White+Other) race <- race %>% select(-Total) census.data <- merge(census.data, race, by.x="pwsid", by.y="pwsid", all=TRUE) #add hh income hh.inc <- merge(all.block.scores, hh.income, by.x="GEOID", by.y="GEOID", all.x=TRUE) #if only a few block groups... do not weight... if more than 5, weight age, otherwise just use basic proportions hh.inc <- hh.inc %>% group_by(pwsid) %>% mutate(count = n()) %>% mutate(d0to24k=ifelse(count>5, ceiling(d0to24k*perArea/100), d0to24k), d25to49k = ifelse(count>5,ceiling(d25to49k*perArea/100), d25to49k), d50to74k=ifelse(count>5, ceiling(d50to74k*perArea/100), d50to74k), d75to100k=ifelse(count>5, ceiling(d75to100k*perArea/100), d75to100k), d100to125k=ifelse(count>5, ceiling(d100to125k*perArea/100), d100to125k), d125to150k=ifelse(count>5, ceiling(d125to150k*perArea/100), d125to150k), d150kmore=ifelse(count>5, ceiling(d150kmore*perArea/100), d150kmore)) #sum and calculate percent hh.inc <- hh.inc %>% group_by(pwsid, service_area) %>% summarize(d0to24k = sum(d0to24k, na.rm=TRUE), d25to49k = sum(d25to49k, na.rm=TRUE), d50to74k = sum(d50to74k, na.rm=TRUE), d75to100k = sum(d75to100k, na.rm=TRUE), d100to125k = sum(d100to125k, na.rm=TRUE), d125to150k = sum(d125to150k, na.rm=TRUE), d150kmore = sum(d150kmore, na.rm=TRUE), totalhh = sum(totalhh, na.rm=TRUE), .groups="drop") hh.inc <- hh.inc %>% mutate(totalhh = d0to24k+d25to49k+d50to74k+d75to100k+d100to125k+d125to150k+d150kmore) hh.inc <- hh.inc %>% mutate(d0to24k = round(d0to24k/totalhh*100,2), d25to49k = round(d25to49k/totalhh*100,2), d50to74k = round(d50to74k/totalhh*100,2), d75to100k = round(d75to100k/totalhh*100,2), d100to125k = round(d100to125k/totalhh*100,2), d125to150k = round(d125to150k/totalhh*100,2), d150kmore = round(d150kmore/totalhh*100,2)) hh.inc <- hh.inc %>% mutate(total = d0to24k+d25to49k+d50to74k+d75to100k+d100to125k+d125to150k+d150kmore) hh.inc <- hh.inc %>% select(-service_area, -totalhh, -total); census.data <- merge(census.data, hh.inc, by.x="pwsid", by.y="pwsid", all = TRUE) summary(census.data) #add in age of buildings build.age <- merge(all.block.scores, build.age, by.x="GEOID", by.y="GEOID", all.x=TRUE) %>% distinct() build.age <- build.age %>% group_by(pwsid) %>% mutate(count=n()) %>% mutate(built_2010later = ifelse(count>5, ceiling(built_2010later*perArea/100), built_2010later), built_2000to2009 = ifelse(count>5, ceiling(built_2000to2009*perArea/100), built_2000to2009), built_1990to1999 = ifelse(count>5, ceiling(built_1990to1999*perArea/100), built_1990to1999), built_1980to1989 = ifelse(count>5, ceiling(built_1980to1989*perArea/100), built_1980to1989), built_1970to1979 = ifelse(count>5, ceiling(built_1970to1979*perArea/100), built_1970to1979), built_1960to1969 = ifelse(count>5, ceiling(built_1960to1969*perArea/100), built_1960to1969), built_1950to1959 = ifelse(count>5, ceiling(built_1950to1959*perArea/100), built_1950to1959), built_1940to1949 = ifelse(count>5, ceiling(built_1940to1949*perArea/100), built_1940to1949), built_1939early = ifelse(count>5, ceiling(built_1939early*perArea/100), built_1939early)) build.age <- build.age %>% group_by(pwsid, service_area) %>% summarize(built_2010later = sum(built_2010later, na.rm=TRUE), built_2000to2009 = sum(built_2000to2009, na.rm=TRUE), built_1990to1999 = sum(built_1990to1999, na.rm=TRUE), built_1980to1989 = sum(built_1980to1989, na.rm=TRUE), built_1970to1979 = sum(built_1970to1979, na.rm=TRUE), built_1960to1969 = sum(built_1960to1969, na.rm=TRUE), built_1950to1959 = sum(built_1950to1959, na.rm=TRUE), built_1940to1949 = sum(built_1940to1949, na.rm=TRUE), built_1939early = sum(built_1939early, na.rm=TRUE), totalhh = sum(totalhh, na.rm=TRUE), .groups="drop") build.age <- build.age %>% mutate(totalhh = built_2010later+built_2000to2009+built_1990to1999+built_1980to1989+built_1970to1979+built_1960to1969+built_1950to1959+built_1940to1949+built_1939early) build.age <- build.age %>% mutate(built_2010later = round(built_2010later/totalhh*100,2), built_2000to2009 = round(built_2000to2009/totalhh*100,2), built_1990to1999 = round(built_1990to1999/totalhh*100,2), built_1980to1989 = round(built_1980to1989/totalhh*100,2), built_1970to1979 = round(built_1970to1979/totalhh*100,2), built_1960to1969 = round(built_1960to1969/totalhh*100,2), built_1950to1959 = round(built_1950to1959/totalhh*100,2), built_1940to1949 = round(built_1940to1949/totalhh*100,2), built_1939early = round(built_1939early/totalhh*100,2)) build.age <- build.age %>% mutate(total = built_2010later+built_2000to2009+built_1990to1999+built_1980to1989+built_1970to1979+built_1960to1969+built_1950to1959+built_1940to1949+built_1939early) build.age <- build.age %>% select(-service_area, -totalhh, -total) census.data <- merge(census.data, build.age, by.x="pwsid", by.y="pwsid", all = TRUE) #add column if too small or keep census.data <- merge(census.data, tooSmall %>% select(-n, -totalArea), by=c("pwsid", "service_area")) write.csv(census.data, paste0(swd_results, "utility_census_summary.csv"), row.names=FALSE) ###################################################################################################################################################################### # # Unemployment rates of counties # ###################################################################################################################################################################### bls.old <- read_excel(paste0(swd_data,"census_time\\county_unemployment.xlsx"), sheet="alldata") %>% as.data.frame() bls.recent <- read.csv(paste0(swd_data, "census_time\\current_unemploy.csv")) %>% as.data.frame() %>% mutate(stateFips=ifelse(nchar(stateFips)==1, paste0("0", stateFips), stateFips)) #filter to relevant state bls.old <- bls.old %>% filter(stateFips %in% state.fips); bls.old$year <- as.numeric(bls.old$year) bls.recent <- bls.recent %>% filter(stateFips %in% state.fips) #keeps ca this way #summarize bls.recent for 2020 bls.recent <- bls.recent %>% mutate(date = as.character(year)) %>% mutate(year_end = ifelse(is.na(as.numeric(substr(date,1,2))),substr(date,5,6), substr(date,1,2))) %>% mutate(month = ifelse(is.na(as.numeric(substr(date,1,2))), substr(date,1,3), substr(date,4,6))) table(bls.recent$year_end, useNA="ifany"); table(bls.recent$month, useNA="ifany") #bls.recent$year_end = as.numeric(gsub("([0-9]+).*$", "\\1", bls.recent$date)) bls.recent <- bls.recent %>% mutate(year = as.numeric(paste0("20", year_end))) %>% mutate(date = paste0(year_end,"-",month)) %>% select(-year_end, -month) bls.2020 <- bls.recent %>% group_by(LAUSID, stateFips, countyFips, name, year) %>% summarize(labor_force = median(labor_force, na.rm=TRUE), employed = median(employed, na.rm=TRUE), unemployed = median(unemployed, na.rm=TRUE), unemploy_rate = median(unemploy_rate, na.rm=TRUE), .groups="drop") %>% as.data.frame() #lets plot only 2020 months require(zoo) bls.2020months <- bls.recent %>% filter(year>=2020) %>% mutate(date = as.yearmon(date, format = "%y-%b")) %>% mutate(date = as.Date(date, frac=0.0)) #sets to end date #add 2020 to end of bls.old bls.annual <- rbind(bls.old, bls.2020) bls.annual = bls.annual %>% mutate(countyFips = ifelse(nchar(countyFips)==1, paste0("00",countyFips), ifelse(nchar(countyFips)==2, paste0("0",countyFips), countyFips))) %>% mutate(county = as.character(paste0(stateFips, countyFips))) #convert to date - make end of month #bls all.county <- all.block.scores %>% select(pwsid, service_area, county) %>% distinct() bls.annual <- bls.annual %>% select(county, year, labor_force, employed, unemployed, unemploy_rate) bls.annual2 <- merge(all.county, bls.annual, by.x="county", by.y="county", all.x=TRUE) #sum up for those covering more than one county bls.annual2 <- bls.annual2 %>% group_by(pwsid, year) %>% summarize(labor_force = sum(labor_force, na.rm=TRUE), employed = sum(employed, na.rm=TRUE), unemployed = sum(unemployed, na.rm=TRUE), .groups="drop") %>% mutate(unemploy_rate = round(unemployed/labor_force*100,2)) summary(bls.annual2) write.csv(bls.annual2, paste0(swd_results, "utility_bls_summary.csv"), row.names=FALSE) bls.2020months = bls.2020months %>% mutate(county = substr(LAUSID,3,7)) bls.20202 <- merge(all.county, bls.2020months, by.x="county", by.y="county", all.x=TRUE) %>% arrange(pwsid, county, date) #sum up for those covering more than one county bls.20202 <- bls.20202 %>% group_by(pwsid, date) %>% summarize(labor_force = sum(labor_force, na.rm=TRUE), employed = sum(employed, na.rm=TRUE), unemployed = sum(unemployed, na.rm=TRUE), .groups="drop") %>% mutate(unemploy_rate = round(unemployed/labor_force*100,2)) %>% as.data.frame(); summary(bls.20202) subset(bls.20202, is.na(date)) write.csv(bls.20202, paste0(swd_results, "utility_bls_monthly.csv"), row.names=FALSE) rm(bls.old, bls.recent, bls.2020months, pop, pop2, race, build.age, census.data, all.county, cws, hh.inc, hh.income, all.block.scores, bls.2020, bls.20202, bls.annual, bls.annual2, age) <file_sep>/rcode/use4_create_files_for_dataviz.R ####################################################################################################################################################### # # Created by <NAME>, 2021 # Simplifies and saves files for data visualization # ######################################################################################################################################################## ################################################################################################################################################################### # # SAVE OUT GEOJSON FOR HTML - IN SIMPLIFIED FORMAT - only need to do for each state # ################################################################################################################################################################### #swd_html = "C:\\Users\\lap19\\Documents\\GitHub\\water-affordability-develop\\water-affordability-dashboard\\data\\" #swd_html = "C:\\Users\\lap19\\Documents\\GitHub\\bkup\\water-affordability-develop\\afford_ws\\data\\" #only need to do once county <- read_sf(paste0(swd_data, "county.geojson")) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = county, fillOpacity= 0.3, fillColor = "white", color="red", weight=1) geojson_write(county, file = paste0(swd_html, "..//mapbox_sources//county.geojson")) state <- read_sf(paste0(swd_data, "state.geojson")) %>% ms_simplify(keep=0.75, keep_shapes=TRUE) #%>% ms_simplify(keep = 0.5, keep_shapes=TRUE) state <- state %>% mutate(data = ifelse(geoid %in% state.fips, "yes", "no")) %>% filter(name != "Alaska") %>% filter(name != "Hawaii") %>% filter(name != "Puerto Rico") state <- state %>% mutate(data = ifelse(name=="Oregon", "muni", data)) #state <- state %>% mutate(data = ifelse(name=="Washington", "hybrid", data)) table(state$name, state$data) geojson_write(state, file = paste0(swd_html, "..//mapbox_sources//state.geojson")) #MUNIS COME FROM DIFFERENT SOURCES - except OR and CA all.muni <- read_sf(paste0(swd_data, "muni.geojson")) bk.up <- all.muni all.muni <- all.muni %>% ms_simplify(keep = 0.40, keep_shapes=TRUE); #remove special characters - do not translate into mapbox all.muni <- all.muni %>% mutate(city_name = iconv(city_name, to='ASCII//TRANSLIT')) leaflet() %>% addProviderTiles("Stamen.TonerLite") %>% addPolygons(data = bk.up, fillOpacity= 0.6, fillColor = "gray", color="black", weight=3) %>% addPolygons(data = all.muni, fillOpacity= 0.3, fillColor = "white", color="red", weight=1) geojson_write(all.muni, file = paste0(swd_html, "..//mapbox_sources//muni.geojson")) #save point file for labels all.muni.pt <- st_centroid(all.muni) geojson_write(all.muni.pt, file = paste0(swd_html, "..//mapbox_sources//muni_centers.geojson")) rm(all.muni.pt, bk.up, all.muni, state, county) ################################################################################################################################################################### # # SAVE OUT UTILITY INFORMATION --> ONLY THOSE SYSTEMS WITH DATA FOR BOTH DRINKING WATER AND WASTEWATER # ################################################################################################################################################################### #Load Rates Data ----------------------------------------------------------------------------------------------------------------------------------------- res.rates <- read.csv(paste0(swd_results, "estimated_bills.csv")) %>% mutate(state=tolower(substr(pwsid,0,2))) res.rates[is.na(res.rates)] <- 0 #number of systems with some rates data print(paste("Number of systems with some rates data:", length(unique(res.rates$pwsid)), "utilities")) #keep only those that provide both water and wasteater services df.2serv <- res.rates %>% filter(hh_use == 4000 & category=="inside" & service =="total") %>% select(pwsid, service_area, category, service, n_services, state) %>% distinct() %>% filter(n_services==2) table(df.2serv$state) print(paste("Number of systems with both drinking water and wastewater data:", length(unique(df.2serv$pwsid)), "utilities")) ################################################################################################################################################################### # # SAVE OUT SHAPEFILES ... ONLY NEED TO DO IF ADD MORE RATES # ################################################################################################################################################################### service.scores <- read.csv(paste0(swd_results, "utility_service_scores_",selected.year,".csv")) print(paste("Number of systems with service area boundaries:", length(unique(service.scores$pwsid)), "utilities")) #for some reason the GEOID character is inconsistent so check with mutate block.scores <- read.csv(paste0(swd_results, "utility_block_scores_",selected.year,".csv"), colClasses=c("GEOID" = "character")) %>% mutate(GEOID = ifelse(nchar(GEOID) ==11, paste0("0",GEOID), GEOID)) zt <- block.scores %>% filter(hh_use==4000) zt <- zt %>% mutate(duplicate = duplicated(zt[,1:2])) check <- zt %>% filter(duplicate==TRUE); dim(check) #find unique values bs <- block.scores %>% select(GEOID, pwsid) %>% distinct() combo <- merge(df.2serv, bs, by.x="pwsid", by.y="pwsid") #remove pwsid in WA that shares same boundaries combo <- combo %>% filter(pwsid != "WA5308273") unique.pwsid <- unique(combo$pwsid) print(paste("Number of systems sufficient data:", length(unique.pwsid), "utilities")) block.scores <- block.scores %>% filter(pwsid %in% unique.pwsid); #filter to those with rates data unique.bgs <- unique(block.scores$GEOID) table(substr(block.scores$GEOID,0,2)) ###################################################################################################################################################################### # # LOAD RATES, CWS Data, UTILITY SUMMARY DATA -- THIS FORMS THE BASIS FOR REMAINING FILES # ###################################################################################################################################################################### all.rates <- read.csv(paste0(swd_results, "utility_rates_table.csv")) cws <- read.csv(paste0(swd_data, "sdwis//cws_systems.csv")) %>% filter(PWSID %in% unique.pwsid) cws <- cws %>% rename(pwsid=PWSID, name = PWS_NAME, population = POPULATION_SERVED_COUNT, owner_type = OWNER_TYPE_CODE) %>% select(pwsid, name, population, owner_type) #lots of duplicates in NJ cws <- cws %>% group_by(pwsid, name, owner_type) %>% summarize(population = median(population, na.rm=TRUE), .groups="drop") #keep the first in the list if different names... will use names in rates cws <- cws %>% distinct(pwsid, .keep_all = TRUE) #Create summary hb_high = 9.2; hb_mod = 4.6; service.scores <- service.scores %>% filter(pwsid %in% unique.pwsid) %>% mutate(LaborHrs = round((LaborHrsMax + LaborHrsMin)/2,2)) %>% mutate(state=tolower(substr(pwsid,0,2))) service.scores <- service.scores %>% mutate(burden = ifelse(PPI >= 35 & HBI >= hb_high, "Very High", ifelse(PPI >=35 & HBI < hb_high & HBI >= hb_mod, "High", ifelse(PPI >= 35 & HBI < hb_mod, "Moderate-High", ifelse(PPI >= 20 & PPI < 35 & HBI >=hb_high, "High", ifelse(PPI >=20 & PPI < 35 & HBI >= hb_mod & HBI < hb_high, "Moderate-High", ifelse(PPI >=20 & PPI < 35 & HBI < hb_mod, "Low-Moderate", ifelse(PPI < 20 & HBI >= hb_high, "Moderate-High", ifelse(PPI < 20 & HBI >= hb_mod & HBI < hb_high, "Low-Moderate", ifelse(PPI < 20 & HBI < hb_mod, "Low", "Unknown")))))))))) %>% mutate(burden = ifelse(is.na(burden)==TRUE, "unknown", burden)) full.summary <- merge(service.scores, cws, by.x="pwsid", by.y="pwsid", all=TRUE) #keep all of them or no? #if NA then set to following full.summary <- full.summary %>% mutate(burden = ifelse(is.na(burden), "Unknown", burden)) table(full.summary$burden, useNA="ifany"); #names simpleCap <- function(x) { s <- strsplit(x, " ")[[1]] paste(toupper(substring(s, 1,1)), tolower(substring(s, 2)), sep="", collapse=" ") } full.summary$name2 = simpleCap(as.character(full.summary$name)) full.summary <- full.summary %>% mutate(service_area = ifelse(is.na(service_area), name2, service_area)) %>% select(-name, -name2) #if a system does not have any sdwis violations - add cws population and size category full.summary <- full.summary %>% mutate(sizeCategory = ifelse(population <= 500, "Very Small", ifelse(population > 500 & population <=3300, "Small", ifelse(population > 3300 & population <= 10000, "Medium", ifelse(population > 10000 & population <= 100000, "Large", ifelse(population > 100000, "Very Large", "Unknown")))))) table(full.summary$sizeCategory, useNA='ifany') table(full.summary$owner_type, useNA="ifany") #full.summary[is.na(full.summary)] <- 0; full.summary <- full.summary %>% mutate(owner_type = ifelse(owner_type == "F", "Federal", ifelse(owner_type == "L", "Local", ifelse(owner_type == "M", "Public/Private", ifelse(owner_type == "S", "State", ifelse(owner_type == "P", "Private", ifelse(owner_type=="N", "Native American", "Unknown"))))))) #redo sizeCategory to provide more nuance table(full.summary$sizeCategory, useNA="ifany")/17 #subset(full.summary, is.na(sizeCategory) & hh_use==4000) vl_break = 500000; ml_break = 75000; full.summary <- full.summary %>% mutate(sizeCategory = ifelse(population >= vl_break, "Very Large", ifelse(population > 10000 & population <= ml_break, "Medium-Large", ifelse(population > ml_break & population < vl_break, "Large", sizeCategory)))) #pull in old data to fill out (some reason sdwis is missing them) old.details <- read.csv(paste0(swd_html, "utility_descriptions.csv")) %>% select(pwsid, sizeCategory, owner_type) merge.sum <- left_join(full.summary, old.details, by = 'pwsid') merge.sum <- merge.sum %>% mutate(owner_type.x = ifelse(is.na(owner_type.x), owner_type.y, owner_type.x), sizeCategory.x = ifelse(is.na(sizeCategory.x), sizeCategory.y, sizeCategory.x)) merge.sum %>% filter(hh_use == 4000 & is.na(owner_type.x)) full.summary <- merge.sum %>% select(-sizeCategory.y, -owner_type.y) %>% rename(owner_type = owner_type.x, sizeCategory = sizeCategory.x) rm(old.details, merge.sum) #fill in missing info not in EPA SDWIS full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="NC5063021", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="NC5063021", "Local", owner_type)); #https://www.ncwater.org/WUDC/app/LWSP/report.php?pwsid=50-63-021&year=2019 full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="PA1230012", "Medium", sizeCategory), owner_type = ifelse(pwsid=="PA1230012", "Private", owner_type)); #https://www.ewg.org/tapwater/system.php?pws=PA1230012 full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="PA2450045", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="PA2450045", "Private", owner_type)); #https://www.nytimes.com/interactive/projects/toxic-waters/contaminants/pa/monroe/pa2450045-mountain-top-estates/index.html full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="PA2520051", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="PA2520051", "Private", owner_type)); #https://www.annualreports.com/HostedData/AnnualReportArchive/m/NASDAQ_MSEX_2018.pdf full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="NM3503129", "Small", sizeCategory), owner_type = ifelse(pwsid=="NM3503129", "Local", owner_type)); full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="NM3524626", "Large", sizeCategory), owner_type = ifelse(pwsid=="NM3524626", "Private", owner_type)); full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="CT0180141", "Small", sizeCategory), owner_type = ifelse(pwsid=="CT0180141", "Private", owner_type)); #https://www.ewg.org/tapwater/system.php?pws=CT0180141 full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="CT1180081", "Medium", sizeCategory), owner_type = ifelse(pwsid=="CT1180081", "Private", owner_type)); #https://www.ewg.org/tapwater/system.php?pws=CT1180081 full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="WA5308273", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="WA5308273", "Local", owner_type)); # subset(full.summary %>% filter(hh_use==4000 & is.na(sizeCategory))) #all these systems are listed as inactive... but so are others that are still in SDWIS as active? full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="KS2000104", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="KS2000104", "Non-Public", owner_type)); #https://dww.kdhe.ks.gov/DWW/JSP/WaterSystemDetail.jsp full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="KS2000108", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="KS2000108", "Non-Public", owner_type)); #https://dww.kdhe.ks.gov/DWW/JSP/WaterSystemDetail.jsp full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="KS2000902", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="KS2000902", "Non-Public", owner_type)); #https://dww.kdhe.ks.gov/DWW/JSP/WaterSystemDetail.jsp full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="KS2008705", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="KS2008705", "Non-Public", owner_type)); #https://dww.kdhe.ks.gov/DWW/JSP/WaterSystemDetail.jsp full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="KS2009907", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="KS2009907", "Non-Public", owner_type)); #https://dww.kdhe.ks.gov/DWW/JSP/WaterSystemDetail.jsp full.summary <- full.summary %>% mutate(sizeCategory = ifelse(pwsid=="KS2020503", "Very Small", sizeCategory), owner_type = ifelse(pwsid=="KS2020503", "Non-Public", owner_type)); #https://dww.kdhe.ks.gov/DWW/JSP/WaterSystemDetail.jsp #remove inactive systems full.summary <- full.summary %>% filter(pwsid %notin% c("KS2000104","KS2000108","KS2000902","KS2008705","KS2009907","KS2020503")) table(full.summary$sizeCategory, useNA='ifany') table(full.summary$owner_type, useNA="ifany") #since so few - F, M, N, and S to "Other" full.summary <- full.summary %>% mutate(owner_type = ifelse(owner_type=="Local" | owner_type == "Private", owner_type, "Other")) #since owner errors in PA and similar start to names - check and make private zt <- subset(full.summary, substr(service_area, 1, 7) == "Aqua PA"); table(zt$owner_type); #looks ok zt <- subset(full.summary, substr(service_area, 1, 21) == "Pennsylvania American"); table(zt$owner_type); #Two are set as local, one to other... set local to Private full.summary <- full.summary %>% mutate(owner_type = ifelse(substr(service_area,1,21) == "Pennsylvania American" & owner_type=="Local", "Private", owner_type)); #set Local to Private zt <- subset(full.summary, substr(service_area, 1, 4) == "Suez"); table(zt$owner_type); #several listed as local... set those to private full.summary <- full.summary %>% mutate(owner_type = ifelse(substr(service_area,1,4) == "Suez" & owner_type=="Local", "Private", owner_type)); #set Local to Private zt <- subset(full.summary, substr(service_area, 1, 19) == "California American"); table(zt$owner_type); #All private zt <- subset(full.summary, substr(service_area, 1, 24) == "California Water Service"); table(zt$owner_type); #1 local - set to private full.summary <- full.summary %>% mutate(owner_type = ifelse(substr(service_area,1,24) == "California Water Service" & owner_type=="Local", "Private", owner_type)); #set Local to Private zt <- subset(full.summary, substr(service_area, 1, 17) == "Aquarion Water Co"); table(zt$owner_type); #All private #remove to those you are using full.summary <- full.summary %>% dplyr::select(-LaborHrsMin, -LaborHrsMax) #combine with block group to get distributions bs.hist <- block.scores %>% group_by(pwsid, hh_use, burden) %>% summarize(count=n(), .groups="drop") %>% spread(key=burden, value=count) bs.hist[is.na(bs.hist)] = 0 bs.hist <- bs.hist %>% mutate(total = High + Low + `Low-Moderate` + `Moderate-High` + `Very High` + unknown) %>% mutate(low = round(Low/total*100, 1), low_mod = round(`Low-Moderate`/total*100, 1), mod_high = round(`Moderate-High`/total*100, 1), high = round(High/total*100, 1), very_high = round(`Very High`/total*100, 1), unknown = round(unknown/total,1)) %>% dplyr::select(pwsid, hh_use, low, low_mod, mod_high, high, very_high, unknown) bs.hist <- bs.hist %>% mutate(total_per = low+low_mod+mod_high+high+very_high+unknown) unique(subset(bs.hist, total_per==0)$pwsid) bs.hist <- bs.hist %>% select(-total_per, -unknown) %>% distinct() full.summary = merge(full.summary, bs.hist, by=c("pwsid", "hh_use")) #Save out characteristics used for filtering that do not change with volume main.data <- full.summary %>% select(pwsid, service_area, state, sizeCategory, owner_type, min_wage, min_year) %>% distinct() write.csv(main.data, paste0(swd_html,"utility_descriptions.csv"), row.names=FALSE) full.summary.short <- full.summary %>% select(pwsid, hh_use, HBI, PPI, TRAD, burden, LaborHrs) write.csv(full.summary.short, paste0(swd_html,"utility_afford_scores.csv"), row.names=FALSE) #commodity price commod.price <- res.rates %>% select(pwsid, category, total, hh_use, service, commodity_unit_price) %>% filter(service != "storm") %>% filter(pwsid %in% main.data$pwsid) %>% filter(service != "total") %>% arrange(pwsid, category, service, hh_use) %>% mutate(commodity_unit_price = round(commodity_unit_price, 2)) commod.price <- commod.price %>% filter(category == "inside" | category == "outside" & total > 0) %>% select(-total) write.csv(commod.price, paste0(swd_html, "commodity_price.csv"), row.names=FALSE) #res rates hh_vols <- c(0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000) for (i in 1:length(hh_vols)){ zt <- res.rates %>% filter(hh_use == hh_vols[i]) %>% filter(category=="inside" | category=="outside" & total>0) %>% filter(pwsid %in% main.data$pwsid) %>% select(-n_services, -service_area, -state, -commodity_unit_price, -hh_use) write.csv(zt, paste0(swd_html, "rates\\rates_",hh_vols[i],".csv"), row.names=FALSE); #can split by hh_volume print(hh_vols[i]) } #make smaller for now all.rates2 <- all.rates %>% select(-percent_variable_water, -percent_variable_sewer, -percent_surcharge_water, -percent_surcharge_sewer, -surcharge_cost_storm, -variable_cost_storm, -base_cost_storm, -service_area) %>% filter(pwsid %in% main.data$pwsid) write.csv(all.rates2, paste0(swd_html, "\\all_rates_table_current.csv"), row.names = FALSE) #######################################################################################################################################################################################3 # # CREATE MAPBOX FILES FOR UTILITIES # #######################################################################################################################################################################################3 #read in water systems - FOR NOW WILL ONLY KEEP THOSE THAT HAVE RATES DATA...#simplify shapefiles differently because NC is so problematic and then combine ca.systems <- read_sf(paste0(swd_data, "ca_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state = "ca") %>% select(pwsid, gis_name, state, geometry) nc.systems <- read_sf(paste0(swd_data, "nc_systems.geojson")) %>% ms_simplify(keep = 0.25, keep_shapes = TRUE) %>% mutate(pwsid = ifelse(gis_name=="Town_of_Forest_City", "NC0181010", pwsid)); ##"NC0363108"; duplicated... forest city is wrong in the pwsid... NC0181010 or.systems <- read_sf(paste0(swd_data, "or_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% select(pwsid, gis_name, state, geometry) pa.systems <- read_sf(paste0(swd_data, "pa_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state = "pa") %>% select(pwsid, gis_name, state, geometry) tx.systems <- read_sf(paste0(swd_data, "tx_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state ="tx") nm.systems <- read_sf(paste0(swd_data, "nm_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state = "nm") nj.systems <- read_sf(paste0(swd_data, "nj_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) ct.systems <- read_sf(paste0(swd_data, "ct_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state = "ct") ks.systems <- read_sf(paste0(swd_data, "ks_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state = "ks") wa.systems <- read_sf(paste0(swd_data, "wa_systems.geojson")) %>% ms_simplify(keep = 0.5, keep_shapes = TRUE) %>% mutate(state = "wa") #save to only those systems with pwsid in unique.pwsid all.systems <- rbind(ca.systems, nc.systems, or.systems, pa.systems, tx.systems, nm.systems, nj.systems, ct.systems, ks.systems, wa.systems) %>% filter(pwsid %in% main.data$pwsid) #mapview::mapview(all.systems) rm(ca.systems, nc.systems, or.systems, pa.systems, tx.systems, nm.systems, nj.systems, ct.systems, wa.systems, ks.systems) simple.systems <- all.systems %>% ms_simplify(keep = 0.005, keep_shapes=TRUE) mapview::mapview(simple.systems) #instead calculate bounding box as.data.frame(table(st_geometry_type(simple.systems))) #geojson_write(simple.systems, file = paste0(swd_html, "simple_water_systems.geojson")); #aim for 1 MB #loop through and save individual volumes hh_vols <- c(0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000) bare.systems <- all.systems %>% dplyr::select(pwsid, geometry) as.data.frame(table(st_geometry_type(bare.systems))) bare.systems <- all.systems %>% group_by(pwsid) %>% summarise() %>% st_cast(); #this dissolves polygons #simplify some bare.systems <- bare.systems %>% ms_simplify(keep = 0.5, keep_shapes=TRUE) #create dataframe zt.box <- bare.systems %>% select(pwsid) st_geometry(zt.box) = NULL zt.box$xmin = zt.box$ymin = zt.box$xmax = zt.box$ymax = NA #fix geometry if (FALSE %in% st_is_valid(bare.systems)) {bare.systems <- suppressWarnings(st_buffer(bare.systems[!is.na(st_is_valid(bare.systems)),], 0.0)); print("fixed")}#fix corrupt shapefiles for block group... takes awhile can try to skip #need to replace all special characters full.summary <- full.summary %>% mutate(service_area = iconv(service_area, to='ASCII//TRANSLIT')) for (i in 1:length(hh_vols)){ zt = NA; zt.systems = NA; zt <- full.summary %>% filter(hh_use == hh_vols[i]) %>% dplyr::select(-hh_use, -population) %>% mutate(HBI = round(HBI, 1), PPI = round(PPI, 1), TRAD = round(TRAD, 1), LaborHrs = round(LaborHrs, 1)) zt.systems <- merge(bare.systems, zt, by.x="pwsid", by.y="pwsid", all.x=TRUE) geojson_write(zt.systems, file = paste0(swd_html, "..\\mapbox_sources\\water_systems_",hh_vols[i],".geojson")); #aim for 5 MB print(hh_vols[i]) } #######################################################################################################################################################################################3 # # BLOCK SCORES AND BLOCK GROUPS FOR WEBSITE # #######################################################################################################################################################################################3 #repeat since removed some block.scores <- block.scores %>% filter(pwsid %in% main.data$pwsid); #filter to those with rates data unique.bgs <- unique(block.scores$GEOID) table(substr(block.scores$GEOID,0,2)) #read in block groups bk.groups <- read_sf(paste0(swd_data, "block_groups_", selected.year, ".geojson")) %>% filter(GEOID %in% unique.bgs) bk.groups <- bk.groups %>% ms_simplify(keep = 0.6, keep_shapes=TRUE); #Trying to balance simplicity and file size #mapview::mapview(bk.groups %>% filter(substring(GEOID,0,2)=="42")) table(substr(bk.groups$GEOID,0,2)) #geojson_write(bk.groups, file = paste0(swd_html, "all_bk_groups.geojson")); #aim for 10MB #will need to break up block scores by hh_use block.scores <- block.scores %>% select(-service_area) %>% mutate(state = tolower(substr(pwsid,0,2))) #rewrite burden score using days of labor hb_high = 9.2; hb_mod = 4.6; block.scores <- block.scores %>% mutate(burden = ifelse(PPI >= 35 & HBI >= hb_high, "Very High", ifelse(PPI >=35 & HBI < hb_high & HBI >= hb_mod, "High", ifelse(PPI >= 35 & HBI < hb_mod, "Moderate-High", ifelse(PPI >= 20 & PPI < 35 & HBI >=hb_high, "High", ifelse(PPI >=20 & PPI < 35 & HBI >= hb_mod & HBI < hb_high, "Moderate-High", ifelse(PPI >=20 & PPI < 35 & HBI < hb_mod, "Low-Moderate", ifelse(PPI < 20 & HBI >= hb_high, "Moderate-High", ifelse(PPI < 20 & HBI >= hb_mod & HBI < hb_high, "Low-Moderate", ifelse(PPI < 20 & HBI < hb_mod, "Low", "Unknown")))))))))) %>% mutate(burden = ifelse(is.na(burden)==TRUE, "unknown", burden)) #In Washington - a bunch of islands all have the same census block group with no houses del.block <- c("530099901000") bk.groups <- bk.groups %>% filter(GEOID %notin% del.block) block.scores <- block.scores %>% filter(GEOID %notin% del.block) hh_vols <- c(0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000) for (i in 1:length(hh_vols)){ zt <- block.scores %>% filter(hh_use == hh_vols[i]) %>% dplyr::select(-hh_use, -hhsize, -totalpop, -state) %>% mutate(HBI = round(HBI, 1), PPI = round(PPI, 1), TRAD = round(TRAD, 1)) zt.systems <- merge(bk.groups, zt, by.x="GEOID", by.y="GEOID", all.x=TRUE) %>% select(-state) geojson_write(zt.systems, file = paste0(swd_html, "..//mapbox_sources//block_groups_",hh_vols[i],".geojson")); #aim for 5 MB #we don't use block scores for much so can slim down zt <- zt %>% select(GEOID, pwsid, burden) write.csv(zt, paste0(swd_html, "block_scores\\block_scores_",hh_vols[i],".csv"), row.names=FALSE); #can split by hh_volume print(hh_vols[i]) } #create bounding box for geojsons for(i in 1:length(bare.systems$pwsid)){ yt <- block.scores %>% filter(pwsid == bare.systems$pwsid[i]) zt <- bk.groups %>% filter(GEOID %in% yt$GEOID); zt.box$xmin[i] = round(st_bbox(zt)[1],2); zt.box$ymin[i] = round(st_bbox(zt)[2],2); zt.box$xmax[i] = round(st_bbox(zt)[3],2); zt.box$ymax[i] = round(st_bbox(zt)[4],2); print(i); } summary(zt.box) write_csv(zt.box, file=paste0(swd_html, "bbox.csv")) ######################################################################################################################################################################################################### ## READ IN RESULTS FOR All States ########################################################################################################################################################################################################## #read in files and save over cs <- read.csv(paste0(swd_results, "\\utility_census_summary.csv")) %>% mutate(state = tolower(substring(pwsid, 0, 2))) %>% filter(pwsid %in% full.summary$pwsid) %>% select(-service_area, -state) write.csv(cs, paste0(swd_html, "\\census_summary.csv"), row.names = FALSE) blm <- read.csv(paste0(swd_results, "\\utility_bls_monthly.csv")) %>% select(pwsid, date, unemploy_rate) write.csv(blm, paste0(swd_html, "\\bls_monthly.csv"), row.names = FALSE) bls <- read.csv(paste0(swd_results, "\\utility_bls_summary.csv")) #to lower file size save out every other year current_year <- year(today()) last_even_year <- ifelse(substr(current_year,4,4) %in% c(1,3,5,7,9), current_year-1, current_year) bls <- bls %>% filter(year %in% c(seq(1990,last_even_year,2), current_year)) %>% select(pwsid, year, unemploy_rate) write.csv(bls, paste0(swd_html, "\\bls_summary.csv"), row.names = FALSE) #IDWS----------------------------------------------------------------------------- all.cost.to.bill <- read.csv(paste0(swd_results, "utility_idws.csv")) table(substr(all.cost.to.bill$pwsid,0,2)) all.cost.to.bill <- all.cost.to.bill %>% select(pwsid, service_area, category, hh_use, percent_income, annual_cost, percent_pays_more) %>% mutate(state = tolower(substr(pwsid, 0, 2))) %>% filter(category=="inside" | category=="outside" & percent_pays_more > 0) %>% filter(pwsid %in% unique(full.summary$pwsid)) #remove very small utilities because not enough data keep.list <- cs %>% filter(keep == "keep") all.cost.to.bill <- all.cost.to.bill %>% filter(pwsid %in% keep.list$pwsid) for (i in 1:length(hh_vols)){ zt <- all.cost.to.bill %>% filter(hh_use == hh_vols[i]) %>% select(pwsid, category, percent_income, annual_cost, percent_pays_more) %>% mutate(percent_pays_more = round(percent_pays_more,1), annual_cost = round(annual_cost, 0)) write.csv(zt, paste0(swd_html, "IDWS\\idws_",hh_vols[i],".csv"), row.names=FALSE); #can split by hh_volume print(hh_vols[i]) } ######################################################################################################################################################################################################### # # SAVE OUT WATER RATES DATA # ######################################################################################################################################################################################################### head(res.rates) #read in all original rates too #Load Rates Data ----------------------------------------------------------------------------------------------------------------------------------------- ca.meta <- read_excel(paste0(swd_data, "rates_data\\rates_ca.xlsx"), sheet="ratesMetadata") %>% mutate(state = "ca") %>% select(-notes) or.meta <- read_excel(paste0(swd_data, "rates_data\\rates_or.xlsx"), sheet="ratesMetadata") %>% mutate(state = "or") %>% select(-notes) %>% select(-GEOID) pa.meta <- read_excel(paste0(swd_data, "rates_data\\rates_pa.xlsx"), sheet="ratesMetadata") %>% mutate(state = "pa") %>% select(-notes) nc.meta <- read_excel(paste0(swd_data, "rates_data\\rates_nc.xlsx"), sheet="ratesMetadata") %>% mutate(state = "nc") %>% select(-notes) %>% mutate(pwsid = paste0("NC",str_remove_all(pwsid, "[-]"))) tx.meta <- read_excel(paste0(swd_data, "rates_data\\rates_tx.xlsx"), sheet="ratesMetadata") %>% mutate(state = "tx") %>% select(-notes) nm.meta <- read_excel(paste0(swd_data, "rates_data\\rates_nm.xlsx"), sheet="ratesMetadata") %>% mutate(state = "nm") %>% select(-notes) nj.meta <- read_excel(paste0(swd_data, "rates_data\\rates_nj.xlsx"), sheet="ratesMetadata") %>% mutate(state = "nj") %>% select(-notes) ct.meta <- read_excel(paste0(swd_data, "rates_data\\rates_ct.xlsx"), sheet="ratesMetadata") %>% mutate(state = "ct") %>% select(-notes) ks.meta <- read_excel(paste0(swd_data, "rates_data\\rates_ks.xlsx"), sheet="ratesMetadata") %>% mutate(state = "ks") %>% select(-notes) wa.meta <- read_excel(paste0(swd_data, "rates_data\\rates_wa.xlsx"), sheet="ratesMetadata") %>% mutate(state = "wa") %>% select(-notes) #condense to similar names all.meta <- rbind(ca.meta, or.meta, pa.meta, nj.meta, nm.meta, nc.meta, tx.meta, ct.meta, ks.meta, wa.meta) all.meta <- all.meta %>% mutate(date = as.Date(paste0(year,"-",month,"-",day), "%Y-%m-%d")) %>% filter(pwsid %in% main.data$pwsid) %>% select(pwsid, service_area, city_name, utility_name, date, year, month, day, service_type, website, last_updated) %>% rename(service = service_type) table(all.meta$service, useNA="ifany") #save most recent data all.meta <- all.meta %>% group_by(pwsid, service_area, city_name, utility_name, service) %>% filter(date == max(date)) %>% ungroup() #remove cities and just keep distinct service area and utility all.meta <- all.meta %>% filter(service != "stormwater" | service == "stormwater" & substr(website,0,4) == "http") %>% distinct() %>% mutate(service = ifelse(service=="sewer", "wastewater", service)) %>% mutate(service = ifelse(service=="sewer_septic", "septic/on-site", service)) %>% mutate(service = ifelse(service=="water", "drinking water", service)) all.meta <- all.meta %>% mutate(order = ifelse(service=="drinking water", 1, ifelse(service=="wastewater", 2, ifelse(service=="septic/on-site", 3, ifelse(service=="stormwater", 4, 5))))) %>% arrange(pwsid, order, utility_name, city_name) %>% distinct() table(all.meta$order, useNA="ifany") all.meta <- all.meta %>% select(-month, -day) #save file write.csv(all.meta, paste0(swd_html, "rates_metadata.csv"), row.names = FALSE) <file_sep>/www/scripts/ratesFunction.js /////////////////////////////////////////////////////////////////////////////////////////////////// // // RATES FUNCTION GRAPHIC SCRIPT /////////////// //// /////////////////////////////////////////////////////////////////////////////////////////////////// function onlyUnique(value, index, self) { return self.indexOf(value) === index; } function createBoxTrace(target){ //var selection = document.billToPlot.waterList; var selection = document.getElementsByName("waterList"); for (i=0; i<selection.length; i++) if (selection[i].checked==true) selWaterType = selection[i].value; plotRates(selectSystem, selectVolume, selWaterType); return selWaterType; } // end create trace function plotRates(selectSystem, selectVolume, selWaterType){ if(selectSystem === "none"){ document.getElementById('ratesTitle').innerHTML = "<strong>Select a utility to see monthly bills</strong>"; document.getElementById('ratesMetaTitle').innerHTML = "<strong>Select a utility to see table of providers</strong>"; document.getElementById('ratesMetaTable').innerHTML = ""; } if(selectSystem !== "none"){ //create a table for the metadata document.getElementById('ratesMetaTitle').innerHTML = "<strong>Utilities providing services in the selected service area</strong>"; document.getElementById('ratesMetaTable').innerHTML = ""; d3.csv("data/rates_metadata.csv").then(function(metaCSV){ var metaSel = metaCSV.filter(function(d) { return d.pwsid === selectSystem; }); //console.log(metaSel); //create table --- scroll options on table height, etc are in the css portion var myTable = "<br><table class='table table-bordered table-striped'>"; //create column header myTable += "<thead><tr>"; myTable += "<th>pwsid</th>"; myTable += "<th>service<br>area</th>"; myTable += "<th>city<br>name</th>"; myTable += "<th>utility<br>name</th>"; myTable += "<th>service<br>type</th>"; myTable += "<th>year rates<br>started</th>"; myTable += "<th>rates found<br>here</th>"; myTable += "<th>data last<br>updated</th>"; //end header and start body to loop through by activity myTable += "</thead><tbody'>"; //loop through and add headers based on number of services for (i = 0, len = metaSel.length; i < len; i++) { var urlText = "<a href=" + metaSel[i].website + " target = '_blank' style='color: '#3f97a8'><u>click here</u></a>"; if (metaSel[i].website.substring(0,4) !== "http") { urlText = "website not available"; } if (metaSel[i].utility_name === "Homeowners") { urlText = "Estimated Septic"; } //console.log(metaSel[i].website.substring(0,4)); myTable += "<tr>"; myTable += "<td>" + selectSystem + "</td>"; myTable += "<td>" + metaSel[i].service_area + "</td>"; myTable += "<td>" + metaSel[i].city_name + "</td>"; myTable += "<td>" + metaSel[i].utility_name + "</td>"; myTable += "<td>" + metaSel[i].service + "</td>"; myTable += "<td>" + metaSel[i].year + "</td>"; myTable += "<td>" + urlText + "</td>"; myTable += "<td>" + metaSel[i].last_updated + "</td>"; myTable += "</tr>"; } myTable += "</tbody></table><br>"; //load table var tableHeight = "350px"; if (metaSel.length <= 5) { tableHeight = "200px"; } document.getElementById('ratesMetaTable').style.maxHeight = tableHeight; document.getElementById("ratesMetaTable").innerHTML = myTable; });//end d3 }//end if statement //################################################################################################################################# // // PLOT MONTHLY DATA // //################################################################################################################################# //read in d3 with rates data Plotly.purge('monthBillChart'); Plotly.purge('commodityChart'); Plotly.purge('boxRateChart'); document.getElementById('monthBillChart').innerHTML=""; //read in csv d3.csv("data/rates/rates_" + selectVolume + ".csv").then(function(costCSV){ costCSV.forEach(function(d){ d.base_cost = +d.base_cost; d.fixed_surcharge = +d.fixed_surcharge; d.total = +d.total; d.vol_cost = +d.vol_cost; d.vol_surcharge = +d.vol_surcharge; d.zone_cost = +d.zone_cost; d.zone_surcharge = +d.zone_surcharge; d.total_surcharge = d.fixed_surcharge + d.vol_surcharge + d.zone_surcharge; d.total_vol = d.vol_cost + d.zone_cost; d.per_fixed = Math.round(d.base_cost/d.total*100*10)/10; }); //grap selected rates var selInsideRates = costCSV.filter(function(d) {return d.pwsid === selectSystem && d.category==="inside"; }); var selOutsideRates = costCSV.filter(function(d) {return d.pwsid === selectSystem && d.category==="outside"; }); //continue to filter based on selection costCSV = costCSV.filter(el => { return selCSV.find(element => { return element.pwsid === el.pwsid; }); }); //filter to inside and outside var insideRates = costCSV.filter(function(d) {return d.category === "inside"; }); var outsideRates = costCSV.filter(function(d) {return d.category === "outside" & d.total > 0; }); var selName = utilityDetails.filter(function(d) {return d.pwsid === selectSystem}) // console.log(insideRates); if(selInsideRates.length>0){ //PLOTLY BAR CHART OF RATES var xValue = [selName[0].service_area.substring(0,20)+"..."]; var waterBill = [selInsideRates.filter(function(d){return d.service==="water";})[0].total]; var sewerBill = [selInsideRates.filter(function(d){return d.service==="sewer";})[0].total]; var stormBill = [selInsideRates.filter(function(d){return d.service==="storm";})[0].total]; var insideTotal = selInsideRates.filter(function(d){return d.service==="total";})[0].total + selInsideRates.filter(function(d){return d.service==="storm";})[0].total; var chartTitle = "Total bill at " + selectVolume.toLocaleString() + " gallons for " + selName[0].service_area + " is ~$" + insideTotal.toFixed(0); if(selOutsideRates.length > 0){ xValue = ["Inside Bill", "Outside Bill"]; waterBill.push(selOutsideRates.filter(function(d){return d.service==="water";})[0].total); sewerBill.push(selOutsideRates.filter(function(d){return d.service==="sewer";})[0].total); stormBill.push(0); var outsideTotal = selOutsideRates.filter(function(d){return d.service==="total";})[0].total; chartTitle = chartTitle + "<span style='font-size: 12px;'>,<br>outside municipal boundaries the bill is $" + outsideTotal.toFixed(0) + "</span>"; } var maxY1 = selInsideRates.map(function(d){return d.total;}); var maxY2 = selOutsideRates.map(function(d){return d.total;}); if (maxY2.length == 0) { maxY2 = [0]; } var maxY = Math.max(d3.max(maxY1), d3.max(maxY2)); //PLOTLY BAR CHART OF RATES var waterBillTrace = { x: xValue, y: waterBill, type: "bar", name: "drinking water", hovertemplate: '$%{y} each month', marker: {color: "#00578a"}, }; var sewerBillTrace = { x: xValue, y:sewerBill, type: "bar", name: "wastewater", hovertemplate: '$%{y} each month', marker: {color: "#8a3300"}, }; var stormBillTrace = { x: xValue, y:stormBill, type: "bar", name: "stormwater", marker: {color: "#556b2f"}, hovertemplate: '$%{y} each month', }; var layout2 = { title: { text: chartTitle, font: {size: 14} }, yaxis: { title: 'Household Monthly Bill ($)', titlefont: {color: 'rgb(0, 0, 0)', size: 14 }, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, showline: false, showgrid: true, showticklabels: true, range: [0, maxY+20] }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: '', titlefont: {color: 'rgb(0, 0, 0)', size: 14}, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, }, height: 350, barmode: "stack", showlegend: true, legend: {x: 0.95, y: 0.98, xanchor: 'left', orientation: "v" }, margin: { t: 70, b: 30, r: 40, l: 45 }, }; data2 = [waterBillTrace, sewerBillTrace, stormBillTrace]; Plotly.newPlot('monthBillChart', data2, layout2, configNoAutoDisplay); }//end if selectSystem !== "none" if(selectSystem === "none"){ document.getElementById('monthBillChart').innerHTML = ""; } //############################################################################################################## // Plot boxplots based on if they select water or wastewater //############################################################################################################## // BOXPLOT TO SHOW RANGE OF RATES //############################################################################################################## //pull out selected rates var selColorType; var selColorOutType; if (selWaterType === "water") { selColorType = "blue"; selColorOutType = "#9d9dff"; } if (selWaterType === "sewer") { selColorType = "#8a3300"; selColorOutType = "#ff9d63"; } var xFixed; var xVariable; var xPercentFixed; var xMonth; var xSurcharge; var xSelFixed; var xSelVariable; var xSelPercentFixed; var xSelMonth; var xSelSurcharge; var xSelLegend; var xOSelFixed; var xOSelVariable; var xOSelPercentFixed; var xOSelMonth; var xOSelSurcharge; var yFixed = ["Fixed <br> Charge ($) "]; var xFixedColor = [selColorType]; var xSize = [12]; var yCommodity = ["Usage <br> Charge ($) "]; var yperFixed = ["% Fixed"]; var ySurcharge = ["Surcharge <br> Charge ($) "]; var yMonth = ["Monthly <br> Bill ($) "]; //use costCSV to get both inside and outside rates var waterInside = costCSV.filter(function(d){return d.service === selWaterType; }); var waterSelInside = selInsideRates.filter(function(d){return d.service === selWaterType; }); //var waterOutside = outsideRates.filter(function(d){return d.service === selWaterType; }); var waterSelOutside = selOutsideRates.filter(function(d) {return d.service === selWaterType; }); //set variables xFixed = waterInside.map(function(d) { return d.base_cost;}); xVariable = waterInside.map(function(d) {return d.total_vol; }); xPercentFixed = waterInside.map(function(d) {return d.per_fixed; }); xSurcharge = waterInside.map(function(d) {return d.total_surcharge; }); xMonth = waterInside.map(function(d) {return d.total; }); if (selectSystem !== "none"){ xSelFixed = [waterSelInside[0].base_cost]; xSelVariable = [waterSelInside[0].total_vol]; xSelPercentFixed = [waterSelInside[0].per_fixed]; xSelSurcharge = [waterSelInside[0].total_surcharge]; xSelMonth = [waterSelInside[0].total]; xSelLegend = ["selected: all or inside rates"]; if (selOutsideRates.length > 0){ xOSelFixed = waterSelOutside[0].base_cost; xSelFixed.push(xOSelFixed); yFixed.push(yFixed[0]); xFixedColor.push(selColorOutType); xSize.push(8); xOSelVariable = waterSelOutside[0].total_vol; xSelVariable.push(xOSelVariable); yCommodity.push(yCommodity[0]); xOSelPercentFixed = waterSelOutside[0].per_fixed; xSelPercentFixed.push(xOSelPercentFixed); yperFixed.push(yperFixed[0]); xOSelSurcharge = waterSelOutside[0].total_surcharge; xSelSurcharge.push(xOSelSurcharge); ySurcharge.push(ySurcharge[0]); xOSelMonth = waterSelOutside[0].total; xSelMonth.push(xOSelMonth); yMonth.push(yMonth[0]); xSelLegend.push("selected: outside rates"); } } //console.log(xSelVariable); console.log(xSelPercentFixed); //CREATE PLOT var fixedtrace = { y: "Fixed Charge ($)", x: xFixed, marker: {color: '#00578a', size: 2}, opacity: 0.6, type: 'box', boxpoints: 'all', name: "Fixed <br> Charge ($) ", showlegend: false }; var selFixedtrace = { y: yFixed, x: xSelFixed, marker: { color: xFixedColor, size: xSize, line: {color: 'black', width: 2 }, }, line: {width: 0, opacity: 0}, hovertemplate: "$%{x} of monthly bill is fixed", type: "markers", opacity: 1, text: xSelLegend, showlegend: false }; var percentFixedtrace = { y: "Percent Fixed", x: xPercentFixed, marker: {color: '#8a3300', size: 2}, opacity: 0.6, type: 'box', boxpoints: 'all', name: "% Fixed", showlegend: false }; var selPerFixedtrace = { y: yperFixed, x: xSelPercentFixed, marker: {color: xFixedColor, size: xSize, line: {color: 'black', width: 2 }, }, line: {width: 0, opacity: 0}, hovertemplate: "%{x}% of monthly bill is fixed", opacity: 1, type: "markers", name: "", showlegend: false }; var variabletrace = { y: "Usage Charge ", x: xVariable, marker: {color: '#00578a', size: 2}, opacity: 0.6, type: 'box', boxpoints: 'all', showlegend: false, name: "Usage <br> Charge ($) " }; var selVariabletrace = { y: yCommodity, x: xSelVariable, marker: { color: xFixedColor, size: xSize, line: {color: 'black', width: 2 }, }, line: {width: 0, opacity: 0}, hovertemplate: "$%{x} of bill based on usage", opacity: 1, type: "marker", name: "", showlegend: false }; var surchargetrace = { y: "Surcharge Charge", x: xSurcharge, marker: {color: '#00578a', size: 2}, opacity: 0.6, type: 'box', boxpoints: 'all', showlegend: false, name: "Surcharge <br> Charge ($) " }; var selSurchargetrace = { y: ySurcharge, x: xSelSurcharge, marker: { color: xFixedColor, size: xSize, line: {color: 'black', width: 2 }, }, line: {width: 0, opacity: 0}, hovertemplate: "$%{x} of monthly bill is a surcharge", opacity: 1, type: "markers", name: "", showlegend: false }; var monthtrace = { y: "Monthly Bill", x: xMonth, marker: {color: '#00578a', size: 2}, opacity: 0.6, type: 'box', boxpoints: 'all', showlegend: false, name: "Monthly <br> Bill ($) " }; var selMonthtrace = { y: yMonth, x: xSelMonth, marker: {color: xFixedColor, size: xSize, line: {color: 'black', width: 2 }, }, line: {width: 0, opacity: 0}, hovertemplate: "$%{x} is the monthly bill", opacity: 1, type: "markers", name: "selected: inside or all rates", showlegend: true }; var selWaterType2; if(selWaterType === "water"){ selWaterType2 = "drinking water"; } if(selWaterType === "sewer"){ selWaterType2 = "wastewater"; } var boxTitle = "Rate components for " + selWaterType2; var layout3 = { title: { text: boxTitle, font: {size: 14} }, yaxis: { title: '', titlefont: {color: 'rgb(0, 0, 0)', size: 14 }, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, showline: false, showgrid: false, showticklabels: true, }, xaxis: { showline: false, showgrid: true, showticklabels: true, title: '<span style="color: #00578a">Bill ($)</span> or <span style="color: #8a3303">Percent</span>', titlefont: {color: 'rgb(0, 0, 0)', size: 14}, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, // range: [0, 100] }, height: 400, showlegend: false, //legend: {x: 1, y: 0.5, xanchor: 'right'}, margin: {t: 70, b: 30, r: 30, l: 75}, fixedrange: false, shapes: [ //legend circles and boxes { type: 'circle', xref: 'paper', yref: 'paper', //ref is assigned to x values x0: 0.75, x1: 0.775, y0: 0.57, y1: 0.60, line: {color: 'black', width: 1}, fillcolor: selColorType }, { type: 'circle', xref: 'paper', yref: 'paper', //ref is assigned to x values x0: 0.75, x1: 0.775, y0: 0.49, y1: 0.52, line: {color: 'black', width: 1}, fillcolor: selColorOutType }, { type: 'circle', xref: 'paper', yref: 'paper', x0: 0.76, x1:0.77, y0: 0.66, y1: 0.67, fillcolor: '#00578a', line: {color: 'black', width: 0} } ], annotations: [ { xref: 'paper', yref: 'paper', x: 0.8, y: 0.69, xanchor: 'left', yanchor: 'top', text: "all utilities", font: {family: 'verdana', size: 11, color: '#00578a'}, showarrow: false }, { xref: 'paper', yref: 'paper', x: 0.8, y: 0.63, xanchor: 'left', yanchor: 'top', text: "selected: inside<br> or all rates", font: {family: 'verdana', size: 11, color: selColorType}, showarrow: false }, { xref: 'paper', yref: 'paper', x: 0.8, y: 0.55, xanchor: 'left', yanchor: 'top', text: "selected: outside <br> rates", font: {family: 'verdana', size: 11, color: selColorOutType}, showarrow: false }, ] }; if (selectSystem === "none"){ data3 = [percentFixedtrace, fixedtrace, variabletrace, surchargetrace, monthtrace]; } if (selectSystem !== "none"){ data3 = [percentFixedtrace, selPerFixedtrace, fixedtrace, selFixedtrace, variabletrace, selVariabletrace, surchargetrace, selSurchargetrace, monthtrace, selMonthtrace]; } Plotly.newPlot('boxRateChart', data3, layout3, configNoAutoDisplay); });//end D3 //############################################################################################################## // PLOT COMMODITY CHARGE COMPARISON BASED ON VOLUME d3.csv("data/commodity_price.csv").then(function(price){ price.forEach(function(d){ d.commodity_unit_price = +d.commodity_unit_price; d.hh_use = +d.hh_use; d.total = +d.total; }); //pull out selected system var selPriceInside = price.filter(function(d){ return d.pwsid === selectSystem && d.service===selWaterType && d.category==="inside"; }); var selPriceOutside = price.filter(function(d){ return d.pwsid === selectSystem && d.service===selWaterType && d.category==="outside"; }); //continue to filter based on selection //filter by map selections price = price.filter(el => { return selCSV.find(element => { return element.pwsid === el.pwsid; }); }); //filter less than 0.20 to save space priceAll = price.filter(function(d){ return d.service === selWaterType && d.pwsid !== selectSystem; }); //pull out selected rates var selColorType; var selColorOutType; if (selWaterType === "water") { selColorType = "blue"; selColorOutType = "#9d9dff"; } if (selWaterType === "sewer") { selColorType = "#8a3300"; selColorOutType = "#ff9d63"; } //pull out selected state var dataPrice = []; var xUse = [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000]; var pwsidOther = priceAll.filter(function(d) {return d.hh_use === 4000; }); pwsidOther = pwsidOther.map(function(d) {return d.pwsid; }); var yOther = []; var insideTrace; var legendShow; for (i=0; i < pwsidOther.length; i++){ tempSelect = pwsidOther[i]; temp = priceAll.filter(function(d) {return d.pwsid === tempSelect; }); //tempName = temp.map(function(d) {return d.service_area.substring(0,15) + ", " + d.state.toUpperCase(); }); tempName = tempSelect; yOther = temp.map(function(d){ return d.commodity_unit_price; }); if (i===0) {legendShow = true; } if (i > 0) {legendShow = false; } //create individual trace insideTrace = { x: xUse, y: yOther, mode: 'lines', type: 'scatter', hovertemplate: tempName, opacity: 0.4, line: {color: '#c5c5c5', width: 1}, //light coral showlegend: legendShow, name: "all utilities" }; //push trace dataPrice.push(insideTrace); } // end for loop //draw selected price var selyin; var selTrace; var selyout; var selOutTrace; var selName = utilityDetails.filter(function(d) {return d.pwsid === selectSystem}) if (selPriceOutside.length > 0 ) { selyout = selPriceOutside.map(function(d) {return d.commodity_unit_price; }); selOutTrace = { y: selyout, x: xUse, marker: {size: 8, color: selColorOutType, line: {color: 'black', width: 1} }, line: {color: selColorOutType, width: 3}, mode: 'lines+markers', type: 'scatter', name: selName[0].service_area.substring(0,6)+"...", hovertemplate: '$%{y} per 1k gallons <br> at %{x} gallons', showlegend: true, name: 'selected: outside usage rates' }; dataPrice.push(selOutTrace); } if (selPriceInside.length > 0 ) { //for (i=0; i < selPriceInside.length; i++){ //tempSelect = selyin = selPriceInside.map(function(d) {return d.commodity_unit_price; }); selTrace = { y: selyin, x: xUse, marker: {size: 8, color: selColorType, line: {color: 'black', width: 1} }, line: {color: selColorType, width: 3}, mode: 'lines+markers', type: 'scatter', name: selName[0].service_area.substring(0,6)+"...", hovertemplate: '$%{y} per 1k gallons <br> at %{x} gallons', legend: "true", name: "selected: inside or all usage rates" }; //}// end selTrace Loop dataPrice.push(selTrace); } var layoutPrice = { title: { text: "Usage cost per 1,000 gallons of water", font: {size: 14} }, yaxis: { title: 'Cost per thousand gallons ($)', titlefont: {color: 'rgb(0, 0, 0)', size: 14 }, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, showline: false, showgrid: true, showticklabels: true, range: [0, 20] }, xaxis: { showline: false, showgrid: true, showticklabels: true, title: 'Volume of water (gallons)', titlefont: {color: 'rgb(0, 0, 0)', size: 14}, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, range: [0, 16000] }, hovermode: 'closest', height: 400, showlegend: true, legend: {orientation: "h", x: 0, y: 1}, margin: { t: 70, b: 30, r: 30, l: 40 }, }; Plotly.newPlot('commodityChart', dataPrice, layoutPrice, configNoAutoDisplay); });//end d3 for commodity }//end plotRates function //plotRates("NC0332010", selectVolume, selWaterType); //plotRates("PA5650032", selectVolume); <file_sep>/rcode/access4_sdwis_data.R ####################################################################################################################################################### # # Downloads and Updates EPA SDWIS data for utilities # CREATED BY <NAME> # FEBRUARY 2021 # ######################################################################################################################################################## ###################################################################################################################################################################### # # CALL API FOR SYSTEMS # ###################################################################################################################################################################### #THIS IS NEEDED TO GET DETAILS ABOUT SYSTEMS - SUCH AS OWNERSHIP AND SIZE baseURL = 'https://data.epa.gov/efservice/WATER_SYSTEM/PWS_TYPE_CODE/CWS/PWS_ACTIVITY_CODE/A/STATE_CODE/' fileType = '/EXCEL' # This is loads in the locations and the urls for other data accessible via web services state.code <- toupper(state.list) i=1 projectsURL = paste0(baseURL,state.code[i],fileType) #projectsURL = paste0(baseURL,pwsidList[i],fileType) df <- read.csv(url(projectsURL)) #convert all columns into characters instead of factors. Removes error in loop and converting variables to NA df <- df %>% mutate_all(as.character) #Loop through the rest of the states for (i in 2:length(state.code)){ projectsURL = paste0(baseURL,state.code[i],fileType) foo <- read.csv(url(projectsURL)) foo <- foo %>% mutate_all(as.character) #if more than 100,000 rows # if(dim(foo)[1] = 100001){ # foo2 <- read.csv(paste0(baseURL, state.code[i], "/ROWS/100001:200000",fileType)) # foo2 <- foo2 %>% mutate_all(as.character) # foo <- rbind(foo, foo2) # } df <- rbind(df, foo) print(paste0("Percent Done: ", round(i/length(state.code)*100,2))) } #rename headers df.headers <- gsub("^.*\\.","",colnames(df)); #remove "WATER_SYSTEM." colnames(df) <- df.headers df$PWSID_STATE <- tolower(substr(df$PWSID,0,2)) #remove columns that are not needed df <- df %>% select(-c(ADMIN_NAME, EMAIL_ADDR, PHONE_NUMBER, ADDRESS_LINE1, ADDRESS_LINE2, POP_CAT_2_CODE, POP_CAT_3_CODE, POP_CAT_4_CODE, POP_CAT_5_CODE, POP_CAT_11_CODE, X, LT2_SCHEDULE_CAT_CODE, DBPR_SCHEDULE_CAT_CODE, FAX_NUMBER, PHONE_EXT_NUMBER, ALT_PHONE_NUMBER)) #limit to active systems df2 <- df %>% filter(PWS_TYPE_CODE == "CWS") %>% filter(PWSID_STATE %in% state.list) %>% filter(PWS_ACTIVITY_CODE != "I") %>% filter(IS_SCHOOL_OR_DAYCARE_IND == "N") #save out files by cws, NTNCWS and TNCWS write.csv(df2, paste0(swd_data,"sdwis\\cws_systems.csv"), row.names = FALSE) ################################################################################################################################################################################################################# rm(baseURL, fileType, state.code, projectsURL, df, foo, df2) <file_sep>/rcode/global0_set_apis_libraries.R ####################################################################################################################################################### # # DOWNLOADS AND CREATES GEOJSON FILES FOR MAP LAYERS IN THE NORTH CAROLINA WATER SUPPLY DASHBOARD # CREATED BY <NAME> # FEBRUARY 2021 # ######################################################################################################################################################## ###################################################################################################################################################################### # # LOAD LIBRARIES # ###################################################################################################################################################################### ## First specify the packages of interest packages = c("rstudioapi", "readxl", "curl", "sf", "rgdal", "spData", "raster", "leaflet", "rmapshaper","geojsonio", "tidycensus", "jsonlite", "rvest", "purrr", "httr", "tidyverse", "lubridate", "plotly", "stringr") ## Now load or install&load all package.check <- lapply( packages, FUN = function(x) { if (!require(x, character.only = TRUE)) { install.packages(x, dependencies = TRUE) library(x, character.only = TRUE) } } ) #New SF package creates problems sf::sf_use_s2(FALSE) options(scipen=999) #changes scientific notation to numeric rm(list=ls()) #removes anything stored in memory rm(list = setdiff(ls(), lsf.str())) #removes anything bunt functions ###################################################################################################################################################################### ###################################################################################################################################################################### # # SET GLOBAL VARIABLES # ###################################################################################################################################################################### #state lists --> ad a state and its fips code as needed state.list <- c("ca", "pa", "nc", "tx", "or", "nj", "nm", "ct", "ks", "wa"); state.fips <- c("06", "42", "37", "48", "41", "34", "35", "09", "20", "53"); state.df <- cbind(state.list, state.fips) %>% as.data.frame(); state.df selected.year <- 2019; folder.year <- 2021; # Set working directory to source file location if code is in similar directory to data files #source_path = rstudioapi::getActiveDocumentContext()$path #setwd(dirname(source_path)) swd_data <- paste0("data_",folder.year,"\\") swd_results <- paste0("results_",folder.year,"\\") swd_html <- paste0("www\\data\\") #census api key - census_api_key("YOUR CENSUS KEY HERE", install=TRUE, overwrite=TRUE); readRenviron("~/.Renviron") #useful function `%notin%` = function(x,y) !(x %in% y); #function to get what is not in the list <file_sep>/www/scripts/demographicFunctions.js /////////////////////////////////////////////////////////////////////////////////////////////////// // // DEMOGRAPHICS GRAPHIC SCRIPT /////////////// //// /////////////////////////////////////////////////////////////////////////////////////////////////// //############################################################################################ // PLOT DATA USING UTILITY_RATES_TABLE_CURRENT //############################################################################################ function plotDemographics(selectSystem) { //remove too small document.getElementById("tooSmall").innerHTML = ""; document.getElementById("annualBLSTitle").innerHTML = "How has unemployment changed over time?"; document.getElementById("monthBLSTitle").innerHTML = "How has COVID-19 affected unemployment?"; //update title if (selectSystem === "none") { document.getElementById("popTimeTitle").innerHTML = "Is population growing, shrinking, or stable?"; document.getElementById("ageTitle").innerHTML = "What percentage of customers are within working age?"; document.getElementById("incomeTitle").innerHTML = "What is the household income distribution?"; document.getElementById("monthBLSTitle").innerHTML = "How has COVID-19 affected unemployment?"; document.getElementById("buildTitle").innerHTML = "When were houses built (infrastructure age)?"; } var plotHeight = 250; //read in csv // d3.csv("data/all_utility_census_summary.csv").then(function (demCSV) { // demCSV.forEach(function (d) { // d.pop1990 = +d.pop1990; // d.pop2000 = +d.pop2000; // d.pop2010 = +d.pop2010; // d.pop2018 = +d.cwsPop; //THIS ONE NEEDS TO HAVE LAST DATE UPDATED EACH YEAR // d.under18 = +d.under18; // d.age18to34 = +d.age18to34; // d.age35to59 = +d.age35to59; // d.age60to64 = +d.age60to64; // d.over65 = +d.over65; // d.Asian = +d.Asian; // d.Black = +d.Black; // d.Native = +d.Native; // d.Other = +d.Other; // d.Hispanic = +d.Hispanic; // d.White = +d.White; // d.d0to24k = +d.d0to24k; // d.d25to49k = +d.d25to49k; // d.d50to74k = +d.d50to74k; // d.d75to100k = +d.d75to100k; // d.d100to125k = +d.d100to125k; // d.d125to150k = +d.d125to150k; // d.d150kmore = +d.d150kmore; // d.built_2010later = +d.built_2010later; // d.built_2000to2009 = +d.built_2000to2009; // d.built_1990to1999 = +d.built_1990to1999; // d.built_1980to1989 = +d.built_1980to1989; // d.built_1970to1979 = +d.built_1970to1979; // d.built_1960to1969 = +d.built_1960to1969; // d.built_1950to1959 = +d.built_1950to1959; // d.built_1940to1949 = +d.built_1940to1949; // d.built_1939early = +d.built_1939early; // }); //filter demCSV and only keep those have enough data demCSV = demData.filter(function (d) { return d.keep === "keep"; }); var selSystem = demData.filter(function (d) { return d.pwsid === selectSystem && d.keep === "keep"; }); //continue to filter based on selection // if (selectState !== "none") { // selCSV = selCSV.filter(function (d) { // return d.state === selectState; // }); // } // if (selectSize !== "none") { // selCSV = selCSV.filter(function (d) { // return d.sizeCategory === selectSize; // }); // } // if (selectOwner !== "none") { // selCSV = selCSV.filter(function (d) { // return d.owner_type === selectOwner; // }); // } //console.log(selCSV) demCSV = demCSV.filter(el => { return selCSV.find(element => { return element.pwsid === el.pwsid; }); }); //console.log(demCSV); //pull out details of selected system selSystemDetails = utilityDetails.filter(function (d){ return d.pwsid === oldSystem; //selectSystem; Need to use old system if change characteristics don't match }); //if not enough data - leave a message saying so and pop out of the function if ((selectSystem !== "none") & (selSystem.length === 0)) { document.getElementById("tooSmall").innerHTML = "This system was too small to estimate census characteristics"; document.getElementById("popTimeTitle").innerHTML = "Is population growing, shrinking, or stable?"; document.getElementById("ageTitle").innerHTML = "What percentage of customers are within working age?"; document.getElementById("incomeTitle").innerHTML = "What is the household income distribution?"; document.getElementById("monthBLSTitle").innerHTML = "How has COVID-19 affected unemployment?"; document.getElementById("buildTitle").innerHTML = "When were houses built (infrastructure age)?"; } //########################################################################################################################### // POPULATION OVER TIME //########################################################################################################################### //popoverTime var maxPop; if ((selectSystem !== "none") & (selSystem.length > 0)) { maxPop = selSystem[0].pop2018 * 1.5; var perChange = Math.round( (selSystem[0].pop2018 / selSystem[0].pop1990) * 100 * 10 ) / 10; var direction; if (perChange >= 105) { direction = " has grown to "; } if (perChange <= 95) { direction = " has shrunk to "; } if (perChange > 95 && perChange < 105) { direction = " has stayed at "; } //redo title document.getElementById("popTimeTitle").innerHTML = selSystemDetails[0].service_area + direction + perChange + "% of 1990 population"; } //end if selected if ((selectSystem === "none") | (selSystem.length === 0)) { pop2018all = demCSV.map(function (d) { return d.pop2018; }); maxPop = Math.max(pop2018all) * 1.5; } //PLOTLY BAR CHART OF RATES // create all traces pwsidAll = demCSV.map(function (d) { return d.pwsid; }); //set up variables //pop var yAll = []; var dataPop = []; var xYear = [1990, 2000, 2010, Number(currentYear)]; var allTrace; //age var dataAge = []; var allTrace2; var yAll2 = []; //race var dataRace = []; var allTrace3; var yAll3 = []; //income var dataIncome = []; var allTrace4; var yAll4 = []; //building age var dataBuild = []; var allTrace5; var yAll5 = []; // loop through and create variables and traces for (i = 0; i < pwsidAll.length; i++) { tempSelect = pwsidAll[i]; temp = demCSV.filter(function (d) { return d.pwsid === tempSelect; }); //populations------------------- yAll = [ temp[0].pop1990, temp[0].pop2000, temp[0].pop2010, temp[0].pop2018, ]; allTrace = { x: xYear, y: yAll, mode: "lines", type: "scatter", hoverinfo: "skip", opacity: 0.3, line: { color: "#c5c5c5", width: 1 }, }; dataPop.push(allTrace); //---------------------- //age ------------------------------------------ yAll2 = [ temp[0].under18, temp[0].age18to34, temp[0].age35to59, temp[0].age60to64, temp[0].over65, ]; //create individual trace allTrace2 = { y: [ "children <br> (under 18)", "working age <br> (18 to 34)", "working age <br> (35 to 59)", "near retirement <br> (60-64)", "retirement age <br> (over 65)", ], x: yAll2, type: "scatter", mode: "lines", opacity: 0.3, hoverinfo: "skip", line: { color: "#c5c5c5" }, }; dataAge.push(allTrace2); //-------------------------------------- //race--------------------------------------------------- yAll3 = [ temp[0].Other, temp[0].White, temp[0].Native, temp[0].Black, temp[0].Asian, temp[0].Hispanic, ]; allTrace3 = { y: [ "Other ", "White ", "Native ", "Black ", "Asian ", "Hispanic ", ], x: yAll3, type: "box", orientation: "h", //type: 'scatter', mode: 'lines', opacity: 0.3, hoverinfo: "skip", line: { color: "#c5c5c5" }, }; dataRace.push(allTrace3); //------------------------------------------------- //income ------------------------------------------------------------------------------ yAll4 = [ temp[0].d0to24k, temp[0].d25to49k, temp[0].d50to74k, temp[0].d75to100k, temp[0].d100to125k, temp[0].d125to150k, temp[0].d150kmore, ]; allTrace4 = { x: [ "$0-<br>24k", "$25-<br>49k", "$50-<br>74k", "$75-<br>99k", "$100-<br>124k", "$125-<br>149k", ">$150k", ], y: yAll4, type: "scatter", mode: "lines", opacity: 0.3, hoverinfo: "skip", line: { color: "#c5c5c5" }, }; dataIncome.push(allTrace4); //build age ------------------------------------------------------------------------------ yAll5 = [ temp[0].built_1939early, temp[0].built_1940to1949, temp[0].built_1950to1959, temp[0].built_1960to1969, temp[0].built_1970to1979, temp[0].built_1980to1989, temp[0].built_1990to1999, temp[0].built_2000to2009, temp[0].built_2010later, ]; allTrace5 = { x: [ "<1939", "1940-<br>1949", "1950-<br>1959", "1960-<br>1969", "1970-<br>1979", "1980-<br>1989", "1990-<br>1999", "2000-<br>2009", ">2010", ], y: yAll5, type: "scatter", mode: "lines", opacity: 0.3, hoverinfo: "skip", line: { color: "#c5c5c5" }, }; dataBuild.push(allTrace5); } // end for loop //####################################### POPULATION ############################################# if (selectSystem !== "none" && selSystem.length > 0) { //selectBurden !== "Unknown" | var popTrace = { x: [1990, 2000, 2010, Number(currentYear)], y: [ selSystem[0].pop1990, selSystem[0].pop2000, selSystem[0].pop2010, selSystem[0].pop2018, ], type: "scatter", mode: "lines+markers", text: selectSystem, name: "selected<br>utility", marker: { color: "#00578a", size: 10, line: { color: "black", width: 2 }, }, line: { color: "black", width: 2 }, hovertemplate: "Population: " + numberWithCommas("%{y}") + " in %{x}", }; dataPop.push(popTrace); } // var layoutPop = { yaxis: { title: "Population", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: true, showticklabels: true, range: [0, maxPop], }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: "", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, }, height: plotHeight, showlegend: false, // legend: {x: 0, y: 0, xanchor: 'left', orientation: "h" }, margin: { t: 30, b: 40, r: 30, l: 50 }, }; Plotly.newPlot("popTimeChart", dataPop, layoutPop, configNoAutoDisplay); //########################################################################################################################### //########################################################################################################################### // AGE BREAKOUT OVER TIME //########################################################################################################################### if (selectSystem !== "none" && selSystem.length > 0) { var working = selSystem[0].age18to34 + selSystem[0].age35to59 + selSystem[0].age60to64; document.getElementById("ageTitle").innerHTML = Math.round(working) + "% of " + selSystemDetails[0].service_area + " population is within working age"; ageColor = ["#8a3300", "#00578a", "#00578a", "#cd8536", "#8a3300"]; var ageTrace = { x: [ selSystem[0].under18.toFixed(1), selSystem[0].age18to34.toFixed(1), selSystem[0].age35to59.toFixed(1), selSystem[0].age60to64.toFixed(1), selSystem[0].over65.toFixed(1), ], y: [ "children <br> (under 18)", "working age <br> (18 to 34)", "working age <br> (35 to 59)", "near retirement <br> (60-64)", "retirement age <br> (over 65)", ], //type: "bar", type: "scatter", mode: "lines+markers", name: "selected<br>utility", marker: { color: ageColor, size: 12, line: { color: "black", width: 2 }, }, line: { color: "black", width: 2 }, hovertemplate: "%{x}% of population %{y}", }; dataAge.push(ageTrace); } //end if var layoutAge = { yaxis: { title: "", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: false, showticklabels: true, }, xaxis: { showline: false, showgrid: true, showticklabels: true, title: "Percent of Population (%)", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, range: [0, 80], }, height: plotHeight, showlegend: false, margin: { t: 30, b: 40, r: 40, l: 100 }, }; Plotly.newPlot("ageChart", dataAge, layoutAge, configNoAutoDisplay); //########################################################################################################################### // RACIAL BREAKOUT OVER TIME //########################################################################################################################### //PLOTLY BAR CHART OF RATES if (selectSystem !== "none" && selSystem.length > 0) { raceColor = [ "#00578a", "#00578a", "#00578a", "#00578a", "#00578a", "#8a3300", ]; var raceTrace = { x: [ selSystem[0].Other.toFixed(1), selSystem[0].White.toFixed(1), selSystem[0].Native.toFixed(1), selSystem[0].Black.toFixed(1), selSystem[0].Asian.toFixed(1), selSystem[0].Hispanic.toFixed(1), ], y: [ "Other ", "White ", "Native ", "Black ", "Asian ", "Hispanic ", ], type: "scatter", mode: "markers", name: "selected<br>utility", hovertemplate: "%{x}% of population<br>identified as %{y}", marker: { color: raceColor, size: 12, line: { color: "black", width: 2 }, }, }; dataRace.push(raceTrace); //console.log("race = ", selSystem[0].Other + selSystem[0].White + selSystem[0].Native + selSystem[0].Hispanic + selSystem[0].Black + selSystem[0].Asian) } //end if var layoutRace = { yaxis: { title: "", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: true, showticklabels: true, }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: "Percent of Population (%)", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, range: [0, 100], }, height: plotHeight, showlegend: false, margin: { t: 30, b: 30, r: 40, l: 70 }, }; Plotly.newPlot("raceChart", dataRace, layoutRace, configNoAutoDisplay); //########################################################################################################################### // INCOME BREAKOUT OVER TIME //########################################################################################################################### if (selectSystem !== "none" && selSystem.length > 0) { //var morethan75 = selSystem[0].d75to100k + selSystem[0].d100to125k + selSystem[0].d125to150k + selSystem[0].d150kmore; var lessthan75 = 100 - (selSystem[0].d75to100k + selSystem[0].d100to125k + selSystem[0].d125to150k + selSystem[0].d150kmore); document.getElementById("incomeTitle").innerHTML = Math.round(lessthan75) + "% of " + selSystemDetails[0].service_area + " households earn less than $75,000"; var incomeTrace = { y: [ selSystem[0].d0to24k.toFixed(1), selSystem[0].d25to49k.toFixed(1), selSystem[0].d50to74k.toFixed(1), selSystem[0].d75to100k.toFixed(1), selSystem[0].d100to125k.toFixed(1), selSystem[0].d125to150k.toFixed(1), selSystem[0].d150kmore.toFixed(1), ], x: [ "$0-<br>24k", "$25-<br>49k", "$50-<br>74k", "$75-<br>99k", "$100-<br>124k", "$125-<br>149k", ">$150k", ], text: [ "less than $24k", "$25k to $49k", "$50k to $74k", "$75k to $99k", "$100k to $124k", "$125k to $149k", "more than $150k", ], //type: "bar", type: "scatter", mode: "lines+markers", name: "selected<br>utility", marker: { color: "#00578a", size: 10, line: { color: "black", width: 2 }, }, line: { color: "black", width: 2 }, hovertemplate: "%{y}% of households<br>earn %{text}", }; dataIncome.push(incomeTrace); } //end if var layoutIncome = { yaxis: { title: "Percent Households (%)", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: true, showticklabels: true, range: [0, 50], }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: "Income Range", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, bargap: 0, }, height: plotHeight, showlegend: false, margin: { t: 30, b: 45, r: 40, l: 35 }, }; Plotly.newPlot( "incomeChart", dataIncome, layoutIncome, configNoAutoDisplay ); //########################################################################################################################### // BUILDING AGE BREAKOUT OVER TIME //########################################################################################################################### if (selectSystem !== "none" && selSystem.length > 0) { //console.log(selSystem); var olderthan70 = selSystem[0].built_1940to1949 + selSystem[0].built_1939early; var olderthan30 = selSystem[0].built_1990to1999 + selSystem[0].built_2000to2009 + selSystem[0].built_2010later; //console.log("Total Building: " + olderthan30 + olderthan70 + selSystem[0].built_1950to1959 + selSystem[0].built_1960to1969 + // selSystem[0].built_1970to1979 + selSystem[0].built_1980to1989); document.getElementById("buildTitle").innerHTML = Math.round(olderthan70) + "% of " + selSystemDetails[0].service_area + " households are more than 70 years old (pre-1950) and " + Math.round(100 - olderthan30) + "% are more than 30 years old (pre-1990)"; var buildTrace = { y: [ selSystem[0].built_1939early.toFixed(1), selSystem[0].built_1940to1949.toFixed(1), selSystem[0].built_1950to1959.toFixed(1), selSystem[0].built_1960to1969.toFixed(1), selSystem[0].built_1970to1979.toFixed(1), selSystem[0].built_1980to1989.toFixed(1), selSystem[0].built_1990to1999.toFixed(1), selSystem[0].built_2000to2009.toFixed(1), selSystem[0].built_2010later.toFixed(1), ], x: [ "<1939", "1940-<br>1949", "1950-<br>1959", "1960-<br>1969", "1970-<br>1979", "1980-<br>1989", "1990-<br>1999", "2000-<br>2009", ">2010", ], text: [ "before 1939", "1940 to 1949", "1950 to 1959", "1960 to 1969", "1970 to 1979", "1980 to 1989", "1990 to 1999", "2000 to 2009", ">2010", ], //type: "bar", type: "scatter", mode: "lines+markers", name: "selected<br>utility", marker: { color: "#00578a", size: 10, line: { color: "black", width: 2 }, }, line: { color: "black", width: 2 }, hovertemplate: "%{y}% of households<br>built %{text}", }; dataBuild.push(buildTrace); } //end if var layoutBuild = { yaxis: { title: "Percent Households (%)", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: true, showticklabels: true, range: [0, 60], }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: "Decade Households Built", titlefont: { color: "rgb(0, 0, 0)", size: 12 }, tickfont: { color: "rgb(0, 0, 0)", size: 10 }, bargap: 0, }, height: plotHeight, showlegend: false, margin: { t: 15, b: 50, r: 40, l: 35 }, }; Plotly.newPlot( "buildChart", dataBuild, layoutBuild, configNoAutoDisplay ); //}); //endD3 //######################################################################## //Unemployment data - call in variable blsCSV var yAllBLS = []; var allBLSTrace; var xAll; var dataBLS = []; // loop through and create variables and traces //as long as loop through same pwsidAll list as above, I don't need to add state, owner, etc. for (i = 0; i < pwsidAll.length; i++) { tempSelect = pwsidAll[i]; temp = blsData.filter(function (d) { return d.pwsid === tempSelect; }); xAll = temp.map(function (d) { return d.year; }); yAllBLS = temp.map(function (d) { return d.unemploy_rate; }); allBLSTrace = { x: xAll, y: yAllBLS, mode: "lines", type: "scatter", hoverinfo: "skip", opacity: 0.3, line: { color: "#c5c5c5", width: 1 }, }; dataBLS.push(allBLSTrace); //---------------------- } //end for loop if (selectSystem !== "none") { var selSystem2 = blsData.filter(function (d) { return d.pwsid === selectSystem; }); var xYear = selSystem2.map(function (d) { return d.year; }); var yRate = selSystem2.map(function (d) { return d.unemploy_rate.toFixed(1); }); var blsTrace = { x: xYear, y: yRate, type: "scatter", mode: "lines", name: "selected<br>utility", text: selectSystem, marker: { color: "#00578a" }, hovertemplate: "%{y}% unemployed in %{x}", }; dataBLS.push(blsTrace); } //end if //PLOTLY BAR CHART OF RATES var layoutBLS = { yaxis: { title: "Unemployment Rate (%)", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: true, showticklabels: true, range: [0, 30], }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: "", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, }, height: plotHeight, showlegend: false, margin: { t: 30, b: 40, r: 30, l: 50 }, }; Plotly.newPlot( "annualBLSChart", dataBLS, layoutBLS, configNoAutoDisplay ); // }); end d3 //read in csv ############################################################################# var parseDate = d3.timeParse("%Y-%m-%d"); if (selectSystem === "none") { document.getElementById("monthBLSChart").innerHTML = "Select a system"; } d3.csv("data/bls_monthly.csv").then(function (blsCSV2) { blsCSV2.forEach(function (d) { //d.date = parseDate(d.date); d.unemploy_rate = +d.unemploy_rate; }); var selSystem3 = blsCSV2.filter(function (d) { return d.pwsid === selectSystem; }); var xMonth = selSystem3.map(function (d) { return d.date; }); var yRate2 = selSystem3.map(function (d) { return d.unemploy_rate.toFixed(1); }); //PLOTLY BAR CHART OF RATES var blsTrace2 = { x: xMonth, y: yRate2, type: "bar", name: "", //type: "scatter", mode: "lines", marker: { color: "#00578a" }, hovertemplate: "%{y}% unemployed in %{x}", }; //console.log(blsTrace2); var layoutBLS = { yaxis: { title: "Unemployment Rate (%)", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, showline: false, showgrid: true, showticklabels: true, range: [0, 30], }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: "", titlefont: { color: "rgb(0, 0, 0)", size: 13 }, tickfont: { color: "rgb(0, 0, 0)", size: 11 }, tickformat: "%b-%Y", //range: [parseDate("2020-01-01"), parseDate("2020-04-01")] }, height: plotHeight, showlegend: false, // legend: {x: 0, y: 0, xanchor: 'left', orientation: "h" }, margin: { t: 30, b: 40, r: 40, l: 50 }, shapes: [ { type: "line", xref: "x", yref: "y", x0: parseDate("2020-03-01"), y0: 0, x1: parseDate("2020-03-01"), y1: 30, //date is march 11 but way box draws it - make earlier //x0: "Mar 2020", y0: 0, x1: "Mar 2020", y1: 30, line: { width: 1, color: "black", dash: "dashdot" }, layer: "below", // draws layer below trace }, ], annotations: [ { xref: "x", yref: "y", //ref is assigned to x values x: parseDate("2020-03-01"), y: 20, //x: "Mar 2020", y: 20, xanchor: "left", yanchor: "bottom", text: "Global Pandemic <br> (March 11)", font: { family: "verdana", size: 11, color: "black" }, showarrow: false, }, ], }; dataBLS2 = [blsTrace2]; if (selectSystem !== "none") { document.getElementById("monthBLSChart").innerHTML = ""; Plotly.newPlot( "monthBLSChart", dataBLS2, layoutBLS, configNoAutoDisplay ); } }); } // end function <file_sep>/www/scripts/idwsFunction.js /////////////////////////////////////////////////////////////////////////////////////////////////// // // IDWS GRAPHIC SCRIPT /////////////// //// /////////////////////////////////////////////////////////////////////////////////////////////////// function togglePlots(target){ //lets make a variable that decides whether to draw a plot or table// var x = document.getElementById("switchDiv").checked; if (x === true) { selectPlotType = "table"; document.getElementById('idwsText').style.display="none"; } if (x === false) { selectPlotType = "plot"; document.getElementById('idwsText').style.display="block"; } document.getElementById('costBillChart').innerHTML = ""; plotCostBill(selectSystem, selectVolume, selectPlotType); return selectPlotType; } /*########################################################################################################3 # # ##########################################################################################################3*/ function plotCostBill(selectSystem, selectVolume, selectPlotType) { //read in csv d3.csv("data/IDWS/idws_"+selectVolume+".csv").then(function(costCSV){ costCSV.forEach(function(d){ d.percent_income = +d.percent_income; d.annual_cost = +d.annual_cost; d.percent_pays_more = +d.percent_pays_more; }); //pull out selected system var selCostInside = costCSV.filter(function(d){ return d.pwsid === selectSystem && d.category === "inside"; }); var selCostOutside = costCSV.filter(function(d){ return d.pwsid === selectSystem && d.category === "outside"; }); //console.log(selCostInside) if (selCostInside.length > 0) { var selName = utilityDetails.filter(function(d) {return d.pwsid === selectSystem}) .map(function(d) { return d.service_area}); document.getElementById('costBillTitle').innerHTML = "Income Dedicated to Water Services for " + selName + " at an annual cost of $" + numberWithCommas(selCostInside[0].annual_cost.toFixed(0)); } //continue to filter based on selection costCSV = costCSV.filter(el => { return selCSV.find(element => { return element.pwsid === el.pwsid; }); }); //filter less than 0.20 to save space costInside = costCSV.filter(function(d){ return d.category === "inside" && d.pwsid !== selectSystem; }); costOutside = costCSV.filter(function(d){ return d.category === "outside" && d.pwsid !== selectSystem; }); if (selectPlotType === "plot"){ //pull out selected state var data = []; var xPercent = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; var pwsidAll = costOutside.filter(function(d) {return d.percent_income==1;}); pwsidAll = pwsidAll.map(function(d) {return d.pwsid; }); var yAll2 = []; var outsideTrace; var legendOnOff; for (i=0; i < pwsidAll.length; i++){ tempSelect = pwsidAll[i]; temp = costOutside.filter(function(d) {return d.pwsid === tempSelect; }); //tempName = temp.map(function(d) {return d.service_area.substring(0,6) + "..., " + d.state.toUpperCase() + " outside rates"; }); tempName = tempSelect// + " outside rates"; yAll2 = temp.map(function(d){ return d.percent_pays_more; }); if (i==0) {legendOnOff = true; }//console.log("draw legend")} else {legendOnOff = false; } //create individual trace outsideTrace = { x: xPercent, y: yAll2, mode: 'lines', type: 'scatter', name: "", hovertemplate: tempName, opacity: 0.5, line: {color: 'rgba(0,87,138,0.4)', width: 1.5}, //light coral name: "outside rates", showlegend: legendOnOff, }; //push trace data.push(outsideTrace); } // end for loop // create all traces for inside state pwsidAll = costInside.filter(function(d) {return d.percent_income==1;}); pwsidAll = pwsidAll.map(function(d) {return d.pwsid; }); var yAll = []; var insideTrace; for (i=0; i<pwsidAll.length; i++){ tempSelect = pwsidAll[i]; temp = costInside.filter(function(d) {return d.pwsid === tempSelect; }); //tempName = temp.map(function(d) {return d.service_area.substring(0,6) + ", " + d.state.toUpperCase() + " inside rates"; }); tempName = tempSelect// + " inside rates" yAll = temp.map(function(d){ return d.percent_pays_more; }); if (i==0) {legendOnOff = true;} else {legendOnOff = false; } //create individual trace insideTrace = { x: xPercent, y: yAll, mode: 'lines', type: 'scatter', name: "", hovertemplate: tempName, opacity: 0.5, line: {color: '#d4ebf2', width: 1.5}, //light blue name: "inside rates", showlegend: legendOnOff }; //push trace data.push(insideTrace); } // end for loop //calculate median value var yMedian = []; var medVal; for(i=0; i<xPercent.length; i++){ temp = costCSV.filter(function(d) {return d.percent_income === xPercent[i]; }); yAll = temp.map(function(d){ return d.percent_pays_more; }); yAll.sort(function(a,b){return a-b; }); medVal = Math.round(d3.quantile(yAll, 0.50)*10)/10; yMedian.push(medVal); } //yMedian.unshift(100); //selected - draw all as present---------------------------------------------------------------- var selyall; if (selCostInside.length > 0 ) { selyall = selCostInside.map(function(d) {return d.percent_pays_more; }); // selyall.unshift(100); } var selyall2; if (selCostOutside.length > 0 ) { selyall2 = selCostOutside.map(function(d) {return d.percent_pays_more; }); } //grab values for annotation var y4annot; var y7annot; var y10annot; var y4annotText; var y7annotText; var y10annotText; if (selCostInside.length > 0) { y4annot = selyall[2].toFixed(1); y4annotText = selyall[2].toFixed(1) + "% of homes spend more than <br> 2% of income on water services"; y7annot = selyall[4].toFixed(1); y7annotText = selyall[4].toFixed(1) + "% of homes spend more than <br> 4% of income on water services"; y10annot = selyall[7].toFixed(1); y10annotText = selyall[7].toFixed(1) + "% of homes spend more than <br> 7% of income on water services"; } //account for no selection made if (selCostInside.length === 0) { y4annotText = "select system"; y7annotText = "select system"; y10annotText = "select system"; y4annot = 65; y7annot = 50; y10annot = 35; } var medtrace = { y: yMedian, x: xPercent, marker: {size: 6, color: '#5d5d5d'}, line: {color: '#5d5d5d', width: 6}, mode: 'lines+markers', type: 'scatter', name: 'median', hovertemplate: 'Median: %{y}% houses spending more than %{x}% of income', showlegend: true, }; var seltrace = { y: selyall, x: xPercent, marker: { size: 8, color: "blue", line: {color: 'black', width: 1} }, line: {color: 'blue', width: 3}, mode: 'lines+markers', type: 'scatter', name: 'selected: all or inside rates', hovertemplate: '%{y}% houses spending more than %{x}% of income', showlegend: true }; var selouttrace = { y: selyall2, x: xPercent, marker: { size: 8, color: "#00578a", line: {color: 'black', width: 1} }, line: {color: '#00578a', width: 3, dash: "dashdot"}, mode: 'lines+markers', type: 'scatter', name: 'selected: outside rates', hovertemplate: '%{y}% houses spending more than %{x}% of income', showlegend: true }; var layout = { yaxis: { title: 'Percent of households paying more', titlefont: {color: 'rgb(0, 0, 0)', size: 14 }, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, showline: false, showgrid: true, showticklabels: true, range: [0, 100] }, xaxis: { showline: false, showgrid: true, showticklabels: true, title: 'Percent of income going to water services', titlefont: {color: 'rgb(0, 0, 0)', size: 14}, tickfont: {color: 'rgb(0, 0, 0)', size: 12}, range: [0, 15] }, hovermode: 'closest', height: 400, //showlegend: false, legend: {x: 1, y: 1, xanchor: 'right'}, margin: { t: 30, b: 30, r: 40, l: 40 }, shapes: [ //days { type: 'line', xref: 'x', yref: 'paper', //ref is assigned to x values x0: day1, y0: 0.0, x1: day1, y1: 1, line: {color: '#001b1b', width: 2, dash: "dot"}, layer: "below", }, { type: 'line', xref: 'x', yref: 'paper', //ref is assigned to x values x0: day1*2, y0: 0.0, x1: day1*2, y1: 1, line: {color: '#001b1b', width: 2, dash: "dot"}, layer: "below", }, { type: 'line', xref: 'x', yref: 'paper', //ref is assigned to x values x0: day1*3, y0: 0.0, x1: day1*3, y1: 1, line: {color: '#001b1b', width: 2, dash: "dot"}, layer: "below", }, { type: 'line', xref: 'x', yref: 'paper', //ref is assigned to x values x0: day1*4, y0: 0.0, x1: day1*4, y1: 1, line: {color: '#001b1b', width: 2, dash: "dot"}, layer: "below", }, ], annotations: [ //days { xref: 'x', yref: 'paper', //ref is assigned to x values x: 2.3, y: 1, xanchor: 'middle', yanchor: 'top', text: "< 1 day", font: {family: 'verdana', size: 11, color: '#001b1b'}, showarrow: false }, { xref: 'x', yref: 'paper', //ref is assigned to x values x: day1+2.3, y: 1, xanchor: 'middle', yanchor: 'top', text: "1-2 days", font: {family: 'verdana', size: 11, color: '#001b1b'}, showarrow: false }, { xref: 'x', yref: 'paper', //ref is assigned to x values x: day1*2+2.3, y: 1, xanchor: 'middle', yanchor: 'top', text: "2-3 days", font: {family: 'verdana', size: 11, color: '#001b1b'}, showarrow: false }, { xref: 'x', yref: 'paper', //ref is assigned to x values x: day1*3+2.3, y: 1, xanchor: 'middle', yanchor: 'top', text: "3-4 days", font: {family: 'verdana', size: 11, color: '#001b1b'}, showarrow: false }, { xref: 'x', yref: 'paper', //ref is assigned to x values x: day1*4+2.3, y: 1, xanchor: 'middle', yanchor: 'top', text: ">4 days", font: {family: 'verdana', size: 11, color: '#001b1b'}, showarrow: false }, //4% threshold { xref: 'x', yref: 'y', //ref is assigned to x values x: 2, y: y4annot, axref: 'x', ayref: 'y', ax: 5, ay: 85, //draws arrow xanchor: 'left', yanchor: 'bottom', text: y4annotText, font: {family: 'verdana', size: 11, color: 'blue'}, showarrow: true, arrowcolor: 'blue', arrowhead: 5//arrowhead style }, //7% threshold { xref: 'x', yref: 'y', //ref is assigned to x values x: 4, y: y7annot, axref: 'x', ayref: 'y', ax: 8, ay: 70, //draws arrow xanchor: 'left', yanchor: 'bottom', text: y7annotText, font: {family: 'verdana', size: 11, color: 'blue'}, showarrow: true, arrowcolor: 'blue', arrowhead: 5//arrowhead style }, //10% threshold { xref: 'x', yref: 'y', //ref is assigned to x values x: 7, y: y10annot, axref: 'x', ayref: 'y', ax: 11, ay: 55, //draws arrow xanchor: 'left', yanchor: 'bottom', text: y10annotText, font: {family: 'verdana', size: 11, color: 'blue'}, showarrow: true, arrowcolor: 'blue', arrowhead: 5//arrowhead style }, ] }; data.push(medtrace); if (selCostInside.length > 0) { data.push(seltrace); document.getElementById('idwsText').innerHTML = "The metric shows how many households share a similar financial burden in the utility in terms of the annual income going to pay for water services. Each 4.6% of income represents roughly a day of labor. This metric allows utilities to see the breadth of affordability challenges given estimated water bills and the distribution of household incomes in the service area."; } if (selectSystem !== "none" & selCostInside.length ===0) { document.getElementById('idwsText').innerHTML = "The metric shows how many households share a similar financial burden in the utility in terms of the annual income going to pay for water services. Each 4.6% of income represents roughly a day of labor. This metric allows utilities to see the breadth of affordability challenges given estimated water bills and the distribution of household incomes in the service area." + "<br><br><span style='font-size: 20px; font-weight: bold; color: rgb(252,57,67)'>The area of this utility was too small for this analysis."; } if (selCostOutside.length > 0) { data.push(selouttrace); } Plotly.newPlot('costBillChart', data, layout, config); }// end if selectPlotType === "plot" if(selectPlotType === "table"){ if(selectSystem != "none"){ //CREATE TABLE SUMMARIZING BY INCOME BRACKETS sel_hh = demData.filter(function(d) {return d.pwsid === selectSystem; }); // console.log(sel_hh); //create table var myTable = "<br><table class='table table-bordered table-striped'>"; //create column header myTable += "<thead><tr>"; myTable += "<th>Income Range</th>"; myTable += "<th>Percent of<br>Households in Income Range</th>"; myTable += "<th>Cumulative Percent of<br>Households in Income Range</th>"; if (selCostOutside.length===0) { myTable += "<th>Percent of Income<br>to Water Services</th>"; } if (selCostOutside.length > 0) { myTable += "<th>Percent of Income<br>to Water Services<br>(Inside)</th>"; myTable += "<th>Percent of Income<br>to Water Services<br>(Outside)</th>"; } //end header and start body to loop through by activity myTable += "</thead><tbody'>"; //tables fill by rows not columns var incomeText = ["Less than $25,000", "$25,000 to $49,999", "$50,000 to $74,999", "$75,000 to $99,999", "$100,000 to $124,999", "$125,000 to $149,999", "More than $150,000"]; var hhBracket = [sel_hh[0].d0to24k, sel_hh[0].d25to49k, sel_hh[0].d50to74k, sel_hh[0].d75to100k, sel_hh[0].d100to125k, sel_hh[0].d125to150k, sel_hh[0].d150kmore]; var cumBracket = [sel_hh[0].d0to24k, sel_hh[0].d0to24k+sel_hh[0].d25to49k, sel_hh[0].d0to24k+sel_hh[0].d25to49k+sel_hh[0].d50to74k, sel_hh[0].d0to24k+sel_hh[0].d25to49k+sel_hh[0].d50to74k+sel_hh[0].d75to100k, sel_hh[0].d0to24k+sel_hh[0].d25to49k+sel_hh[0].d50to74k+sel_hh[0].d75to100k+sel_hh[0].d100to125k, sel_hh[0].d0to24k+sel_hh[0].d25to49k+sel_hh[0].d50to74k+sel_hh[0].d75to100k+sel_hh[0].d100to125k+sel_hh[0].d125to150k, sel_hh[0].d0to24k+sel_hh[0].d25to49k+sel_hh[0].d50to74k+sel_hh[0].d75to100k+sel_hh[0].d100to125k+sel_hh[0].d125to150k+sel_hh[0].d150kmore]; var annualCost = selCostInside[0].annual_cost; var insideBracketMed = [annualCost/12500*100, annualCost/37500*100, annualCost/62500*100, annualCost/87500*100, annualCost/112500*100, annualCost/137500*100, annualCost/162500*100]; var insideBracketMin = [annualCost/25000*100, annualCost/50000*100, annualCost/75000*100, annualCost/100000*100, annualCost/125000*100, annualCost/150000*100, annualCost/500000*100]; var insideBracketMax = [100, annualCost/25000*100, annualCost/50000*100, annualCost/75000*100, annualCost/100000*100, annualCost/125000*100, annualCost/150000*100]; if (selCostOutside.length > 0){ var annualOutCost = selCostOutside[0].annual_cost; var outsideBracketMed = [annualOutCost/12500*100, annualOutCost/37500*100, annualOutCost/62500*100, annualOutCost/87500*100, annualOutCost/112500*100, annualOutCost/137500*100, annualOutCost/162500*100]; var outsideBracketMin = [annualOutCost/25000*100, annualOutCost/50000*100, annualOutCost/75000*100, annualOutCost/100000*100, annualOutCost/125000*100, annualOutCost/150000*100, annualOutCost/500000*100]; var outsideBracketMax = [100, annualOutCost/25000*100, annualOutCost/50000*100, annualOutCost/75000*100, annualOutCost/100000*100, annualOutCost/125000*100, annualOutCost/150000*100]; } if(sel_hh[0].keep!=="keep"){ for (i = 0; i < hhBracket.length; i++) { hhBracket[i] = "No Data"; cumBracket[i] = "No Data"; } } //console.log(insideBracket); for (i = 0; i < hhBracket.length; i++) { myTable += "<tr>"; //add income range myTable += "<td>" + incomeText[i] +"</td>"; //add percent of households if(sel_hh[0].keep === "keep"){ myTable += "<td>" + hhBracket[i].toFixed(1) +"%</td>"; myTable += "<td>" + cumBracket[i].toFixed(1) +"%</td>"; } else { myTable += "<td>" + hhBracket[i] +"</td>"; myTable += "<td>" + cumBracket[i] +"</td>"; } //add percent income //myTable += "<td>" + insideBracketMin[i].toFixed(1) + " to " + insideBracketMax[i].toFixed(1) + "</td>"; if (i===0){myTable += "<td>More than " + insideBracketMin[i].toFixed(1) + "%"; } if (i > 0 & i < (hhBracket.length-1)) { //myTable += "<td>" + insideBracketMed[i].toFixed(1) + " &plusmn; " + ((insideBracketMax[i]-insideBracketMin[i])/2).toFixed(1) + "</td>"; myTable += "<td>" + insideBracketMed[i].toFixed(1) + "% (range: " + insideBracketMin[i].toFixed(1) + " to " + insideBracketMax[i].toFixed(1) + "%)</td>"; } if (i===(hhBracket.length-1)){myTable += "<td>Less than " + insideBracketMax[i].toFixed(1) + "%"; } if(selCostOutside.length > 0){ if (i===0){myTable += "<td>More than " + outsideBracketMin[i].toFixed(1) + "%"; } if (i > 0 & i < (hhBracket.length-1)) { //myTable += "<td>" + outsideBracketMed[i].toFixed(1) + " &plusmn; " + ((outsideBracketMax[i]-outsideBracketMin[i])/2).toFixed(1) + "</td>"; myTable += "<td>" + outsideBracketMed[i].toFixed(1) + "% (range: " + outsideBracketMin[i].toFixed(1) + " to " + outsideBracketMax[i].toFixed(1) + "%)</td>"; } if (i===(hhBracket.length-1)){myTable += "<td>Less than " + outsideBracketMax[i].toFixed(1) +"%"; } } myTable += "</tr>"; }//end for loop myTable += "</tbody></table><br>"; if(sel_hh[0].keep==="keep"){ document.getElementById("costBillChart").innerHTML = "<br><p>This table shows the percent of households in the service area in each income range and the percent of income those households" + " are spending on water services. The percent income is based on the middle of the income range.</p>" + myTable; } else { document.getElementById('costBillChart').innerHTML = "<br><p>This table shows the percent of households in the service area in each income range and the percent of income those households" + " are spending on water services. The percent income is based on the middle of the income range.</p>" + "<p style='color: rgb(252,57,67)';>This system was too small to estimate percent of households</p><br>" + myTable; } }//end if selected pwsid }//end if selectPlotType==="table" }); //end D3 cost bill } //plotCostBill("NC0332010", selectVolume); <file_sep>/results/RESULTS FOLDER README.md # Living Data and Code for the Water Affordability Dashboard operated by the Nicholas Institute for Environmental Policy Solutions This folder is where results will be saved from the rscripts. Run the rscripts and the results will be saved in this folder. The files are large and are not duplicated here. A streamlined version of the files are provided in the www folder instead.<file_sep>/www/scripts/mapHoverClickFunctions.js /////////////////////////////////////////////////////////////////////////////////////////////////// // INTERACTIONS WITH MAP /////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /*------------------------------------------------------------------------------------------------------- //////////// CREATE HOVER OVER MAP FUNCTIONS /////////// --------------------------------------------------------------------------------------------------------*/ //create variable so info boxes disappear and reset when you are not hovering over a utility var utilityID = null; //create layout for plot when you hover over utility var layoutHist = { title: { text: "Block Group Burden", font: { size: 12 } }, yaxis: { title: 'Block Groups (%)', titlefont: { color: 'rgb(0, 0, 0)', size: 10 }, tickfont: { color: 'rgb(0, 0, 0)', size: 10 }, showline: false, showgrid: true, showticklabels: true, range: [0, 100] }, xaxis: { showline: false, showgrid: false, showticklabels: true, title: '', titlefont: { color: 'rgb(0, 0, 0)', size: 8 }, tickfont: { color: 'rgb(0, 0, 0)', size: 10 }, }, height: 173, width: 170, showlegend: false, margin: { t: 18, b: 30, r: 5, l: 25 }, }; var xHist = ["Low", "Low<br>Mod", "Mod<br>High", "High", "Very<br>High"]; var colHist = [afford_low, afford_low_moderate, afford_moderate_high, afford_high, afford_very_high]; var yHist = []; var dataHist; var histTrace; //function for when you hover over a utility------------------------------------------------------------------------------- map.on('mousemove', 'utilities-layer', function (e) { map.getCanvas().style.cursor = 'pointer'; //check if feature exist if (e.features.length > 0) { document.getElementById('map_hover_box').innerHTML = '<p><b>' + e.features[0].properties.service_area + '</b> (' + e.features[0].properties.pwsid + ')<br> has a <b>' + e.features[0].properties.burden + "</b> burden level at <b>" + numberWithCommas(selectVolume) + '</b> gallons' + '<br>Utility Size: ' + e.features[0].properties.sizeCategory + '<br>Owner: ' + e.features[0].properties.owner_type + '<br>Minimum Wage Hours: ' + Number(e.features[0].properties.LaborHrs).toFixed(1) + ' hours' + '<br>Household Burden (low income): ' + e.features[0].properties.HBI.toFixed(1) + '%<br>Poverty Prevalence: ' + e.features[0].properties.PPI.toFixed(1) + '%<br>Traditional (median income): ' + e.features[0].properties.TRAD.toFixed(1) + '%</p>'; //create a bar plot document.getElementById('histChart').innerHTML = ""; yHist = [e.features[0].properties.low, e.features[0].properties.low_mod, e.features[0].properties.mod_high, e.features[0].properties.high, e.features[0].properties.very_high]; histTrace = { x: xHist, y: yHist, type: "bar", name: "block groups", marker: { color: colHist }, hoverinfo: 'skip' }; dataHist = [histTrace]; Plotly.newPlot('histChart', dataHist, layoutHist, { displayModeBar: false }); }// end if hover over map utilityID = e.features[0].pwsid; if (utilityID) { map.setFeatureState( { source: 'utilities', sourceLayer: 'utilities', id: utilityID }, { hover: true } ); //end setFeatureState }//end if UtiltiydID }); //end map.on---------------------------------------------------------------------------------------------------------- //function for when your mouse moves off a utility ----------------------------------------------------------------------- map.on('mouseleave', 'utilities-layer', function () { //reset info boxes and turn off hover if (utilityID) { map.setFeatureState({ source: 'utilities', id: utilityID }, { hover: false } ); } utilityID = null; document.getElementById('histChart').innerHTML = "<p>Hover over a utility</p>"; document.getElementById('map_hover_box').innerHTML = '<p>Hover over a utility</p>'; map.getCanvas().style.cursor = ''; //resent point }); //end map.on--------------------------------------------------------------------------------------------------------------- /*------------------------------------------------------------------------------------------------------- //////////// CREATE CLICK ON MAP FUNCTIONS /////////// --------------------------------------------------------------------------------------------------------*/ // set up if utilities-layer is clicked map.on('click', 'utilities-layer', function (e) { //check if select-bkgroup-layer exists so that it doesn't keep reloading and rezooming map if (typeof map.getLayer('select-bkgroup-layer') !== 'undefined') { var f = map.queryRenderedFeatures(e.point, { layers: ['utilities-layer', 'select-bkgroup-layer'] }); if (f.length > 1) { return; } } //if they used the geocoder to find the utility, clear it. geocoder.clear(); selectSystem = e.features[0].properties.pwsid; //set drop down to selected value document.getElementById("setSystem").value = selectSystem; //call this function to zoom into map and load charts highlightUtility(selectSystem); }); /*---------------------- Mouse hover functions for block group layer-------------------------*/ // Function for when you hover over a block group map.on('mousemove', 'select-bkgroup-layer', function (e) { map.getCanvas().style.cursor = 'pointer'; // Check if feature exist if (e.features.length > 0) { // Create information for hover box document.getElementById('map_hover_box').innerHTML = '<p><strong>Block Group ID: ' + e.features[0].properties.GEOID + '</strong><br>' + 'Households: ' + Number(e.features[0].properties.totalhh).toLocaleString() + '<br>Low Income (20%): $' + Number(e.features[0].properties.income20).toLocaleString() + '<br>' + 'Median Income: $' + Number(e.features[0].properties.medianIncome).toLocaleString() + '<br>Household Burden (low income): ' + e.features[0].properties.HBI + '%<br>Poverty Prevalence: ' + e.features[0].properties.PPI + '%<br>Traditional (median income): ' + e.features[0].properties.TRAD + '%<br> Percent in Service Area: ' + Number(e.features[0].properties.perArea).toFixed(1) + '%</p>'; // Remove block highlight if it already exists var blockHighlightLayer = map.getLayer("bkgroup_highlight"); if (typeof blockHighlightLayer !== 'undefined') { map.removeLayer('bkgroup_highlight'); } // Redraw block highlight layer for current hover map.addLayer({ 'id': 'bkgroup_highlight', 'type': 'line', 'source': 'select-bkgroup', 'source-layer': 'block_groups_' + selectVolume, 'filter': ['in', 'GEOID', e.features[0].properties.GEOID], 'paint': { 'line-color': 'white', 'line-width': 3 }, }); } }); //function when mouse leaves hover over block group ------------------------------------------------------------------------ map.on('mouseleave', 'select-bkgroup-layer', function (e) { map.removeLayer('bkgroup_highlight'); document.getElementById('map_hover_box').innerHTML = '<p>Hover over a utility</p>'; map.getCanvas().style.cursor = ''; //resent point }); //end map.on------------------------------------------------------------------------------------------------------------- /*/////////////////////////////////////////////////////////////////////////////////////////////////////////////// FUNCTION WHEN CLICK ON A UTILITY //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/ function highlightUtility(selectSystem) { if (map.getLayer('select-utility-layer')) { map.removeLayer('select-utility-layer'); } //if (map.getSource('select-utility')) { map.removeSource('select-utility'); } if (typeof map.getLayer('select-bkgroup-layer') !== 'undefined') { if (typeof map.getLayer('bkgroup_highlight') !== 'undefined') { map.removeLayer('bkgroup_highlight'); } map.removeLayer('select-bkgroup-layer'); map.removeSource('select-bkgroup'); } /*------------------------------------------------------------------------------------------ ADD CENSUS BLOCKS OVERLAY STUFF -----------------------------------------------------------------------------------------*/ // If a system is selected (might not be in drop down menu) then load appropriate mbtile for the selectVolume if (selectSystem !== "none") { // Create Filter var blockFilter = ["all"]; // Apply PWSID Filter blockFilter.push(["==", "pwsid", selectSystem]); // Only Add Layers For Selected NVol (Monthly Usage) Filter //mapbox url varies depending on volume selected var select_url; switch (selectVolume) { case 0: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 1000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 2000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 3000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 4000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 5000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 6000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 7000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 8000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 9000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 10000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 11000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 12000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 13000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 14000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 15000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; case 16000: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID'; break; default: select_url = 'mapbox://YOUR MAPBOX TILESET USERNAME.ID' break; } //end switch case map.addSource('select-bkgroup', { type: 'vector', url: select_url }); map.addLayer({ 'id': 'select-bkgroup-layer', 'type': 'fill', 'source': 'select-bkgroup', 'source-layer': 'block_groups_' + selectVolume, 'filter': blockFilter, 'paint': { 'fill-color': [ 'match', ['get', 'burden'], 'Low', '#3b80cd', 'Low-Moderate', '#36bdcd', 'Moderate-High', '#cd8536', 'High', '#ea3119', 'Very High', '#71261c',//'#a7210f', 'Unknown', 'darkgray', '#ccc' ], 'fill-outline-color': 'black', 'fill-opacity': 0.7, } }); //zoom into selected feature selFeature = gisSystemData.features.find(d => d.properties.pwsid === selectSystem); if(selectSystem !== oldSystem){ map.fitBounds(turf.bbox(selFeature), {padding: 50}); } //draw selected feature on the map map.addLayer({ 'id': 'select-utility-layer', 'type': 'line', 'source': 'utilities', 'source-layer': 'water_systems_'+ selectVolume, 'paint': { 'line-color': 'black', 'line-width': 5, }, 'filter': ["==", "pwsid", selectSystem] }); }//end if selectSystem !=="none" // Display selected utility below filter panel var utilityText = document.getElementById("utilityResult"); if (selectSystem === "none") { utilityText.innerHTML = "<h4>No utility service provider found or selected.</h4>"; } else { myUtility = utilityDetails.filter(function (d) { return d.pwsid === selectSystem; }); utilityText.innerHTML = "<h4>You selected " + myUtility[0].service_area + " service area (pwsid: " + selectSystem + ").</h4>"; } oldSystem = selectSystem; // Call other filter functions if (target === "#metrics") { createMatrix(selectSystem, matrixLegend); allScores(selectSystem); plotCostBill(selectSystem, selectVolume, selectPlotType); } else if (target === "#rates") { plotRates(selectSystem, selectVolume, selWaterType); } else if (target === "#census") { plotDemographics(selectSystem); } if (target === "#summary") { createSummary(); } return oldSystem; } // end highlight utility function
54f169f905eba48552c63e505de00f29a9ff09f3
[ "JavaScript", "R", "Markdown" ]
18
JavaScript
NIEPS-Water-Program/water-affordability
e656a173d7b793d51ef6699fc17ad066fad65ef5
9a8e6dbdf014899a7a49b25932f2dad9d3c6c4c6
refs/heads/master
<repo_name>srujana093/Asset-Management<file_sep>/src/app/model/item.model.ts export class Items{ assetId:string; id:string; item_name:string; date_of_manufacture:string; quantity:number; date_of_purchase:string; }<file_sep>/src/app/services/asset.service.ts import {Asset} from '../model/asset.model' import {Items} from '../model/item.model' export class AssetService{ public assets:Asset[]=[]; public items:Items[]=[]; public constructor(){ } public getAssetInfo(){ return this.assets; } public getItems(id){ for(let i=0;i<this.items.length;i++){ if(this.items[i].assetId==id){ return this.items[i] } } } }<file_sep>/src/app/app.component.ts import { Component ,} from '@angular/core'; import { FormBuilder, FormControl, FormGroup, AbstractControl, Validators } from '@angular/forms'; import { Asset } from './model/asset.model'; import { AssetService } from './services/asset.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { addAssetForm: FormGroup; //updateform: FormGroup; assets: Asset[] = []; assetId: any; assetName: any; // IsForUpdate:boolean=false; // disableField:boolean=false; constructor(private formBuilder: FormBuilder, public assetService: AssetService,public router:Router) { // this.updateform = formBuilder.group({ // _id: [''], // firstname: [null, [Validators.required, Validators.minLength(2), Validators.maxLength(40), Validators.pattern('^[a-zA-Z0-9]+[a-zA-Z0-9.\\-_.,*#]*$')]], // lastname: [null, [Validators.required, Validators.minLength(2), Validators.maxLength(40), Validators.pattern('^[a-zA-Z0-9]+[a-zA-Z0-9.\\-_.,*# ]*$')]], // email: ['', [Validators.required, Validators.email, Validators.minLength(3), Validators.maxLength(64), Validators.pattern('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$')]] // }); this.addAssetForm = formBuilder.group({ assetId: [null, [Validators.required]], assetName: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(40), Validators.pattern('^[a-zA-Z0-9]+[a-zA-Z0-9.\\-_.,*# ]*$')]], // email: ['', [Validators.required, Validators.email, Validators.minLength(3), Validators.maxLength(64), Validators.pattern('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$')]] }); } ngOnInit() { this.getAssets(); // console.log(this.user) } addAsset(frm) { // console.log(frm.value); // if (frm.value.firstName || frm.value.lastName || frm.value.email != '') { if (this.addAssetForm.valid) { // this.userService.registerUser(frm.value).subscribe(res => { // // console.log(res); // alert(res.message) // window.location.reload(); // }) this.assetService.assets.push(frm.value) this.getAssets(); } else { alert("Invalid Credentials") window.location.reload(); } } itemInfo(id){ console.log(id) this.router.navigate(['/item/'+id]) } getAssets(){ this.assets=this.assetService.getAssetInfo(); } // delete(index) { // // console.log("Item to be del:"+this.products[j].pname); // // console.log(index) // // console.log("Item to be del:"+this.user); // // this.products.splice(j,1); // this.userService.delete(index); // window.location.reload() // } // EditUser(u) { // this.id = u._id; // let Assets: Asset; // this.Assets.forEach(asset => { // if (asset._id == this.id) { // Assets = user; // //console.log(Users); // } // }) // this.updateform.patchValue(Users); // } // // console.log(id); // updateUser(frm) { // // console.log(frm.value); // this.userService.update(frm.value); // window.location.reload(); // } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AssetService } from './services/asset.service'; import { ItemComponent } from './item/item.component'; import { Router, RouterModule, Routes } from '@angular/router'; const appRoutes: Routes=[ {path: 'item/:assetId',component: ItemComponent} ]; @NgModule({ declarations: [ AppComponent, ItemComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot( appRoutes, //{ enableTracing:true} ), ], providers: [AssetService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/model/asset.model.ts import {Items} from '../model/item.model' export class Asset{ id:any; assetName:string; }<file_sep>/src/app/item/item.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, AbstractControl, Validators } from '@angular/forms'; import { AssetService } from '../services/asset.service'; import { Router, ActivatedRoute } from '@angular/router'; import { Items } from '../model/item.model'; @Component({ selector: 'app-item', templateUrl: './item.component.html', styleUrls: ['./item.component.scss'] }) export class ItemComponent implements OnInit { addItemForm; FormGroup; id_asset: any; items: any; constructor(private formBuilder: FormBuilder, public assetService: AssetService,public router:Router,private route:ActivatedRoute) { this.addItemForm = formBuilder.group({ id: [null, [Validators.required]], item_name: [null, [Validators.required]], date_of_manufacture: [null,[Validators.required]], quantity:[null,[Validators.required]], date_of_purchase:[null,[Validators.required]] }); } addItem(form){ console.log(form.value) this.route.params.subscribe(param=>{ this.id_asset=param.assetId form.value.assetId=this.id_asset; this.assetService.items.push(form.value); console.log(this.assetService.items) this.getItems() }) //console.log() } getItems(){ this.items=this.assetService.items; } ngOnInit() { this.getItems() } }
3f513115e2e4eb40751e0fab557691bcd2c7b9b3
[ "TypeScript" ]
6
TypeScript
srujana093/Asset-Management
6e354fba1316853d07c9dafb2178f14acbfd162a
c1f91c1696000d818d9b78faf4782326d25be321
refs/heads/master
<file_sep>--- layout: page --- <h3>Resourses</h3> {% for res in site.data.resourses %} {% assign r = res[1] %} {% if r.category == 'other' %} <div> <a href="{{ r.url }}">{{ r.description }}</a> <p> <!-- {{ r.text }} --> </p> </div> {% endif %} {% endfor %} <h4>Hardware</h4> {% for res in site.data.resourses %} {% assign r = res[1] %} {% if r.category == 'hardware' %} <div> <a href="{{ r.url }}">{{ r.description }}</a> </div> {% endif %} {% endfor %} <file_sep>--- layout: post title: "A Major Problem" date: 2018-03-25 12:33:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: 'WP_20180128_21_15_22_Pro.jpg' thumbnail_alt: 'A major problem' author: cosma --- A Major Problem A rash decision causes an extended period of down time. <!--more--> Following a long discussion we decided that it makes sense that, moving forward, the bots should be as closely aligned as possible... Using a schematic produced by Phil I made my own version of the sensor pod. I had to modify the design as my sensors are in a pod at the front and Phils are spread around the machine. The end result can be seen here. On the right, we have an Arduino and on the left is a 10 Degrees of Freedom (10DoF) sensor that helps the bot to know where it is facing (useful when turning corners). <img src="/assets/images/sz_large/WP_20180128_21_15_22_Pro.jpg" alt="SPI Interface for sensors" > The GPIO SPI pins conflict with the motor control pins I have been using and so, in keeping with the standardisation plan, I decided to move my pins to keep in line with Phils. At the January meeting of Hack Horsham, I decided to start making some of the modifications that would allow me to run the new code base. Doing this at an HH meeting was not the cleverest of choices. I, somewhat stupidly, started moving connections about without shutting the Pi down. To cut a long story short, the Pi hung and would not boot anymore! I thought I had borked the SD card. We tested it on a different Pi and it worked! So I tried to boot my Pi from a different card. No go! It seemed to me, at that point, that I probably had a short somewhere. There now follows a period of brain fart on my part. I spent a good month trying to clone the SD card from my bot, in the belief that it had "issues". In the end, I managed to use a Pi to DD an image of the card to my server and then DD it back to a new card. This was a great bit of learning for me and I can now take Linux images across my network. This is a useful skill, but really gets me nowhere with my problem. I tested my new card in the original Pi (no good) and a different Pi (it boots). I decided to disconnect everything from the Pi and test again. No difference. Finally, the fog started to clear from my brain and I realised that the problem was with the Pi on my bot! I swapped it out and, hey presto, things started to work. After some fiddling, with the power off, my bot now connects to a PS3 controller and can read the sensors or, more specifically, ask the Arduino for the current sensor data. So what have I learned? Well... Connecting to the Pi's GPIO while the Pi is turned on is a really bad idea. I seem to have cooked a Pi 3 by trying to be clever and save some time by not shutting down while moving things about. So what next? Well, Phil has managed to continue working on the bot body and has it starting to look good. He has built it to use a Pi cam instead of a webcam, and so I need to revise the master code branch to use the Pi cam. Fortunately, the original code was written for Pi cam and so that should not be too big a problem. Watch this space for future Updates...<file_sep>--- layout: post title: "Dalek V2 Begins..." date: 2017-10-14 09:20:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: '111.jpg' thumbnail_alt: 'Dalek V1' author: cosma --- Dalek V2 Begins... <!--more--> This year we were armed with some observations from last year’s Pi Wars. It was very apparent that going with caterpillar tracks (at least of the type we had previously used) was not going to work. We also realised that we had nowhere near enough ground clearance for some of the tasks. It was decided that we were going to 3D print the body this time. An initial design was made and printed. <img src="/assets/images/sz_large/202.jpg" alt="Initial construction" > But some very basic testing proved that it was far too small and was going to be too weak, with nowhere near enough space for our requirements. <img src="/assets/images/sz_large/203.jpg" alt="Initial construction" > A second, simpler, sturdier version was designed and printed. <img src="/assets/images/sz_large/201.jpg" alt="Initial construction" > <img src="/assets/images/sz_large/204.jpg" alt="Initial construction" > <img src="/assets/images/sz_large/205.jpg" alt="Initial construction" > This one was sturdier and had plenty of space. We had already decided on 4-WD for better power, this would require 2 motor controllers and more batteries (we went with 8 rechargeable AA’s). <img src="/assets/images/sz_large/206.jpg" alt="Initial construction" > At this point it struck us that we should make sure that we were within the rules in terms of size! <img src="/assets/images/sz_large/207.jpg" alt="Initial construction" > <img src="/assets/images/sz_large/208.jpg" alt="Initial construction" > <img src="/assets/images/sz_large/209.jpg" alt="Initial construction" > <img src="/assets/images/sz_large/210.jpg" alt="Initial construction" > We breathed a collective sigh of relief when we discovered we were (by the skin of our teeth). We decided that we needed a new motor controller module, as the one we had only worked for 2 wheel drive and steering. We wrote one and started to test it. <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="https://www.youtube.com/embed/gXLWULd3ya8" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></div> As you can see, the bot moves (which is a good thing), but very poorly. After much head scratching and crying we made a break through. Extra batteries were added (now up to 16!), they were moved to underneath the bot (for stability) and also a speaker and amp were added for sound effects. <img src="/assets/images/sz_large/214.jpg" alt="More POWER!!!" > We also added some voltage monitors and a pHat as a status indicator. With all the extra batteries we installed a MoPi. This allows us to use the 2 banks of batteries as fall-back for each other and power the Pi up and down cleanly, without having a screen attached. The MoPi regulates the 2 12v battery banks so the Pi only gets the 5V it needs. It transpires that the MoPi is not fully compatible with a Pi 3, but it works well enough for our needs. <img src="/assets/images/sz_large/215.jpg" alt="Rearranged" > We also modified the motor controller module so that it now works!! Time to work on the tasks!. <file_sep>--- layout: post title: "More Development..." date: 2016-10-15 09:20:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: '104.jpg' thumbnail_alt: 'Dalek V1' author: cosma --- More Development. <!--more--> It transpired that we were exhibiting at the 2017 Pi Wars and not competing. This proved to be quite fortuitous. Having never been to see Pi Wars before we really did not know what we were letting ourselves into. The DalekBot itself was at a convenient point in development in that everything that we had built was working and we were running out of time. <img src="/assets/images/sz_large/107.jpg" alt="Final V1 DalekBot" > The pHat was added to let us know what the DalekBot was doing and it was trained to shout “Exterminate!” We then started working on making it look Dalekish. This picture features my son, Alex, and a friend (the one with the Laser cutter) after we had the “skirt” plotted and cut. This actually happened shortly after the blue bit was cut, but this is a better point to show it. <img src="/assets/images/sz_large/106.jpg" alt="The beginning of the skirt" > The skirt was cut, bent to shape and taped to hold it’s position. <img src="/assets/images/sz_large/108.jpg" alt="The beginning of the skirt" > Further bits of card were shaped and hot glued in to position. <img src="/assets/images/sz_large/110.jpg" alt="The body takes shape" > Then we started with the “interesting” part (and that is not “interesting” in a good way). Parts such as the weapons, ears, eye and head were to be 3D printed. The weapons, ears and eye were fairly easy to print, but the head (dome) proved to be a real challenge. Due to issues with the printer and the filament, we used the better filament in failed attempts to print the head so were left with a small quantity of aging Black filament. Due to its age, the filament broke regularly. Also the build files called for a central support that was supposed to be made from a different filament that was to be removed after the print. Alas we did not have the luxury of using two types. Once the printer started printing we had no choice but to baby sit it, reinserting filament in the extruder head every time it broke. The image below shows the beginning of the head and the central support, <img src="/assets/images/sz_large/111.jpg" alt="The head begins" > After three days we had a head (Dome). <img src="/assets/images/sz_large/112.jpg" alt="The dome takes shape" > <img src="/assets/images/sz_large/113.jpg" alt="The finished Dome" > The completion of the dome came as we were starting to panic about having enough filament left! <img src="/assets/images/sz_large/112a.jpg" alt="The remains" > The failed attempts to print the dome were pressed into service as shapers for the neck section. LED’s were added to the eye and ears for effect and then the whole bot was sprayed with mat back paint. <img src="/assets/images/sz_large/114.jpg" alt="The finished Dalek" > <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="https://www.youtube.com/embed/gGsmTVTXqmA" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></div> <file_sep>import os, fnmatch from PIL import Image from pathlib import Path # This runs in python 3.* ## pip3 install Pillow ## run from the command line # > python .\resizeImages.py origin_directory = "images/imagesToProcess" def processImages(fileExt): listOfFiles = os.listdir(origin_directory) pattern = "*." + fileExt for entry in listOfFiles: if fnmatch.fnmatch(entry, pattern): resizeImage("images/sz_xSmall",entry,200) resizeImage("images/sz_small",entry,600) resizeImage("images/sz_large",entry,1200) origin = os.path.join(origin_directory,entry ) dest = os.path.join("images/Processed",entry) my_image = Path(dest) if my_image.exists(): # if it already exists just delete original os.remove(origin) else: # of move to new folder. os.rename(origin,dest) def resizeImage(saveDirectory, image, baseWidth): # Open the image file. path = os.path.join(origin_directory, image) print("Processing image: {} to width: {}".format(path,baseWidth)) img = Image.open(path) # Calculate the height using the same aspect ratio widthPercent = (baseWidth / float(img.size[0])) height = int((float(img.size[1]) * float(widthPercent))) # Resize it. img = img.resize((baseWidth, height), Image.BILINEAR) # Save it back to disk in new location. img.save(os.path.join(saveDirectory, image)) processImages("png") processImages("jpg") print("#############################\n\n All Done \n\n#############################")<file_sep>--- layout: post title: "Dalek V1 Takes Shape..." date: 2016-10-14 09:20:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: 'dalekbot114.jpg' thumbnail_alt: 'Dalek V1' author: cosma --- Dalek V1 takes shape. <!--more--> Having decided that we were to be going down the caterpillar track route we had to give some consideration to appearance (this is where the blue bit comes in again, see I told you it would be back). The plan was to create a cowling that would be Dalek shaped. The base of the Dalek (the wooden bit) was not really conducive to the cowling idea and so we decided that what we needed was a place to attach the cowling. We located some accurate plans for a Dalek (specifically a “Renegade” Dalek) and plotted out the base in a CAD program. This was then scaled and cut out of Perspex using a laser cutter, leaving space for the tracks to pass through. We then put the parts we had together so we could start coding and testing. <img src="/assets/images/sz_large/103.jpg" alt="Initial construction" > In this picture you can see the caterpillar tracks attached to a wooden board with the blue shaper attached to the bottom. The silver box is a USB mobile phone charger, that is used to power the Pi and the Green batteries are powering the motors. Also visible is our motor controller. After some basic testing we decided to start working on the tasks. <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="https://www.youtube.com/embed/RMf9grEWjmQ" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></div> It became apparent that we would need some sensors for tasks such as line following and the Minimal Maze. After some more testing it was decided that we could not have the line following sensors sticking out from the front of the Dalek as they a, were vulnerable to being broken and b, looked silly and spoiled the overall effect. Some holes were drilled and a small platform was made to hold the circuit board and ultrasonic sensor. <img src="/assets/images/sz_large/104.jpg" alt="Sensors" > <img src="/assets/images/sz_large/105.jpg" alt="Sensors" > This proved to be quite effective so development continued. <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="https://www.youtube.com/embed/w931UuQiumw" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></div> <file_sep>--- layout: resources title: Resources --- This is somewhere we can publish and store links to things we may need or might help others.<file_sep>--- layout: code title: Code permalink: /code/ --- ```javascript void; ```<file_sep>--- layout: post title: "Welcome Dalekbot" date: 2017-11-26 09:20:39 +0000 categories: jekyll update excerpt_separator: <!--more--> thumbnail_file_name: 'DSC_1632.jpg' thumbnail_alt: 'a picture of something' author: phil --- Lorem ipsum, dolor sit amet consectetur adipisicing elit. Magni, eum. Rem, atque ipsa! Modi blanditiis quia culpa tempora asperiores id natus similique mollitia temporibus eaque alias veniam necessitatibus, error ipsa <!--more--> # temporibus eaque alias veniam ## temporibus eaque alias veniam ### temporibus eaque alias veniam Lorem ipsum, dolor sit amet consectetur adipisicing elit. Magni, eum. Rem, atque ipsa! Modi blanditiis quia culpa tempora asperiores id natus similique mollitia temporibus eaque alias veniam necessitatibus, error ipsa doloremque nostrum deserunt neque sint, molestiae doloribus quasi. Incidunt necessitatibus tempora hic dolore consequatur, numquam amet cum quisquam distinctio ab inventore saepe sunt eaque dolorem expedita ratione, porro asperiores beatae doloremque! Quia hic ducimus maxime iure qui! Officia autem praesentium sint possimus obcaecati dolore id. Nihil, sint, sunt temporibus debitis quidem facilis, non tempora ratione nostrum minus quisquam inventore. Odit voluptatibus repudiandae quisquam quidem dolor consectetur harum dolores id sapiente! <file_sep>--- layout: page title: About permalink: /about/ --- ### About #### Roboteers <ul> {% for person in site.data.people %} {% assign p = person[1] %} <li> <a href="/roboteer/{{person[0]}}"> {{ p.name }} </a> </li> {% endfor %} </ul><file_sep>DalekBot_web ## To create a new new blog post To create a new blog post you will need to be in the root of the repo and have python 3. installed note: I use _'py'_ to run _'python'_ as it handles the different versions on the computer better. Requirements: ``` > py -m pip install pillow ``` ``` >py .\create_new_blog_post.py -t 'this is a test blog' ``` you can use the -h flag to see all options ``` >py .\create_new_blog_post.py -h ``` Once the blog post has been created, just add your pictures to the "assets/images/imagesToProcess" folder, they should be processed and added to your blog automatically. The blog post lives in the /_posts folder, if you are using visual studio code click the 'open preview button' at the top of the tabs and your will see a rough preview or the post when done ctrl + c to stop the process ## To Only resize images only Here we use the -p or --pics flag. ``` >py .\create_new_blog_post.py -p ``` <file_sep>--- layout: post title: "Dalek V2a Begins..." date: 2017-10-14 09:20:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: 'DSC_1630.jpg' thumbnail_alt: 'DalekBot V2a' author: cosma --- Dalek V2a Begins... <!--more--> Our team is widely dispersed with between Greenwich and Horsham, which makes working together harder. We have taken the decision to start a second bot, using the same code base, to allow testing of different approaches to the tasks. Meet DalekBot V2a. <img src="/assets/images/sz_large/DSC_1630.jpg" alt="DalekBot V2a" > This bot is based upon the same hardware motor controllers and motors and can, therefore, use the same code (with some minor changes). In this picture you can see the Magnetometer (the little board on top) and the servo controller (log board on the right with yellow and red connectors). We have yet to decide if we will be using either one of those to control anything, but it does open up some interesting possibilities. <img src="/assets/images/sz_large/DSC_1624.jpg" alt="Magnetometer and Servo Controller" > In this picture you can see the Ultrasonic distance detectors (the 2 round black items in the side) <img src="/assets/images/sz_large/DSC_1631.jpg" alt="Ultrasonics" > There are detectors on all 4 sides which are constantly read by an Arduino. This frees up some pins on the Pi and reduces its workload somewhat. This contrasts with the DalekBot V2 which has the detectors on a removable module that sits at the front. <img src="/assets/images/sz_large/216.jpg" alt="More Ultrasonics" > Further testing will allow us to decide which is the best approach. This Video shows the V2a running the new, improved, motor control code. <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="https://www.youtube.com/embed/lDWncYVLexs" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></div> Now we have the basic bots working we can start to address the code for performing the tasks. <file_sep>--- layout: post title: "Stuff Todo" date: 2017-02-01 09:20:39 +0000 categories: TODO excerpt_separator: <!--more--> thumbnail_file_name: 'DSC_1631.jpg' thumbnail_alt: 'a picture of something' author: phil --- Incidunt necessitatibus tempora hic dolore consequatur, numquam amet cum quisquam distinctio ab inventore saepe sunt eaque dolorem expedita <!--more--> {% assign author = site.data.people[page.author] %} {{ author.name }} <file_sep>--- layout: home title: Home --- ### From the makers at [HackHorsham](http://hackhorsham.org.uk) #### Welcome one of the most merciless robots ever to roll the earth, the <span class="dalekbot">DalekBot</span> <img class="wrap-left-mobile mdl-cell--hide-desktop mdl-cell--hide-tablet" src="/assets/images/logos/dalekbot.svg" alt="I am DalekBot..."> Inspired by former Horsham resident, <NAME>ick designer of the Dalek, we are creating a robot to that will conquer human civilization once and for all. <img class="wrap-left mdl-cell--hide-phone" src="/assets/images/logos/dalekbot.svg" alt="I am DalekBot..."> <span class="dalekbot">DalekBot</span> will start taking over the earth once it has competed in the [2018 PiWars challenge competition](https://piwars.org/) and is currently honing it's skills and absorbing knowledge from it's evil creators and advanced onboard artificial intelligence system namely the RaspberryPi. This <span class="dalekbot">DalekBot</span> site is collection of evil ideas and monstrous creations that are going into the creation of this final formidable foe.<file_sep>--- layout: post title: "test on github" date: 2017-11-26 20:20:39 +0000 categories: Start excerpt_separator: <!--more--> thumbnail_file_name: 'DSC_1631.jpg' thumbnail_alt: 'a picture of something' author: phil --- just write on the web interface <file_sep>--- layout: post title: "Let Battle Commence" date: 2018-04-22 12:33:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: 'WP_20180422_11_40_13_Pro.jpg' thumbnail_alt: 'Let Battle Commence' author: cosma --- Let Battle Commence After a year of blood sweat and tears, we have arrived and are almost ready to compeate. <!--more--> Blow By Blow rundown of the day.. The day started with a major loss of code! The Git Repository seems to have been overwritten with some older versions of our files!! After some panicked rewriting and restoration we managed to get the bot running for Event #1. The Obstacle course. <iframe width="560" height="315" src="https://www.youtube.com/embed/k92NcoDAoF0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> There then followed some manic coding by Phil to fix some errors in our straight line code (this is happening as I speak) Watch this space for more updates…. <file_sep>#! python3 import os import fnmatch import time from PIL import Image, ExifTags from pathlib import Path import threading # pip3 install Pillow origin_directory = "assets/images/imagesToProcess" def processImages(fileExt): listOfFiles = os.listdir(origin_directory) pattern = "*." + fileExt list_of_processed_files = [] for entry in listOfFiles: if fnmatch.fnmatch(entry, pattern): # print(list_of_processed_files) list_of_processed_files.append(entry) # print(entry) resizeImage("assets/images/sz_xSmall", entry, 200) resizeImage("assets/images/sz_small", entry, 600) resizeImage("assets/images/sz_large", entry, 1200) origin = os.path.join(origin_directory, entry) dest = os.path.join("assets/images/Processed", entry) # print("{} > {}".format(origin,dest)) print("\n") my_image = Path(dest) # if it already exists just delete original if my_image.exists(): try: time.sleep(0.5) os.remove(origin) except: print("err: removing file ") # of move to new folder. else: os.rename(origin, dest) return list_of_processed_files def clean(): ''' removes all files from the output paths. use this in development only as you will lose all your pics. ''' clean_folder("assets/images/sz_xSmall") clean_folder("assets/images/sz_large") clean_folder("assets/images/sz_small") clean_folder("assets/images/Processed") clean_folder("assets/images/imagesToProcess") def clean_folder(folder_path): ''' removes all files from the output paths. use this in development only as you will lose all your pics. ''' listOfFiles = os.listdir(folder_path) for entry in listOfFiles: origin = os.path.join(folder_path, entry) os.remove(origin) def flip_horizontal(im): return im.transpose(Image.FLIP_LEFT_RIGHT) def flip_vertical(im): return im.transpose(Image.FLIP_TOP_BOTTOM) def rotate_180(im): return im.transpose(Image.ROTATE_180) def rotate_90(im): return im.transpose(Image.ROTATE_90) def rotate_270(im): return im.transpose(Image.ROTATE_270) def transpose(im): return rotate_90(flip_horizontal(im)) def transverse(im): return rotate_90(flip_vertical(im)) orientation_funcs = [None, lambda x: x, flip_horizontal, rotate_180, flip_vertical, transpose, rotate_270, transverse, rotate_90 ] def apply_orientation(im): """ Extract the oritentation EXIF tag from the image, which should be a PIL Image instance, and if there is an orientation tag that would rotate the image, apply that rotation to the Image instance given to do an in-place rotation. :param Image im: Image instance to inspect :return: A possibly transposed image instance """ try: kOrientationEXIFTag = 0x0112 if hasattr(im, '_getexif'): # only present in JPEGs e = im._getexif() # returns None if no EXIF data if e is not None: # log.info('EXIF data found: %r', e) orientation = e[kOrientationEXIFTag] # print(orientation) f = orientation_funcs[orientation] return f(im) # else: # print("no exif") except: # print("err no exif") # We'd be here with an invalid orientation value or some random error? pass # log.exception("Error applying EXIF Orientation tag") return im def resizeImage(saveDirectory, image, baseWidth): time.sleep(.2) # Open the image file. path = os.path.join(origin_directory, image) print("Processing image: {} to width: {}".format(path, baseWidth)) img = Image.open(path) img = apply_orientation(img) # Calculate the height using the same aspect ratio widthPercent = (baseWidth / float(img.size[0])) height = int((float(img.size[1]) * float(widthPercent))) # Resize it. img = img.resize((baseWidth, height), Image.BILINEAR) # Save it back to disk in new location. img.save(os.path.join(saveDirectory, image)) img.close() class ProcessFolder(threading.Thread): ''' just a loop waiting for images to be added to files ''' def __init__(self): super().__init__() self.running = False def run(self): self.running = True while self.running: processImages("png") processImages("jpg") time.sleep(1) def stop_running(self): self.running = False def main(): while True: ''' This will run every second to check if files have been added to the folder. ''' # print("retry") processImages("png") processImages("jpg") time.sleep(1) if __name__ == "__main__": pass <file_sep>--- layout: page title: Help permalink: /help/ --- ### Getting Started The site is using GitHub version of Jekyll. it is quite simple when you get how it works. I find GitHub desktop is the easiest as it does all the login and ssh key stuff for you once you log into your GitHub account in the app. The best way to work is to pull the repo and work locally, then push it back when you have finished this way you always have a local copy. If you can use a linx box or windows with a version of ruby on it you can run the jekyll server and see your results locally too. You can work directly on the GitHub server if you want too but it is a pain if you see any errors as you have to keep adding a new commit. The posts and pages are in the markdown format that GitHub uses The Master branch of the repo is the branch that is compiled to the web site. Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. [jekyll-docs]: https://jekyllrb.com/docs/home ### Blog Posts You’ll find the blog posts in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` eg: "2016-11-10-start-of-bot.md" and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works. This is the default 'front matter' for a post ```javascript --- layout: post title: "Title of the post" date: 2017-02-01 09:20:39 +0000 categories: code electronics excerpt_separator: <!--more--> thumbnail_file_name: 'DSC_1630.jpg' thumbnail_alt: 'a picture of something' author: phil --- ``` ### Images Images are uploaded to the "/assets/images/sz_original" folder. I will resize them with a script in Photoshop or the size are 1. sz_small: max With=600px max Hight=600px 1. sz_Large: max With=1200px max Hight=1200px ### Video For your Video wrap it in an outer div as follows ```html <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="your-video-url" frameborder="0" allowfullscreen></iframe> </div> ``` ### Pages Pages are created in the "/assets/" folder. Just add a new file and the 'front matter' at the top of the file and it will be added to the main site menu. ```javascript --- layout: page title: Help permalink: /Help/ --- ``` <file_sep>If you add an scss file remember to add it to @import it in the assets/main.scss file, otherwise it will not be added and compiled to it.<file_sep>#! python3 from optparse import OptionParser from time import gmtime, strftime import os from helpers import resize_images from pathlib import Path import time origin_directory = "assets/images/imagesToProcess" dest_directory = "_posts/" def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-t", "--title", dest="title", help="set the title of the blog") parser.add_option("-i", "--image", dest="image", help="set the image to be used as the thumbnail") parser.add_option("-l", "--alt", dest="alt_text", help="set the image alt text") parser.add_option("-p", "--pics", dest="pictures", help="Process the pictures in the '/assets/images/imagesToProcess' folder ", default=False, action="store_true",) parser.add_option("-a", "--author", dest="author", help="Set the Author of the post") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() # print(options) # if len(args) == 0: # parser.error("incorrect number of arguments") # if options.verbose: # print("reading %s..." % options.filename) if options.pictures is not None: process_Images_only() return if options.title is None: print("\n\nYou need to supply a title for the blog use" + " -t or --title\n\n") return else: if check_if_blog_exists(options.title): return if options.image is None: print("\n\nAdd your first image added to the " + "'{}' folder to creates the thumbnail \n\n" .format(origin_directory)) options.image = "001.jpg" if options.alt_text is None: options.alt_text = "" if options.author is None: options.author = "cosma" # print(options) write_text_to_file(options.title, options.image, options.alt_text, options.author ) process_images_for_post(options.title) # process_image_folder = resize_images.ProcessFolder() # process_image_folder.start() # process_image_folder.join() def process_Images_only(): resize_images.processImages('png') resize_images.processImages('jpg') def process_images_for_post(title): while True: data = resize_images.processImages('png') if len(data) > 0: print(data) add_images_to_blog(title, data) data = resize_images.processImages('jpg') if len(data) > 0: print(data) add_images_to_blog(title, data) time.sleep(1) def add_images_to_blog(title, list_of_images): file_title = title.replace(" ", "-") file_path = os.path.join(dest_directory,strftime("%Y-%m-%d-", gmtime()) + file_title + '.md') f = open(file_path, 'a') for image in list_of_images: f.write("\n![alt Image text needs to be added]" + "(/assets/images/sz_large/{})" .format(image)) f.write("\n![alt Image text needs to be added]" + "(/assets/images/sz_small/{})" .format(image)) f.close() def check_if_blog_exists(title): file_title = title.replace(" ", "-") file_path = os.path.join(dest_directory,strftime("%Y-%m-%d-", gmtime()) + file_title + '.md') fname = Path(file_path) if fname.is_file(): print("\n\nA Post already exists with the title '{}'.\n\n" .format(title)) return True else: return False def write_text_to_file(title, thumbnail_image, thumbnail_alt, author): file_title = title.replace(" ", "-") file_path = os.path.join(dest_directory,strftime("%Y-%m-%d-", gmtime()) + file_title + '.md') if check_if_blog_exists(title): return f = open(file_path, 'x') today = strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " +0000" lines = ["---\n", "layout: post\n", "title: \'" + title, "\'\n", "date: ", today, "\n", "categories: blog\n", "excerpt_separator: <!--more-->", "\n", "thumbnail_file_name: \'" + thumbnail_image, "\'\n", "thumbnail_alt: \'" + thumbnail_alt, "\'\n", "author: ", author, "\n", "---", "\n", "\n", "Your summary goes here.", "\n""\n", "<!--more-->", "\n", "body text here.", "\n", ] f.writelines(lines) f.close() if __name__ == "__main__": main() <file_sep>--- layout: page title: offline --- ## You have no internet connection :-(<file_sep>--- title: foo link: bbc.co.uk date: 2017-11-12 categories: electronics --- This is the text for the first resource in our blog. <file_sep>--- layout: post title: "Some modifications for the New Year" date: 2018-01-01 15:42:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: 'WP_20180101_15_40_22_Pro.jpg' thumbnail_alt: 'Some modifications for the New Year' author: cosma --- Some modifications for the New Year We have decided to make some modifications to my bot for better standardisation and code sharing. <!--more--> Following a long discussion we have decided that it makes sense that, moving forward, the bots should be as closely aligned as possible. This will still allow us to develop and test different strategies, but will make code sharing easier. As can be seen from the image below by Pi is connected to the UltraSonic sensors directly (via the ribbon cable). <img src="/assets/images/sz_large/WP_20180101_15_40_22_Pro.jpg" alt="DalekBot V2 Prior to clean up" > This made sense in the initial development phase, but has led to the situation that I am running out of pins on the GPIO. Phil has built and tested an alternative approach that uses an Arduino to “talk” to the sensors, and the Pi queries the Arduino (over SPI) every time it needs a distance measure. This uses 4 pins, instead if the 8 I am currently using. This may not sound like much of an improvement, but you need to understand that this approach is driving 4 sensors instead of the 3 that I am using and will require no more pin usage, even if we add more sensors, whereas my approach will require 2 more pins per additional sensor. The following diagrams show my current pin usage and my colleagues (Phil) pin usage that I will have to replicate (and then modify my code to match). <div class="mdl-grid"> <div class="mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--12-col-phone "> <img src="/assets/images/sz_small/Pin_Usage01_Cos.jpg" alt="My Pin Usage" > </div> <div class="mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--12-col-phone "> <img src="/assets/images/sz_small/Pin_Usage_Phil.jpg" alt="Phil’s Pin Usage" > </div> </div> As can be seen, I will need to make the following moves: <img class="mdl-cell mdl-cell--6-col-desktop mdl-cell--6-col-tablet mdl-cell--12-col-phone " src="/assets/images/sz_large/Cos_Pin_Swaps.jpg" alt="Cos Pin Swaps" width="50"> I will then have to make the code changes to make it work. On top of that I want to swap from using a WiiMote to using a PS3 controller (Christmas present to myself) as it has more buttons. Wish me luck! about an hour later.... Changes made and it seems to work!! Now I need to work out what to do with all these wires :) <img src="/assets/images/Processed/WP_20180101_18_12_11_Pro.jpg" alt="Spare bits"> I am actually waiting for some female header connectors to get here from China so I can build a controller board for the Ultrasonic sensor array. My initial thought is to mount it above the current board (removing the ribbon cable and directly connecting to the pins). One consideration is that I do need to be able to remove the sensor array. Another possible alternative is to install the UltraSonic sensors permanently, much in the same way as Phil has done (by drilling holes in the sides of the body). All my batteries and speaker are hidden under there, so I would need to decide if there is space. Another small issue-ette is that I have run out of sensors so I would need to get some more ordered ASAP. Oh the pain!  There are pros and cons to relocating the sensors. Yes, they would be safer and less prone to being damaged and yes, I could leave them connected permanently, but having the side sensors ahead of the body could be advantageous for the Minimal Maze. I think some testing is in order. But first I need to get the board built and working. Also I need to get the control modified for the PS3 Controller. Better see the family now before they think I have been abducted. <file_sep>--- layout: post title: "Copy files to Pi" date: 2017-11-16 09:20:39 +0000 categories: code excerpt_separator: <!--more--> thumbnail_file_name: '2017-12-02.jpg' thumbnail_alt: 'a picture of something' author: phil --- Writing code directly on the Raspberry Pi is fine when writing small scripts, but when your codebase gets bigger and more time has been invested into it, the better option is to work from a remote computer. <!--more--> The problem with working from a remote computer is yet another step in the tool chain to break the flow. Working with web technology this problem has more or less been fixed over the past few years with tools like grunt, gulp and webpack, so while working on the Dalekbot project I thought I should use one of these tool to make life easier. My setup is a Windows 10 PC, and I have installed [samba on the Raspberry Pi](https://www.raspberrypi.org/magpi/samba-file-server/) and have a share folder available it the Networks folder in file explorer on the PC. Next you need to have node.js installed on your PC from powershell run the command ```powershell > node -v ``` You should get somthing like this as a result. ```powershell C:\Users\userame> node -v v9.2.0 C:\Users\username> ``` If you get and error then install [node.js from here](https://nodejs.org/en/) Now clone or download my [copy-to-pi repo from github](https://github.com/philstenning/Copy-To-Pi) to your working folder on your PC, extract it if you downloaded the zip file. You need powershell to navigate to the root folder of this project or type in the full file path, so I use file explorer to navigate to it ![screen shot](/assets/images/sz_large/2017-12-02.jpg) Then type 'powershell' in the address bar, hit enter and it opens to the folder for you. ![screen shot](/assets/images/sz_large/2017-12-01.jpg) You already have npm installed as is comes with node.js, so you can install the node_modules needed by running the command ```powershell > npm install ``` Edit the gulpfile.js to the networked folder of you Raspberry Pi, the way I do it is by navigating to the folder on the RPI in file explorer, then copying the path from the explorer bar and changing the \ to /. ```javascript var gulp = require('gulp'), watch = require('gulp-watch'); gulp.task('python', function() { return watch('./src/*.py') gulp.src('./src/*.py') .pipe(gulp.dest('//RASPI/PiShare/myFolderOnPi')); }); gulp.task('default', function(){ return watch('./src/**',function(){ gulp.src('src/**') .pipe(gulp.dest('//RASPI/PiShare/myFolderOnPi')); }) }); ``` From here on, you don't need to worry about this folder again, only to start and end the gulp script. The src is your working folder and anything you do in there is copied to the raspberry Pi automatically when a file changed in it. To start the copy process run the command ```powershell > gulp ``` or to copy only the python files ```powershell > gulp python ``` or you could change it for any files you are working with ```javascript var gulp = require('gulp'), watch = require('gulp-watch'); //first line is your task name gulp.task('myCSharpfiles', function() { // second is the folder to watch return watch('./src/*.cs') // third is the files to copy (** matches everything ) gulp.src('./src/*.cs') // finally this is the folder on the Raspberry Pi // but could be anywhere you like. .pipe(gulp.dest('//RASPI/PiShare/myFolderOnPi')); }); ``` So with the script running you are free to work in the src folder and do as you please. I usually start by creating a new git repo, and if you are only copying the python files to the RPI, your folders there do not have any of the cruft of your working folders. One thing to remember is that files are not deleted on the RPI when they are deleted on the Development PC, if you want to do that, then use the [gulp-clean](https://www.npmjs.com/package/gulp-clean) plugin or do it manually. For more info on [gulp.js have a look at their docs](https://github.com/gulpjs/gulp/blob/master/docs/API.md) <file_sep>--- layout: post title: "The Story So Far..." date: 2015-10-14 09:20:39 +0000 categories: blog excerpt_separator: <!--more--> thumbnail_file_name: '001.jpg' thumbnail_alt: 'a picture of something' author: cosma --- Our intrepid team of Roboteers are given an unexpected challenge. <!--more--> Our journey to PiWars 2018 actually started in 2015 with a simple 2 wheeled bot that was controllable using a WiiMote. This allowed us to work on the motor control code and start to experiment with ultra-sonic sensors. <div class="videoWrapper"> <!-- Copy & Pasted from YouTube --> <iframe width="560" height="315" src="https://www.youtube.com/embed/TKsTlL6SR3w" frameborder="0" allowfullscreen></iframe> </div> At this stage it was just a bit of fun and we had not really thought about entering PiWars. This all changed in 2016 when the organisers of Hack Horsham (thank you Marcus and Nik) told us that we had been entered in to PiWars 2017! Gulp! We would be the official Hack Horsham team and so we decided that we needed to pull our fingers out and actually try to be if not competitive, at least not an embarrassment! After many discussions it was decided that we would go for a tracked design. A bit of Googling revealed a suitable set of tank tracks and a little more googling found a suitable twin motor gearbox assembly. It was intended to make the bot Dalek shaped as a homage to the inventor of the Daleks, who was from Horsham. In this photo you can see the Caterpillar track assembly and the control Pi, which is camouflaging the gearbox and motors. The Blue part is vital to the end result, but more of that later... <img src="/assets/images/sz_large/102.jpg" alt="Gathering the Parts" >
94dd6a91eb2c5a93db806c1528471a9e8d6b7e8f
[ "Markdown", "Python", "HTML" ]
25
HTML
Dalekbot/Dalekbot.github.io
18913275fd023589f24f6e98f21da7141bf47804
c92865faa3bb2444ee45fd5b8933e3d46d8b4c89
refs/heads/master
<repo_name>Arcangel01/Crud-Node<file_sep>/appUsers/src/routes/user.js const express = require('express'); const router = express.Router(); // Instanciamos la conexion. const mysqlConnect = require('../database'); // Creamos una ruta para listar router.get('/user', (req, res) => { mysqlConnect.query('SELECT * FROM mesero', (err, rows, fields) => { if(!err) { res.json({"status": 200, "error": null, "response": rows}); //res.send(JSON.stringify({"status": 200, "error": null, "response": rows})); } else { //console.log(err); res.json({"status": 500, "error": err, "response": null}); //Hay un error a la hora de conectarse a la BBDD } }); }); // Creamos la ruta para consultar por id router.get('/user/:id', (req, res) => { const { id } = req.params; mysqlConnect.query('SELECT * FROM mesero WHERE idMesero = ?', [id], (err, rows, fields) => { if(!err) { //res.json(rows[0]); res.json({"status": 200, "error": null, "response": rows[0]}); } else { // console.log(err); res.json({"status": 500, "error": err, "response": null}); } }) }); // Creamos ruta para insertar router.post('/user', (req, res) => { const { id, nombre, apellido, edad } = req.body; mysqlConnect.query(`INSERT INTO mesero VALUES(?, ?, ?, ?)`, [id, nombre, apellido, edad], (err, rows, fields) => { if (!err) { res.json({"status": 201, "error": null, "response": `Usuario agregado`}); //res.status(201).send(`Usuario agregado`); } else { console.log(err); res.json({"status": 500, "error": err, "response": null}); } }); }); // Creamos ruta para modificar router.put('/user/:id', (req, res) => { //const { nombre, apellido, edad } = req.body; const { id } = req.params; mysqlConnect.query(`UPDATE mesero SET ? WHERE idMesero = ?`, [req.body, id], (err, rows, fields) => { if (!err) { res.json({"status": 201, "error": null, "response": `Usuario modificado`}); //res.status(201).send(`Usuario modificado`); } else { // console.log(err); res.json({"status": 500, "error": err, "response": null}); } }); }); // Ruta para eliminar router.delete('/user/:id', (req, res) => { const { id } = req.params; mysqlConnect.query('DELETE FROM mesero WHERE idMesero = ?', [id], (err, rows, fields) => { if (!err) { res.json({"status": 200, "error": null, "response": `Usuario eliminado`}); } else { //console.log(err); res.json({"status": 500, "error": err, "response": null}); } }); }); module.exports = router;<file_sep>/appUsers/src/index.js const express = require('express'); // Requerimos de express const app = express(); // Lo almacenamos en una constante para utilizar las rutas // Config app.set('port', process.env.PORT || 3000); // Middlewares app.use(express.json()); // configurar cabeceras http app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method'); res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE'); res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); next(); }); // Routes app.use(require('./routes/user')); // Hacemos uso de express para iniciar el servidor app.listen(app.get('port'), () => { console.log('Server en el puerto 3000'); });<file_sep>/appUsers/src/database.js const mysql = require('mysql'); // Requerimos la dependencia de mysql.s // Le pasamos los parametros correspondientes para la conexion con la db. const mysqlConect = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'restaurante' }); // Validamos el resultado de la conexion. mysqlConect.connect(err => { if(err) { console.log(err); return; } else { console.log('conectados'); } }); // Exportamos la constante de la conexion. module.exports = mysqlConect;
ce52180aca14b767c88c75fde8a28787c9b18fc4
[ "JavaScript" ]
3
JavaScript
Arcangel01/Crud-Node
6e7668dcc0858888f24fe5ce964ae04334602985
0cf05f011c3d0ca10d36fe1a8f7a68c52189fb1b
refs/heads/master
<repo_name>kergalym/qtile_config<file_sep>/autostart.sh #!/bin/bash feh --bg-scale /home/galym/.config/qtile/walls/korlan_poster.png #telegram-desktop & #skypeforlinux & #hexchat & parcellite & kbdd & mpd & setxkbmap -layout "us,ru" -option "grp:alt_shift_toggle,grp_led:scroll" xrdb ~/.Xresources ~/bin/pycharm.sh & cherrytree & <file_sep>/config.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os # import stat import subprocess from libqtile.config import Key, Screen, Drag, Click from libqtile.config import Group, Match from libqtile.command import lazy from libqtile import layout, bar, widget from libqtile import hook from re import sub ###################################################### # # KEY DEFINITIONS # ###################################################### mod = "mod4" keys = [ Key([mod], "z", lazy.spawn("morc_menu")), Key([mod], "x", lazy.spawn("rofi -combi-modi drun -show combi")), # Switch between windows in current stack pane Key([mod], "k", lazy.layout.up()), Key([mod], "j", lazy.layout.down()), Key([mod], "h", lazy.layout.left()), Key([mod], "l", lazy.layout.right()), # Move windows up or down in current stack Key([mod, "shift"], "k", lazy.layout.shuffle_up()), Key([mod, "shift"], "j", lazy.layout.shuffle_down()), Key([mod, "shift"], "h", lazy.layout.shuffle_left()), Key([mod, "shift"], "l", lazy.layout.shuffle_right()), # Grow windows up or down in current stack Key([mod, "control"], "k", lazy.layout.grow_up()), Key([mod, "control"], "j", lazy.layout.grow_down()), Key([mod, "control"], "h", lazy.layout.grow_left()), Key([mod, "control"], "l", lazy.layout.grow_right()), # Normalize windows Key([mod], "n", lazy.layout.normalize()), # Switch window focus to other pane(s) of stack Key([mod], "space", lazy.layout.next()), # Swap panes of split stack Key([mod, "shift"], "space", lazy.layout.rotate()), # Toggle between split and unsplit sides of stack. # Split = all windows displayed # Unsplit = 1 window displayed, like Max layout, but still with # multiple stack panes Key([mod, "shift"], "Return", lazy.layout.toggle_split()), Key([mod], "Return", lazy.spawn("urxvt")), # Toggle between different layouts as defined below Key([mod], "Tab", lazy.next_layout()), Key([mod], "w", lazy.window.kill()), # Qtile system keys Key([mod, "control"], "r", lazy.restart()), Key([mod, "control"], "q", lazy.shutdown()), Key([mod], "r", lazy.spawncmd()), # Key([], 'Print', lazy.spawn(commands.screenshot)), # Sound Key([], "XF86AudioMute", lazy.spawn("amixer -q set Master toggle")), Key([], "XF86AudioPlay", lazy.spawn("ncmpcpp play")), Key([], "XF86AudioPlay", lazy.spawn("ncmpcpp pause")), Key([], "XF86AudioLowerVolume", lazy.spawn( "amixer -c 0 sset Master 1- unmute")), Key([], "XF86AudioRaiseVolume", lazy.spawn( "amixer -c 0 sset Master 1+ unmute")) ] ###################################################### # # LAYOUT GROUPS DEFINITIONS # ###################################################### groups = [ Group("DEV " + u"\u2713", matches=[Match(wm_class=["urxvt"]), Match(wm_class=["PyCharm"])]), Group("MEDIA " + u"\u266B", matches=[Match(wm_class=["ncmpcpp"]), Match(wm_class=["mpv"]), Match(wm_class=["urxvt"])]), Group("GRAPHICS " + u"\U0001F58C", matches=[Match(wm_class=["feh"]), Match(wm_class=["mupdf"]), Match(wm_class=["GNU Image \ Manipulation \ Program"]), Match(wm_class=["Krita"])]), Group("3D " + u"\U0001F4BB", matches=[Match(wm_class=["Blender"])]), Group("TORRENTS " + u"\U0001F572", matches=[Match(wm_class=["rtorrent"]), Match(wm_class=["Ktorrent"])]), Group("GAMES " + u"\U0001F3AE", matches=[Match(wm_class=["wine"]), Match(wm_class=["Panda"])]), Group("TALKING " + u"\U0001F4AC", matches=[Match(wm_class=["HexChat"]), Match(wm_class=["Skype"])]), Group("WEB " + u"\U0001F578", matches=[Match(wm_class=["Chromium"]), Match(wm_class=["Firefox"]), Match(wm_class=["Opera"])]), Group("OFFICE " + u"\U0001F3E2", matches=[Match(wm_class=["LibreOffice"])]), ] grplist = [] # Make group list with respective integers for i in range(len(groups)): grplist.append(i) # Start the integer from one to bind it later grplist.remove(0) grplist.append(len(grplist)+1) # Iterate and bind index as key for k, v in zip(grplist, groups): keys.extend([ # mod1 + letter of group = switch to grouplazy.group[j].toscreen() Key([mod], str(k), lazy.group[v.name].toscreen()), # mod1 + shift + letter of group = switch to # & move focused window to group Key([mod, "shift"], str(k), lazy.window.togroup(v.name)), ]) ###################################################### # # LAYOUT DEFINITIONS # ###################################################### layouts = [ layout.Columns(border_focus='#ffd700', border_normal='#881111'), layout.Stack(num_stacks=2) ] ###################################################### # # WIDGET DEFAULTS # ###################################################### widget_defaults = dict( font='JetBrainsMono-Bold', fontsize=16, padding=3, ) extension_defaults = widget_defaults.copy() ###################################################### # # SCREEN DEFINITIONS # ###################################################### def get_my_gpu_temp(): if os.path.isfile("/opt/bin/nvidia-smi"): data = subprocess.Popen(["/opt/bin/nvidia-smi", "--query-gpu=temperature.gpu", "--format=csv"], stdout=subprocess.PIPE).communicate() return "{} °C".format(sub("\D", "", str(data))) screens = [ Screen( top=bar.Bar( [ widget.GroupBox(background='#808080', foreground='#ffffff', active='#ffffff', this_current_screen_border="#470000", borderwidth=1, highlight_method='block', font='JetBrainsMono-Bold', fontsize=12), widget.WindowName(background='#808080', foreground='#ffffff'), widget.Net(background='#470000', foreground='#ffffff', interface='eth0'), widget.TextBox(u"\U0001F5AE", background='#808080', foreground='#ffffff', font='JetBrainsMono-Bold'), widget.KeyboardKbdd(configured_keyboards=['us', 'ru'], update_interval=1, background='#470000'), widget.TextBox(u"\U0001F50A", background='#808080', foreground='#ffffff', font='JetBrainsMono-Bold'), widget.Volume(background='#808080', foreground='#ffffff'), widget.Systray(background='#808080', foreground='#ffffff'), widget.Clock(background='#808080', foreground='#ffffff', format='%a, %d.%m.%Y, %H:%M %p'), ], 24, ), bottom=bar.Bar( [ widget.Prompt(background='#000000', foreground='#ffffff'), widget.Spacer(background='#808080'), widget.TextBox("ROOT SPACE:", background='#808080', foreground='#ffffff'), widget.HDDGraph(background='#808080', foreground='#000000', core='all', border_color="#470000", fill_color="#470000", path="/"), widget.TextBox("ST3 SPACE:", background='#808080', foreground='#ffffff'), widget.HDDGraph(background='#808080', foreground='#000000', core='all', border_color="#470000", fill_color="#470000", path="/media/ST3"), widget.TextBox("WDBL SPACE:", background='#808080', foreground='#ffffff'), widget.HDDGraph(background='#808080', foreground='#000000', core='all', border_color="#470000", fill_color="#470000", path="/media/WDBL"), widget.TextBox("i7 3770:", background='#808080', foreground='#ffffff'), widget.ChThermalSensor(chip='coretemp-isa-0000', background='#470000', foreground='#ffffff'), widget.TextBox("GTX 1050 Ti:", background='#808080', foreground='#ffffff'), widget.GenPollText(func=get_my_gpu_temp, update_interval=1, background='#470000', foreground='#ffffff'), widget.TextBox("SSD:", background='#808080', foreground='#ffffff'), widget.HDThermalSensor(drive_name='/dev/sda', background='#470000', foreground='#ffffff'), widget.TextBox("HD0:", background='#808080', foreground='#ffffff'), widget.HDThermalSensor(drive_name='/dev/sdb', background='#470000', foreground='#ffffff'), widget.TextBox("HD1:", background='#808080', foreground='#ffffff'), widget.HDThermalSensor(drive_name='/dev/sdc', background='#470000', foreground='#ffffff'), widget.TextBox("CPU USAGE:", background='#808080', foreground='#ffffff'), widget.CPUGraph(background='#808080', foreground='#000000', core='all', border_color="#470000", fill_color="#470000"), widget.TextBox("MEM USAGE:", background='#808080', foreground='#ffffff'), widget.MemoryGraph(background='#808080', foreground='#000000', type='box', border_color="#470000", fill_color="#470000"), widget.TextBox("HD IO:", background='#808080', foreground='#ffffff'), widget.HDDBusyGraph(background='#808080', foreground='#000000', fill_color="#470000"), widget.TextBox("NET USAGE:", background='#808080', foreground='#ffffff'), widget.NetGraph(background='#808080', foreground='#000000', fill_color="#470000"), ], 24, ), ), ] ###################################################### # # MOUSE DRAG DEFINITIONS # ###################################################### # Drag floating layouts. mouse = [ Drag([mod], "Button1", lazy.window.set_position_floating(), start=lazy.window.get_position()), Drag([mod], "Button3", lazy.window.set_size_floating(), start=lazy.window.get_size()), Click([mod], "Button2", lazy.window.bring_to_front()) ] groups_key_binder = None dgroups_app_rules = [] main = None follow_mouse_focus = True bring_front_click = False cursor_warp = False floating_layout = layout.Floating(float_rules=[ {'wmclass': 'confirm'}, {'wmclass': 'dialog'}, {'wmclass': 'download'}, {'wmclass': 'error'}, {'wmclass': 'file_progress'}, {'wmclass': 'notification'}, {'wmclass': 'splash'}, {'wmclass': 'toolbar'}, {'wmclass': 'confirmreset'}, # gitk {'wmclass': 'makebranch'}, # gitk {'wmclass': 'maketag'}, # gitk {'wname': 'branchdialog'}, # gitk {'wname': 'pinentry'}, # GPG key password entry {'wmclass': 'ssh-askpass'}, # ssh-askpass ], border_focus='#ffd700', border_normal='#881111') ###################################################### # # HOOKS & AUTOSTART DEFINITIONS # ###################################################### @hook.subscribe.client_new def floating_dialogs(window): dialog = window.window.get_wm_type() == 'dialog' transient = window.window.get_wm_transient_for() if dialog or transient: window.floating = True @hook.subscribe.startup_once def autostart(): auto = os.path.expanduser('~/.config/qtile/autostart.sh') subprocess.Popen([auto]) ###################################################### # # WINDOW BEHAVIOR DEFINITIONS # ###################################################### # urgent: urgent flag is set for the window # focus: automatically focus the window # smart: automatically focus if the window is in the current group auto_fullscreen = True focus_on_window_activation = "urgent" ###################################################### # # WM NAME DEFINITION # ###################################################### # XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this # string besides java UI toolkits; you can see several discussions on the # mailing lists, github issues, and other WM documentation that suggest setting # this string if your java app doesn't work correctly. We may as well just lie # and say that we're a working one by default. # # We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in # java that happens to be on java's whitelist. wmname = "LG3D" # wmname = "QTile" <file_sep>/README.md # My Qtile WM config 2017: <img src="https://user-images.githubusercontent.com/9489149/33507162-636c4896-d71d-11e7-8b48-5eab2cb45fbd.png"/> <img src="https://user-images.githubusercontent.com/9489149/64248532-df035d00-cf00-11e9-900f-76d8d9062cb9.png"/> 2020: <img src="https://i.imgur.com/8we65zg.jpg"/> <img src="https://i.imgur.com/nKXFozx.jpg"/> <img src="https://i.imgur.com/sv1PgtN.png"/> ## My Daily Apps & Frameworks: * Qtile WM (Sitting inside IT!) * MPD + NCMPCPP (Listening music) * MPV (Watching video) * Ranger (Doing file management) * Vim + Leafpad (Writing some texts) * Feh (Looking at the images) * Mupdf (Reading pdfs) * Parcellite (Looking at the buffer manager to copypaste something) * Xarchiver (Backing up my precious data into the archives) * Rtorrent (Downloading restricted torrents while someone not looking at me) * Skype + Telegram + Hexchat + Firefox (Using this useless shit) * CherryTree (Making notes) * PyCharm (Having fun with Python code) * Blender (Doing my game assets) * Panda3D (Making my game using this awesomely small game engine) ## Requirements: * Python 3.x * dev-python/psutil * Sensor plugins and patch (included) Screenshots change constantly...
6cb5409e3e695d80219017d36b17362342df9f0e
[ "Markdown", "Python", "Shell" ]
3
Shell
kergalym/qtile_config
2746d1d794f1cadcbb9967ffad87cf09411f7e5a
47e3b7f4154ad77b1b3b231e62f8762620713693
refs/heads/master
<file_sep>import { Controller, Inject } from '@nestjs/common'; import { ClientKafka, MessagePattern, Payload } from '@nestjs/microservices'; @Controller() export class ReplyController { @MessagePattern('valida_algo') validaAlgo(@Payload() message) { console.log(message.value); return { reply:"reply" } } } <file_sep>version: "3.7" services: producer: build: context: . restart: always working_dir: /usr/src/app volumes: - .:/usr/src/app #networks: # - kafka_network extra_hosts: - "host.docker.internal:172.17.0.1" #networks: # kafka_network: # external: true volumes: dbdata: driver: local labels: mf.project.name: kafka-first-steps-producer<file_sep>const Kafka = require('no-kafka'); var valueSum = 0; // Create an instance of the Kafka consumer const consumer = new Kafka.SimpleConsumer({"connectionString":"host.docker.internal:9094"}) var data = function (messageSet) { messageSet.forEach(function (m) { if (typeof m.message.value !== 'object') { var value = parseInt(m.message.value.toString('utf8')); valueSum = valueSum + value; console.log("@@@ SUM: ",valueSum); return } console.log("@@@ OBJECT", m.message.value.toString()) }); }; // Subscribe to the Kafka topic return consumer.init().then(function () { return consumer.subscribe('my-first-topic', data); });<file_sep>import { NestFactory } from '@nestjs/core'; import { Transport } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // for consumers app.connectMicroservice({ transport: Transport.KAFKA, options: { client: { clientId: 'kafkaSample', brokers: ['host.docker.internal:9094'], }, consumer: { groupId: 'my-kafka-consumer' + Math.random() // Should be the same thing we give in consumer } } }); await app.startAllMicroservicesAsync(); await app.listen(3000); } bootstrap(); <file_sep>const express = require('express'); const app = express(); const Nightwatch = require('nightwatch'); app.get('/', (req, res) => { Nightwatch.cli(async function() { const runner = Nightwatch.CliRunner({ _source: ['tests/test.js'], }); await runner.setup({ 'selenium' : { start_process: false, 'host': 'standalone-chrome', cli_args: { 'webdriver.chrome.driver': require('chromedriver').path } }, desiredCapabilities: { browserName: 'chrome', javascriptEnabled: true, chromeOptions : { w3c: false }, }, //'testObject': message.value, -- passagem de dados para os testes }).startWebDriver(); try { await runner.runTests(); const testData = runner.testRunner.globalReporter.globalResults.modules.test.completed.test_generic; const results = testData.assertions; console.log('[result] = ', testData, results); } catch (err) { console.error('An error occurred:', err); } await runner.stopWebDriver(); }); }); app.listen(3000, () => { console.log('Server started at 3000'); });<file_sep>from kafka import KafkaProducer import json import random from time import sleep from datetime import datetime # Create an instance of the Kafka producer producer = KafkaProducer( bootstrap_servers='host.docker.internal:9094', #api_version=(2,6,0), value_serializer=lambda v: str(v).encode('utf-8') ) # Call the producer.send method with a producer-record count = 0; while (count<2): num = random.randint(1,999) producer.send('my-first-topic', num) print('sent num ', num) producer.flush() count = count+1 print("Good bye")<file_sep>import { Controller, Inject, OnModuleInit } from '@nestjs/common'; import { ClientKafka, MessagePattern, Payload } from '@nestjs/microservices'; @Controller() export class ConsumersController implements OnModuleInit { constructor( @Inject("KAFKA_SERVICE") private clientKafka: ClientKafka, ) { console.log("client kafka injected"); } async onModuleInit() { // Need to subscribe to topic // so that we can get the response from kafka microservice this.clientKafka.subscribeToResponseOf('valida_algo'); } @MessagePattern("horses") consumerHorse(@Payload() message){ console.log('consumer',message.value); return { status: "ok" } } @MessagePattern('horses') reply(@Payload() message) { console.log('reply', message); // observalbe -> promise this.clientKafka.send('valida_algo', {status:"ok"}).subscribe(reply => console.log(reply)); } } <file_sep>import { Module } from '@nestjs/common'; import { ClientsModule, Transport } from '@nestjs/microservices'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ConsumersController } from './consumers/consumers.controller'; import { ReplyController } from './reply/reply.controller'; @Module({ imports: [ // for producer ClientsModule.register([ { name: "KAFKA_SERVICE", transport: Transport.KAFKA, options: { client: { clientId: 'kafkaSample', brokers: ['host.docker.internal:9094'], }, consumer: { groupId: 'my-kafka-consumer' + Math.random() // Should be the same thing we give in consumer } } } ]) ], controllers: [AppController, ConsumersController, ReplyController], providers: [AppService], }) export class AppModule {} <file_sep>module.exports = { elements: { googleInputBox: '//input[@type="text"]', searchButton: '(//input[@value="Google Search"])[2]', headingText: `//h3[contains(text(),'Nightwatch.js')]` } }<file_sep>version: "3.7" services: nestjs: image: "node:current-alpine" privileged: true tty: true stdin_open: true restart: always working_dir: /home/node/app environment: - NODE_ENV=devlopment volumes: - ./src/:/home/node/app ports: - "3000:3000" command: "npm run start:dev" #networks: # - backend #- kafka_network extra_hosts: - "host.docker.internal:172.17.0.1" #networks: # backend: # kafka_network: # external: true volumes: dbdata: driver: local labels: mf.project.name: nestjs-apache-kafka-producer<file_sep>import { Test, TestingModule } from '@nestjs/testing'; import { ConsumersController } from './consumers.controller'; describe('ConsumersController', () => { let controller: ConsumersController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [ConsumersController], }).compile(); controller = module.get<ConsumersController>(ConsumersController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); }); <file_sep>import { Controller, Get, Inject, OnModuleInit } from '@nestjs/common'; import { Client, ClientKafka, MessagePattern, Payload, Transport } from "@nestjs/microservices"; import { Producer } from '@nestjs/microservices/external/kafka.interface'; import { AppService } from './app.service'; @Controller() export class AppController implements OnModuleInit { private kafkaProducer: Producer; constructor( private readonly appService: AppService, @Inject("KAFKA_SERVICE") private clientKafka: ClientKafka, ) { console.log("client kafka injected"); } async onModuleInit() { // Need to subscribe to topic // so that we can get the response from kafka microservice //this.clientKafka.subscribeToResponseOf('horses'); this.kafkaProducer = await this.clientKafka.connect(); } @Get() async goHorse() { const result = await this.kafkaProducer.send({ topic:"horses", messages: [ { key: Math.random()+"", value: JSON.stringify( { fruits: ["apple","banana","pineapple"] } ) } ] }); console.log('result', result); } } <file_sep>version: "3.7" services: worker: container_name: worker build: context: . restart: on-failure privileged: true tty: true stdin_open: true working_dir: /home/node/app environment: - NODE_ENV=devlopment volumes: - ./src:/home/node/app networks: - backend ports: - 3000:3000 #- kafka_network #extra_hosts: # - "host.docker.internal:172.17.0.1" depends_on: - standalone-chrome command: bash -c 'dockerize -wait tcp://standalone-chrome:4444 -timeout 60s -wait-retry-interval 10s node server.js' #e2e-test -- features/google.feature" links: - "standalone-chrome" #node-chrome: # container_name: node-chrome # image: selenium/node-chrome # volumes: # - /dev/shm:/dev/shm # ports: # - "6900:5900" # networks: # - backend #extra_hosts: # - "host.docker.internal:172.17.0.1" standalone-chrome: container_name: standalone-chrome image: selenium/standalone-chrome volumes: - /dev/shm:/dev/shm ports: - "4444:4444" networks: - backend #extra_hosts: # - "host.docker.internal:172.17.0.1" networks: backend: #kafka_network: # external: true volumes: dbdata: driver: local labels: mf.project.name: nigthwatchjs-cucumber<file_sep>npm run e2e-test -- features/file1.feature features/file2.feature
3931b63476bca4f48637359c5719c3e4f2ea93a2
[ "JavaScript", "Python", "TypeScript", "YAML" ]
14
TypeScript
marcosfreitas/first-steps-apache-kafka
90b8ca7d16dfaebf41e77d12070f888f7d44819b
4c4d69df0e09ef3b404f9182ab693e42355af9a8
refs/heads/master
<repo_name>eliehaykal/weatherapp_pub<file_sep>/weather.py import requests import time import datetime from flask import Flask, render_template, url_for, request, escape from requests.exceptions import HTTPError app = Flask(__name__) @app.route('/viewlog') def view_the_log(): # with open('vsearch.log') as log: # contents = log.read() # return escape(contents) contents = [] with open('vsearch.log') as log: for line in log: contents.append([]) for item in line.split('|'): contents[-1].append(escape(item)) print("Content List is:", contents) titles = ('Form Data', 'Remote_addr', 'User Agent', 'Lat/Long') # return str(contents) return render_template('viewlog.html', the_title='View Log', the_row_titles=titles, the_data=contents,) @app.route('/') def index(): return render_template('index.html') # return render_template('oops.html') @app.route('/getweather', methods=["POST"]) def getweather(): city = "none" longtitude = "none" latitude = "none" if(request.form['long'] != '' and request.form['lat'] != ''): longtitude = request.form['long'] latitude = request.form['lat'] print(latitude, longtitude, city) #################################################### ## Helper Functions ## def log_request(req, latitude, longtitude): with open('vsearch.log', 'a') as log: print(req.form, req.remote_addr, req.user_agent, latitude, longtitude, file=log, sep='|') # req attributes checked using print(str(dir(req))) def getCurrentDateDay(epochDate): # timeStr = time.strftime('%Y-%m-%d - %A', time.localtime(epochDate)) timeStr = time.strftime('%a (%d/%m) %H:%M:%S', time.localtime(epochDate)) # Full Documentation: https://docs.python.org/2/library/time.html#time.strftime return timeStr def getCurrentDateOpenWeather(epochDate): # timeStr = time.strftime('%Y-%m-%d - %A', time.localtime(epochDate)) timeStr = time.strftime('%a', time.localtime(epochDate)) + " -- " + time.strftime('%H:%M', time.localtime(epochDate)) # Full Documentation: https://docs.python.org/2/library/time.html#time.strftime return timeStr def getCurrentDateDayLineGraph(epochDate): # timeStr = time.strftime('%Y-%m-%d - %A', time.localtime(epochDate)) timeStr = "-" + time.strftime('%a', time.localtime(epochDate)) + \ " - " + time.strftime('%H:%M', time.localtime(epochDate)) # Full Documentation: https://docs.python.org/2/library/time.html#time.strftime return timeStr def getTimeFromEpoch(epochDate): timeStr = time.strftime('%H:%M:%S', time.localtime(epochDate)) return timeStr def roundNumbers(number): number = round(number) return number def averageDailyTemperature(): averageDailyTemperatureValue = float(darkSky["currentTemperature"]) + float( weatherStack["wsFeelsLike"]) + float(climaCell["ccDay1FeelsLike"]) averageDailyTemperatureValue = averageDailyTemperatureValue / 3 return roundNumbers(averageDailyTemperatureValue) def averageDailyHumidity(): averageDailyHumidityValue = float(darkSky["currentHumidity"]) + float( darkSky["dailyHumidity"]) + float(weatherStack['wsHumidity']) averageDailyHumidityValue = averageDailyHumidityValue / 3 return roundNumbers(averageDailyHumidityValue) def averageChanceOfRain(): averageChanceOfRainValue = float( darkSky['currentRainChance']) + float(darkSky['dailyRainChance']) averageChanceOfRainValue = averageChanceOfRainValue / 2 return roundNumbers(averageChanceOfRainValue) def percentageValueFix(precipProbability): precipProbability = round(int(precipProbability * 100)) return precipProbability #################################################### # OPENWEATHERMAP try: openweathermapURL_Coord = 'https://api.openweathermap.org/data/2.5/forecast?lat={}&lon={}&appid=bbe70a05814d1c2af5d001cb57b44910&units=metric' openweatherRes = requests.get( openweathermapURL_Coord.format(latitude, longtitude)) openweatherRes.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 return render_template('oops.html') except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 return render_template('oops.html') else: print('OpenWeather Success!') openweatherRes = openweatherRes.json() # print("OpenWeatherRes: ", openweatherRes) # Check for error in request # openweatherResText = str(openweatherRes) # print("OpenWeather Text: ", openweatherResText) openWeatherList = [] class C_OpenWeatherMap: EpochDate = "" Temp = "" TempMin = "" TempMax = "" Humidity = "" Weather = "" WeatherDescription = "" # print("Number of items in OpenWeather List:", len(openweatherRes['list'])) # if(skipAccuWeather == False and len(accuWeatherRes['DailyForecasts']) != 0): offSet = 0 for number in range(len(openweatherRes['list'])): if(offSet < 40): # 40 entries in list and need 10 items # print("offset:",offSet) OpenWeatherMapObject = C_OpenWeatherMap() OpenWeatherMapObject.EpochDate = getCurrentDateOpenWeather( openweatherRes['list'][offSet]['dt']) OpenWeatherMapObject.Temp = roundNumbers( openweatherRes['list'][offSet]['main']['temp']) OpenWeatherMapObject.MinTemp = roundNumbers( openweatherRes['list'][offSet]['main']['temp_min']) OpenWeatherMapObject.MaxTemp = roundNumbers( openweatherRes['list'][offSet]['main']['temp_max']) OpenWeatherMapObject.Humidity = roundNumbers( openweatherRes['list'][offSet]['main']['humidity']) OpenWeatherMapObject.Weather = openweatherRes['list'][offSet]['weather'][0]['main'] OpenWeatherMapObject.WeatherDescription = openweatherRes[ 'list'][offSet]['weather'][0]['description'] # print(OpenWeatherMapObject.Weather) offSet += 1 # print("\nPrinting openweather object: ",OpenWeatherMapObject) openWeatherList.append(OpenWeatherMapObject) # Forecast openWeatherMap = { 'day1Date': getCurrentDateDay(openweatherRes['list'][4]['dt']), 'day1Temp': roundNumbers(openweatherRes['list'][4]['main']['temp']), 'day1Min': roundNumbers(openweatherRes['list'][4]['main']['temp_min']), 'day1Max': roundNumbers(openweatherRes['list'][4]['main']['temp_max']), 'day1Humidity': roundNumbers(openweatherRes['list'][4]['main']['humidity']), 'day1Weather': openweatherRes['list'][4]['weather'][0]['main'], 'day1WeatherDescription': openweatherRes['list'][4]['weather'][0]['description'], 'day2Date': getCurrentDateDay(openweatherRes['list'][6]['dt']), 'day2Min': roundNumbers(openweatherRes['list'][6]['main']['temp_min']), 'day2Max': roundNumbers(openweatherRes['list'][6]['main']['temp_max']), 'day2Humidity': roundNumbers(openweatherRes['list'][6]['main']['humidity']), 'day2Temp': roundNumbers(openweatherRes['list'][6]['main']['temp']), 'day2Weather': openweatherRes['list'][6]['weather'][0]['main'], 'day2WeatherDescription': openweatherRes['list'][6]['weather'][0]['description'], 'day3Date': getCurrentDateDay(openweatherRes['list'][9]['dt']), 'day3Min': roundNumbers(openweatherRes['list'][9]['main']['temp_min']), 'day3Max': roundNumbers(openweatherRes['list'][9]['main']['temp_max']), 'day3Humidity': roundNumbers(openweatherRes['list'][9]['main']['humidity']), 'day3Temp': roundNumbers(openweatherRes['list'][9]['main']['temp']), 'day3Weather': openweatherRes['list'][9]['weather'][0]['main'], 'day3WeatherDescription': openweatherRes['list'][9]['weather'][0]['description'], 'day4Date': getCurrentDateDay(openweatherRes['list'][13]['dt']), 'day4Min': roundNumbers(openweatherRes['list'][13]['main']['temp_min']), 'day4Max': roundNumbers(openweatherRes['list'][13]['main']['temp_max']), 'day4Humidity': roundNumbers(openweatherRes['list'][13]['main']['humidity']), 'day4Temp': roundNumbers(openweatherRes['list'][13]['main']['temp']), 'day4Weather': openweatherRes['list'][13]['weather'][0]['main'], 'day4WeatherDescription': openweatherRes['list'][13]['weather'][0]['description'], 'day5Date': getCurrentDateDay(openweatherRes['list'][16]['dt']), 'day5Min': roundNumbers(openweatherRes['list'][16]['main']['temp_min']), 'day5Max': roundNumbers(openweatherRes['list'][16]['main']['temp_max']), 'day5Humidity': roundNumbers(openweatherRes['list'][16]['main']['humidity']), 'day5Temp': roundNumbers(openweatherRes['list'][16]['main']['temp']), 'day5Weather': openweatherRes['list'][16]['weather'][0]['main'], 'day5WeatherDescription': openweatherRes['list'][16]['weather'][0]['description'], 'day6Date': getCurrentDateDay(openweatherRes['list'][20]['dt']), 'day6Min': roundNumbers(openweatherRes['list'][20]['main']['temp_min']), 'day6Max': roundNumbers(openweatherRes['list'][20]['main']['temp_max']), 'day6Humidity': roundNumbers(openweatherRes['list'][20]['main']['humidity']), 'day6Temp': roundNumbers(openweatherRes['list'][20]['main']['temp']), 'day6Weather': openweatherRes['list'][20]['weather'][0]['main'], 'day6WeatherDescription': openweatherRes['list'][20]['weather'][0]['description'], 'day7Date': getCurrentDateDay(openweatherRes['list'][24]['dt']), 'day7Min': roundNumbers(openweatherRes['list'][24]['main']['temp_min']), 'day7Max': roundNumbers(openweatherRes['list'][24]['main']['temp_max']), 'day7Humidity': roundNumbers(openweatherRes['list'][24]['main']['humidity']), 'day7Temp': roundNumbers(openweatherRes['list'][24]['main']['temp']), 'day7Weather': openweatherRes['list'][24]['weather'][0]['main'], 'day7WeatherDescription': openweatherRes['list'][24]['weather'][0]['description'] } # print('openweathermap object' , openWeatherMap) #################################################### #################################################### # Darksky: xxxxxx # 33.875558399999996, 35.5237888 # Documentation: https://darksky.net/dev/docs#forecast-request # epochTime = int(time.time()) # darkskyURL = "https://api.darksky.net/forecast/xxxxxx/33.875558399999996,35.5237888,{}?units=si" # darkskyURL = "https://api.darksky.net/forecast/xxxxxx/{},{},{}?units=si" # darkskyRes = requests.get(darkskyURL.format(latitude,longtitude,epochTime)).json() # print("Darksky URL: ", darkskyURL.format(latitude,longtitude,epochTime)) # print("############################") # print("Darksky Response: ", darkskyRes) try: epochTime = int(time.time()) darkskyURL = "https://api.darksky.net/forecast/xxxxxx/{},{},{}?units=si" darkskyRes = requests.get(darkskyURL.format( latitude, longtitude, epochTime)) darkskyRes.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 return render_template('oops.html') except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 return render_template('oops.html') else: print('DarkSky Success!') darkskyRes = darkskyRes.json() # print("Darksky Response: ", darkskyRes) darkSky = { "currentSummary": darkskyRes['currently']['summary'], "currentTemperature": roundNumbers(darkskyRes['currently']['temperature']), "currentHumidity": roundNumbers(percentageValueFix(darkskyRes['currently']['humidity'])), "currentWindSpeed": darkskyRes['currently']['windSpeed'], "currentWindGust": darkskyRes['currently']['windGust'], "currentuvIndex": darkskyRes['currently']['uvIndex'], "currentRainChance": roundNumbers(percentageValueFix(darkskyRes['currently']['precipProbability'])), "currentCloudCover": roundNumbers(percentageValueFix(darkskyRes['currently']['cloudCover'])), # "currentRainType":darkskyRes['currently']['precipType'], "hourlySummaryH1": darkskyRes['hourly']['data'][5]['summary'], "hourlyRainChanceH1": percentageValueFix(darkskyRes['hourly']['data'][5]['precipProbability']), "hourlyTemperatureH1": roundNumbers(darkskyRes['hourly']['data'][5]['temperature']), "hourlyHumidityH1": percentageValueFix(darkskyRes['hourly']['data'][5]['humidity']), "hourlyWindSpeedH1": darkskyRes['hourly']['data'][5]['windSpeed'], "hourlyWindGustH1": darkskyRes['hourly']['data'][5]['windGust'], "hourlyuvIndexH1": darkskyRes['hourly']['data'][5]['uvIndex'], "hourlySummaryH2": darkskyRes['hourly']['data'][9]['summary'], "hourlyRainChanceH2": percentageValueFix(darkskyRes['hourly']['data'][9]['precipProbability']), "hourlyTemperatureH2": roundNumbers(darkskyRes['hourly']['data'][9]['temperature']), "hourlyHumidityH2": percentageValueFix(darkskyRes['hourly']['data'][9]['humidity']), "hourlyWindSpeedH2": darkskyRes['hourly']['data'][9]['windSpeed'], "hourlyWindGustH2": darkskyRes['hourly']['data'][9]['windGust'], "hourlyuvIndexH2": darkskyRes['hourly']['data'][9]['uvIndex'], "hourlySummaryH3": darkskyRes['hourly']['data'][15]['summary'], "hourlyRainChanceH3": percentageValueFix(darkskyRes['hourly']['data'][15]['precipProbability']), "hourlyTemperatureH3": roundNumbers(darkskyRes['hourly']['data'][15]['temperature']), "hourlyHumidityH3": percentageValueFix(darkskyRes['hourly']['data'][15]['humidity']), "hourlyWindSpeedH3": darkskyRes['hourly']['data'][15]['windSpeed'], "hourlyWindGustH3": darkskyRes['hourly']['data'][15]['windGust'], "hourlyuvIndexH3": darkskyRes['hourly']['data'][15]['uvIndex'], "hourlySummaryH4": darkskyRes['hourly']['data'][20]['summary'], "hourlyRainChanceH4": percentageValueFix(darkskyRes['hourly']['data'][20]['precipProbability']), "hourlyTemperatureH4": roundNumbers(darkskyRes['hourly']['data'][20]['temperature']), "hourlyHumidityH4": percentageValueFix(darkskyRes['hourly']['data'][20]['humidity']), "hourlyWindSpeedH4": darkskyRes['hourly']['data'][20]['windSpeed'], "hourlyWindGustH4": darkskyRes['hourly']['data'][20]['windGust'], "hourlyuvIndexH4": darkskyRes['hourly']['data'][20]['uvIndex'], "dailySummary": darkskyRes['daily']['data'][0]['summary'], "dailyTempHigh": roundNumbers(darkskyRes['daily']['data'][0]['temperatureHigh']), "dailyTempLow": roundNumbers(darkskyRes['daily']['data'][0]['temperatureLow']), "dailyRainChance": roundNumbers(percentageValueFix(darkskyRes['daily']['data'][0]['precipProbability'])), # "dailyRainType":darkskyRes['daily']['data'][0]['precipType'], "dailyHumidity": roundNumbers(percentageValueFix(darkskyRes['daily']['data'][0]['humidity'])), "dailyDewPoint": roundNumbers(darkskyRes['daily']['data'][0]['dewPoint']), "dailyWindSpeed": roundNumbers(darkskyRes['daily']['data'][0]['windSpeed']), "dailyWindGust": roundNumbers(darkskyRes['daily']['data'][0]['windGust']), "dailyCloudCover": roundNumbers(percentageValueFix(darkskyRes['daily']['data'][0]['cloudCover'])), "dailyMoonPhase": darkskyRes['daily']['data'][0]['moonPhase'], "dailySunrise": getTimeFromEpoch(darkskyRes['daily']['data'][0]['sunriseTime']), "dailySunset": getTimeFromEpoch(darkskyRes['daily']['data'][0]['sunsetTime']) } # print('Darksky object', darkSky) ##################WEATHERSTACK################################## # Weatherstack: xxxxxx (FREE PLAN: only current weather) # Documentation: https://weatherstack.com/documentation#query_parameter # weatherstackURL = "http://api.weatherstack.com/current?access_key=xxxxxx&&query=33.875558399999996,35.5237888&forecast_days=0&hourly=0&units=m" # weatherStackRes = requests.get(weatherstackURL).json() try: weatherstackURL = "http://api.weatherstack.com/current?access_key=xxxxxx&&query={},{}&units=m" weatherStackRes = requests.get( weatherstackURL.format(latitude, longtitude)) weatherStackRes.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 return render_template('oops.html') except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 return render_template('oops.html') else: print('WeatherStack Success!') weatherStackRes = weatherStackRes.json() # weatherstackURL = "http://api.weatherstack.com/current?access_key=xxxxxx&&query={},{}&forecast_days=5&hourly=0&units=m" weatherstackURL = "http://api.weatherstack.com/current?access_key=xxxxxx&&query={},{}&units=m" weatherStackRes = requests.get( weatherstackURL.format(latitude, longtitude)).json() # print("############################") # print("WeatherStack: ", weatherStackRes) weatherStack = { "wsTemperature": '-', "wsFeelsLike": '-', "wsWeatherIcon": '-', "wsWeatherDescription": '-', "wsWindSpeed": '-', "wsWindDirection": '-', "wsPrecipitation": '-', "wsHumidity": '-', "wsPressure": '-', "wsCloudCover": '-', "wsVisibility": '-', "wsUVIndex": '-', "wsGeoName": '-', "wsGeoCountry": '-', "wsGeoRegion": '-' } weatherStack = { "wsTemperature": weatherStackRes['current']['temperature'], "wsFeelsLike": weatherStackRes['current']['feelslike'], "wsWeatherIcon": weatherStackRes['current']['weather_icons'][0], "wsWeatherDescription": weatherStackRes['current']['weather_descriptions'][0], "wsWindSpeed": weatherStackRes['current']['wind_speed'], "wsWindDirection": weatherStackRes['current']['wind_dir'], "wsPrecipitation": weatherStackRes['current']['precip'], "wsHumidity": weatherStackRes['current']['humidity'], "wsPressure": weatherStackRes['current']['pressure'], "wsCloudCover": weatherStackRes['current']['cloudcover'], "wsVisibility": weatherStackRes['current']['visibility'], "wsUVIndex": weatherStackRes['current']['uv_index'], "wsGeoName": weatherStackRes['location']['name'], "wsGeoCountry": weatherStackRes['location']['country'], "wsGeoRegion": weatherStackRes['location']['region'], } # print("############################") # print("WeatherStack Object\n", weatherStack) ######################CLIMACELL############################## endDate = datetime.date.today() + datetime.timedelta(days=5) # print("End Date is: ", endDate) try: # Daily climacellDailyURL = "https://api.climacell.co/v3/weather/forecast/daily" querystringDaily = {"unit_system": "si", "start_time": "now", "end_time": endDate, "fields": "temp,precipitation,feels_like,wind_speed,moon_phase,weather_code", "apikey": "xxxxxx", "lat": latitude, "lon": longtitude} climaCellRes = requests.request( "GET", climacellDailyURL, params=querystringDaily) climaCellRes.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 return render_template('oops.html') except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 return render_template('oops.html') else: print('ClimaCell Daily Success!') climaCellRes = climaCellRes.json() # print("ClimacellRes: ", climaCellRes) try: # Realtime climacellRealtimeURL = "https://api.climacell.co/v3/weather/realtime" querystringRealtime = {"unit_system": "si", "apikey": "xxxxxx", "lat": latitude, "lon": longtitude, "fields": "temp,feels_like,dewpoint,humidity,wind_speed,precipitation,precipitation_type,epa_primary_pollutant,epa_aqi,pollen_tree,epa_health_concern,moon_phase,weather_code"} climaCellRealTimeRes = requests.request( "GET", climacellRealtimeURL, params=querystringRealtime) climaCellRealTimeRes.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 return render_template('oops.html') except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 return render_template('oops.html') else: print('ClimaCell Realtime Success!') climaCellRealTimeRes = climaCellRealTimeRes.json() # print("climaCellRealTimeRes: ", climaCellRealTimeRes) # Daily # climacellDailyURL = "https://api.climacell.co/v3/weather/forecast/daily" # querystringDaily = {"unit_system":"si","start_time":"now","end_time":endDate, # "fields":"temp,precipitation,feels_like,wind_speed,moon_phase,weather_code", # "apikey":"xxxxxx", "lat":latitude, "lon":longtitude} # climaCellRes = requests.request("GET", climacellDailyURL, params=querystringDaily).json() # print("ClimaCell Daily:",climaCellRes) # Realtime climacellRealtimeURL = "https://api.climacell.co/v3/weather/realtime" querystringRealtime = {"unit_system": "si", "apikey": "xxxxxx", "lat": latitude, "lon": longtitude, "fields": "temp,feels_like,dewpoint,humidity,wind_speed,precipitation,precipitation_type,epa_primary_pollutant,epa_aqi,pollen_tree,epa_health_concern,moon_phase,weather_code"} climaCellRealTimeRes = requests.request( "GET", climacellRealtimeURL, params=querystringRealtime).json() # print("CCRES Realtime" , climaCellRealTimeRes) climaCell = { "ccDay1ObservationTime": climaCellRes[0]['temp'][0]['observation_time'], "ccDay1MinTemp": roundNumbers(climaCellRes[0]['temp'][0]['min']['value']), "ccDay1MaxTemp": roundNumbers(climaCellRes[0]['temp'][1]['max']['value']), "ccDay1Precip": roundNumbers(climaCellRes[0]['precipitation'][0]['max']['value']), "ccDay1FeelsLike": roundNumbers(climaCellRes[0]['feels_like'][0]['min']['value']), "ccDay1WindSpeed": roundNumbers(climaCellRes[0]['wind_speed'][1]['max']['value']), "ccDay1MoonPhase": climaCellRes[0]['moon_phase']['value'], "ccDay2ObservationTime": climaCellRes[1]['temp'][0]['observation_time'], "ccDay2MinTemp": roundNumbers(climaCellRes[1]['temp'][0]['min']['value']), "ccDay2MaxTemp": roundNumbers(climaCellRes[1]['temp'][1]['max']['value']), "ccDay2Precip": roundNumbers(climaCellRes[1]['precipitation'][0]['max']['value']), "ccDay2FeelsLike": roundNumbers(climaCellRes[1]['feels_like'][0]['min']['value']), "ccDay2WindSpeed": roundNumbers(climaCellRes[1]['wind_speed'][1]['max']['value']), "ccDay2MoonPhase": climaCellRes[1]['moon_phase']['value'], "ccDay3ObservationTime": climaCellRes[2]['temp'][0]['observation_time'], "ccDay3MinTemp": roundNumbers(climaCellRes[2]['temp'][0]['min']['value']), "ccDay3MaxTemp": roundNumbers(climaCellRes[2]['temp'][1]['max']['value']), "ccDay3Precip": roundNumbers(climaCellRes[2]['precipitation'][0]['max']['value']), "ccDay3FeelsLike": roundNumbers(climaCellRes[2]['feels_like'][0]['min']['value']), "ccDay3WindSpeed": roundNumbers(climaCellRes[2]['wind_speed'][1]['max']['value']), "ccDay3MoonPhase": climaCellRes[2]['moon_phase']['value'], "ccDay4ObservationTime": climaCellRes[3]['temp'][0]['observation_time'], "ccDay4MinTemp": roundNumbers(climaCellRes[3]['temp'][0]['min']['value']), "ccDay4MaxTemp": roundNumbers(climaCellRes[3]['temp'][1]['max']['value']), "ccDay4Precip": roundNumbers(climaCellRes[3]['precipitation'][0]['max']['value']), "ccDay4FeelsLike": roundNumbers(climaCellRes[3]['feels_like'][0]['min']['value']), "ccDay4WindSpeed": roundNumbers(climaCellRes[3]['wind_speed'][1]['max']['value']), "ccDay4MoonPhase": climaCellRes[3]['moon_phase']['value'], "ccDay5ObservationTime": climaCellRes[4]['temp'][0]['observation_time'], "ccDay5MinTemp": roundNumbers(climaCellRes[4]['temp'][0]['min']['value']), "ccDay5MaxTemp": roundNumbers(climaCellRes[4]['temp'][1]['max']['value']), "ccDay5Precip": roundNumbers(climaCellRes[4]['precipitation'][0]['max']['value']), "ccDay5FeelsLike": roundNumbers(climaCellRes[4]['feels_like'][0]['min']['value']), "ccDay5WindSpeed": roundNumbers(climaCellRes[4]['wind_speed'][1]['max']['value']), "ccDay5MoonPhase": climaCellRes[4]['moon_phase']['value'], "ccDay6ObservationTime": climaCellRes[5]['temp'][0]['observation_time'], "ccDay6MinTemp": roundNumbers(climaCellRes[5]['temp'][0]['min']['value']), "ccDay6MaxTemp": roundNumbers(climaCellRes[5]['temp'][1]['max']['value']), "ccDay6Precip": roundNumbers(climaCellRes[5]['precipitation'][0]['max']['value']), "ccDay6FeelsLike": roundNumbers(climaCellRes[5]['feels_like'][0]['min']['value']), "ccDay6WindSpeed": roundNumbers(climaCellRes[5]['wind_speed'][1]['max']['value']), "ccDay6MoonPhase": climaCellRes[5]['moon_phase']['value'], "ccRealtimeTemp": roundNumbers(climaCellRealTimeRes['temp']['value']), "ccRealtimeFeelsLike": roundNumbers(climaCellRealTimeRes['feels_like']['value']), "ccRealtimeWindSpeed": climaCellRealTimeRes['wind_speed']['value'], "ccRealtimeHumidity": roundNumbers(climaCellRealTimeRes['humidity']['value']), "ccRealtimeDewPoint": climaCellRealTimeRes['dewpoint']['value'], "ccRealtimePrecipitation": climaCellRealTimeRes['precipitation']['value'], "ccRealtimeEpaValue": climaCellRealTimeRes['epa_aqi']['value'], "ccRealtimeHealthConcern": climaCellRealTimeRes['epa_health_concern']['value'], "ccRealtimeMoonPhase": climaCellRealTimeRes['moon_phase']['value'], "ccRealtimeWeatherCode": climaCellRealTimeRes['weather_code']['value'] # "ccRealtimeArea":climaCellRealTimeRes['Getting Accuweather City']['AdministrativeArea']['LocalizedName'], # "ccRealtimeCountryID":climaCellRealTimeRes['Getting Accuweather City']['AdministrativeArea']['CountryID'], # "ccRealtimeTimeZone":climaCellRealTimeRes['Getting Accuweather City']['AdministrativeArea']['GmtOffset'], # "ccRealtimeElevation":climaCellRealTimeRes['Getting Accuweather City']['GeoPosition']['Elevation']['Metric']['Value'] } # print("############################") # print(climaCell) # print("#MoonPhase is ------------ ", climaCell["ccRealtimeMoonPhase"]) # ACCUWEATHER###############################accuweather: xxxxxx try: cityURL = "http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=xxxxxx&q={}%2C{}" accuweatherURL = "http://dataservice.accuweather.com/forecasts/v1/daily/5day/{}?apikey=xxxxxx&metric=true" getCity = requests.get(cityURL.format(latitude, longtitude)).json() # print("Getting Accuweather City:", getCity) getCityText = str(getCity) except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Python 3.6 return render_template('oops.html') except Exception as err: print(f'Other error occurred: {err}') # Python 3.6 return render_template('oops.html') else: skipAccuWeather = False # Code': 'ServiceUnavailable', 'Message': 'The allowed number of requests has been exceeded.', ' # Reference': '/locations/v1/cities/geoposition/search?apikey=xxxxxx&q=33.893791300000004%2C35.5017767'} if('exceeded' not in getCityText): accuCityInfo = { 'accuCityName': getCity['LocalizedName'], 'accuCountryName': getCity['Country']['LocalizedName'], 'accuAdministrativeArea': getCity['AdministrativeArea']['LocalizedName'], 'accuTimeZone': getCity['TimeZone']['GmtOffset'], 'accuGeoPositionLat': getCity['GeoPosition']['Latitude'], 'accuGeoPositionLong': getCity['GeoPosition']['Longitude'], 'accuGeoPositionElevation': getCity['GeoPosition']['Elevation']['Metric']['Value'] } accuWeatherRes = requests.get( accuweatherURL.format(getCity)).json() # accuWeatherResText = requests.get(accuweatherURL.format(getCity)).text accuWeatherResText = str(accuWeatherRes) # print("PRINTING ACCUWEATHER #####", accuWeatherRes) # print("PRINTING accuWeatherResText #####", accuWeatherResText) # Check if api calls are exceeded if("exceeded" in accuWeatherResText or "failed" in accuWeatherResText): skipAccuWeather = True # Error Message # {'Code': 'ServiceUnavailable', 'Message': 'The allowed number of requests has been exceeded.', # 'Reference': '/locations/v1/cities/geoposition/search?apikey=xxxxxx&q=33.893791300000004%2C35.5017767'} # accuWeatherHeadline = { # "accuHeadlineText": accuWeatherRes['Headline']['Text'], # "accuHeadlineCategory": accuWeatherRes['Headline']['Category'] # } accuWeatherList = [''] accuWeatherValid = False class AccuweatherObject: EpochDate = "" TempMin = "" TempMax = "" DaySummary = "" NightSummary = "" DayHasPrecipitation = "" DayPrecipitationType = "" DayPrecipitationIntensity = "" NightHasPrecipitation = "" NightPrecipitationType = "" NightPrecipitationIntensity = "" # print("SkipAccuWeather?", skipAccuWeather) # print("dailyForecast", len(accuWeatherRes['DailyForecasts'])) # check if we have one item if(skipAccuWeather == False and len(accuWeatherRes['DailyForecasts']) != 0): for day in range(len(accuWeatherRes['DailyForecasts'])): dayObj = AccuweatherObject() # Init Object dayObj.EpochDate = getCurrentDateDay( accuWeatherRes['DailyForecasts'][day]['EpochDate']) dayObj.TempMin = accuWeatherRes['DailyForecasts'][day]['Temperature']['Minimum']['Value'] dayObj.TempMax = accuWeatherRes['DailyForecasts'][day]['Temperature']['Maximum']['Value'] dayObj.DaySummary = accuWeatherRes['DailyForecasts'][day]['Day']['IconPhrase'] dayObj.NightSummary = accuWeatherRes['DailyForecasts'][day]['Night']['IconPhrase'] dayObj.DayHasPrecipitation = accuWeatherRes[ 'DailyForecasts'][day]['Day']['HasPrecipitation'] # Checking Day Precipitation dayObj.DayHasPrecipitation = accuWeatherRes[ 'DailyForecasts'][day]['Day']['HasPrecipitation'] if accuWeatherRes['DailyForecasts'][day]['Day']['HasPrecipitation'] == True: dayObj.DayPrecipitationType = accuWeatherRes[ 'DailyForecasts'][day]['Day']['PrecipitationType'] dayObj.DayPrecipitationIntensity = accuWeatherRes[ 'DailyForecasts'][day]['Day']['PrecipitationIntensity'] # Checking Night Precipitation dayObj.NightHasPrecipitation = accuWeatherRes[ 'DailyForecasts'][day]['Night']['HasPrecipitation'] if accuWeatherRes['DailyForecasts'][day]['Night']['HasPrecipitation'] == True: dayObj.NightPrecipitationType = accuWeatherRes[ 'DailyForecasts'][day]['Night']['PrecipitationType'] dayObj.NightPrecipitationIntensity = accuWeatherRes[ 'DailyForecasts'][day]['Night']['PrecipitationIntensity'] # Append Object accuWeatherList.append(dayObj) accuWeatherValid = True # print(type(accuWeatherList), accuWeatherList, accuWeatherList[0].TempMax) else: skipAccuWeatherCity = True skipAccuWeather = True accuCityInfo = {} accuWeatherList = [''] accuWeatherValid = False ########################################################### # Calculate Global Average Values which are displayed at the top of the page globalTemp = averageDailyTemperature() globalHumidity = averageDailyHumidity() globalRainChance = averageChanceOfRain() # print("Printing openweatherlist: ",openWeatherList , '## count:', len(openWeatherList)) ########################################################### # return "" # return render_template('weather.html', openWeatherMap=openWeatherMap, darksky=darkSky, weatherStack=weatherStack, climaCell=climaCell, lenAccuWeather = len(accuWeatherList) ,accuWeatherList=accuWeatherList, accuWeatherValid=accuWeatherValid) # Generate logs log_request(request, latitude, longtitude) return render_template( 'weather.html', openWeatherMap=openWeatherMap, darksky=darkSky, weatherStack=weatherStack, climaCell=climaCell, globalTemp=globalTemp, globalHumidity=globalHumidity, globalRainChance=globalRainChance, lenAccuWeather=len(accuWeatherList), accuWeatherList=accuWeatherList, lenOpenWeather=len(openWeatherList), openWeatherList=openWeatherList, accuWeatherValid=accuWeatherValid, accuCityInfo=accuCityInfo ) if __name__ == '__main__': # app.run(debug=True, host='0.0.0.0', port='8080',ssl_context='adhoc') #turn on debug for compiling changes on the fly app.run(debug=True) # turn on debug for compiling changes on the fly <file_sep>/README.md # weatherapp_pub A Weather app created using Flask. Fetches weather data from 5 well-known sources. * API Keys have been removed for obvious reasons * I coded this as a hobby and it was a great learning experience as it was developed using Python/HTML5/CSS/Javascript skills. <file_sep>/templates/weather.html <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>WEATHER 360&#176;</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> <!-- Chartist --> <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css"> <!-- My CSS --> <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet"> <link href="{{ url_for('static', filename='css/localcss.css') }}" rel="stylesheet"> <!-- Chartist JS --> <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script> </head> <body> <div class='pageTitle'><img class="pageTitleImg" src="{{ url_for('static', filename='assets/img/main/sun.png') }}"> Weather 360&#176; <img class="pageTitleImg" src="{{ url_for('static', filename='assets/img/main/rain.png') }}"></div> <div class="container"> <!-- <script type="text/javascript" src="..\static\javascript\geolocation.js"></script> --> <script type="text/javascript" src="{{ url_for('static', filename='javascript/geolocation.js')}}"></script> <!-- ..\static\javascript\geolocation.js --> <!-- <p class="globalTitle">Calulcated Weather for Today</p> --> <table class="table"> <tbody> <!-- <tr> <td></td> <td></td> <td style="text-align: center;">{{weatherStack.wsGeoName}} - {{weatherStack.wsGeoRegion}} - {{weatherStack.wsGeoCountry}}</td> <td></td> <td></td> </tr> --> <tr> <td></td> <td></td> <td style="text-align: center;"><u>Location:</u> {{accuCityInfo.accuCityName}}, {{accuCityInfo.accuAdministrativeArea}}, {{accuCityInfo.accuCountryName}} - <u>TimeZone (GMT):</u> {{accuCityInfo.accuTimeZone}} </td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td style="text-align: center;"><u>Lat:</u> {{accuCityInfo.accuGeoPositionLat}} - <u>Long:</u> {{accuCityInfo.accuGeoPositionLong}} - <u>Elevation:</u> {{accuCityInfo.accuGeoPositionElevation}} m </td> <td></td> <td></td> </tr> </tbody> </table> <!-- accuCityInfo = { 'accuCityName':getCity['LocalizedName'], 'accuCountryName':getCity['Country']['LocalizedName'], 'accuAdministrativeArea':getCity['AdministrativeArea']['LocalizedName'], 'accuTimeZone':getCity['TimeZone']['GmtOffset'], 'accuGeoPositionLat':getCity['GeoPosition']['Latitude'], 'accuGeoPositionLong':getCity['GeoPosition']['Longitude'], 'accuGeoPositionElevation':getCity['GeoPosition']['Elevation']['Metric']['Value'] } --> <div style="text-align: center;"><img src="{{weatherStack.wsWeatherIcon}}"></div> <div id="weatherTitle"> {{darksky.currentSummary}}<br><span class='summaryDaily'>({{darksky.dailySummary}})</span> </div> <div class="container calculatedTemp"> <div class="row global"> <div class="col-sm"> <p><span class="globalText"><img src="..\static\assets\img\temp.png" width="60px" title="Temperature" ></span> <span class="globalTemp">{{globalTemp}}&#8451;</span> </p> </div> <div class="col-sm"> <p><span class="globalText"><img src="..\static\assets\img\humidity.png" width="60px" title="Humidity"></span> <span class="globalHumidity">{{globalHumidity}}%</span> </p> </div> <div class="col-sm"> <p><span class="globalText"><img src="..\static\assets\img\umbrella.svg" width="60px" title="Rain Chance"></span> <span class="globalRain">{{globalRainChance}}%</span></p> </div> </div> <div class="row global"> <div class="col-sm"> <p><span class="globalLabel">Air Quality:<br></span> {{climaCell.ccRealtimeEpaValue}}<br>({{climaCell.ccRealtimeHealthConcern}}) </p> </div> <div class="col-sm"> <p><span class="globalLabel">Cloud Cover:<br></span> {{darksky.currentCloudCover}}%</p> </div> <div class="col-sm"> <p><span class="globalLabel">Visibility:<br></span> {{weatherStack.wsVisibility}} KM</p> </div> <!-- <div class="col-sm"> <p>Moon Phase: {% if climaCell.ccRealtimeMoonPhase == 'new_moon' %} <img src="..\static\assets\img\moon\new_moon.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waxing_crescent' %} <img src="..\static\assets\img\moon\waxing_crescent.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waning_crescent' %} <img src="..\static\assets\img\moon\waning_crescent.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'first_quarter' %} <img src="..\static\assets\img\moon\first_quarter.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'third_quarter' %} <img src="..\static\assets\img\moon\third_quarter.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waxing_gibbous' %} <img src="..\static\assets\img\moon\waxing_gibbous.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waning_gibbous' %} <img src="..\static\assets\img\moon\waning_gibbous.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'full_moon' %} <img src="..\static\assets\img\moon\full_moon.png" width="60px" title="New Moon">{% endif %} </p> </div> --> </div> <div class="row global"> <div class="col-sm"> <p><span class="globalLabel">Pressure:<br></span> {{weatherStack.wsPressure}} millibar</p> </div> <div class="col-sm"> <p></p> </div> <div class="col-sm"> <p><span class="globalLabel">Wind:</span><br>{{weatherStack.wsWindSpeed}} (km/h) - {{weatherStack.wsWindDirection}} </p> </div> </div> <div class="row global"> </div> <div class="row global"> <div class="col-sm"> <p><img src="..\static\assets\img\sunrise.png" width="60px" title="Sunrise"> {{darksky.dailySunrise}}</p> </div> <div class="col-sm"> <p> <span class="globalLabel">Moon Phase:<br></span> <!-- {{climaCell.ccRealtimeMoonPhase}} --> {% if climaCell.ccRealtimeMoonPhase == 'new' %} <img src="..\static\assets\img\moon\new_moon.png" width="60px" title="New Moon">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waxing_crescent' %} <img src="..\static\assets\img\moon\waxing_crescent.png" width="60px" title="Waxing Crescent">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waning_crescent' %} <img src="..\static\assets\img\moon\waning_crescent.png" width="60px" title="Waning Crescent">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'first_quarter' %} <img src="..\static\assets\img\moon\first_quarter.png" width="60px" title="First Quarter">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'third_quarter' %} <img src="..\static\assets\img\moon\third_quarter.png" width="60px" title="Third Quarter">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waxing_gibbous' %} <img src="..\static\assets\img\moon\waxing_gibbous.png" width="60px" title="Waxing Gibbous">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'waning_gibbous' %} <img src="..\static\assets\img\moon\waning_gibbous.png" width="60px" title="Waning Gibbous">{% endif %} {% if climaCell.ccRealtimeMoonPhase == 'full' %} <img src="..\static\assets\img\moon\full_moon.png" width="60px" title="Full Moon">{% endif %} </p> </div> <div class="col-sm"> <p><img src="..\static\assets\img\sunset.png" width="60px" title="Sunset"> {{darksky.dailySunset}}</p> </div> </div> </div> <!-- <table class="table table-bordered table-sm text-center"> <thead> <tr> <th style="background-color: #333333; color:#fff8dc;">The Day Ahead</th> <th><u>Current:</u> {{darksky.currentSummary}}</th> <th><u>All Day:</u> {{darksky.dailySummary}}</th> </tr> </thead> </table> --> <!-- <p class="subtitlev1">Current Weather:</p><p class="summary">{{darksky.currentSummary}}</p> --> <!-- Aggregate Table --> <p class="subtitlev1">Right Now</p> <table class="table table-borderless"> <thead> <tr> <th><u>Source</u></th> <th><u>DarkSky</u></th> <th><u>ClimaCell</u></th> <th><u>WeatherStack</u></th> </tr> </thead> <tbody> <tr> <td class="temp customTable">Temperature (&#8451;) [Feels Like]</td> <td>{{darksky.currentTemperature}}</td> <td>{{climaCell.ccRealtimeTemp}} <b>[{{climaCell.ccRealtimeFeelsLike}}]</b></td> <td>{{weatherStack.wsTemperature}} <b>[{{weatherStack.wsFeelsLike}}]</b></td> </tr> <tr> <td class="humidity customTable"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> Humidity </td> <td>{{darksky.currentHumidity}}%</td> <td>{{climaCell.ccRealtimeHumidity}}%</td> <td>{{weatherStack.wsHumidity}}%</td> </tr> <tr> <td class="customTable"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed"> Wind (Gust) </td> <td>{{darksky.currentWindSpeed}}m/s ({{darksky.currentWindGust}}m/s)</td> <td>{{climaCell.ccRealtimeWindSpeed}}m/s</td> <td>{{weatherStack.wsWindSpeed}} <b>kph</b> - {{weatherStack.wsWindDirection}} </td> </tr> <tr> <td class="rain customTable"><img src="..\static\assets\img\umbrella.svg" width="30px" title="Rain"> Rain</td> <td>Chance: {{darksky.currentRainChance}}% ({{darksky.currentRainType}})</td> <td>{{climaCell.ccRealtimePrecipitation}} mm</td> <td>{{weatherStack.wsPrecipitation}} mm</td> </tr> <tr> <td class="customTable"><img src="..\static\assets\img\uv.png" width="30px" title="UV Index"> UV</td> <td> {% if darksky.currentuvIndex <= 2 %} <span class="lowIndex">{{darksky.currentuvIndex}} (Low)</span>{% endif %} {% if darksky.currentuvIndex > 2 and darksky.currentuvIndex <=5 %} <span class="mediumIndex"> {{darksky.currentuvIndex}} (Medium)</span>{% endif %} {% if darksky.currentuvIndex > 5 and darksky.currentuvIndex <=7 %} <span class="highIndex"> {{darksky.currentuvIndex}} (High)</span>{% endif %} {% if darksky.currentuvIndex > 7 and darksky.currentuvIndex <=10 %} <span class="veryHighIndex"> {{darksky.currentuvIndex}} (Very High)</span>{% endif %} {% if darksky.currentuvIndex > 10 %} <span class="extremelyHighIndex">{{darksky.currentuvIndex}} (Extremely High)</span>{% endif %} </td> <td> {% if weatherStack.wsUVIndex <= 2 %} <span class="lowIndex">{{weatherStack.wsUVIndex}} (Low)</span>{% endif %} {% if weatherStack.wsUVIndex > 2 and weatherStack.wsUVIndex <=5 %} <span class="mediumIndex"> {{weatherStack.wsUVIndex}} (Medium)</span>{% endif %} {% if weatherStack.wsUVIndex > 5 and weatherStack.wsUVIndex <=7 %} <span class="highIndex"> {{weatherStack.wsUVIndex}} (High)</span>{% endif %} {% if weatherStack.wsUVIndex > 7 and weatherStack.wsUVIndex <=10 %} <span class="veryHighIndex"> {{weatherStack.wsUVIndex}} (Very High)</span>{% endif %} {% if weatherStack.wsUVIndex > 10 %} <span class="extremelyHighIndex">{{weatherStack.wsUVIndex}} (Extremely High)</span>{% endif %} </td> </tr> </tbody> </table> <hr> <p class="subtitlev1">Day Summary</p> <table class="table table-striped table-borderless"> <thead> <tr> <th scope="col">Time</th> <th scope="col">Summary</th> <th scope="col" class="temp">Temp (&#8451;)</th> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> <th scope="col"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed">(m/s)</th> <th scope="col">Wind Gust</th> <th scope="col"><img src="..\static\assets\img\uv.png" width="30px" title="UV Index"></th> <th scope="col" class="rain"><img src="..\static\assets\img\umbrella.svg" width="30px" title="Rain Chance"></th> <th scope="col" class="rain">Rain Type</th> </tr> </thead> <tbody> <tr> <td><span class="timeperiod">Early Morning</span></td> <td>{{darksky.hourlySummaryH1}}</td> <td>{{darksky.hourlyTemperatureH1}}</td> <td>{{darksky.hourlyHumidityH1}}%</td> <td>{{darksky.hourlyWindSpeedH1}}</td> <td>{{darksky.hourlyWindGustH1}}</td> <td>{{darksky.hourlyuvIndexH1}}</td> <td>{{darksky.hourlyRainChanceH1}}%</td> <td>{{darksky.hourlyRainTypeH1}}</td> </tr> <tr> <td><span class="timeperiod">Morning</span></td> <td>{{darksky.hourlySummaryH2}}</td> <td>{{darksky.hourlyTemperatureH2}}</td> <td>{{darksky.hourlyHumidityH2}}%</td> <td>{{darksky.hourlyWindSpeedH2}}</td> <td>{{darksky.hourlyWindGustH2}}</td> <td>{{darksky.hourlyuvIndexH2}}</td> <td>{{darksky.hourlyRainChanceH2}}%</td> <td>{{darksky.hourlyRainTypeH2}}</td> </tr> <tr> <td><span class="timeperiod">Afternoon</span></td> <td>{{darksky.hourlySummaryH3}}</td> <td>{{darksky.hourlyTemperatureH3}}</td> <td>{{darksky.hourlyHumidityH3}}%</td> <td>{{darksky.hourlyWindSpeedH3}}</td> <td>{{darksky.hourlyWindGustH3}}</td> <td>{{darksky.hourlyuvIndexH3}}</td> <td>{{darksky.hourlyRainChanceH3}}%</td> <td>{{darksky.hourlyRainTypeH3}}</td> </tr> <tr> <td><span class="timeperiod">Evening</span></td> <td>{{darksky.hourlySummaryH4}}</td> <td>{{darksky.hourlyTemperatureH4}}</td> <td>{{darksky.hourlyHumidityH4}}%</td> <td>{{darksky.hourlyWindSpeedH4}}</td> <td>{{darksky.hourlyWindGustH4}}</td> <td>{{darksky.hourlyuvIndexH4}}</td> <td>{{darksky.hourlyRainChanceH4}}%</td> <td>{{darksky.hourlyRainTypeH4}}</td> </tr> </tbody> </table> <p class="subtitlev1">All Day</p> </p> <table class="table table-borderless"> <thead> <tr> <!-- <th scope="col">Summary</th> --> <th scope="col" class="temp">Min (&#8451;)</th> <th scope="col" class="temp">Max (&#8451;)</th> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> <th scope="col"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed">(m/s)</th> <th scope="col">Wind Gust</th> <th scope="col" class="rain"><img src="..\static\assets\img\umbrella.svg" width="30px" title="Rain Chance"></th> <th scope="col" class="rain">Rain Type</th> <th scope="col">Dewpoint (&#8451;)</th> <th scope="col">Cloud Cover</th> <!-- <th scope="col">Moon Phase</th> --> </tr> </thead> <tbody> <tr> <!-- <td>{{darksky.dailySummary}}</td> --> <td>{{darksky.dailyTempLow}}</td> <td>{{darksky.dailyTempHigh}}</td> <td>{{darksky.dailyHumidity}}%</td> <td>{{darksky.dailyWindSpeed}}</td> <td>{{darksky.dailyWindGust}}</td> <td>{{darksky.dailyRainChance}}%</td> <td>{{darksky.dailyRainType}}</td> <td>{{darksky.dailyDewPoint}}</td> <td>{{darksky.dailyCloudCover}}%</td> <!-- <td>{{darksky.dailyMoonPhase}}</td> --> </tr> </tbody> </table> <hr> <p class="subtitlev1">Forecast</p> <p class="source">Source: OpenWeather</p> <table class="table table-striped table-borderless table-sm"> <thead> <tr> <th scope="col">Date</th> <th scope="col" class="temp">Temp (&#8451;)</th> <!-- <th scope="col" class="temp">Min (&#8451;)</th> --> <!-- <th scope="col" class="temp">Max (&#8451;)</th> --> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> <th scope="col">Weather</th> <th scope="col">Weather Description</th> </tr> </thead> <tbody> {%for i in range(lenOpenWeather)%} <tr> <th scope="row" class="dates">{{openWeatherList[i].EpochDate}}</th> <td>{{openWeatherList[i].Temp}} </td> <!-- <td>{{openWeatherList[i].MinTemp}} </td> --> <!-- <td>{{openWeatherList[i].MaxTemp}}</td> --> <td>{{openWeatherList[i].Humidity}}% </td> <!-- <td>{{openWeatherList[i].Weather}} </td> --> <td> {% if openWeatherList[i].Weather == "Rain" or openWeatherList[i].Weather == "Snow" or openWeatherList[i].Weather == "Drizzle" %}<span class='rain'>{{openWeatherList[i].Weather}}</span>{% endif %} {% if openWeatherList[i].Weather == "Clouds" %}<span class='cloud'>{{openWeatherList[i].Weather}}</span>{% endif %} {% if openWeatherList[i].Weather == "Clear" %}<span class='clear'>{{openWeatherList[i].Weather}}</span>{% endif %} </td> <!-- <td>{{openWeatherList[i].Weather}}</td> --> <td>{{openWeatherList[i].WeatherDescription}}</td> </tr> {%endfor%} </tbody> </table> <p class="source">Source: ClimaCell</p> <table class="table table-striped table-borderless table-sm"> <thead> <tr> <th scope="col">Day</th> <th scope="col" class="temp">Feels Like (&#8451;)</th> <th scope="col" class="rain">Precipitation</th> <th scope="col"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed"></th> <th scope="col">Moon Phase</th> </tr> </thead> <tbody> <tr> <th scope="row" class="dates">{{climaCell.ccDay1ObservationTime}}</th> <td>{{climaCell.ccDay1FeelsLike}}</td> <td>{{climaCell.ccDay1Precip}} </td> <td>{{climaCell.ccDay1WindSpeed}}</td> <td>{{climaCell.ccDay1MoonPhase}}</td> </tr> <tr> <th scope="row" class="dates">{{climaCell.ccDay2ObservationTime}}</th> <td>{{climaCell.ccDay2FeelsLike}}</td> <td>{{climaCell.ccDay2Precip}} </td> <td>{{climaCell.ccDay2WindSpeed}}</td> <td>{{climaCell.ccDay2MoonPhase}}</td> </tr> <tr> <th scope="row" class="dates">{{climaCell.ccDay3ObservationTime}}</th> <td>{{climaCell.ccDay3FeelsLike}}</td> <td>{{climaCell.ccDay3Precip}} </td> <td>{{climaCell.ccDay3WindSpeed}}</td> <td>{{climaCell.ccDay3MoonPhase}}</td> </tr> <tr> <th scope="row" class="dates">{{climaCell.ccDay4ObservationTime}}</th> <td>{{climaCell.ccDay4FeelsLike}}</td> <td>{{climaCell.ccDay4Precip}} </td> <td>{{climaCell.ccDay4WindSpeed}}</td> <td>{{climaCell.ccDay4MoonPhase}}</td> </tr> <tr> <th scope="row" class="dates">{{climaCell.ccDay5ObservationTime}}</th> <td>{{climaCell.ccDay5FeelsLike}}</td> <td>{{climaCell.ccDay5Precip}} </td> <td>{{climaCell.ccDay5WindSpeed}}</td> <td>{{climaCell.ccDay5MoonPhase}}</td> </tr> <tr> <th scope="row" class="dates">{{climaCell.ccDay6ObservationTime}}</th> <td>{{climaCell.ccDay6FeelsLike}}</td> <td>{{climaCell.ccDay6Precip}} </td> <td>{{climaCell.ccDay6WindSpeed}}</td> <td>{{climaCell.ccDay6MoonPhase}}</td> </tr> </tbody> </table> <!-- Charting --> <h1>Temp Forecast</h1> <div class="ct-chart ct-series-a ct-line" id="chartTemp"> </div> <h1>Humidity Forecast</h1> <div class="ct-chart" id="chartHumidty"> </div> <!-- bootstrap container --> <hr> <hr> <hr> <hr> <hr> <table class="table table-borderless"> <thead> <tr> <th scope="col" class="temp">Temp (&#8451;)</th> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> <th scope="col"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed">(m/s)</th> <!-- Wind Speed--> <th scope="col">Wind Gust</th> <th scope="col"><img src="..\static\assets\img\uv.png" width="30px" title="UV Index"></th> <!--UV Index--> <th scope="col" class="rain"><img src="..\static\assets\img\umbrella.svg" width="30px" title="Rain Chance"></th> <th scope="col" class="rain">Rain Type</th> <th scope="col">Cloud Cover</th> </tr> </thead> <tbody> <tr> <td>{{darksky.currentTemperature}}</td> <td>{{darksky.currentHumidity}}%</td> <td>{{darksky.currentWindSpeed}}</td> <td>{{darksky.currentWindGust}}</td> <td>{{darksky.currentuvIndex}}</td> <td>{{darksky.currentRainChance}}%</td> <td>{{darksky.currentRainType}}</td> <td>{{darksky.currentCloudCover}}%</td> </tr> </tbody> </table> <p class="source">Source: ClimaCell (Realtime)</p> <table class="table table-borderless"> <thead> <tr> <th scope="col" class="temp">Temp (&#8451;)</th> <th scope="col" class="temp">Feels Like (&#8451;)</th> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> <th scope="col"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed">(m/s)</th> <th scope="col" class="rain">Precipitation</th> <th scope="col">Dewpoint (&#8451;)</th> <!-- <th scope="col">Air Quality</th> --> <!-- <th scope="col">Health Concern</th> --> <th scope="col">Weather</th> <!-- <th scope="col">Moon</th> --> </tr> </thead> <tbody> <tr> <!-- <th scope="row">Today</th> --> <td>{{climaCell.ccRealtimeTemp}}</td> <td>{{climaCell.ccRealtimeFeelsLike}}</td> <td>{{climaCell.ccRealtimeHumidity}}%</td> <td>{{climaCell.ccRealtimeWindSpeed}}</td> <td>{{climaCell.ccRealtimePrecipitation}} mm</td> <td>{{climaCell.ccRealtimeDewPoint}}</td> <!-- <td>{{climaCell.ccRealtimeEpaValue}}</td> --> <!-- <td>{{climaCell.ccRealtimeHealthConcern}}</td> --> <td>{{climaCell.ccRealtimeWeatherCode}}</td> <!-- <td>{{climaCell.ccRealtimeMoonPhase}}</td> --> </tr> </tbody> </table> <hr> <p class="source">Source: WeatherStack (Realtime)</p> <table class="table table-borderless"> <thead> <tr> <!-- <th scope="col">Date</th> --> <!-- <th scope="col">Summary</th> --> <th scope="col" class="temp">Temp (&#8451;)</th> <th scope="col" class="temp">Feels Like (&#8451;)</th> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> <th scope="col"><img src="..\static\assets\img\wind.png" width="30px" title="Wind Speed"></th> <!-- <th scope="col">Wind Drection</th> --> <th scope="col" class="rain"><img src="..\static\assets\img\umbrella.svg" width="30px" title="Rain Chance"></th> <th scope="col">Pressure</th> <th scope="col">Cloud Cover</th> <th scope="col"><img src="..\static\assets\img\uv.png" width="30px" title="UV Index"></th> <th scope="col">Visibility</th> <th scope="col">Name</th> <!-- <th scope="col">Country</th> <th scope="col">Region</th> <th scope="col">Graphic</th> --> </tr> </thead> <tbody> <tr> <!-- <th scope="row">Today</th> --> <!-- <td>{{weatherStack.wsWeatherDescription}}</td> --> <td>{{weatherStack.wsTemperature}}</td> <td>{{weatherStack.wsFeelsLike}}</td> <td>{{weatherStack.wsHumidity}}%</td> <td>{{weatherStack.wsWindSpeed}} - {{weatherStack.wsWindDirection}} </td> <!-- <td>{{weatherStack.wsWindDirection}}</td> --> <td>{{weatherStack.wsPrecipitation}} mm</td> <td>{{weatherStack.wsPressure}}</td> <td>{{weatherStack.wsCloudCover}}%</td> <td>{{weatherStack.wsUVIndex}}</td> <td>{{weatherStack.wsVisibility}} KM</td> <!-- <td>{{weatherStack.wsGeoName}}</td> <td>{{weatherStack.wsGeoCountry}}</td> <td>{{weatherStack.wsGeoRegion}}</td> --> <td><img src="{{weatherStack.wsWeatherIcon}}"></td> </tr> </tbody> </table> <p class="source">Source: OpenWeather</p> <table class="table table-striped table-borderless table-sm"> <thead> <tr> <th scope="col">Date</th> <th scope="col">Weather</th> <th scope="col">Weather Description</th> <th scope="col" class="temp">Temp (&#8451;)</th> <!-- <th scope="col" class="temp">Min (&#8451;)</th> --> <!-- <th scope="col" class="temp">Max (&#8451;)</th> --> <th scope="col" class="humidity"><img src="..\static\assets\img\humidity.png" width="30px" title="Humidity"> </th> </tr> </thead> <tbody> <tr> <th scope="row" class="dates">{{openWeatherMap.day1Date}}</th> <td>{{openWeatherMap.day1Weather}}</td> <td>{{openWeatherMap.day1WeatherDescription}}</td> <td>{{openWeatherMap.day1Temp}}</td> <!-- <td>{{openWeatherMap.day1Min}}</td> --> <!-- <td>{{openWeatherMap.day1Max}}</td> --> <td>{{openWeatherMap.day1Humidity}}%</td> </tr> <tr> <th scope="row" class="dates">{{openWeatherMap.day2Date}}</th> <td>{{openWeatherMap.day2Weather}}</td> <td>{{openWeatherMap.day2WeatherDescription}}</td> <td>{{openWeatherMap.day2Temp}}</td> <!-- <td>{{openWeatherMap.day2Min}}</td> --> <!-- <td>{{openWeatherMap.day2Max}}</td> --> <td>{{openWeatherMap.day2Humidity}}%</td> </tr> <tr> <th scope="row" class="dates">{{openWeatherMap.day3Date}}</th> <td>{{openWeatherMap.day3Weather}}</td> <td>{{openWeatherMap.day3WeatherDescription}}</td> <td>{{openWeatherMap.day3Temp}}</td> <!-- <td>{{openWeatherMap.day3Min}}</td> --> <!-- <td>{{openWeatherMap.day3Max}}</td> --> <td>{{openWeatherMap.day3Humidity}}%</td> </tr> <tr> <th scope="row" class="dates">{{openWeatherMap.day4Date}}</th> <td>{{openWeatherMap.day4Weather}}</td> <td>{{openWeatherMap.day4WeatherDescription}}</td> <td>{{openWeatherMap.day4Temp}}</td> <!-- <td>{{openWeatherMap.day4Min}}</td> --> <!-- <td>{{openWeatherMap.day4Max}}</td> --> <td>{{openWeatherMap.day4Humidity}}%</td> </tr> <tr> <th scope="row" class="dates">{{openWeatherMap.day5Date}}</th> <td>{{openWeatherMap.day5Weather}}</td> <td>{{openWeatherMap.day5WeatherDescription}}</td> <td>{{openWeatherMap.day5Temp}}</td> <!-- <td>{{openWeatherMap.day5Min}}</td> --> <!-- <td>{{openWeatherMap.day5Max}}</td> --> <td>{{openWeatherMap.day5Humidity}}%</td> </tr> <tr> <th scope="row" class="dates">{{openWeatherMap.day6Date}}</th> <td>{{openWeatherMap.day6Weather}}</td> <td>{{openWeatherMap.day6WeatherDescription}}</td> <td>{{openWeatherMap.day6Temp}}</td> <!-- <td>{{openWeatherMap.day6Min}}</td> --> <!-- <td>{{openWeatherMap.day6Max}}</td> --> <td>{{openWeatherMap.day6Humidity}}%</td> </tr> <tr> <th scope="row" class="dates">{{openWeatherMap.day7Date}}</th> <td>{{openWeatherMap.day7Weather}}</td> <td>{{openWeatherMap.day7WeatherDescription}}</td> <td>{{openWeatherMap.day7Temp}}</td> <!-- <td>{{openWeatherMap.day7Min}}</td> --> <!-- <td>{{openWeatherMap.day7Max}}</td> --> <td>{{openWeatherMap.day7Humidity}}%</td> </tr> </tbody> </table> <hr> </div> </body> <script> var data1 = { // A labels array that can contain any sort of values // labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], labels: [ '{{openWeatherList[0].EpochDate}}', '{{openWeatherList[1].EpochDate}}', '{{openWeatherList[2].EpochDate}}', '{{openWeatherList[3].EpochDate}}', '{{openWeatherList[4].EpochDate}}', '{{openWeatherList[5].EpochDate}}', '{{openWeatherList[6].EpochDate}}', '{{openWeatherList[7].EpochDate}}', '{{openWeatherList[8].EpochDate}}', '{{openWeatherList[9].EpochDate}}', '{{openWeatherList[10].EpochDate}}', '{{openWeatherList[11].EpochDate}}', '{{openWeatherList[12].EpochDate}}', '{{openWeatherList[13].EpochDate}}', '{{openWeatherList[14].EpochDate}}', '{{openWeatherList[15].EpochDate}}', '{{openWeatherList[16].EpochDate}}', '{{openWeatherList[17].EpochDate}}', '{{openWeatherList[18].EpochDate}}', '{{openWeatherList[19].EpochDate}}', ], // Our series array that contains series objects or in this case series data arrays // series: [ // [5, 2, 4, 2, 0] // ] series: [ [ '{{openWeatherList[0].Temp}}', '{{openWeatherList[1].Temp}}', '{{openWeatherList[2].Temp}}', '{{openWeatherList[3].Temp}}', '{{openWeatherList[4].Temp}}', '{{openWeatherList[5].Temp}}', '{{openWeatherList[6].Temp}}', '{{openWeatherList[7].Temp}}', '{{openWeatherList[8].Temp}}', '{{openWeatherList[9].Temp}}', '{{openWeatherList[10].Temp}}', '{{openWeatherList[11].Temp}}', '{{openWeatherList[12].Temp}}', '{{openWeatherList[13].Temp}}', '{{openWeatherList[14].Temp}}', '{{openWeatherList[15].Temp}}', '{{openWeatherList[16].Temp}}', '{{openWeatherList[17].Temp}}', '{{openWeatherList[18].Temp}}', '{{openWeatherList[19].Temp}}', ], ] }; var data2 = { // A labels array that can contain any sort of values // labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], labels: [ '{{openWeatherList[0].EpochDate}}', '{{openWeatherList[1].EpochDate}}', '{{openWeatherList[2].EpochDate}}', '{{openWeatherList[3].EpochDate}}', '{{openWeatherList[4].EpochDate}}', '{{openWeatherList[5].EpochDate}}', '{{openWeatherList[6].EpochDate}}', '{{openWeatherList[7].EpochDate}}', '{{openWeatherList[8].EpochDate}}', '{{openWeatherList[9].EpochDate}}', '{{openWeatherList[10].EpochDate}}', '{{openWeatherList[11].EpochDate}}', '{{openWeatherList[12].EpochDate}}', '{{openWeatherList[13].EpochDate}}', '{{openWeatherList[14].EpochDate}}', '{{openWeatherList[15].EpochDate}}', '{{openWeatherList[16].EpochDate}}', '{{openWeatherList[17].EpochDate}}', '{{openWeatherList[18].EpochDate}}', '{{openWeatherList[19].EpochDate}}', ], series: [ [ '{{openWeatherList[0].Humidity}}', '{{openWeatherList[1].Humidity}}', '{{openWeatherList[2].Humidity}}', '{{openWeatherList[3].Humidity}}', '{{openWeatherList[4].Humidity}}', '{{openWeatherList[5].Humidity}}', '{{openWeatherList[6].Humidity}}', '{{openWeatherList[7].Humidity}}', '{{openWeatherList[8].Humidity}}', '{{openWeatherList[9].Humidity}}', '{{openWeatherList[10].Humidity}}', '{{openWeatherList[11].Humidity}}', '{{openWeatherList[12].Humidity}}', '{{openWeatherList[13].Humidity}}', '{{openWeatherList[14].Humidity}}', '{{openWeatherList[15].Humidity}}', '{{openWeatherList[16].Humidity}}', '{{openWeatherList[17].Humidity}}', '{{openWeatherList[18].Humidity}}', '{{openWeatherList[19].Humidity}}', ] ] }; var options1 = { width: 1200, height: 300 }; // Create a new line chart object where as first parameter we pass in a selector // that is resolving to our chart container element. The Second parameter // is the actual data object. new Chartist.Line('#chartTemp', data1, options1); new Chartist.Line('#chartHumidty', data2, options1); </script> </html>
ea3dd77304a36f5a879f8c06a7165907f1661eae
[ "Markdown", "Python", "HTML" ]
3
Python
eliehaykal/weatherapp_pub
79744249aebeec5c78f429209135c477b841edf0
f345b587b866748117d9026f4037025c2db13c68
refs/heads/master
<repo_name>mecus/urgy-front<file_sep>/src/app/store-management/actions/ordersum.action.ts import { Action } from '@ngrx/store'; export const PUSH = '[SUM] PUSH'; <file_sep>/src/app/router-outlets/check-outlet.component.ts import { Component, OnInit } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Cart } from '../store-management/models/cart.model'; import * as Rx from 'rxjs/Rx'; import * as fromRoot from '../store-management/reducers/reducers'; import { PUSH } from '../store-management/actions/ordersum.action'; @Component({ selector: 'check-outlet', templateUrl: './check-outlet.component.html', styleUrls: ['./styles.scss'] }) export class CheckOutletComponent implements OnInit { basket; totalPrice; ship = 0.00; constructor(private store: Store<any>){ this.basket = store.select('cart'); store.pipe(select(fromRoot.selectFeatureShip)).subscribe((shp)=>{ this.ship = Number(shp.price); // console.log(shp); store.dispatch({type: PUSH, payload: {total: (this.totalPrice + this.ship)}}); }); store.pipe(select('cart')).subscribe((cart: Cart[]) => { let total = cart.map(cart=>cart.qty * Number(cart.price)); this.totalPrice = Number(total.reduce(this.reducePrice, 0).toFixed(2)); // console.log(this.totalPrice + this.ship) store.dispatch({type: PUSH, payload: {total: (this.totalPrice + this.ship)}}); }); } reducePrice(sum, num){ return sum + num; } ngOnInit(){ Rx.Observable.timer(300).subscribe ((T) => { let main = document.getElementById('main-content'); let sideC = document.getElementById('sidecart'); let side = document.getElementById('inner-side'); main.style.width = "70%"; sideC.style.width = "30%"; main.style.transition = "0.3s"; sideC.style.transition = "0.3s"; side.style.marginRight = "0px"; side.style.transition = "0.4s"; }); } }<file_sep>/src/app/services/order.service.ts import { Injectable } from '@angular/core'; import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore'; import { HttpClient, HttpRequest, HttpHeaders, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/merge'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/share'; import { Serverendpoints } from '../environment-var'; @Injectable() export class OrderService { host: string = Serverendpoints.host; api_v1: string = Serverendpoints.api_v; itemUrl: string = "items/"; url; options; constructor(private _http: HttpClient){ this.url = this.host+this.api_v1; this.options = { headers: new HttpHeaders({ "Content-Type": "application/json" }) } } getCustomerOrders(customer_no){ let options = {params: new HttpParams().set('qy', customer_no)}; return this._http.get(this.url+"customer_orders", options); } postOrder(order){ return this._http.post(this.url+"orders", order, this.options); // .subscribe(); } updateOrder(update){ return this._http.post(this.host+this.api_v1+"update_order", update, this.options); } deleteOrder(id){ let options = {params: new HttpParams().set('id', id)}; return this._http.delete(this.host+this.api_v1+"delete_order", options); } // Function Deprecated createOrderItems(item){ return this._http.post(this.url+this.itemUrl, item, this.options) .map((data)=>{ return data; },(err)=>console.log(err)); // .subscribe(); } }<file_sep>/src/app/admin/advertisements/advert-list.component.ts import { Component, OnInit } from '@angular/core'; import { StoreService } from '../services/store.service'; import { UploadImageService } from '../services/image-upload.service'; @Component({ selector: 'admin-advert', templateUrl: './advert-list.component.html', styleUrls: ['./adverts.component.scss'] }) export class AdvertsComponent implements OnInit { advert$; constructor( private storeService: StoreService, private uploadImage: UploadImageService, ) { this.advert$ = storeService.getAdverts() .map(snapshot => { return snapshot.map(ad => { let id = ad.payload.doc.id; let data = ad.payload.doc.data(); return {id, ...data}; }) }); } async removeAdvert(ad){ let d = confirm("Are you sure"); let path = "adverts/" if(d){ let deletAd = await this.storeService.removeAdverts(ad.id); let deletIm = await this.uploadImage.removeStorageFile(path, ad.image_name); console.log("Advert Deleted:", deletAd); console.log("Image Removed:", deletIm); } } ngOnInit() { } }<file_sep>/src/app/admin/advertisements/advert-add.component.ts import { Component, OnInit, HostListener } from '@angular/core'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { UploadImageService } from '../services/image-upload.service'; import { StoreService } from '../services/store.service'; import { Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import * as Rx from 'rxjs/Rx'; @Component({ selector: 'admin-advert-add', templateUrl: './advert-add.component.html', styleUrls: ['./adverts.component.scss'] }) export class AdvertAddComponent implements OnInit { statusdMsg; files; formInput: FormGroup; color; timer = Rx.Observable.timer(2000); sections = ["home", "home slide", "department", "product", "product offer"]; constructor( private fb: FormBuilder, private uploadImage: UploadImageService, private storeService: StoreService, private _router: Router ) { this.formGroup(); } formGroup(){ this.formInput = this.fb.group({ title: ["", Validators.required], section: ["", Validators.required], image_name: [""], tag: [""], image_url: [""] }); } @HostListener('change', ['$event']) fileCahnge(e:any){ e.preventDefault(); e.stopPropagation(); if(!e.target.files){ return; } this.files = e.target.files[0]; } async sendAdvert(ad){ console.log(ad); if(!this.files){ this.color = 'red'; return this.statusdMsg = "Please upload image before submitting"; } this.color = 'blue'; this.statusdMsg = "Image Upload Started...."; let path = 'adverts/'; let imageUrl = await this.uploadImage.uploadImage(this.files, path); if(imageUrl){ this.color = 'green'; this.statusdMsg = "Image Upload Completed!! Saving files in the database..."; ad.image_url = imageUrl.downloadURL; ad.image_name = this.files.name; this.storeService.saveAdvert(ad).then((res)=>{ console.log(res) this.color = 'green'; this.statusdMsg = "Process Completed Successfully"; this.timer.subscribe(T => { this._router.navigate(["/admin/advertisements"]); }) }) .catch((err)=> { console.log(err); }); } } ngOnInit() { } }<file_sep>/src/app/services/payment.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { AccountService } from './account.service'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/merge'; import { Serverendpoints } from '../environment-var'; @Injectable() export class PaymentService { host: string = Serverendpoints.host; api: string = Serverendpoints.api_v; url:string; cardUrl: string; transactionUrl: string; constructor(private _http:HttpClient){ this.url = this.host+this.api+"gettoken"; this.cardUrl = this.host+this.api+"payment/customer/"; this.transactionUrl = this.host+"api_v1/transaction"; } public getClientToken():Observable<any>{ return this._http.get(this.url); } //Creating payment method public createPaymentMethod(payload, methd){ let data = {...payload, "type": methd}; let options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } return this._http.post(this.host+this.api+"payment_method", data, options); // .subscribe(); } //fatching customer with payment method fetchCard(key){ return this._http.get(this.cardUrl+key) } //Creating payment transaction paymentTransaction(payment){ let options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } return this._http.post(this.transactionUrl, payment, options); } // Get Customer with the payment method getCustomerWithPaymentMethod(id){ const options = {params: new HttpParams().set('id', id)}; return this._http.get(this.host+this.api+"get_customer", options); } }<file_sep>/src/app/store-management/models/shipping.model.ts export interface iShip { option: string, price: string }<file_sep>/src/app/store-management/reducers/ordersum.reducer.ts import { Action, ActionReducer } from '@ngrx/store'; import { PUSH } from '../actions/ordersum.action'; interface Sum { total: string; } const init = { total: '2.50' } export function ordersumReducer<ActionReducer>(state:Sum = init, action){ switch(action.type){ case PUSH: return action.payload; default: return state; } }<file_sep>/src/app/store-management/actions/shipping.ts import { Action } from '@ngrx/store'; export const PUSH = '[SHIP] PUSH'; <file_sep>/src/app/services/clearfunction.service.ts import { Injectable } from '@angular/core'; import { WindowService } from "./window.service"; import { Store } from '@ngrx/store'; import * as shopActions from '../store-management/actions/shop.action'; @Injectable() export class ClearHeighlightMenu { document; constructor( private windowRef:WindowService, private store: Store<any>){ this.document = this.windowRef.getDocumentRef(); } clearMenu(){ let i; let tab = this.document.getElementsByClassName('nav-link'); for (i = 0; i < tab.length; i++) { // tab[i].className = tab[i].className.replace("active", ""); tab[i].style.backgroundColor = "transparent"; tab[i].style.color = "#ffffff"; } // this.store.dispatch({type: shopActions.DEPARTMENT, payload: {id: null, name: null}}); } }<file_sep>/src/app/functions/payment-methods.ts export class PaymentMethods { public braintreeCardForm; constructor(storeService){ this.braintreeCardForm = ()=>{ var form = document.querySelector('#my-sample-form'); var submit = document.querySelector('input[type="submit"]'); braintree.client.create({ authorization: storeService.retriveData('token') }, function (err, clientInstance) { if (err) { console.error(err); return; } // Create input fields and add text styles braintree.hostedFields.create({ client: clientInstance, styles: { 'input': { 'color': '#282c37', 'font-size': '16px', 'transition': 'color 0.1s', 'line-height': '3' }, // Style the text of an invalid input 'input.invalid': { 'color': '#E53A40' }, // placeholder styles need to be individually adjusted '::-webkit-input-placeholder': { 'color': 'rgba(0,0,0,0.6)' }, ':-moz-placeholder': { 'color': 'rgba(0,0,0,0.6)' }, '::-moz-placeholder': { 'color': 'rgba(0,0,0,0.6)' }, ':-ms-input-placeholder': { 'color': 'rgba(0,0,0,0.6)' } }, // Add information for individual fields fields: { number: { selector: '#card-number', placeholder: '1111 1111 1111 1111' }, cvv: { selector: '#cvv', placeholder: '123' }, expirationDate: { selector: '#expiration-date', placeholder: '10 / 2019' } } }, function (err, hostedFieldsInstance) { if (err) { console.error(err); return; } hostedFieldsInstance.on('validityChange', function (event) { // Check if all fields are valid, then show submit button var formValid = Object.keys(event.fields).every(function (key) { return event.fields[key].isValid; }); if (formValid) { $('#button-pay').addClass('show-button'); } else { $('#button-pay').removeClass('show-button'); } }); hostedFieldsInstance.on('empty', function (event) { $('header').removeClass('header-slide'); $('#card-image').removeClass(); $(form).removeClass(); }); hostedFieldsInstance.on('cardTypeChange', function (event) { // Change card bg depending on card type if (event.cards.length === 1) { $(form).removeClass().addClass(event.cards[0].type); $('#card-image').removeClass().addClass(event.cards[0].type); $('header').addClass('header-slide'); // Change the CVV length for AmericanExpress cards if (event.cards[0].code.size === 4) { hostedFieldsInstance.setAttribute({ field: 'cvv', attribute: 'placeholder', value: '1234' }); } } else { hostedFieldsInstance.setAttribute({ field: 'cvv', attribute: 'placeholder', value: '123' }); } }); submit.addEventListener('click', function (event) { event.preventDefault(); hostedFieldsInstance.tokenize(function (err, payload) { if (err) { console.error(err); return; } // This is where you would submit payload.nonce to your server alert('Submit your nonce to your server here!'); }); }, false); }); }); } } } <file_sep>/src/app/container/check-out/payment-method/payment-method.component.ts import { Component, OnInit, OnDestroy, HostListener } from '@angular/core'; import { Router } from '@angular/router'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { AccountService } from '../../../services/account.service'; import { StorageService } from '../../../services/storage.service'; import { Observable } from 'rxjs/Observable'; import { PaymentService } from "../../../services/payment.service"; import { WindowService } from "../../../services/window.service"; import { AuthService } from "../../../authentications/authentication.service"; import { OrderService } from "../../../services/order.service"; import { CartService } from "../../../services/cart.service"; // import { TempOrderType } from "../../../models/tempOrder.model"; import * as _ from 'lodash'; import { ProgressService } from '../../../services/checkout-progress.service'; import { Store } from '@ngrx/store'; @Component({ selector: 'app-payment-method', templateUrl: './payment-method.component.html', styleUrls: ['./payment-method.component.scss', './card.scss'] }) export class PaymentMethodComponent implements OnInit, OnDestroy{ document; paymentMethod; paymentAdded; notice:string; customer; paypal; card; constructor(private accountService:AccountService, private authService:AuthService, private storeService:StorageService, private _fb:FormBuilder, private _router:Router, private paymentService:PaymentService, private windowService:WindowService, private cartService:CartService, private orderService:OrderService, private store: Store<any>) { this.document = this.windowService.getDocumentRef(); store.select('auth').subscribe((auth)=>{ if(auth.uid){ this.customer = { uid: auth.uid, method :{ customerId: auth.account_no, paymentMethodNonce: null, options: { makeDefault: true }, billingAddress: { streetAddress: auth.address.address, locality: auth.address.city, postalCode: auth.address.post_code, countryName: auth.address.country } } } this.paymentService.getCustomerWithPaymentMethod(auth.account_no) .subscribe((cus: any)=> { console.log(cus); this.paypal = cus.paypal; this.card = cus.card; }); } }); } // Push Token to the store or local storage paymentToken(token){ console.log(token); let confarm = confirm('Click OK if you are happy to use your selection'); if(!confarm){ return null; } this.storeService.storeData('payToken', token); this._router.navigate(["/check/delivery_method"]); } ngOnInit() { this.braintreeCardForm(); this.braintreePaypal(); } ngOnDestroy(){ } // Card Payment Method function braintreeCardForm = () =>{ var form = document.querySelector('#my-sample-form'); var submit = document.querySelector('input[type="submit"]'); braintree.client.create({ authorization: this.storeService.retriveData('token') }, (err, clientInstance)=> { if (err) { console.error(err); return; } // Create input fields and add text styles braintree.hostedFields.create({ client: clientInstance, styles: { 'input': { 'color': '#282c37', 'font-size': '16px', 'transition': 'color 0.1s', 'line-height': '3' }, // Style the text of an invalid input 'input.invalid': { 'color': '#E53A40' }, // placeholder styles need to be individually adjusted '::-webkit-input-placeholder': { 'color': 'rgba(0,0,0,0.6)' }, ':-moz-placeholder': { 'color': 'rgba(0,0,0,0.6)' }, '::-moz-placeholder': { 'color': 'rgba(0,0,0,0.6)' }, ':-ms-input-placeholder': { 'color': 'rgba(0,0,0,0.6)' } }, // Add information for individual fields fields: { number: { selector: '#card-number', placeholder: '1111 1111 1111 1111' }, cvv: { selector: '#cvv', placeholder: '123' }, expirationDate: { selector: '#expiration-date', placeholder: '10 / 2019' } } }, (err, hostedFieldsInstance)=> { if (err) { console.error(err); return; } hostedFieldsInstance.on('validityChange', (event)=> { // Check if all fields are valid, then show submit button let formValid = Object.keys(event.fields).every( (key)=> { return event.fields[key].isValid; }); if (formValid) { $('#button-pay').addClass('show-button'); } else { $('#button-pay').removeClass('show-button'); } }); hostedFieldsInstance.on('empty', (event)=> { $('header').removeClass('header-slide'); $('#card-image').removeClass(); $(form).removeClass(); }); hostedFieldsInstance.on('cardTypeChange', (event)=> { // Change card bg depending on card type if (event.cards.length === 1) { $(form).removeClass().addClass(event.cards[0].type); $('#card-image').removeClass().addClass(event.cards[0].type); $('header').addClass('header-slide'); // Change the CVV length for AmericanExpress cards if (event.cards[0].code.size === 4) { hostedFieldsInstance.setAttribute({ field: 'cvv', attribute: 'placeholder', value: '1234' }); } } else { hostedFieldsInstance.setAttribute({ field: 'cvv', attribute: 'placeholder', value: '123' }); } }); submit.addEventListener('click', (event)=> { event.preventDefault(); hostedFieldsInstance.tokenize( (err, payload)=> { if (err) { console.error(err); return; } // This is where you would submit payload.nonce to your server // alert('Submit your nonce to your server here!'); const methods = this.customer; methods.method.paymentMethodNonce = payload.nonce; this.paymentService.createPaymentMethod(methods, "card") .subscribe((res: any)=>{ // this.returnResult.emit(res); // update ui for the user info const token = res.result.paymentMethod.token; this.paymentToken(token); console.log(res); }); }); }, false); }); }); } // Initialize Paypal Button braintreePaypal = ()=> { braintree.client.create({ authorization: this.storeService.retriveData('token') },(clientErr, clientInstance)=> { // Stop if there was a problem creating the client. // This could happen if there is a network error or if the authorization // is invalid. if (clientErr) { console.error('Error creating client:', clientErr); return; } braintree.dataCollector.create({ client: clientInstance, paypal: true }, (err, dataCollectorInstance)=> { if (err) { // Handle error console.log(err); return; } // At this point, you should access the dataCollectorInstance.deviceData value and provide it // to your server, e.g. by injecting it into your form as a hidden input. var myDeviceData = dataCollectorInstance.deviceData; // console.log(dataCollectorInstance); this.storeService.storeData('deviceData', myDeviceData); //dataCollectorInstance.teardown(); }); // Create a PayPal Checkout component. braintree.paypalCheckout.create({ client: clientInstance }, (paypalCheckoutErr, paypalCheckoutInstance)=> { // Stop if there was a problem creating PayPal Checkout. // This could happen if there was a network error or if it's incorrectly // configured. if (paypalCheckoutErr) { console.error('Error creating PayPal Checkout:', paypalCheckoutErr); return; } // Set up PayPal with the checkout.js library paypal.Button.render({ env: 'sandbox', // or 'production' payment: ()=> { return paypalCheckoutInstance.createPayment({ flow: 'vault', billingAgreementDescription: 'You have agreed to provide your details for this payment', enableShippingAddress: false, // shippingAddressEditable: false, // shippingAddressOverride: { // recipientName: '<NAME>', // line1: '1234 Main St.', // line2: 'Unit 1', // city: 'Chicago', // countryCode: 'US', // postalCode: '60652', // state: 'IL', // phone: '123.456.7890' // } }); }, onAuthorize: (data, actions)=> { return paypalCheckoutInstance.tokenizePayment(data) .then((payload)=> { // Submit `payload.nonce` to your server. // console.log(payload); const methods = { uid: this.customer.uid, method: { customerId: this.customer.method.customerId, paymentMethodNonce: payload.nonce, } } this.paymentService.createPaymentMethod(methods, "paypal") .subscribe((res: any)=>{ const token = res.result.paymentMethod.token; this.paymentToken(token); console.log(res); // this.returnResult.emit(res); }); }); }, onCancel: (data)=> { console.log('checkout.js payment cancelled'); }, onError: (err)=> { console.error('checkout.js error', err); } }, '#paypal-button').then( ()=> { // The PayPal button will be rendered in an html element with the id // `paypal-button`. This function will be called when the PayPal button // is set up and ready to be used. // console.log("Paypal Process Completed"); }); }); }); } } // this.authService.authState().subscribe((user)=>{ // if(!user){return null;} // this.userId = user.uid; // this.user = user; // // this.checkForCardPresent(user.email); // }) // Configuring stripe payment // let handler = StripeCheckout.configure({ // key: '<KEY>', // image: 'https://stripe.com/img/documentation/checkout/marketplace.png', // locale: 'auto', // token: function(token) { // console.log(token); // // You can access the token ID with `token.id`. // // Get the token ID to your server-side code for use. // } // }); // this.document.getElementById('payButton').addEventListener('click', function(e) { // // Open Checkout with further options: // handler.open({ // name: 'uRGy Shop', // description: 'Shopping payments', // currency: 'gbp', // // amount: 20000 // }); // e.preventDefault(); // }); // // Close Checkout on page navigation: // window.addEventListener('popstate', function() { // handler.close(); // }); <file_sep>/src/app/container/check-out/payment/payment.component.ts import { Component, OnInit, AfterViewInit } from '@angular/core'; import { AuthService } from "../../../authentications/authentication.service"; import { TempOrderService } from "../../../services/temp-order.service"; import { OrderService } from "../../../services/order.service"; import { AccountService } from '../../../services/account.service'; import { StorageService } from '../../../services/storage.service'; import { PaymentService } from "../../../services/payment.service"; import { WindowService } from "../../../services/window.service"; import { CartService } from "../../../services/cart.service"; import * as _ from 'lodash'; import { ProgressService } from '../../../services/checkout-progress.service'; import { Store } from '@ngrx/store'; @Component({ selector: 'app-payment', templateUrl: 'payment.component.html', styleUrls: ['payment.component.scss'] }) export class PaymentComponent implements OnInit, AfterViewInit { order; document; grayPage; declineMsg; acceptedMsg; processMsg:string; status:string = "unknown"; customerOrder; constructor(private orderService:OrderService, private accountService:AccountService, private authService:AuthService, private storeService:StorageService, private paymentService:PaymentService, private windowService:WindowService, private store: Store<any>) { this.document = windowService.getDocumentRef(); store.select('auth').subscribe((auth)=>{ orderService.getCustomerOrders(auth.account_no).subscribe((orders:any)=>{ let ord = orders.orders[0]; this.customerOrder = orders.orders[0]; this.order = { payment : { paymentMethodToken: storeService.retriveData('payToken'), amount: ord.amount, orderId: ord.order_no, deviceData: storeService.retriveData('deviceData') || null, options: { submitForSettlement: true } } }; console.log(this.order); }); }); } createTransaction(){ this.grayPage = true; let payment = this.order; this.paymentService.paymentTransaction(payment) .subscribe((res)=> { console.log(res); this.grayPage = false; let update = { id: this.customerOrder.id, order: { updatedAt: Date.now(), status: 'completed' } } this.orderService.updateOrder(update) .subscribe((res)=>{ console.log(res) }) }); } // runPaymentOrder(payobject){ // let final = {name: "finish"}; // this.paymentService.paymentTransaction(payobject) // .subscribe((response: any)=>{ // if(response.success == 'true' || response.success == true){ // //Do cleanup here // // this.cleanUp(); // // this.progressService.setProgress(final); // let result = this.document.querySelector('.payment-completed'); // let container = this.document.querySelector('.main-container'); // this.windowService.getWindowObject().setTimeout(()=>{ // this.grayPage = false; // result.style.display = "block"; // container.style.display = "none"; // this.status = response.payment_status; // this.acceptedMsg = "Thanks for completing your order, payment has been taken from your account." // }, 3000) // console.log(response); // }else if(response.success == 'false' || response.success == false){ // let result = this.document.querySelector('.payment-completed'); // let container = this.document.querySelector('.main-container'); // this.windowService.getWindowObject().setTimeout(()=>{ // this.grayPage = false; // result.style.display = "block"; // container.style.display = "none"; // this.processMsg = response.message || null; // this.status = response.payment_status; // this.declineMsg = "Your payment was delined.. please try again possibly with a different payment method"; // }, 3000) // }else{ // return null; //do something here // } // }); // return false; // } ngOnInit() { } ngAfterViewInit(){ } } <file_sep>/src/app/home/mobile-slider/home-slider.component.ts import { Component, OnInit } from '@angular/core'; import { AdvertService } from '../../services/advert.service'; @Component({ selector: 'mobile-slider', templateUrl: './home-slider.component.html', styleUrls: ['./home-slider.component.scss'] }) export class MobileSliderComponent implements OnInit { ads; options = { speed: 100000, width: "100%", height: "200px", opacity: "1" }; constructor( private advertService: AdvertService, ) { } ngOnInit() { let sec, tag; this.advertService.getShopAdverts(sec = "home slide", tag = "slide") .map(advert => { let urls = []; advert.forEach((a:any) => { urls.push(a.image_url); }); return urls; }) .subscribe((adv)=> { this.ads = adv; }); } }<file_sep>/src/app/store-management/reducers/shipping.reducer.ts import { Action, ActionReducer } from '@ngrx/store'; import { iShip } from '../models/shipping.model'; import { PUSH } from '../actions/shipping'; const init = { option: 'Royal Mail 3-5 Working days', price: '2.50' } export function shippingReducer<ActionReducer>(state:iShip = init, action){ switch(action.type){ case PUSH: return action.payload; default: return state; } }<file_sep>/src/app/store-management/models/sum.model.ts export interface Sum { total: string }<file_sep>/src/app/store-management/reducers/reducers.ts import { createSelector, createFeatureSelector } from '@ngrx/store'; import { iShip } from '../models/shipping.model'; import { Sum } from '../models/sum.model'; export interface FeatureState { sum: Sum, ship: iShip } export interface AppState { check: FeatureState } export const selectFeature = createFeatureSelector<FeatureState>('check'); export const selectFeatureSum = createSelector(selectFeature, (state: FeatureState) => state.sum); export const selectFeatureShip = createSelector(selectFeature, (state: FeatureState) => state.ship);<file_sep>/src/app/container/check-out/order/order.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { AccountService } from "../../../services/account.service"; import { StorageService } from "../../../services/storage.service"; import { PaymentService } from "../../../services/payment.service"; import { AuthService } from "../../../authentications/authentication.service"; import { Router } from "@angular/router"; import { CartService } from "../../../services/cart.service"; import { OrderService } from "../../../services/order.service"; import { WindowService } from "../../../services/window.service"; import * as _ from 'lodash'; import { ProgressService } from '../../../services/checkout-progress.service'; import { Store, select } from '@ngrx/store'; import * as Rx from 'rxjs/Rx'; import * as fromRoot from '../../../store-management/reducers/reducers'; @Component({ selector: 'app-order', templateUrl: 'order.component.html', styleUrls: ['order.component.scss'] }) export class OrderComponent implements OnInit { total = 0.00; ordForm; document; grayPage; currentUser; existingOrder; acNo; errMsg; // saveProg = new Array(); constructor(private accountService:AccountService, private authService:AuthService, private storeService:StorageService, private _fb:FormBuilder, private _router:Router, private paymentService:PaymentService, private windowService:WindowService, private cartService:CartService, private store: Store<any>, private orderService:OrderService, private progressService:ProgressService) { this.document = this.windowService.getDocumentRef(); this.orderForm(); store.pipe(select(fromRoot.selectFeatureSum)).subscribe((sum)=>{ this.total = Number(sum.total); this.ordForm.patchValue({ amount: Number(sum.total) }); // console.log(shp); }); store.pipe(select(fromRoot.selectFeatureShip)).subscribe((ship)=>{ if(ship){ this.ordForm.patchValue({ delivery_method: ship.option }); // console.log(ship); } }); store.select('auth').subscribe((auth)=> { // Set user data including address if(auth.uid){ this.acNo = auth.account_no; this.getExistingOrder(auth.account_no); authService.getUserAddresses(auth.uid).subscribe((addresses)=>{ // console.log(addresses); let address = addresses.filter((ad: any) => { return ad.address_type == 'delivery'}); if(!address.length){ // Patching Form Items this.patchOrderForm(auth, auth.address); return this.currentUser = auth.address; } // Patching Form Items this.patchOrderForm(auth, _.last(address)); this.currentUser = _.last(address); // console.log(address); }); } }); store.select('cart').subscribe((cart)=>{ // console.log(cart); this.ordForm.patchValue({ items: cart }); }); } orderForm(){ this.ordForm = this._fb.group({ order_no: null, customer_name: null, customer_no: null, uid: null, amount: null, note: null, email: null, telephone:null, delivery_method: null, status: null, ip_address: null, delivery_address: null, createdAt: null, updatedAt: null, items: [] }) } patchOrderForm(user, addres?){ this.ordForm.patchValue({ customer_name: user.displayName, email: user.email, uid: user.uid, customer_no: user.account_no, telephone: user.phone, delivery_address: { name: addres.displayName, address: addres.address, city: addres.city, post_code: addres.post_code, country: "United Kingdom" }, status: "pending" }) } //Craeting Customer Order here createOrder(order){ // this._router.navigate(["/check/payment"]); //Checking for existing order status if(this.existingOrder && this.existingOrder.status == 'pending'){ alert('Please complete or cancel pending order to continue!!'); return; } this.grayPage = true; //Generate Order number let order_no = order.customer_no * 100 + Math.floor((Math.random() * 10) + 1); let nowDate = Date.now().toString().slice(8);//5 digit let cm_no = order_no.toString().slice(5);//7 digit order.order_no = 9+nowDate+cm_no; order.createdAt = Date.now(); order.updatedAt = Date.now(); // console.log(order); this.orderService.postOrder(order).subscribe((res: any)=>{ console.log(res); if(res.status == "Order Failed"){ this.grayPage = false; return this.errMsg = "Sorry! Your order failed to create, try again later."; } this.grayPage = false; this._router.navigate(["/check/payment"]); }); } getExistingOrder(account_no){ this.orderService.getCustomerOrders(account_no).subscribe((orders:any)=>{ this.existingOrder = orders.orders[0]; console.log(this.existingOrder); }); } deletePendingOrder(){ let id = this.existingOrder.id; let confarm = confirm("Are you sure?"); if(!confarm){ return null; } this.orderService.deleteOrder(id) .subscribe((res)=>{ console.log(res); this.getExistingOrder(this.acNo); }); } completePendingOrder(val: string){ const option = { id: this.existingOrder.id, order: { status: val } } this.orderService.updateOrder(option) .subscribe((res)=>{ console.log(res); }); } ngOnInit() { } } <file_sep>/src/app/environment-var.ts // Initialize Firebase export const firebaseConfig = { apiKey: "<KEY>", authDomain: "urgy-a513c.firebaseapp.com", databaseURL: "https://urgy-a513c.firebaseio.com", projectId: "urgy-a513c", storageBucket: "urgy-a513c.appspot.com", messagingSenderId: "228207469124" // apiKey: "<KEY>", // authDomain: "shop-5e89b.firebaseapp.com", // databaseURL: "https://shop-5e89b.firebaseio.com", // projectId: "shop-5e89b", // storageBucket: "shop-5e89b.appspot.com", // messagingSenderId: "777977280371" }; //Postcode finder api and admin key export const PostcodeApiConfig = { url: "https://api.getAddress.io/find/", api_key: "<KEY>", admin_key: "<KEY>" } export const Serverendpoints = { host: "http://localhost:8080/", api_v: "api_v1/" }<file_sep>/README.md # UrgyFront Client application for shopping site # Author <NAME> # Job Title Full stack Web Developer<file_sep>/src/app/container/check-out/deliverymethod/deliverymethod.component.ts import { Component, OnInit, HostListener } from '@angular/core'; import { Router } from '@angular/router'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { trigger, state, style, stagger, transition, animate, keyframes, query } from '@angular/animations'; // import { TempOrderService } from "../../../services/temp-order.service"; import { AuthService } from "../../../authentications/authentication.service"; // import { TempOrderType } from "../../../models/tempOrder.model"; import { AccountService } from "../../../services/account.service"; import * as _ from 'lodash'; import { Store } from '@ngrx/store'; import { PUSH } from '../../../store-management/actions/shipping'; // import { StorageService } from "../../../services/storage.service"; // import { ProgressService } from '../../../services/checkout-progress.service'; @Component({ selector: 'delivery-method', templateUrl: 'delivery.component.html', styleUrls: ['delivery.component.scss'] }) export class DeliveryMethodComponent implements OnInit { currentUser; deliveryForm; errorMsg; addressForm:boolean = false; selectedOption; deliveryoptions = [ {option: "Royal Mail 3-5 Working days", price: 2.50}, {option: "Royal Mail 1-2 Working days", price: 3.50}, {option: "Royal Mail Next day delivery", price: 4.90}, {option: "Royal Mail Same days delivery", price: 5.90} ]; constructor(private _fb:FormBuilder, private store: Store<any>, private authService:AuthService, private _router:Router, private accountService:AccountService, ){ store.select('auth').subscribe((auth)=> { // this.currentUser = auth; if(auth.uid){ authService.getUserAddresses(auth.uid).subscribe((addresses)=>{ // console.log(addresses); let address = addresses.filter((ad: any) => { return ad.address_type == 'delivery'}); if(!address.length){ return this.currentUser = auth.address; } this.currentUser = _.last(address); console.log(address); }); } }); this.deliveryForm = _fb.group({ displayName: [null, Validators.required], address: [null, Validators.required], city: null, post_code: [null, Validators.required], country: "United Kingdom" }) } //Set billing address as delivery address @HostListener('change', ['$event']) selectOption(e){ // console.log(e.value); this.selectedOption = e.value; this.store.dispatch({type: PUSH, payload: {...e.value}}); } //After every condition is met then go to order page goToOrder(){ let delivery = this.selectedOption || {option: "Royal Mail 5-10 Working days", price: 2.50}; console.log(delivery); this._router.navigate(["/check/order_review"]); } //Saving temp order address to firebase deliveryAddress(address){ if(this.deliveryForm.status == 'INVALID'){ return this.errorMsg = "Please fill in all required feild"; } let addr = { address_type: 'delivery', displayName: address.displayName, address: address.address, city: address.city, post_code: address.post_code, country: address.country, uid: this.currentUser.uid } this.authService.saveUserAddresses(addr).then(res => { this.addAddress(); }) .catch(err => console.log(err)); } addAddress(){ if(!this.addressForm){ this.addressForm = true; // window.scrollTo(0, 0); }else{ this.addressForm = false; // window.scrollTo(0, 0); } } // addressFound(event){ // this.address = event.addresPick; // this.postCode = event.postCode; // this.deliveryForm.patchValue({ // address: event.addresPick, // post_code: event.postCode // }) // } //Retrieve temp order from firebase // getDeliveryAddress(){ // this.tempOrderService.getTempOrder(this.currentUser.uid).subscribe((address)=>{ // if(address){ // // console.log(address['delivery_option']); // this.selectAddress = address['delivery_address']; // this.addressForm = true; //address['delivery_address']; // if(address['delivery_address'] && address['delivery_option']){ // this.certify = true; // }else{ this.certify = false; } // if(address['delivery_address'].address){ // this.selectAddressNotice = false; // this.trueAddress = true; // this.deliveryForm.patchValue({ // full_name: address['delivery_address'].full_name, // address: address['delivery_address'].address, // address2: address['delivery_address'].address2, // city: address['delivery_address'].city, // post_code: address['delivery_address'].post_code, // country: address['delivery_address'].country // }) // }else{ // // this.selectAddressNotice = false; // // alert("You can now load address from the server"); // } // } // }) // } //Checking for existence on delivery addresses // checkForExistingAddress(){ // this.accountService.getAccount(this.storeService.retriveData('email')) // .subscribe((account)=>{ // this.accountService.getAddress(account._id).subscribe((addresses)=>{ // this.selectAddress =_.last(_.filter(addresses, {"address_type":"delivery"})); // this.billingAddresses = _.last(_.filter(addresses, {"address_type":"billing"})); // if(!this.selectAddress){ // this.selectAddressNotice = true; // console.log("No Old address found"); // // this.getDeliveryAddress(); // } // if(this.selectAddress){ // this.addressForm = true; // this.trueAddress = true; // this.notify = true; // this.deliveryForm.patchValue({ // full_name: this.selectAddress.full_name, // address: this.selectAddress.address, // address2: this.selectAddress.address2, // city: this.selectAddress.city, // post_code: this.selectAddress.post_code, // country: this.selectAddress.country // }) // } // }) // }); // } ngOnInit(){ // this.store.select('auth').subscribe((auth)=>{ // if(auth.uid){ // console.log(auth); // } // }); // this.authService.authState().subscribe((user)=>{ // if(user){ // this.currentUser = user; // }else{ // console.log("No user logged in"); // this._router.navigate(["/login"]); // } // }); } }
96abd28d5a78a549bfb8b22e7fa406c8d0dd2b69
[ "Markdown", "TypeScript" ]
21
TypeScript
mecus/urgy-front
45e9cb903570a3d07bcbf2c4a4b043c591944c28
9ad73f00f306c9b0bedb9b9e199dab0541887d31
refs/heads/master
<repo_name>malavolti/ansible-monitoring<file_sep>/roles/rsyslog/templates/conf/remove-old-logs.j2 #!/bin/bash find /data/var/log -type f -ctime +180 -exec rm {} \; find /data/var/log -type d -ctime +180 -exec rmdir {} \; <file_sep>/README.md # ansible-monitoring Ansible Playbook to manage some monitoring tools (tested on Debian 9 "Stretch" servers): * [Kibana](https://www.elastic.co/products/kibana) * [Elasticsearch](https://www.elastic.co/products/elasticsearch) * [Rsyslog](https://www.rsyslog.com/) * [Rsnapshot](http://rsnapshot.org/) * [Check_MK](http://mathias-kettner.com/index.html) ## Requirements * [Ansible](https://www.ansible.com/) - Tested with Ansible v2.9.10 ## HOWTO configure the monitoring servers with this ansible playbook **NOTE**: In our production environment, we provide elasticsearch/rsyslog servers with a persistent storage device to store all we need. 1. Become ROOT: * `sudo su -` 2. Retrieve GIT repository of the project: * `apt-get install git` * `cd /opt ; git clone https://github.com/[malavolti|ConsortiumGARR|GEANT]/ansible-monitoring.git` * `cd /opt/ansible-monitoring ; git clone https://github.com/[malavolti|ConsortiumGARR|GEANT]/ansible-monitoring-inventories inventories` 3. Create your `.vault_pass.txt` that contains the encryption password (this is needed ONLY when you use Ansible Vault): * `cd /opt/ansible-monitoring` * `openssl rand -base64 64 > .vault_pass.txt` 4. Create the right inventory file/files about your servers by following the templates provided: * `inventories/development/development.ini` for your development servers. * `inventories/production/production.ini` for your production servers. * `inventories/test/test.ini` for your test servers. 5. Create the monitoring configuration file/files by following the templates provided(example for 'production' environment): * `/opt/ansible-monitoring/inventories/production/host_vars/checkmk.example.org.yml` * `/opt/ansible-monitoring/inventories/production/host_vars/elasticsearch1.example.org.yml` * `/opt/ansible-monitoring/inventories/production/host_vars/kibana.example.org.yml` * `/opt/ansible-monitoring/inventories/production/host_vars/data-backups.example.org.yml` * `/opt/ansible-monitoring/inventories/production/host_vars/logs.example.org.yml` These files will provide to Ansible all variables needed to instance each server. 6. Check the "`inventories/files`" directory to understand what files each server needs and provide them. 7. Encrypt the monitoring configuration files with Ansible Vault (Optional: this is needed ONLY when you need Ansible Vault). Example for 'production' environment: * `cd /opt/ansible-monitoring` * `ansible-vault encrypt inventories/production/host_vars/FQDN.yml --vault-password-file .vault_pass.txt` 8. Execute this command to run Ansible on production inventory and configure your servers: * `ansible-playbook site.yml -i inventories/production/production.ini --vault-password-file .vault_pass.txt` ## Useful Commands 1. Test that the connection with the server(s) is working: * `ansible all -m ping -i /opt/ansible-monitoring/inventories/#_environment_#/#_environment_#.ini -u debian` ("`debian`" is the user used to perform the SSH connection with the client to synchronize) 2. Get the facts from the server(s): * `ansible HOST_NAME -m setup -i /opt/ansible-monitoring/inventories/#_environment_#/#_environment_#.ini -u debian` Examples: * without encrypted files: `ansible HOST_NAME -m setup -i /opt/ansible-monitoring/inventories/#_environment_#/#_environment_#.ini -u debian` * with encrypted files: `ansible HOST_NAME -m setup -i /opt/ansible-monitoring/inventories/#_environment_#/#_environment_#.ini -u debian --vault-password-file .vault_pass.txt` ("`.vault_pass.txt`" is the file you have created that contains the encryption password) 3. Encrypt files: * `ansible-vault encrypt inventories/#_environment_#/host_vars/FQDN.yml --vault-password-file .vault_pass.txt` 4. Decrypt Encrypted files: * `ansible-vault decrypt inventories/#_environment_#/host_vars/FQDN.yml --vault-password-file .vault_pass.txt` 5. View Encrypted files: * `ansible-vault view inventories/#_environment_#/host_vars/FQDN.yml --vault-password-file .vault_pass.txt` ## Authors #### Original Author and Development Lead * <NAME> (<EMAIL>) <file_sep>/roles/rsyslog/templates/conf/gzip-remote-logs.j2 #!/bin/sh find /data/var/log -type f -ctime +1 -exec gzip {} \; > /dev/null 2>&1
5d81abb35f46a929f867ce5af73bccc90cb44462
[ "Markdown", "Shell" ]
3
Shell
malavolti/ansible-monitoring
582708f68e138c39d073e587dd0b79df23e568d8
f960cfe0593aa1c06fdf7308ca5bc68ef8eeb1ff
refs/heads/master
<file_sep>extern crate serde; pub extern crate chrono; extern crate serde_json; extern crate clap; use std::process::Command; use std::convert::AsRef; use std::fmt; use std::path::{Path, PathBuf}; use std::fs::File; use std::fs::OpenOptions; use std::io::{Read, Write}; use std::env; use serde::{Serialize, Deserialize}; use chrono::{Datelike, Timelike}; use std::sync::{Arc, Mutex}; #[derive(Serialize, Deserialize, Clone)] pub struct Plan { pub name: String, pub link: String, pub times: Vec<TimeDay>, } #[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] pub struct TimeDay { pub time: chrono::NaiveTime, pub day: chrono::Weekday, } impl TimeDay { pub fn new(t: chrono::NaiveTime, d: chrono::Weekday) -> Self { TimeDay { time: t, day: d, } } } impl fmt::Display for TimeDay { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "time: {}, day: {},\n", self.time, self.day) } } impl Plan { pub fn new(n: String, l: String, t: Vec<TimeDay>) -> Self { Plan { name: n, link: l, times: t, } } pub fn new_user_friendly(n: &str, l: &str, t: &str, d: &str) -> Self { let time = chrono::NaiveTime::parse_from_str(&t, "%H:%M").expect("date cannot be parsed"); let day = match d.to_lowercase().as_str() { "monday" => chrono::Weekday::Mon, "tuesday" => chrono::Weekday::Tue, "wednesday" => chrono::Weekday::Wed, "thursday" => chrono::Weekday::Thu, "friday" => chrono::Weekday::Fri, "saturday" => chrono::Weekday::Sat, "sunday" => chrono::Weekday::Sun, _ => panic!("undefined day") }; let mut tdv = Vec::new(); tdv.push(TimeDay::new(time, day)); Self::new(n.to_string(), l.to_string(), tdv) } pub fn remove_matching_time(&mut self, td: &TimeDay) { let length = self.times.len(); for i in 0..length { if self.times.get(i).unwrap() == td { self.times.remove(i); break } } } } impl fmt::Display for Plan { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut times = String::new(); for t in self.times.clone() { times += format!("{}", &t).as_str(); } write!(f, "name: {},\n\ntimes:\n{}\nlink: {}\n", self.name, times, self.link) } } pub fn export<T: AsRef<Path>>(v: Vec<Plan>, p: T) { let mut file = OpenOptions::new().write(true).open(p).expect("error in opening config file"); //File::open(p).expect("error in opening config file"); let _ = file.set_len(0); let _ = file.write(serde_json::to_string(&v).expect("error in serializing").as_bytes()); } pub fn import<T: AsRef<Path>>(p: T) -> Vec<Plan> { let file = File::open(&p); let mut file = match file.is_err() { true => { let _ = File::create(&p); File::open(&p).unwrap() }, false => file.unwrap(), }; let mut buf = Vec::new(); let _ = file.read_to_end(&mut buf); if buf.len() == 0 { Vec::new() } else { serde_json::from_slice(&buf).expect("error while parsing config file") } } pub fn check(p: &Plan, td: &TimeDay) -> bool { let mut result = false; for t in &p.times { if td == t { open_link(&p.link); result |= true } else { result |= false } } result } pub fn check_all(v: &Vec<Plan>) { let mut cv = v.clone(); loop { let day = chrono::Local::now().naive_local().date().weekday(); let time = chrono::Local::now().naive_local().time(); let time = chrono::NaiveTime::from_hms(time.hour(), time.minute(), 0); let timeday = TimeDay::new(time, day); let length = cv.len(); for i in 0..length { if check(cv.get(i).unwrap(), &timeday) { let mut p = cv.get(i).unwrap().clone(); p.remove_matching_time(&timeday); cv.remove(i); cv.push(p); break } } let mut times = 0; for p in &cv { times += p.times.len(); } if times == 0 { cv = v.clone() } std::thread::sleep(std::time::Duration::new(5, 0)) } } #[cfg(target_os = "macos")] pub fn open_link(z: &String) { Command::new("open").arg(z).spawn().expect("error in opening link using open"); } #[cfg(all(not(target_os = "macos"), target_family = "unix"))] pub fn open_link(z: &String) { Command::new("xdg-open").arg(z).spawn().expect("error in opening link using xdg-open"); } #[cfg(target_os = "windows")] pub fn open_link(z: &String) { Command::new("start").arg(z).spawn().expect("error in opening link using start"); } <file_sep>mod private; pub use private::{Plan, TimeDay}; pub use private::{import, export, check, check_all, open_link}; pub extern crate chrono; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } <file_sep># autolink-lib
5896defa597bee7c07d9a06f8dd553b6d272ed3b
[ "Markdown", "Rust" ]
3
Rust
styrowolf/autolink-lib
c2ac1f2de0707f1fcdb7f59d9a17a5cdb6f42acc
8f4a68b392ebdc8de0d7596387cca88186991af2
refs/heads/master
<repo_name>alskra/detailing-plus<file_sep>/app_components/Igor10k-ikSelect-d5a1480/docs/js/script.js $(function () { $.ikSelect.extendDefaults({ extraWidth: 1 }); var $sectionSet = $('.section'); $('.intro-select1').ikSelect({ customClass: 'intro-select1', ddFullWidth: false, filter: true }); $('.intro-select2').ikSelect({ syntax: '<div class="ik_select_link"><div class="ik_select_link_inner"><span class="ik_select_link_text"></span></div></div><div class="ik_select_dropdown"><div class="ik_select_list"></div></div>', customClass: 'intro-select2', extractLink: true, ddMaxHeight: 1000, onShow: function (inst) { inst.$dropdown.css({ top: inst.$link.offset().top - inst.$hover.position().top }); setTimeout(function () { inst.$link.add(inst.$dropdown).addClass('transition'); inst.$link.add(inst.$dropdown).addClass('animate'); }, 0); }, onHide: function (inst) { inst.$link.add(inst.$dropdown).removeClass('animate'); inst.$link.add(inst.$dropdown).removeClass('transition'); }, onKeyDown: function (inst, keycode) { if (keycode === 40 || keycode === 38) { inst.$dropdown.css({ top: inst.$link.offset().top - inst.$hover.position().top }); inst._makeOptionActive(inst.hoverIndex, true); } } }); $('.intro-select-link').ikSelect({ customClass: 'intro-select-link', dynamicWidth: true }); $('.intro-select-osx').ikSelect({ customClass: 'intro-select-osx' }); $('.intro-select-ie').ikSelect({ customClass: 'intro-select-ie' }); $sectionSet.each(function () { var $section = $(this); if ($section.data('hidden')) { $section.hide(); } }); $('.header').each(function () { var $header = $(this); $(window).on('resize scroll', function () { if ($(window).width() < 960) { $header.css({ left: 0, marginLeft: -$(window).scrollLeft() }); } else { $header.css({ left: '50%', marginLeft: -490 }); } }); }); $('.header-nav').each(function () { var $nav = $(this); var $linkSet = $('a', $nav); var $activeLink = $linkSet.eq(0); $(window).on('scroll', function () { var $section; for (var i = 0; i < $sectionSet.length; i++) { $section = $sectionSet.eq(i); if ($section.is(':visible') && $section.offset().top + $section.outerHeight() >= $(window).scrollTop() + 115) { break; } } $activeLink.removeClass('active'); $activeLink = $linkSet.eq(i).addClass('active'); }); $(window).scroll(); }); $('.header-nav a, .features-link').on('click', function (event) { event.preventDefault(); var $link = $(this); var $block = $($link.attr('href')); if ($block.data('hidden')) { $block.show(); var height = $block.height(); var marginBottom = parseInt($block.css('marginBottom'), 10); $block.css({ height: 0, marginBottom: 0, overflow: 'hidden' }); $block.addClass('transition'); $block.css({ height: height, marginBottom: marginBottom }); $(window).scroll(); } $('html, body').animate({ 'scrollTop': $block.offset().top - 115 }); }); $('.examples-options, .examples-callbacks').each(function () { var $example = $(this); var $select = $('select', this); var selectOptions = {}; $select.ikSelect(); $('.list-examples', $example).each(function () { var $list = $(this); var $buttonSet = $('button', $list); $buttonSet.each(function () { var $button = $(this); var key = $('.key', $button).text(); var value = $button.data('value'); var currentValue = value; var altValue = $button.data('altvalue'); var $value = $('.value', $button); var renderValue = function () { $value.text(typeof currentValue === 'string' ? ('\'' + currentValue + '\'') : currentValue); }; var storeValue = function () { selectOptions[key] = currentValue; if (typeof currentValue === 'string') { if (currentValue.indexOf('function') === 0) { selectOptions[key] = eval('callback = ' + currentValue, currentValue); } } }; renderValue(); storeValue(); $button.on('click', function (event) { event.preventDefault(); currentValue = currentValue === value ? altValue : value; renderValue(); storeValue(); $select.ikSelect('detach').prop('disabled', false).ikSelect(selectOptions); }); }); }); }); $('.examples-api').each(function () { var $example = $(this); var $select = $('select', this); var $selectWrap = $('.select-wrap', this); var $placeHelper = $('<div/>'); var $selectBackup = $select.clone(); $select.before($placeHelper); $select.ikSelect(); $(window).on('scroll', function () { if ($(window).scrollTop() > $example.offset().top - 37) { $selectWrap.addClass('floating'); } else { $selectWrap.removeClass('floating'); } }); $('.list-examples', $example).each(function () { var $list = $(this); var $buttonSet = $('button', $list); $buttonSet.each(function () { var $button = $(this); var altValue = $button.data('altvalue'); var $value = $('.value', $button); var value = $value.html(); var currentValue = value; var method = $('.method', $button).html(); if ($.isArray(altValue)) { altValue = '[' + altValue.join(', ') + ']'; } $button.on('click', function (event) { event.preventDefault(); if ($button.data('reset')) { $select.ikSelect('detach').remove(); $select = $selectBackup.clone(); $placeHelper.after($select); $select.ikSelect(); } if (currentValue === value) { if (typeof altValue !== 'undefined') { if ($button.data('extend')) { currentValue = altValue; eval('$.ikSelect.extendDefaults(' + currentValue + ')'); } else { currentValue = ', ' + altValue; eval('$select.ikSelect(' + method + currentValue + ')'); } } else { setTimeout(function () { eval('$select.ikSelect(' + (method || '') + ')'); }, 1); } } else { currentValue = value; } $value.html(currentValue); }); }); }); }); }); <file_sep>/app_components/Igor10k-ikSelect-d5a1480/README.md # [ikSelect 1.1.0](http://igor10k.github.com/ikSelect/) ikSelect helps you stylize selects. Check the plugin's [page](http://igor10k.github.com/ikSelect/) for more info. ## Features * works in all popular browsers including IE6+ * **custom syntax** support * works perfect as an **inline-block** * **no z-index bugs** in IE * **optgroups** support * great **API** * **add/remove** `<option>`s and `<optgroup>`s * **disable/enable anything** (select, optgoup, option) * optional **filter** text field * can be used with **hidden parents** * compatible with **mobile devices** * behavior is as **authentic** as possible * **callbacks** and **event triggers** * **automatic calculations** * dropdown position, so it's always visible when opened * needed width for the select or it's dropdown (can be disabled) * active option appears in the center of the opened dropdown * **keyboard support** * search by letters/numbers/etc * navigation * tab and shift+tab * **fast** and **easy** to use * built with attention to details * according to the poll, **100% of people love it** &nbsp;&nbsp; <sub><sup>of all the five friends I asked<sup></sub> ## Installation * Include jQuery if it's still not included. The easiest way is to use some public CDN. ```html <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> ``` * Download latest ikSelect script from [here](https://github.com/Igor10k/ikSelect/zipball/master)</p> * Include ikSelect script after jQuery ```html <script src="ikSelect.min.js"></script> ``` * Initialize the script somewhere. Better do it after the DOM is ready. ```javascript $(function () { $('select').ikSelect(); }); ``` * Add some CSS ```css .ik_select { /* Wraps all the plugin's HTML code. Probably you should not add any styles here */ } .ik_select_link { /* Fake select you click on to open the dropdown */ } .ik_select_link_focus { /* Focused state of the fake select */ } .ik_select_link_disabled { /* Disabled state of the fake select */ } .ik_select_link_text { /* Wrapper for the text inside the link. It's best to add some width limiting rules here like display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; */ } .ik_select_dropdown { /* Dropdown wrapper. Needed for script calculations. You should not add any visual styles here. You can shift the position of the dropdown by changing top and left values like top: -2px; left: -5px; */ } .ik_select_list { /* Wrapper for the options list. Now that's a good place to add visual styles. */ } .ik_select_optgroup { /* Optgroup */ } .ik_select_optgroup_label { /* Optgroup label */ } .ik_select_option { /* Option */ } .ik_select_option_label { /* Option label */ } .ik_select_hover { /* The hovered state of an option */ } .ik_select_active { /* The active state of an option */ } .ik_select_filter_wrap { /* Wrapper for the filter input */ } .ik_select_filter { /* Filter input */ } .ik_nothing_found { /* Block that's shown when there's nothing found. */ } ``` ## Options All the options can be set using HTML5 **data-** attributes or as an object passed to the plugin. For the **data-** attibutes use lowercased options! *(data-autowidth="true", data-customclass="someclass", etc)* ```javascript syntax: '&lt;div class="ik_select_link"&gt;&lt;span class="ik_select_link_text"&gt;&lt;/span&gt;&lt;/div&gt;&lt;div class="ik_select_dropdown"&gt;&lt;div class="ik_select_list"&gt;&lt;/div&gt;&lt;/div&gt;' /* Custom syntax for the fake select. The only condition is that "ik_select_link_text" should be inside of "ik_select_link" and "ik_select_list" should be inside of "ik_select_dropdown". */ autoWidth: true, /* Set width of the select according to the longest option. */ ddFullWidth: true, /* Set width of the dropdown according to the longest option. */ equalWidths: true, /* Add dropdown's scrollbar width to the fake select's width. */ dynamicWidth: false, /* Adjust fake select's width according to its contents. */ extractLink: false, /* Tells if fake select should be moved to body when clicked along with the dropdown */ customClass: '', /* Add custom class to the fake select's wrapper. */ linkCustomClass: '', /* Add custom class to the fake select. Uses customClass with '-link' appended if only the former presents. */ ddCustomClass: '', /* Add custom class to the fake select's dropdown. Uses customClass with '-dd' appended if only the former presents. */ ddMaxHeight: 200, /* Maximum allowed height for dropdown. */ isDisabled: false, /* Set the initial state of the select. Overrides the *disabled* attribute. */ filter: false, /* Appends filter text input. */ nothingFoundText: 'Nothing found' /* The text to show when filter is on and nothing is found. */ ``` ## Callbacks and events After each callback there's also an event emitted. Just replace **on** with **ik** and use lowercase. *(ikshow, ikkeydown, etc)* ```javascript onInit: function (inst) {} /* Called just after plugin is initialized. */ onShow: function (inst) {} /* Called just after dropdown was showed. */ onHide: function (inst) {} /* Called just after dropdown was hidden. */ onKeyDown: function (inst) {} /* Called when a key on a keyboard is pressed. */ onKeyUp: function (inst) {} /* Called when a key on a keyboard is released. */ onHoverMove: function (inst) {} /* Called when some other option is hovered. */ ``` ## API ```javascript $.ikSelect.extendDefaults(settings); /* Override defaults for new instances. */ $(selector).ikSelect('reset'); /* Recreates fake select from scratch. */ $(selector).ikSelect('redraw'); /* Recalculates dimensions for the dropdown. Use this if select's parent was hidden when ikSelect was applied to it right after *show()*, *fadeIn()* or whatever you are using there. */ $(selector).ikSelect('addOptions', optionObject[, optionIndex, optgroupIndex]); $(selector).ikSelect('addOptions', optionObjectsArray[, optionIndex, optgroupIndex]); /* Add one or many options. By default appends to the dropdown's root. Optionally, tell at what index the option should appear. Optionally, tell to optgroup at what index to add the option. optionIndex is relative to optgroupIndex when the latter presents. */ $(selector).ikSelect('addOptgroups', optgroupObject[, optgroupIndex]); $(selector).ikSelect('addOptgroups', optgroupObjectsArray[, optgroupIndex]); /* Add one or many optgroups. By default appends to the dropdown's root. Optionally, tell at what index the optgroup should appear. */ $(selector).ikSelect('removeOptions', optionIndex[, optgroupIndex]); $(selector).ikSelect('removeOptions', optionIndexesArray[, optgroupIndex]); /* Remove one or many options by index. Optionally, set *optgroupIndex* to look for indexes within particular optgroup. Set *optgroupIndex* as -1 to look only within root. */ $(selector).ikSelect('removeOptgroups', optgroupIndex); $(selector).ikSelect('removeOptgroups', optgroupIndexesArray); /* Remove one or many optgroups by index. */ $(selector).ikSelect('select', optionValue[, isIndex]); /* Change selected option using option's value by default or index if *isIndex* is *true*. */ $(selector).ikSelect('showDropdown'); /* Show fake select's dropdown. Caution: on mobile devices this method shows the fake dropdown, not the native one that is shown by default when tapping on the fake select itself. */ $(selector).ikSelect('hideDropdown'); /* Hide fake select's dropdown. */ $(selector).ikSelect('disable'); /* Disable select. Also adds 'ik_select_link_disabled' class to the 'ik_select_link'. */ $(selector).ikSelect('enable'); /* Enable select. Also removes 'ik_select_link_disabled' class from the 'ik_select_link'. */ $(selector).ikSelect('toggle'[, enableOrDisable]); /* Toggle select's state. Optionally, set *enableOrDisable* as *true* or *false* to specify needed state. */ $(selector).ikSelect('disableOptions', optionIndexOrValue[, isIndex]); $(selector).ikSelect('disableOptions', optionIndexesOrValuesArray[, isIndex]); /* Disable one or many options using option values by default or option indexes if *isIndex* is *true* */ $(selector).ikSelect('enableOptions', optionIndexOrValue[, isIndex]); $(selector).ikSelect('enableOptions', optionIndexesOrValuesArray[, isIndex]); /* Enable one or many options using option values by default or option indexes if *isIndex* is *true* */ $(selector).ikSelect('toggleOptions', optionIndexOrValue[, isIndex, enableOrDisable]); $(selector).ikSelect('toggleOptions', optionIndexesOrValuesArray[, isIndex, enableOrDisable]); /* Toggle one or many optgroups' state. Optionally, set *enableOrDisable* as true/false to specify needed state. */ $(selector).ikSelect('disableOptgroups', optgroupIndex); $(selector).ikSelect('disableOptgroups', optgroupIndexesArray); /* Disable one or many optgroups. */ $(selector).ikSelect('enableOptgroups', optgroupIndex); $(selector).ikSelect('enableOptgroups', optgroupIndexesArray); /* Enable one or many optgroups. */ $(selector).ikSelect('toggleOptgroups', optgroupIndex[, enableOrDisable]); $(selector).ikSelect('toggleOptgroups', optgroupIndexesArray[, enableOrDisable]); /* Toggle one or many optgroups' state. Optionally, set *enableOrDisable* as true/false to specify needed state. */ $(selector).ikSelect('detach'); /* Detach plugin from select and remove all traces. */ ``` ## Examples Check the [Examples](http://igor10k.github.com/ikSelect/examples.html) page. ## License ``` The MIT License (MIT) Copyright (c) 2013 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` --- author: [http://igorkozlov.me](http://igorkozlov.me) <file_sep>/sources/blocks/field/field.js $('.field').on('blur.hasValue', function () { $(this).toggleClass('field--has-value', $(this).val() !== ''); }).triggerHandler('blur.hasValue');
d2342d22d2bab37e7f45ec56328b4caa2933bde9
[ "JavaScript", "Markdown" ]
3
JavaScript
alskra/detailing-plus
1fd66af453403f72e584f18275f1abe211fa429d
9411d3a0e27b4a1d3f3717188aca5be27b45e186
refs/heads/main
<repo_name>kimku-0112/2021ESWContest_free_1126<file_sep>/launch_ui.sh source ~/catkin_ws/devel/setup.bash roslaunch MR_2_UI MR_2_UI_full.launch <file_sep>/launch_ui_size_max.sh source ~/catkin_ws/devel/setup.bash roslaunch MR_2_UI MR_2_UI_max.launch
bd3075d9ace5b447e3dd18edb5ea4c890be86fcc
[ "Shell" ]
2
Shell
kimku-0112/2021ESWContest_free_1126
50f59fcd0aec8d2de8030b954069cb789c203232
c178f8a84cf9ab0ee135b743bb112ceff0a22023
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import junit.framework.Assert; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import teamivan.TestDrivenMenthods; public class TestClass { @Test public void addingTwoNumbers() { TestDrivenMenthods.add(3,2); } @Test public void addingTwoNumbersEqualsTwo(){ Assert.assertEquals(5, TestDrivenMenthods.add(2,3)); } }
721560ba027743988224a9c57d1a045b44122ac8
[ "Java" ]
1
Java
ivanorillos123/TestDriven
72d3bf9140ffdcfe4cc092c21e7f06034c792998
ea437bf92ba5cfba7858feb74a8ecca765285e37
refs/heads/master
<file_sep>#include <iostream> #include <fstream> int** Graph; //Двумерный массив, матрица смежности int NumberOfVertex, StartVertex = 0, Distance = 0; //Количество вершин bool* Found; using namespace std; void Dispose() { for (int i = 0; i < NumberOfVertex; i++) { delete[] Graph[i]; } delete[] Found; } void Path(int Start, int Distanceance) { if (Distanceance == 0) { //Если расстояние до вершины равно нулю, значит существует путь от Start Found[Start] = true; } else { for (int V = 0; V < NumberOfVertex; ++V) { //Цикл для всех вершин, кроме исходной if ((Graph[Start][V] > 0)) { if ((V != Start)) { if ((Distanceance >= Graph[Start][V])) { Path(V, Distanceance - Graph[Start][V]); /*Запускаем рекурсию для всех вершин, кроме исходной уменьшая расстояние, так как прошли один путь*/ } } } } } } void Init(const string pathToFile) { ifstream fin(pathToFile); //Файл с начальными значениями, в первой строке 1 это кол-во вершин, 2-исходная вершина, 3-исходная длина fin >> NumberOfVertex >> StartVertex >> Distance; //Считывание значений количества вершин, конечной вершины и расстояния. Found = new bool[NumberOfVertex]; //Массив с проверенными элементами. Graph = new int* [NumberOfVertex]; for (int i = 0; i < NumberOfVertex; ++i) { //Инициализация графа Graph[i] = new int[NumberOfVertex]; Found[i] = false; for (int j = 0; j < NumberOfVertex; ++j) { int d = 0; fin >> d; Graph[i][j] = d; } } fin.close(); //Закрытие потока файла } int main() { const string path = "input.txt"; Init(path); //функция инициализации графа Path(StartVertex, Distance); ofstream fout; fout.open("output.txt"); for (int i = 0; i < NumberOfVertex; ++i) { //Вывод вершин if (Found[i]) { fout << i << ' '; } } fout.close(); Dispose(); //Удаление выделившейся памяти return (0); }
4b7cc81725b44a149e97411453e1a0c6f16d04c3
[ "C++" ]
1
C++
mnguzd/orgraph
02cce2388967a242dd34ced8b6518d6face8b5f2
b0f673ea9ba1ab6119427facf539406e126b9368
refs/heads/master
<file_sep>import alpaca_trade_api as tradeapi import requests import ssl import numpy as np import pandas as pd import turicreate as tc from sklearn.preprocessing import MinMaxScaler import os import time import joblib class TradeBot: def __init__(self,ticker1='ZM',ticker2='LBTYK',win=5,past=6,API_KEY=None,API_SECRET=None): requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context self.past = past self.ticker1 = ticker1 self.ticker2 = ticker2 self.win = win self.period = past * win self.API_KEY = API_KEY self.API_SECRET = API_SECRET def accuracy(self, x_valid, rnn_forecast): a = [] b = [] n = min(len(x_valid), len(rnn_forecast)) for i in range(1, n): a.append(x_valid[i] - x_valid[i - 1]) b.append(rnn_forecast[i] - rnn_forecast[i - 1]) a = np.array([1 if x > 0 else -1 for x in a]) b = np.array([1 if x > 0 else -1 for x in b]) c = a * b acc = sum([1 if x > 0 else 0 for x in c]) acc = float(acc) / n return acc def get_data_x(self, tickX): # tickerX = yf.Ticker(tickX) # histX = tickerX.history(period=period) histX = self.load_data(tickX, 30*self.period) df = pd.DataFrame(histX) for i in range(self.win, self.past * self.win): df['lag-' + str(i)] = df['Close'].shift(i) df = df.drop(columns=['Close']) return df.dropna() def get_data_y(self, tickY): # tickerY = yf.Ticker(tickY) # histY = tickerY.history(period=period) histY = self.load_data(tickY, 30*self.period) df = pd.DataFrame(histY) df['avg'] = df['Close'].rolling(self.win).mean() df = df.drop(columns=['Close']) return df.dropna() def pair_loss(self): # win = 5 # period = '2y' # ticker1 = 'AAPL' # ticker2 = 'FB' scalerX = MinMaxScaler() scalerY = MinMaxScaler() x = self.get_data_x(self.ticker1) y = self.get_data_y(self.ticker2) #print(x) # print(y) # print(y.values) #print(x.values.shape) x = pd.DataFrame(scalerX.fit_transform(x.values), columns=x.columns, index=x.index) y = pd.DataFrame(scalerY.fit_transform(y.values), columns=y.columns, index=y.index) joblib.dump(scalerX, self.ticker1 + "-" + self.ticker2 + '-scalerX.gz') joblib.dump(scalerY, self.ticker1 + "-" + self.ticker2 + '-scalerY.gz') # print(x) # print(y) # df = x.merge(y, on='Date').dropna() df = x.merge(y, left_index=True, right_index=True).dropna() data = tc.SFrame(df) # Make a train-test split train_data, test_data = data.random_split(0.8) myFeatures = [] for i in range(self.win, self.past * self.win): myFeatures.append('lag-' + str(i)) # Automatically picks the right model based on your data. model = tc.regression.create(train_data, target='avg', features=myFeatures) # Save predictions to an SArray results = model.evaluate(test_data) model.save(self.ticker1 + "-" + self.ticker2 + '-regression') predictions = model.predict(test_data) predictions = pd.DataFrame(predictions, columns=['X1']).rolling(self.win).mean() chart = tc.SFrame(predictions) chart['actual'] = test_data['avg'] acc = self.accuracy(chart['actual'], chart['X1']) print(acc) results['accuracy'] = acc return results def predictPrice(self): scalerX = joblib.load(self.ticker1 + "-" + self.ticker2 + '-scalerX.gz') scalerY = joblib.load(self.ticker1 + "-" + self.ticker2 + '-scalerY.gz') myFeatures = [] for i in range(self.win,self.past*self.win): myFeatures.append('lag-' + str(i)) # Automatically picks the right model based on your data. model = tc.load_model(self.ticker1 + "-" + self.ticker2 + '-regression') hist = self.load_data(self.ticker1,self.period) current = np.array(hist.iloc[-1*(self.past-1)*self.win:].values).reshape(1,-1) #print(current) current = scalerX.transform(current) current = tc.SFrame(current) future = model.predict(current) #print(hist) price = hist['Close'].values current = tc.SFrame(price[-1*(self.past-1)*self.win:]) future = model.predict(current) future = np.expand_dims(future, axis=0) print(future[0][0]) future = scalerY.inverse_transform(future) print("predicted price after transform is {}".format(future[0][0])) return future[0][0] def load_data(self,ticker,period): APCA_API_BASE_URL = "https://paper-api.alpaca.markets" api = tradeapi.REST(self.API_KEY, self.API_SECRET, APCA_API_BASE_URL, 'v2') # Get daily price data for AAPL over the last 5 trading days. barset = api.get_barset(ticker, 'minute', limit=period) bars = barset[ticker] df = pd.DataFrame( [ b.c for b in bars], columns=['Close'] ) #df['Date'] = range(len(bars)) #df.set_index('Date') # See how much AAPL moved in that timeframe. #week_open = aapl_bars[0].o #week_close = aapl_bars[-1].c #percent_change = (week_close - week_open) / week_open * 100 #print('AAPL moved {}% over the last 5 minutes'.format(percent_change)) #print(df) return df def buy(self,symbol,price): APCA_API_BASE_URL = "https://paper-api.alpaca.markets" api = tradeapi.REST(self.API_KEY, self.API_SECRET, APCA_API_BASE_URL, 'v2') symbol_price = api.get_last_quote(symbol) symbol_price = symbol_price.askprice spread = (price - symbol_price) / symbol_price print("predicted spread is {}".format(spread)) toBuy = False if spread < 0 : print("No profit") toBuy = False return #position = api.get_position(symbol) # Get a list of all of our positions. toBuy = True portfolio = api.list_positions() # Print the quantity of shares for each position. for position in portfolio: if position.symbol == symbol: toBuy = False print("current position is {}".format(position.qty)) if (int(position.qty) <= 3 and spread > 0): print("place order") spread = 0.4 api.submit_order( symbol=symbol, qty=1, side='buy', type='market', time_in_force='gtc', order_class='bracket', stop_loss={'stop_price': symbol_price * (1-spread), 'limit_price': symbol_price * (1-spread)*0.95}, take_profit={'limit_price': symbol_price * (1+spread)} ) if toBuy == True: spread = 0.4 api.submit_order( symbol=symbol, qty=1, side='buy', type='market', time_in_force='gtc', order_class='bracket', stop_loss={'stop_price': symbol_price * (1 - spread), 'limit_price': symbol_price * (1 - spread) * 0.95}, take_profit={'limit_price': symbol_price * (1 + spread)} ) <file_sep>import os from google.cloud import secretmanager_v1 from google.cloud import storage from google.cloud import pubsub_v1 from google.cloud import bigquery import alpaca_trade_api as tradeapi from flask import Flask from flask import request from zipfile import ZipFile from TradeBot import TradeBot from StockCorrelation import StockCorrelation from os.path import basename from datetime import date import json import base64 app = Flask(__name__) PRJID="139391369285" Q1=""" select distinct ticker1,ticker2 from ( with dateList as ( select create_dt from `iwasnothing-self-learning.stock_cor.stock_cor_short_list` order by create_dt desc ) SELECT ticker1,ticker2,accuracy/(10*rmse) as score FROM `iwasnothing-self-learning.stock_cor.stock_cor_short_list` where create_dt in (select create_dt from dateList limit 1) ORDER BY score desc ) LIMIT 3 """ def init_vars(): client = secretmanager_v1.SecretManagerServiceClient() name = f"projects/{PRJID}/secrets/APCA_API_KEY_ID/versions/latest" response = client.access_secret_version(request={'name': name}) print(response) os.environ["APCA_API_KEY_ID"] = response.payload.data.decode('UTF-8') key = response.payload.data.decode('UTF-8') name = f"projects/{PRJID}/secrets/APCA_API_SECRET_KEY/versions/latest" response = client.access_secret_version(request={'name': name}) print(response) os.environ["APCA_API_SECRET_ID"] = response.payload.data.decode('UTF-8') secret = response.payload.data.decode('UTF-8') return (key,secret) def download_files(ticker1,ticker2): bucket_name = "iwasnothing-cloudml-job-dir" wdir = "/app/" prefix = ticker1 + "-" + ticker2 + "-" filename = prefix + "regression.zip" download_blob(bucket_name, filename, wdir + filename) with ZipFile(wdir+filename, 'r') as zipObj: zipObj.extractall( wdir + prefix + "regression") print("ls dir after unzip",wdir+filename) print(os.listdir( wdir + prefix + "regression")) print(os.listdir( wdir )) filename = prefix + "scalerX.gz" download_blob(bucket_name, filename, wdir + filename) filename = prefix + "scalerY.gz" download_blob(bucket_name, filename, wdir + filename) def zip_model(dirName): # create a ZipFile object with ZipFile(dirName + '.zip', 'w') as zipObj: # Iterate over all the files in directory for folderName, subfolders, filenames in os.walk(dirName): for filename in filenames: # create complete filepath of file in directory filePath = os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, basename(filePath)) def upload_files(ticker1 , ticker2): bucket_name = "iwasnothing-cloudml-job-dir" wdir = "/app/" prefix = ticker1 + "-" + ticker2 + "-" filename = prefix + "regression.zip" upload_blob(bucket_name, wdir + filename, filename) filename = prefix + "scalerX.gz" upload_blob(bucket_name, wdir + filename, filename) filename = prefix + "scalerY.gz" upload_blob(bucket_name, wdir + filename, filename) def download_list(): bucket_name = "iwasnothing-cloudml-job-dir" wdir = "/app/" filename = "list.txt" download_blob(bucket_name, filename, wdir + filename) @app.route('/genstocks', methods=['GET']) def genStocks(): project_id = "iwasnothing-self-learning" topic_id = "stock_pair" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) download_list() with open('/app/list.txt', 'r') as fp: list = fp.read().splitlines() print(list) for ticker1 in list: for ticker2 in list: if ticker2 != ticker1: # The `topic_path` method creates a fully qualified identifier # in the form `projects/{project_id}/topics/{topic_id}` data = {"ticker1": ticker1, "ticker2": ticker2} # Data must be a bytestring data = json.dumps(data) data = data.encode("utf-8") # When you publish a message, the client returns a future. future = publisher.publish(topic_path, data) print(future.result()) return ('', 204) @app.route('/correlation', methods=['POST']) def correlation(): envelope = request.get_json() if not envelope: msg = 'no Pub/Sub message received' print(f'error: {msg}') return f'Bad Request: {msg}', 400 if not isinstance(envelope, dict) or 'message' not in envelope: msg = 'invalid Pub/Sub message format' print(f'error: {msg}') return f'Bad Request: {msg}', 400 pubsub_message = envelope['message'] name = 'World' if isinstance(pubsub_message, dict) and 'data' in pubsub_message: name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip() print(f'Hello {name}!') req_json = json.loads(name) ticker1 = req_json['ticker1'] ticker2 = req_json['ticker2'] print(ticker1,ticker2) r = StockCorrelation() cor = r.pair_loss(ticker1,ticker2,period='2y',win=5) print(cor) project_id = "iwasnothing-self-learning" topic_id = "stock_filter" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) data = cor # Data must be a bytestring data = json.dumps(data) data = data.encode("utf-8") # When you publish a message, the client returns a future. future = publisher.publish(topic_path, data) print(future.result()) return (data, 204) return ('', 204) @app.route('/filter', methods=['POST']) def filter(): envelope = request.get_json() if not envelope: msg = 'no Pub/Sub message received' print(f'error: {msg}') return f'Bad Request: {msg}', 400 if not isinstance(envelope, dict) or 'message' not in envelope: msg = 'invalid Pub/Sub message format' print(f'error: {msg}') return f'Bad Request: {msg}', 400 pubsub_message = envelope['message'] name = 'World' if isinstance(pubsub_message, dict) and 'data' in pubsub_message: name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip() print(f'Filter {name}!') req_json = json.loads(name) ticker1 = req_json['ticker1'] ticker2 = req_json['ticker2'] rmse = req_json['rmse'] acc = req_json['accuracy'] future = req_json['future'] today = date.today() todstr = today.strftime("%Y-%m-%d") print(ticker1,ticker2,rmse,acc,future,today) if rmse <= 0.04 and acc >= 0.65: print("insert stock") bigquery_client = bigquery.Client() # Prepares a reference to the dataset dataset_ref = bigquery_client.dataset('stock_cor') table_ref = dataset_ref.table('stock_cor_short_list') table = bigquery_client.get_table(table_ref) # API call rows_to_insert = [ (ticker1, ticker2, rmse, acc, future, todstr) ] errors = bigquery_client.insert_rows(table, rows_to_insert) print(errors) return ('', 204) @app.route('/predictall', methods=['GET']) def predictAll(): # Construct a BigQuery client object. project_id = "iwasnothing-self-learning" topic_id = "stock_predict" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) client = bigquery.Client() today = date.today() todstr = today.strftime("%Y-%m-%d") query = """ SELECT ticker1,ticker2,rmse,accuracy,future FROM `iwasnothing-self-learning.stock_cor.stock_cor_short_list` WHERE DATE(create_dt) = \"{}\" ORDER BY accuracy DESC LIMIT 3 """.format(todstr) query_job = client.query(Q1) # Make an API request. print("The query data:") for row in query_job: for val in row: print(val) # The `topic_path` method creates a fully qualified identifier # in the form `projects/{project_id}/topics/{topic_id}` print(row) data = {"ticker1": row[0], "ticker2": row[1]} data = json.dumps(data) print(data) # Data must be a bytestring data = data.encode("utf-8") # When you publish a message, the client returns a future. future = publisher.publish(topic_path, data) print(future.result()) return ('', 204) @app.route('/predict', methods=['POST']) def predict(): envelope = request.get_json() if not envelope: msg = 'no Pub/Sub message received' print(f'error: {msg}') return f'Bad Request: {msg}', 400 if not isinstance(envelope, dict) or 'message' not in envelope: msg = 'invalid Pub/Sub message format' print(f'error: {msg}') return f'Bad Request: {msg}', 400 pubsub_message = envelope['message'] name = 'World' if isinstance(pubsub_message, dict) and 'data' in pubsub_message: name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip() print(f'Filter {name}!') req_json = json.loads(name) ticker1 = req_json['ticker1'] ticker2 = req_json['ticker2'] print(ticker1,ticker2) (key,secret) = init_vars() download_files(ticker1,ticker2) #ticker1='ZM' #ticker2='LBTYK' win = 5 past = 6 bot = TradeBot(ticker1,ticker2,win,past,key,secret) result = bot.predictPrice() print(result) bot.buy(ticker2,result) return 'Hello {}!'.format(str(result)) return ('', 204) @app.route('/trainall', methods=['GET']) def trainAll(): # Construct a BigQuery client object. project_id = "iwasnothing-self-learning" topic_id = "stock_train" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) client = bigquery.Client() today = date.today() todstr = today.strftime("%Y-%m-%d") query = """ SELECT ticker1,ticker2,rmse,accuracy,future FROM `iwasnothing-self-learning.stock_cor.stock_cor_short_list` WHERE DATE(create_dt) = \"{}\" ORDER BY accuracy DESC LIMIT 3 """.format(todstr) query_job = client.query(Q1) # Make an API request. print("The query data:") for row in query_job: for val in row: print(val) # The `topic_path` method creates a fully qualified identifier # in the form `projects/{project_id}/topics/{topic_id}` print(row[0]) print(row[1]) data = {"ticker1": row[0], "ticker2": row[1]} data = json.dumps(data) print(data) # Data must be a bytestring data = data.encode("utf-8") # When you publish a message, the client returns a future. future = publisher.publish(topic_path, data) print(future.result()) return ('', 204) @app.route('/train', methods=['POST']) def train(): envelope = request.get_json() if not envelope: msg = 'no Pub/Sub message received' print(f'error: {msg}') return f'Bad Request: {msg}', 400 if not isinstance(envelope, dict) or 'message' not in envelope: msg = 'invalid Pub/Sub message format' print(f'error: {msg}') return f'Bad Request: {msg}', 400 pubsub_message = envelope['message'] name = 'World' if isinstance(pubsub_message, dict) and 'data' in pubsub_message: name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip() print(f'Filter {name}!') req_json = json.loads(name) print(req_json) ticker1 = req_json['ticker1'] ticker2 = req_json['ticker2'] print(ticker1,ticker2) (API_KEY,API_SECRET) = init_vars() #ticker1='ZM' #ticker2='LBTYK' win = 5 past = 6 bot = TradeBot(ticker1,ticker2,win,past,API_KEY,API_SECRET) result = bot.pair_loss() print(result) prefix = ticker1 + "-" + ticker2 + "-" zip_model(prefix + 'regression') upload_files(ticker1,ticker2) return 'Hello {}!'.format(str(result)) return ('', 204) @app.route('/trade', methods=['POST']) def trade(): envelope = request.get_json() if not envelope: msg = 'no Pub/Sub message received' print(f'error: {msg}') return f'Bad Request: {msg}', 400 if not isinstance(envelope, dict) or 'message' not in envelope: msg = 'invalid Pub/Sub message format' print(f'error: {msg}') return f'Bad Request: {msg}', 400 pubsub_message = envelope['message'] name = 'World' if isinstance(pubsub_message, dict) and 'data' in pubsub_message: name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip() print(f'Filter {name}!') msg = json.loads(name) ticker = msg["ticker"] #spread = msg['spread'] spread = 0.4 print(ticker) print(spread) (API_KEY,API_SECRET) = init_vars() APCA_API_BASE_URL = "https://paper-api.alpaca.markets" api = tradeapi.REST(API_KEY, API_SECRET, APCA_API_BASE_URL, 'v2') ticker_price = api.get_last_quote(ticker) ticker_price = ticker_price.askprice print(ticker_price) # We could buy a position and add a stop-loss and a take-profit of 5 % try: api.submit_order( symbol=ticker, qty=1, side='buy', type='market', time_in_force='gtc', order_class='bracket', stop_loss={'stop_price': ticker_price * (1 - spread), 'limit_price': ticker_price * (1 - spread) * 0.95}, take_profit={'limit_price': ticker_price * (1 + spread)} ) except Exception as e: print(e.message) return ('', 204) @app.route('/dayend', methods=['GET']) def sellAll(): (API_KEY,API_SECRET) = init_vars() APCA_API_BASE_URL = "https://paper-api.alpaca.markets" api = tradeapi.REST(API_KEY, API_SECRET, APCA_API_BASE_URL, 'v2') print("cancel order") api.cancel_all_orders() portfolio = api.list_positions() for position in portfolio: print("{} shares of {}".format(position.qty, position.symbol)) api.submit_order( symbol=position.symbol, qty=position.qty, side='sell', type='market', time_in_force='gtc' ) return ('', 204) def download_blob(bucket_name, source_blob_name, destination_file_name): """Downloads a blob from the bucket.""" # bucket_name = "your-bucket-name" # source_blob_name = "storage-object-name" # destination_file_name = "local/path/to/file" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) if blob.exists(): try: ret = blob.download_to_filename(destination_file_name) print("download ",destination_file_name,ret) if ret is not None: print("Blob {} downloaded to {}.".format(source_blob_name, destination_file_name)) return True except: return False return False def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" # bucket_name = "your-bucket-name" # source_file_name = "local/path/to/file" # destination_blob_name = "storage-object-name" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print( "File {} uploaded to {}.".format( source_file_name, destination_blob_name ) ) if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080))) <file_sep>import requests import ssl import pandas as pd import yfinance as yf import turicreate as tc from datetime import datetime, timedelta, date from newsapi import NewsApiClient import turicreate.aggregate as agg class NewsPredictor: def __init__(self,key=None,list="/app/list.txt"): requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context self.key = key self.shortlist = [] self.list_loc = list self.model_loc = "newsapiprediction.model" def download_news(self,ticker,period=30): tod = date.today() startday = datetime.today() - timedelta(period) print(startday,tod) newsapi = NewsApiClient(api_key=self.key) all_articles = newsapi.get_everything(q=ticker+' price', from_param=startday, to=tod, language='en', sort_by='relevancy', page_size=30, page=1) result_list = [] for news in all_articles['articles']: toks = news['publishedAt'].split('T') day = toks[0] d = datetime.strptime(day,'%Y-%m-%d') if news['title'] is None: news['title'] = " " if news['content'] is None: news['content'] = " " result = {'text': news['title'] + news['content'], 'datetime': d } result_list.append(result) if len(result_list) > 0: data = pd.DataFrame(result_list) data['stock'] = data['datetime'].apply(lambda x: ticker) print(data) else: data = None return data def load_price(self,tic,period): ticker = yf.Ticker(tic) hist = ticker.history(period=period) stock_data = hist.reset_index() stock_data['rise'] = stock_data[['Open','Close']].apply(lambda x: 1 if x['Close'] >= x['Open'] else 0, axis=1) #stock_data['month'] = stock_data['Date'].apply(lambda x: x.month) #stock_data['day'] = stock_data['Date'].apply(lambda x: x.day) stock_data['stock'] = stock_data['Date'].apply(lambda x: tic) return stock_data def training(self): period='1y' all = [] price = [] #for i in ['AAPL','FB','GOOG','AMZN','NFLX']: with open(self.list_loc, 'r') as fp: list = fp.read().splitlines() for i in list: df = self.download_news(i,30) all.append(df) df_tic = self.load_price(i,period) print(df_tic) price.append(df_tic) data = pd.concat(all, ignore_index=True) data['next-day'] = data['datetime'].apply(lambda x: x + timedelta(days=1) ) #data['month'] = data['datetime'].apply(lambda x: x.month) #data['day'] = data['datetime'].apply(lambda x: x.day) data['text'] = data[['stock','text','next-day']].groupby(['next-day'])['text'].transform(lambda x: ','.join(x)) text_data = data[['stock','text','next-day']].drop_duplicates().sort_values('next-day').reset_index() print(text_data) stock_data = pd.concat(price,ignore_index=True) print(stock_data) combined_df = pd.merge(left=text_data, right=stock_data, how='left', left_on=['stock','next-day'], right_on=['stock','Date']).dropna() print(combined_df) today = date.today() todstr = today.strftime("%Y-%m-%d") combined_df.to_csv('newsout-'+todstr+'.zip', index=False,compression='zip') sf = tc.SFrame(combined_df) sf['label'] = sf.apply(lambda x: int(x['rise'])) # Split the data into training and testing training_data, test_data = sf.random_split(0.8) # Create a model using higher max_iterations than default model = tc.text_classifier.create(training_data, 'label', features=['text'], max_iterations=100) # Save the model for later use in Turi Create model.save(self.model_loc) # Save predictions to an SArray predictions = model.predict(test_data) predictions.explore() # Make evaluation the model metrics = model.evaluate(test_data) print(metrics['accuracy']) def predict(self): all = [] with open(self.list_loc, 'r') as fp: list = fp.read().splitlines() for i in list: df = self.download_news(i,1) all.append(df) data = pd.concat(all, ignore_index=True) print(data) sf = tc.SFrame(data) model = tc.load_model(self.model_loc) # Save predictions to an SArray predictions = model.predict(sf) sf['prediction'] = predictions #sf.explore() trade_list = sf.groupby(key_column_names='stock', operations={'avg': agg.MEAN('prediction'), 'count': agg.COUNT()}) #trade_list['label'] = trade_list.apply(lambda x: 'rise' if (x['avg'] >= 0.8 and x['count'] >= 10) else 'drop') self.shortlist = trade_list.to_dataframe() def getShortList(self): return self.shortlist def getModelLocation(self): return self.model_loc <file_sep>gcloud pubsub subscriptions create stock_pair_handler --topic stock_pair \ --push-endpoint=https://helloworld-s3yk5iivva-uc.a.run.app/correlation \ --push-auth-service-account=<EMAIL> gcloud pubsub subscriptions create stock_filter_handler --topic stock_filter \ --push-endpoint=https://helloworld-s3yk5iivva-uc.a.run.app/filter \ --push-auth-service-account=<EMAIL> gcloud pubsub subscriptions create stock_train_handler --topic stock_train \ --push-endpoint=https://helloworld-s3yk5iivva-uc.a.run.app/train \ --push-auth-service-account=<EMAIL> gcloud pubsub subscriptions create stock_predict_handler --topic stock_predict \ --push-endpoint=https://helloworld-s3yk5iivva-uc.a.run.app/predict \ --push-auth-service-account=<EMAIL> <file_sep>import matplotlib.pyplot as plt import yfinance as yf import requests import ssl import numpy as np import pandas as pd import turicreate as tc from sklearn.preprocessing import MinMaxScaler import os import time import numpy as np from numpy import genfromtxt class StockCorrelation: def __init__(self): requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context self.plot_chart = False def accuracy(self,x_valid,rnn_forecast): a = [] b = [] n = min(len(x_valid),len(rnn_forecast)) for i in range(1,n): a.append(x_valid[i]-x_valid[i-1]) b.append(rnn_forecast[i]-rnn_forecast[i-1]) a = np.array([1 if x > 0 else -1 for x in a]) b = np.array([1 if x > 0 else -1 for x in b]) c = a*b acc = sum ([ 1 if x > 0 else 0 for x in c]) acc = float(acc) / n return acc def load_data(self,tic,period): n = 0 while n == 0: ticker = yf.Ticker(tic) hist = ticker.history(period=period) n = hist.shape[0] time.sleep(1) return hist def get_data_x(self,tickX, period,win): #tickerX = yf.Ticker(tickX) #histX = tickerX.history(period=period) histX = self.load_data(tickX,period) df = pd.DataFrame(histX['Close']) for i in range(win , 3 * win ): df['lag-' + str(i)] = df['Close'].shift(i) df = df.drop(columns=['Close']) return df.dropna() def get_data_y(self,tickY, period, win): #tickerY = yf.Ticker(tickY) #histY = tickerY.history(period=period) histY = self.load_data(tickY,period) df = pd.DataFrame(histY['Close']) df['avg'] = df['Close'].rolling(win).mean() df = df.drop(columns=['Close']) return df.dropna() def pair_loss(self,ticker1,ticker2,period,win): #win = 5 #period = '2y' #ticker1 = 'AAPL' #ticker2 = 'FB' scalerX = MinMaxScaler() scalerY = MinMaxScaler() x = self.get_data_x(ticker1,period,win) y = self.get_data_y(ticker2,period,win) #print(x) #print(y) #print(y.values) x = pd.DataFrame(scalerX.fit_transform(x.values), columns=x.columns, index=x.index) y = pd.DataFrame(scalerY.fit_transform(y.values), columns=y.columns, index=y.index) df = x.merge(y, on='Date').dropna() data = tc.SFrame(df)# Make a train-test split train_data, test_data = data.random_split(0.8) myFeatures = [] for i in range(win,3*win): myFeatures.append('lag-' + str(i)) # Automatically picks the right model based on your data. model = tc.regression.create(train_data, target='avg', features = myFeatures) # Save predictions to an SArray results = model.evaluate(test_data) predictions = model.predict(data) chart = tc.SFrame(predictions) chart['actual'] = data['avg'] # Evaluate the model and save the results into a dictionary acc = self.accuracy(chart['actual'], chart['X1']) print(acc) results['accuracy'] = acc #tickerX = yf.Ticker(ticker1) #hist = tickerX.history(period='1mo') #price = hist['Close'].values #current = tc.SFrame(price[:2*win]) hist = self.load_data(ticker1,period) price = hist['Close'].values current = tc.SFrame(price[-2*win:]) future = model.predict(current) future = np.expand_dims(future, axis=0) print(future) future = scalerY.inverse_transform(future) print(future) results['future'] = future[0][0] results['ticker1'] = ticker1 results['ticker2'] = ticker2 #if plot_chart == True: if self.plot_chart == True and results['rmse'] <= 0.06: #print(chart) plt.clf() plt.plot(range(len(chart['actual'])), chart['X1'], "g-") plt.plot(range(len(chart['actual'])), chart['actual'], "y-") plt.xlabel("Time") plt.ylabel("Value") plt.grid(True) #plt.show() plt.savefig(ticker2 + "-prediction.png") #chart.show() return results def del_list_files(self,list,period): for tic in list: filename = tic + "-" + period + ".csv" os.remove(filename) def getAllCorrelation(self): #final_table = [] period = '2y' win = 5 with open('list.txt','r') as fp: list = fp.read().splitlines() tickerMap = {} for idx,ticker in enumerate(list): tickerMap[ticker] = idx n = len(list) rmse_matrix = np.zeros((n,n)) acc_matrix = np.zeros((n,n)) pred_matrix = np.zeros((n,n)) print(list) for ticker1 in list: for ticker2 in list: if ticker2 != ticker1: result = self.pair_loss(ticker1, ticker2, period, win) #print(result) row = {"ticker1": ticker1, "ticker2": ticker2 , "rmse": result['rmse'], "future":result['future'], "accuracy":result['accuracy']} x = tickerMap[ticker1] y = tickerMap[ticker2] rmse_matrix[x,y] = row['rmse'] acc_matrix[x,y] = row['accuracy'] pred_matrix[x,y] = row['future'] np.savetxt('rmse.csv',rmse_matrix,delimiter=',') np.savetxt('acc.csv',acc_matrix,delimiter=',') np.savetxt('pred.csv',pred_matrix,delimiter=',') self.del_list_files(list,period) ind = np.unravel_index(np.argmax(acc_matrix, axis=None), acc_matrix.shape) print(ind) print(list[ind[0]],list[ind[1]]) print(acc_matrix[ind]) n = acc_matrix.shape[0] m = acc_matrix.shape[1] for i in range(n): for j in range(m): if acc_matrix[i,j] >= 0.7: print(i,j,list[i],list[j],rmse_matrix[i,j],acc_matrix[i,j], pred_matrix[i,j]) n = rmse_matrix.shape[0] for i in range(n): rmse_matrix[i,i] = 1000 ind = np.unravel_index(np.argmin(rmse_matrix, axis=None), rmse_matrix.shape) print(ind) print(list[ind[0]],list[ind[1]]) print(rmse_matrix[ind]) n = rmse_matrix.shape[0] m = rmse_matrix.shape[1] for i in range(n): for j in range(m): if rmse_matrix[i,j] <= 0.04 and acc_matrix[i,j] > 0.6: print(list[i],list[j],rmse_matrix[i,j],acc_matrix[i,j],pred_matrix[i,j]) <file_sep>#!/bin/sh DIR="/Users/kahingleung/PycharmProjects/newturi" cp $DIR/main.py main.py cp $DIR/TradeBot.py TradeBot.py cp $DIR/StockCorrelation.py StockCorrelation.py APCA_API_KEY_ID=`gcloud secrets versions access latest --secret=APCA_API_KEY_ID` APCA_API_SECRET_KEY=`gcloud secrets versions access latest --secret=APCA_API_SECRET_KEY` echo $APCA_API_KEY_ID echo $APCA_API_SECRET_KEY gcloud builds submit --tag gcr.io/iwasnothing-self-learning/helloworld gcloud run deploy helloworld --image gcr.io/iwasnothing-self-learning/helloworld --platform managed \ --memory=512Mi \ --concurrency=1 \ --cpu=1 \ --max-instances=1 \ --set-env-vars "APCA_API_KEY_ID=$APCA_API_KEY_ID,APCA_API_SECRET_KEY=$APCA_API_SECRET_KEY,APCA_API_BASE_URL=https://paper-api.alpaca.markets" \ --service-account=<EMAIL> \ --no-allow-unauthenticated \ --region=us-central1 \ --timeout=5m <file_sep>import yfinance as yf import math import turicreate as tc import pandas as pd import requests import ssl class MAPredictor: def __init__(self,list="/app/list.txt"): requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context self.list_loc = list def load_price(self,tic,period): ticker = yf.Ticker(tic) hist = ticker.history(period=period) print(hist) stock_data = hist.reset_index() stock_data['rise'] = stock_data[['Open','Close']].apply(lambda x: 1 if x['Close'] >= x['Open'] else 0, axis=1).astype('int32') stock_data['hi-lo-spread'] = stock_data[['High','Low']].apply(lambda x: x['High'] - x['Low'] , axis=1) stock_data['log-vol'] = stock_data['Volume'].apply(lambda x: math.log(x+1)) return stock_data def rolling_avg(self,df,win): return df['Close']-df['Close'].rolling(win).mean() def train_evaluate(self,tic): df = self.load_price(tic,'4y') df = df.dropna() df['return'] = df['Close'].diff() df['log-vol-diff'] = df['log-vol'].diff() for x in range(10,40,10): df['gt-' + str(x) + '-avg'] = self.rolling_avg(df,x) df['label'] = df['rise'].shift(-1) cols = ['hi-lo-spread','return','log-vol-diff','gt-10-avg','gt-20-avg','gt-30-avg','label'] print(df[cols]) last = df.tail(1) last = tc.SFrame(last[cols[:-1]]) dataset = df[cols].dropna().reset_index(drop=True) dataset['label'] = dataset['label'].astype('int32').apply(lambda x: "rise" if x == 1 else "drop") data = dataset.sample(frac=0.8, random_state=786) data_unseen = dataset.drop(data.index) data.reset_index(inplace=True, drop=True) data_unseen.reset_index(inplace=True, drop=True) print('Data for Modeling: ' + str(data.shape)) print('Unseen Data For Predictions: ' + str(data_unseen.shape)) sf = tc.SFrame(data) # Make a train-test split train_data, test_data = sf.random_split(0.8) # Automatically picks the right model based on your data. model = tc.classifier.create(train_data, target='label', features=cols[:-1]) # Save predictions to an SArray results = model.evaluate(test_data) prediction = model.predict(last) print(prediction) results['prediction'] = prediction[0] return results def trainAll(self): result_list = [] with open(self.list_loc, 'r') as fp: list = fp.read().splitlines() for i in list: #for i in ['AAPL', 'FB', 'GOOG', 'AMZN', 'NFLX', "SQ", "MTCH", "AYX", "ROKU", "TTD"]: results = self.train_evaluate(i) result_list.append({"stock":i,"accuracy":results['accuracy'],'prediction':results['prediction']}) #print(result_list) df = pd.DataFrame(result_list).sort_values('accuracy',ascending=False) print(df) print(df.info()) self.shortlist = df def getShortList(self): return self.shortlist
b820dff49c8407f593535ce9833b16d4cf61242e
[ "Python", "Shell" ]
7
Python
iwasnothing/TradeBot
f6fc9b2bfe6e272ce864447cfa48e85509392469
7c20b4c5443d4e5d58c5f8e34af9c8e1b550bdd6
refs/heads/master
<file_sep># create a Motor class and create a Car class that "Has A" Motor<file_sep># create a category class with a name for now # and build upon it further in future iterations class Category: def __init__(self, name): self.name = name def __str___(self): return "No products available in " + self.name
9031fb46251ef80d091707ff690775e302210824
[ "Python" ]
2
Python
Anubhav311/gp-cseu2-P2D1
79ac8d6cbd3d25101b1cc7ffa814a8b0e78ffef7
04ec016bd045985fb64be1d6672686c36d2eeec3
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe ZipUploadsController, :type => :controller do end <file_sep>class Folder < ActiveRecord::Base attr_accessible :name, :parent_id, :user_id has_many :zip_uploaders # validates_uniqueness_of :name, :scope => :parent_id validates_presence_of :name belongs_to :user def is_root? self.parent_id.nil? && !new_record? end end <file_sep>FactoryGirl.define do factory :note do message "" user_id 1 order_id 1 end end <file_sep>task :Schedule =>:environment do order = Order.new order.name = 's' order.no_of_sheets = '23232323' order.sheet_type = "pdf" order.from_date = '2016-02-08'.to_date order.to_date = '2016-02-08'.to_date order.user_id = 3 order.save! Delayed::Job.enqueue SendEmailsJob.new(order) end<file_sep>class AddFolderIdToZipUploaders < ActiveRecord::Migration def change add_column :zip_uploaders, :folder_id, :integer add_column :users, :folder_id, :integer end end <file_sep>class CreateZipUploaders < ActiveRecord::Migration def change create_table :zip_uploaders do |t| t.string :zip t.integer :order_id t.timestamps end end end <file_sep>$(document).ready(function(){ $(".open_modal").click(function(){ $("#order_id").val($(this).attr('id')); $("#note_modal").modal(); }); $(".open_modal_upload_file").click(function(){ $("#folder_id").val($(this).attr('id')); $("#folder_modal").modal(); }); $(".move-folder-file").click(function(){ $("#move_file_id").val($(this).attr('id')); name_string = $(this).attr('name'); $("#name_of_moving_item").html(''); $("#name_of_moving_item").html('<strong>'+ name_string +'</strong>'); str = $(this).attr('id'); arr = str.split('-'); $.ajax({ type: 'get', url: '/folders/get_folder_list', dataType:'JSON', data: { 'type' : arr[1], 'id' : arr[0] }, success:function(data){ //clear the current content of the select $select = $("#user_folders_select"); $select.html(''); $select.html('<option></option>'); //iterate over the data and append a select option if(arr[1] == 'folder') { if(data["parent"] != null) { $select.append('<option value="' + data["parent"].id + '" name="' + data["parent"].id + '" >' + data["parent"].name + '</option>'); } $.each(data["folders"], function(key, val){ if(val.id != arr[0]) { $select.append('<option value="' + val.id + '" name="' + val.id + '" >' + val.name + '</option>'); } }) }else{ $.each(data["folders"], function(key, val){ $select.append('<option value="' + val.id + '" name="' + val.id + '" >' + val.name + '</option>'); }) } $("#move_modal").modal(); } }); }); $('.list-table').DataTable(); $('#tree-my').on('changed.jstree', function (e, data) { var parent = "#"+ data.node.id arr = parent.split('-'); arr1 = arr[0].split('#'); id = arr1[1] $.ajax({ type: 'get', url: '/folders/get_html', dataType: 'html', data: { 'id' : id }, success: function (data) { $("#main-div-data").html(''); $("#main-div-data").html(data); } }); // data.instance.toggle_node(data.node); }); $("#tree-my").on("open_node.jstree", function(event, data) { // console.log(data.instance); var parent = "#"+ data.node.id // Call Ajax Here to get children of targeted folder $.ajax({ type: 'get', url: '/folders/get_folders', dataType: 'json', data: { 'id' : data.node.id }, success: function (data) { // Apply loop here to create nodes for(var i= 0 ; i< data.length; i++) { child = $('#'+data[i].fdr_id+'-child') if(child.length) { }else{ createNode(parent, data[i].fdr_id , data[i].name , 'first', data[i].sub_fdr); } } if(data.length > 0 ) { $('#ch-1').remove(); $(parent+"-child").remove(); } } }); }); function createNode(parent_node, new_node_id, new_node_text, position, sub_fdr) { $('#tree-my').jstree('create_node', $(parent_node), { "text":new_node_text, "id":new_node_id+'-child' }, position, false, false); if(sub_fdr == 1 ) { $('#tree-my').jstree('create_node', $("#"+new_node_id+ '-child'), { "text":'', "id":new_node_id+'-child-child' }, position, false, false); } } $("#tree-my").jstree({ 'core' : { 'check_callback' : true, 'data': [{ 'id' : $('#root_folder_id').val()+'-root', 'text' : '', 'state' : {'opened':false}, 'children' : [{'id': 'ch-1', 'text': 'child 1'}]}] } }); }) <file_sep>CarrierWave.configure do |config| # config.fog_provider = 'fog/aws' # required config.fog_credentials = { provider: 'AWS', # required aws_access_key_id: '<KEY>', # required aws_secret_access_key: '<KEY>', # required scheme: 'http' } config.fog_directory = 'devsinc-bucket' # required config.fog_public = false # optional, defaults to true config.fog_authenticated_url_expiration = 24.hours end # CarrierWave.configure do |config| # config.dropbox_app_key = "x1onzty41hyaes0" # config.dropbox_app_secret = "<KEY>" # config.dropbox_access_token = "<KEY>" # config.dropbox_access_token_secret = "<KEY>" # config.dropbox_user_id = "123312905" # config.dropbox_access_type = "app_folder" # end <file_sep>class DashboardController < ApplicationController def index if current_user.present? redirect_to orders_path end end end <file_sep>class ZipUploadersController < ApplicationController def new authorize :zip_upload @order = Order.find(params[:order_id]) @zip_upload = @order.zip_uploaders.build end def create # order = Order.find(params[:order_id]) # @zip = order.zip_uploaders.build(params[:zip_uploader]) # if @zip.save # flash[:success] ="successfully uploaded" # redirect_to request.referrer # else # flash[:danger] = "Something went wrong." # redirect_to :back # end # following code integratde with folder folder = Folder.find(params[:folder_id]) @zip = folder.zip_uploaders.build(params[:zip_uploader]) if @zip.save flash[:success] ="successfully uploaded" redirect_to request.referrer else flash[:danger] = "Something went wrong." redirect_to :back end end def files @order = Order.find(params[:order_id]) @files = @order.zip_uploaders end def download file = ZipUploader.find(params[:id]) url = file.zip.url data = open(url).read send_data data, :disposition => 'attachment', :filename=> "#{file.zip_identifier}" end end <file_sep>module FoldersHelper def breadcrumbs(folder, breadcrumbs = '') parent_name = Folder.find(folder.parent_id).name parent = Folder.find(folder.parent_id) breadcrumbs = "<span class=\"breadcrumb nowrap\">#{link_to(parent_name, parent)}</span> &raquo; #{breadcrumbs}" breadcrumbs = breadcrumbs(parent, breadcrumbs) unless parent == Folder.find_by_name_and_parent_id('Root folder', nil) breadcrumbs.html_safe end end <file_sep>FactoryGirl.define do factory :order do name "MyString" no_of_sheets "MyString" sheet_type "MyString" from_date "2016-02-24" to_date "2016-02-24" end end <file_sep>class ZipUploadPolicy attr_reader :current_user, :record def initialize(current_user, record) @current_user = current_user @user = record end def new? @current_user.roles.where(name: ["Super Admin", "Admin"]).any? end end <file_sep>class Note < ActiveRecord::Base attr_accessible :message, :order_id, :user_id belongs_to :order belongs_to :user end <file_sep>FactoryGirl.define do factory :zip_uploader do zip "MyString" order_id 1 end end <file_sep>roles = [{name: 'Super Admin'}, {name: 'Admin'}, {name: 'User'}] roles.each do |role| Role.create!(name: role[:name]) end # user = User.create!({ # :username=>"admin", # :email=>"<EMAIL>", # :password=>"<PASSWORD>", # :password_confirmation=>"<PASSWORD>", # }) # role = user.user_roles.build # role.role_id = Role.find_by_name('Super Admin').id # role.save! user = User.create!({ :username=>"Faisal Admin", :email=>"<EMAIL>", :password=>"<PASSWORD>", :password_confirmation=>"<PASSWORD>", }) role = user.user_roles.build role.role_id = Role.find_by_name('Admin').id role.save! user = User.create!({ :username=>"<NAME>", :email=>"<EMAIL>", :password=>"<PASSWORD>", :password_confirmation=>"<PASSWORD>", }) role = user.user_roles.build role.role_id = Role.find_by_name('Admin').id role.save!<file_sep>source 'https://rubygems.org' ruby '2.1.7' gem 'rails', '3.2.14' gem 'heroku' gem 'american_date' gem 'will_paginate', '~> 3.0.5' gem 'pundit' gem 'delayed_job_active_record' gem 'rubyzip', '>= 1.1.0' # will load new rubyzip version # gem 'jstree-rails', :git => 'git://github.com/tristanm/jstree-rails.git' gem 'jstree-rails-4' # gem 'test-unit' group :production do gem 'pg' end group :development, :test do gem 'sqlite3' gem 'mysql2', '~>0.3.10' end group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'uglifier', '>= 1.0.3' gem 'therubyracer' gem 'execjs' end gem 'jquery-rails', '~> 2.2.1' gem 'bootstrap-sass', '~> 2.3.2.2' # gem 'twitter-bootstrap-rails' gem 'devise' gem 'simple_form' gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails' group :development do gem 'better_errors' gem 'quiet_assets' end group :development, :test do gem 'factory_girl_rails' gem 'rspec-rails' end group :test do gem 'capybara' gem 'cucumber-rails', :require=>false gem 'database_cleaner', '1.0.1' gem 'email_spec' #gem 'launchy' end gem 'rmagick' gem 'fog' gem 'carrierwave' gem 'carrierwave-dropbox'<file_sep>class ApplicationController < ActionController::Base include Pundit rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized protect_from_forgery # before_filter :authenticate_user! #Custom route for devise, reroutes back to the homepage this is the root_path or root_url def after_sign_in_path_for(resource) if current_user && current_user.roles.where(name: ["Super Admin", "Admin"]).any? users_path else orders_path end end #Custom route for devise, after registration def after_sign_up_path_for(resource) orders_path end private def user_not_authorized flash[:danger] = "Access denied." redirect_to (request.referrer || root_url) end end <file_sep>SendEmailsJob = Struct.new(:order) do def perform users = User.all # order = Order.find(id) users.each do |user| if user.roles.where(name: ["Super Admin", "Admin"]).any? UserMailer.notification(user,order).deliver end end end def max_attempts 2 end end <file_sep>class Order < ActiveRecord::Base attr_accessible :from_date, :name, :no_of_sheets, :sheet_type, :to_date,:email, :phone attr_accessor :email, :phone belongs_to :user has_many :notes has_many :zip_uploaders validates :from_date, presence: true validates :to_date, presence: true validates :name, presence: true, uniqueness: true validates :no_of_sheets, presence: true validates :sheet_type, presence: true end <file_sep>PaperLess::Application.routes.draw do devise_for :users, path_names: {sign_in: "login", sign_out: "logout"} root :to => "dashboard#index" resources :users do collection do post 'change_role' end resources :orders resources :folders end resources :folders, :shallow => true, :except => [:new, :create] do collection do get 'get_folders' get 'get_html' get 'get_folder_list' post 'move_folder' end resources :folders, :only => [:new, :create] resources :files, :only => [:new, :create] resources :zip_uploaders end resources :orders do collection do post 'guest_order' end resources :notes resources :zip_uploaders do collection do get 'files' end end end resources :notes resources :zip_uploaders, only: [] do member do get 'download' end end end<file_sep>class ZipUploader < ActiveRecord::Base attr_accessible :order_id, :zip,:folder_id belongs_to :folder belongs_to :order mount_uploader :zip, ZipFileUploader end <file_sep>class FoldersController < ApplicationController def index if params[:user_id].present? @user = User.find(params[:user_id]) else @user = current_user end # @folder = Folder.find(@user.folder_id) @root_folder = @user.folders.where('parent_id IS NULL').try(:first) @folder = @root_folder @folders = @user.folders.where("parent_id IS NOT NULL AND parent_id = ?", @root_folder.id) # @files = @folder.try(:zip_uploaders) end def new @target_folder = Folder.find(params[:folder_id]) @folder = Folder.new end def create @target_folder = Folder.find(params[:folder_id]) folder = Folder.new(params[:folder]) folder.parent_id = @target_folder.id folder.user_id = @target_folder.user_id if folder.save user = User.where(folder_id: @target_folder.id).try(:first) redirect_to folder_path(@target_folder) else redirect_to :back, :notice=> "Something wnet wrong." end end def show @folder = Folder.find(params[:id]) if current_user.roles.where(name: ["Super Admin", "Admin"]).any? user = @folder.user @root_folder = user.folders.where('parent_id IS NULL').try(:first) else @root_folder = current_user.folders.where('parent_id IS NULL').try(:first) end @folders = Folder.where(parent_id: @folder.id) end def get_folders id = params[:id] if id == 'root' folder = current_user.folders.where('parent_id IS NULL').try(:first) folders = Folder.where(parent_id: folder.id) else # folder = current_user.folders.where('parent_id IS NULL').try(:first) folders = Folder.where(parent_id: id) end @folder_hash = [] folders.each do |f| if Folder.where(parent_id: f.id).present? sub_fdr = 1 else sub_fdr = 0 end fdr_att = { "fdr_id" => "#{f.id}", "name" => "#{f.name}", "sub_fdr" => sub_fdr } @folder_hash << fdr_att end return render json: @folder_hash end def get_html @folder = Folder.find(params[:id]) user = @folder.user @root_folder = user.folders.where('parent_id IS NULL').try(:first) @folders = Folder.where(parent_id: @folder.id) return render partial: 'shared/page_view' end def edit @folder = Folder.find(params[:id]) end def update @folder = Folder.find(params[:id]) @folder.update_attributes(params[:folder]) parent_folder = Folder.where(parent_id: @folder.parent_id).first redirect_to folder_path(parent_folder) end def get_folder_list folder_array = [] if params[:type] == 'file' folders = current_user.folders.where("parent_id IS NOT NULL") folder_array << folders else folder = Folder.find(params[:id]) parent = Folder.find(folder.parent_id) if parent.parent_id.present? parent_of_parent = Folder.find(parent.parent_id) end folders = Folder.where(parent_id: folder.parent_id) # folder_array << parent folder_array << folders end return render json: {folders: folders, parent: parent_of_parent} end def move_folder str = params[:move_file_id] arr = str.split('-') move_to_folder = Folder.find(params[:move_to]) if(arr[1] == 'folder') folder = Folder.find(arr[0]) # Scenario# => 1 if folder.id == move_to_folder.parent_id move_to_folder.parent_id = folder.parent_id move_to_folder.save! end folder.parent_id = move_to_folder.id folder.save! else file = ZipUploader.find(arr[0]) file.folder_id = move_to_folder.id file.save! end flash[:success] = "successfully updated." redirect_to :back end end <file_sep>class GENRES_CONSTANT GENRES_TYPE = ['Action and Adventure', 'Apps','Children and Middle Grade','Christian Fiction','Contemporary Fiction','istorical Romance'] PAYMENT_STATUS = ['preAuth','decline','None'] DATE_FLEXIBLE = ['Yes','No'] Links_RETAILORS = ['Apple iBooks', 'Barnes & Noble','Google', 'Kobo', 'Sony'] end<file_sep>FactoryGirl.define do factory :user_model do user_id 1 role_id 1 end end <file_sep>class OrdersController < ApplicationController before_filter :authenticate_user!, only: [:index, :show, :create, :edit, :update] def index if params[:user_id].present? @user = User.find(params[:user_id]) @orders = @user.orders else @orders = current_user.orders end end def new @order = Order.new end def create @order = current_user.orders.build(params[:order]) if @order.save Delayed::Job.enqueue SendEmailsJob.new(@order) flash[:success] = "Successfully submitted." redirect_to orders_path else flash[:danger] = "Please Fill All Fields" redirect_to :back end end def show @order = Order.find(params[:id]) @notes = @order.notes.order('created_at DESC').includes(:user) if current_user.roles.where(name: ["Super Admin", "Admin"]).any? @admin = true end end def edit @order = Order.find(params[:id]) end def update order = Order.find(params[:id]) order.update_attributes(params[:order]) flash[:success] = "Successfully updated." redirect_to orders_path end def guest_order user = User.new user.email = params[:order][:email] user.phone = params[:order][:phone] user.password = <PASSWORD>) # cookie used only for the guest user. because there are two ways to signup. 1. signup 2. while posting order as guest then automatically new user regisered and sent an email for reset password if he/she want to continue. at this time no need to sign in. cookies[:login_user_as_guest] = "yes" if user.save role = user.user_roles.build role.role_id = Role.find_by_name('User').id role.save! order = user.orders.build(params[:order]) order.save! user.send_reset_password_instructions cookies.delete :login_user_as_guest # Delayed::Job.enqueue SendEmailsJob.new(order) flash[:success] = "Successfully submitted. Please check your email." redirect_to root_url else flash[:error] = "Please fill all the fields." redirect_to :back end end end <file_sep>class NotesController < ApplicationController def create if params[:message].length > 0 order = Order.find(params[:order_id]) note = order.notes.build note.user_id = current_user.id note.message = params[:message] note.save! flash[:success] = "Successfully submitted." end redirect_to request.referrer end def new authorize :note end end
6e8baddefcf65ddefedb1cca596d6d3d89a382b5
[ "JavaScript", "Ruby" ]
27
Ruby
HaroonSarfraz/paperless
0eb522aa6a4d4b761f06538b442c98891ceaf7a5
340a0edcfcd05a1453f40928dcc2dae28b036fad
refs/heads/master
<file_sep> #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> struct three { char data[10],temp[7]; }s[30]; int main() { char d1[7],d2[7]="t"; int i=0,j=1,len=0; FILE *f1,*f2; f1=fopen("sum.txt","r"); f2=fopen("out.txt","w"); while(fscanf(f1,"%s",s[len].data)!=EOF) len++; itoa(j,d1,7); strcat(d2,d1); strcpy(s[j].temp,d2); strcpy(d1,""); strcpy(d2,"t"); if(!strcmp(s[3].data,"+")) { fprintf(f2,"%s=%s+%s",s[j].temp,s[i+2].data,s[i+4].data); j++; } else if(!strcmp(s[3].data,"-")) { fprintf(f2,"%s=%s-%s",s[j].temp,s[i+2].data,s[i+4].data); j++; } for(i=4;i<len-2;i+=2) { itoa(j,d1,7); strcat(d2,d1); strcpy(s[j].temp,d2); if(!strcmp(s[i+1].data,"+")) fprintf(f2,"\n%s=%s+%s",s[j].temp,s[j-1].temp,s[i+2].data); else if(!strcmp(s[i+1].data,"-")) fprintf(f2,"\n%s=%s-%s",s[j].temp,s[j-1].temp,s[i+2].data); strcpy(d1,""); strcpy(d2,"t"); j++; } fprintf(f2,"\n%s=%s",s[0].data,s[j-1].temp); fclose(f1); fclose(f2); } <file_sep> public class _2f { public static void main(String args[]){ String s1="I AM A STUDENT OF CSE"; String[] words=s1.split("\\s"); for(String w:words){ System.out.println(w); } } } <file_sep> public class _2d { public static void main(String[] args){ String s="Hello World"; System.out.println(s.substring(0,5)); System.out.println(s.substring(6)); } }
1b53a80bcb640fa1bf7d095b539547d337f44cf4
[ "Java", "C++" ]
3
C++
Atira003/Compiler
2ec45bedac92fa886b4d98ce09ca1b8e4fd117c5
a50be2069527aac0f7ad8445b4d3c0b4ac886a68
refs/heads/master
<file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 #define mx 10 #define valid(tx,ty) tx>=1 && tx<=row && ty>=1 && ty<=col typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; int fx[] = {-2,-2,+2,+2,-1,+1,-1,+1}; int fy[] = {-1,+1,-1,+1,-2,-2,+2,+2}; int row = 8, col = 8; int dis[mx][mx], vis[mx][mx]; int BFS(int x1, int y1, int x2, int y2){ memset(dis, 0, sizeof(dis)); memset(vis, 0, sizeof(vis)); queue<ii> Q; Q.push(ii(x1,y1)); vis[x1][y1] = 1; bool found = false; while(!Q.empty()){ ii u = Q.front(); Q.pop(); for(int k=0; k<8; k++){ int tx = u.first + fx[k]; int ty = u.second + fy[k]; if(valid(tx,ty) && vis[tx][ty]==0){ vis[tx][ty] = 1; dis[tx][ty] = dis[u.first][u.second] + 1; Q.push(ii(tx,ty)); if(tx==x2 && ty==y2) found = true; } } if(found) break; } return dis[x2][y2]; } int main(){ string ch = "abcdefgh", s1, s2; int r1, c1, r2, c2; while(cin>>s1>>s2){ r1 = s1[1] - 48; c1 = ch.find(s1[0]) + 1; r2 = s2[1] - 48; c2 = ch.find(s2[0]) + 1; int moves = BFS(r1,c1,r2,c2); printf("To get from %s to %s takes %d knight moves.\n", s1.c_str(), s2.c_str(), moves); } return 0; } <file_sep>#include <stdio.h> #include <string.h> #define Max 10000 #define Base 10 int transform_to_array(char num[], int arr[]) { int len, j, i; len = strlen(num); j = 0; for(i=len-1; i>=0; i--) arr[j++] = num[i]-48; return len; //returning the length of the input to define the 'max' length } void addition(int arr1[], int arr2[], int max) { int i, j, carry = 0, sum; int result[Max]; for(i=0; i<max; i++){ sum = arr1[i] + arr2[i] + carry; if(sum>=Base){ carry = 1; sum -= Base; } else carry = 0; result[i] = sum; } if(carry){ if(max<Max) result[i++] = carry; else printf("Overflow in Addition!\n"); } printf("The result of Addition: \n"); for(j=i-1; j>=0; j--){ printf("%d", result[j]); } printf("\n\n"); } void subtraction(int arr1[], int arr2[], int max) { int i, j, carry=0, sub, temp; int result[Max]; for(i=0; i<max; i++){ if(arr1[i]<arr2[i]) temp = Base; else temp = 0; result[i] = (arr1[i]+temp) - (arr2[i]+carry); if(arr1[i]<arr2[i]) carry = 1; else carry = 0; } printf("The result of Subtraction: \n"); if(carry) { printf("(Subtraction Result is negative)\n"); printf("-"); } for(j=i-1; j>=0; j--){ printf("%d", result[j]); } printf("\n\n"); } int main() { char num1[Max], num2[Max]; int arr1[Max], arr2[Max]; int s1, s2, max, choice; loc: printf("Enter the first Number: \n num1: "); gets(num1); printf("Enter the second Number: \n num2: "); gets(num2); memset(arr1, 0, sizeof(arr1)); memset(arr2, 0, sizeof(arr2)); s1 = transform_to_array(num1, arr1); s2 = transform_to_array(num2, arr2); max = s1>s2 ? s1 : s2; do{ printf("What do you want to do?\n"); printf("\t1.Addition\n\t2.Subtraction\n\t"); printf("3.Retake Input\n\t4.None(Exit)\n Choice:"); scanf("%d", &choice); switch(choice){ case 1: addition(arr1, arr2, max); break; case 2: subtraction(arr1, arr2, max); break; case 3: getchar(); goto loc; break; case 4: printf("Exiting....\n"); break; default: printf("Your Choice is undefined! Retry:\n"); } }while(choice && choice!=4); return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; /* Givennitems, each with its own value Vi and weight Wi , ∀i∈[0..n-1],and a maximum knapsack size S, compute the maximum value of the items that we can carry; */ int n; int arr[100][1000]; //n*s; int w[] ={10, 4, 6, 12}; int v[] ={100, 70, 50, 10}; int findMax(int id, int remW){ if(remW==0) return 0; else if(id==n) return 0; else if(w[id]>remW) return arr[id][remW] = findMax(id+1, remW); else return arr[id][remW] = max(findMax(id+1, remW), v[id]+findMax(id+1, remW-w[id])); } int main() { IOS; int i, j; n = (sizeof(v)/sizeof(v[0])); int s = 12; int ans = findMax(0, s); cout<<ans<<endl; } <file_sep>#include <iostream> #include <algorithm> #include <vector> #include<bits/stdc++.h> using namespace std; int main() { int n=5, r; vector<bool> v(5); string vowel = "aeiou"; for(int k=1; k<=5; k++){ fill(v.begin(), v.begin() + k, true); do { string s; for (int i = 0; i <5; ++i) { if (v[i]) { s+=vowel[i]; } } sort(s.begin(), s.end()); std::cout <<s<<"\n"; } while (std::prev_permutation(v.begin(), v.end())); fill(v.begin(), v.end(), false); } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rsort(a) sort(all(a), greater<int>()) #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define mx (int)1e5+7 using namespace std; typedef long long ll; typedef pair<int, int> pi; typedef vector<int> vi; vi adj[mx], result; bitset<mx> vis; void dfs(int u){ vis[u] = 1; for(auto v: adj[u]){ if(vis[v]==0){ result.pb(v); dfs(v); } } } int main() { IOS; int i, j, n, e, a, b; cin>>n>>e; //7, 7 for(i=0; i<e; i++){ cin>>a>>b; //input (1,4), (4,3), (4, 6) (3,2), (2, 5), (2,7), (7,6) adj[a].pb(b); adj[b].pb(a); } result.pb(1); dfs(1); for(auto it: result) cout<<it<<" "; cout<<endl; if(result.size()==n) cout<<"Graph is Connected"<<endl; else cout<<"Graph is not connected"<<endl; return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; long long inv_count; int Merge(int arr[],int temp[],int left,int mid,int right) { int i = left,j = mid,k = left; while((i <= mid-1) and (j <= right)){ if(arr[i] <= arr[j]) temp[k++] = arr[i++]; else{ temp[k++] = arr[j++]; inv_count += (mid - i); } } while(i <= mid-1) temp[k++] = arr[i++]; while(j <= right) temp[k++] = arr[j++]; for(i=left; i<=right; i++) arr[i] = temp[i]; } int MergeSort(int arr[],int temp[],int left,int right) { int mid; if(right > left){ mid = (right+left) >> 1; MergeSort(arr,temp,left,mid); MergeSort(arr,temp,mid+1,right); Merge(arr,temp,left,mid+1,right); } } int main() { int t, i, n; cin>>t; while(t--){ cin>>n; int arr[n], temp[n]; for(i=0; i<n; i++){ cin>>arr[i]; } inv_count = 0; MergeSort(arr,temp,0,n-1); cout<<inv_count<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int BinarySearch(int arr[], int lo, int hi, int x) { while(lo<=hi){ int mid = lo + (hi-lo)/2; if(arr[mid]==x) return mid; else if(arr[mid]<x) lo = mid+1; else hi = mid-1; } return -1; } void BubbleSort(int arr[], int n){ for(int i=0; i<n; i++){ for(int j=n; j>=i; j--){ if(arr[j]<arr[i]){ int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } } } int main() { int arr[] = {12, 10, 11, 15, 13, 19, 17, 18, 20, 14}; int x, lo = 0, hi = (sizeof(arr)/sizeof(arr[0])) - 1; BubbleSort(arr, hi); for(int i=0; i<=hi; i++){ printf("%d ", arr[i]); } printf("\n\nEnter the number to search: \n"); while(scanf("%d", &x)==1){ int r = BinarySearch(arr, lo, hi, x); if(r<0) printf("%d is not found in the array\n\n", x); else printf("%d is found at position %d\n\n", x, r+1); } return 0; } <file_sep>#include<bits/stdc++.h> #define N 200000 #define i64 long long using namespace std; int main() { i64 ans[N] ,n,min,sub,j , num,count; char str[N+1]; scanf("%I64d",&n); scanf("%s",str); count = 0; j = -1 ; sub = 0; for(int i=0;i<n;i++){ scanf("%I64d",&num); if(str[i]=='R') j= num; else if(str[i]=='L' && num>j &&j!=-1){ count++; sub = (num - j)/2; if(count==1) min = sub; if(sub<min) min = sub; } } if(count!=0) printf("%I64d\n",min); else printf("-1\n"); return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int parent[MAX], siz[MAX]; //Initialize the array in main function int Find(int x){ if(parent[x]==x) return x; else return parent[x] = Find(parent[x]); } void Union(int x, int y){ int p = Find(x); int c = Find(y); if(p==c) return; if(siz[c]>siz[p]) swap(c, p); parent[c] = p; siz[p] += siz[c]; } int main() { IOS; for(int i=0; i<MAX; i++){ parent[i] = i; siz[i] = 1; } Union(3, 4); Union(6, 7); Union(3, 8); int s = Find(3); cout<<s<<endl; cout<<siz[s]<<endl; } <file_sep>#include <bits/stdc++.h> using namespace std; #define sieve_size 10000010 //size of sieve,work upto 10^7 typedef long long ll; typedef vector<int> vi; ll Size; bitset<sieve_size> bs; vi primes; void sieve() { bs.set(); //set all bits to 1; bs[0] = bs[1] = 0; for(ll i=1; i<=sieve_size; i++){ if(bs[i]){ for(ll j=i*i; j<=sieve_size; j+=i) bs[j] = 0; primes.push_back((int)i); } } } bool isPrime(ll N) { if(N<=sieve_size) return bs[N]; int s = primes.size(); for(int i=0; i<s; i++){ if(N%primes[i]==0) return false; } return true; }// note: only work for N <= (last prime in vi "primes")^2 int main() { sieve(); printf("%d\n", isPrime(2147483647)); // 10-digits prime printf("%d\n", isPrime(136117223861LL)); } <file_sep>#include <stdio.h> typedef long long LL; LL Big_Mod(LL base, LL power, LL mod); int main() { LL base, power, mod; printf("Enter Base, Power & the number to Mod:\n"); scanf("%lld %lld %lld", &base, &power, &mod); printf("The result of %lld^%lld %% %lld = %lld\n",base, power, mod, Big_Mod(base, power, mod)); } LL Big_Mod(LL base, LL power, LL mod) { LL r = 1; while(power!=0){ if(power%2!=0) r = (r*base)%mod; base = (base*base)% mod; power/=2; } return r; } /* lets look at the whole example: (3%7) = 3 (Base case, Lowest level of the tree) (3^2)%7 = ( (3%7) * (3%7) ) % 7 = 9 % 7 = 2 here base*base = 9%7=2 = new base; (3^4)%7 = ( ((3^2)%7) * ((3^2)%7) ) %7 = ( 2 * 2)%7 = 4%7 = 4 (3^5)%7 = ( ((3^4)%7) * 3%7)%7 = (4*3)%7 = 12 % 7 = 5. The answer is 5. */ <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 #define mx 200 typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; vector<int> adj[mx]; int dst[mx]; int BFS(int st, int en){ queue<int> Q; int i, j, a; for(i=0; i<mx; i++) dst[i]=INF; Q.push(st); dst[st] = 0; while(!Q.empty()){ int u = Q.front(); Q.pop(); int l = adj[u].size(); for(i=0; i<l; i++){ int v = adj[u][i]; if(dst[v]==INF){ dst[v] = 1 - dst[u]; Q.push(v); } else if(dst[u]==dst[v]) return false; } } return true; } int main(){ int n, a, b, l, i; while(scanf("%d", &n) && n){ scanf("%d", &l); for(i=0; i<n; i++) adj[i].clear(); for(i=0; i<l; i++){ cin>>a>>b; adj[a].pb(b); adj[b].pb(a); } if(BFS(a,b)) cout<<"BICOLORABLE."<<endl; else cout<<"NOT BICOLORABLE."<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)100 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int n, cnt; int vis[MAX][MAX], moves[MAX][MAX], cell[MAX][MAX]; inline bool valid(int &row, int &col){ return (row>=1 && row<=n && col>=1 && col<=n); } inline bool check(int &a, int &b){ if(cell[a+1][b-1] && cell[a+1][b] && cell[a+1][b+1] && cell[a+2][b]){ cell[a+1][b-1] = 0; cell[a+1][b] = 0; cell[a+1][b+1] = 0; cell[a+2][b] = 0; cnt += 4; return true; } else return false; } int Bfs(int x, int y){ if(valid(x, y) && check(x, y)) return true; else return false; } int main() { IOS; int m, i, j; memset(cell, 0, sizeof(cell)); cin>>n; string s; int one = 0; for(i=0; i<n; i++){ cin>>s; for(j=0; j<n; j++){ if(s[j]=='.') { cell[i+1][j+1] = 1; one ++; } } } cnt = 0; for(i=1; i<=n; i++){ for(j=1; j<=n; j++){ if(cell[i][j]==1){ cnt++; cell[i][j] = 0; bool flag = Bfs(i, j); if(flag==false){cnt = -1; break;} } } } if(cnt==one) cout<<"YES"<<endl; else cout<<"NO"<<endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back map<string, vector<string> > adj; vector<string> vs; map<string, int> vis; int BFS(string st, string en){ queue<string> Q; Q.push(st); vis[st] = 0; while(!Q.empty()){ string u = Q.front(); Q.pop(); if(u==en) break; int l = adj[u].size(); for(int i=0; i<l; i++){ if(vis[adj[u][i]]==0){ vis[adj[u][i]] = vis[u] + 1; Q.push(adj[u][i]); } } } return vis[en]; } bool is(string a, string b){ int l1 = a.size(); int l2 = b.size(); int cnt=0; if(l1==l2){ for(int i=0; i<l1; i++){ if(a[i]!=b[i]) ++cnt; } if(cnt==1) return true; } return false; } int main() { int n, flag=0; string s, t; cin>>n; while(n--){ while(cin>>s, s!="*"){ int l = vs.size(); for(int i=0; i<l; i++){ if(is(vs[i], s)){ adj[vs[i]].pb(s); adj[s].pb(vs[i]); } } vs.pb(s); } cin.ignore(); string line; if(flag) cout<<endl; flag = 1; while (getline(cin, line) && line != ""){ stringstream ss(line); ss >> s >> t; int steps = BFS(s, t); cout<<s<<" "<<t<<" "<<steps<<endl; vis.clear(); } adj.clear(); } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; typedef long long ll; #define Max 200005 int A[Max], B[Max], BIT[Max], n; void update(int x, int val) //Adding value in index x { for(; x <=n; x += x&-x){ BIT[x] += val; } } ll query(int x){ ll sum = 0; for(; x>0; x -= x&-x) sum += BIT[x]; return sum; } int main() { int t, i; cin>>t; while(t--){ memset(BIT, 0, sizeof(BIT)); cin>>n; for(i=0; i<n; i++){ cin>>A[i]; B[i] = A[i]; // B is the copy of array A } sort(B, B+n); //sort array B for(i=0; i<n; i++){ int pos = (int)(lower_bound(B, B+n, A[i]) - B); A[i] = pos + 1; //Replace the value of A using its index in the sorted array B } ll inv_count = 0; for(int i=n-1; i>=0; --i){ ll freq = query(A[i]); inv_count += freq; update(A[i], 1); } cout<<inv_count<<endl; } } <file_sep>#include<bits/stdc++.h> using namespace std; int lcs( string X, string Y, int m, int n ) { if (m == 0 || n == 0) return 0; if ( (X[m] == Y[n]) && (m>0&&n>0) ) return 1 + lcs(X, Y, m-1, n-1); else return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); } int main() { string X,Y; cin>>X>>Y; int m = X.size(); int n = Y.size(); cout<<endl<<"Length of LCS is = "<<lcs( X, Y, m, n )<<endl; return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int n, i, j; int arr[MAX]; cin>>n; for(i=0; i<n; i++) cin>>arr[i]; sort(arr, arr+n); j = 0; int Max = 1; for(i=1; i<n; i++){ if(arr[i]-arr[j]<=5){ Max = max(Max, i-j+1); } else{ while(arr[i]-arr[j]>5) ++j; Max = max(Max, i-j+1); } } cout<<Max<<endl; return 0; } <file_sep>/// Time Complexity: O(nlogn) #include <bits/stdc++.h> using namespace std; void Merge(int arr[],int left,int mid,int right) { int i = left, j = mid+1, k = left; int temp[right]; while((i <= mid) and (j <= right)){ if(arr[i] <= arr[j]) temp[k++] = arr[i++]; else temp[k++] = arr[j++]; } while(i <= mid) temp[k++] = arr[i++]; while(j <= right) temp[k++] = arr[j++]; for(i=left; i<=right; i++) arr[i] = temp[i]; } void MergeSort(int arr[],int left,int right) { int mid; if(right > left){ mid = left + (right-left)/2; MergeSort(arr,left,mid); MergeSort(arr,mid+1,right); Merge(arr,left,mid,right); } } int main() { int n; scanf("%d",&n); int arr[n]; for(int i=0; i<n; i++) scanf("%d",arr+i); MergeSort(arr,0,n-1); for(int i=0; i<n; i++) printf("%d ",arr[i]); return 0; } <file_sep>//complexity O(nlogn) & @(1) space complexity #include<bits/stdc++.h> using namespace std; int n; void SIFT_DOWN(int arr[],int i,int nn) { bool done = false; if(2*i>nn) return ; do{ i = 2*i; if(i+1 <= nn && arr[i+1] > arr[i]) i++; if(arr[i/2] < arr[i]) swap(arr[i], arr[i/2]); else done = true; }while(2*i < nn && done == false); } void MAKEHEAP(int arr[]) { for(int i=n/2; i>=1; i--) SIFT_DOWN(arr, i, n); } void HEAPSORT(int arr[]){ MAKEHEAP(arr); for(int j=n; j>=2; j--){ swap(arr[j], arr[1]); SIFT_DOWN(arr, 1, j-1); } } int main() { scanf("%d",&n); int arr[n+1]; for(int i=1; i<=n; i++) scanf("%d",arr+i); HEAPSORT(arr); for(int i=1; i<=n; i++) printf("%d ",arr[i]); return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 #define mx 10010 typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; vector<int> adj[mx]; int dst[mx]; int BFS(int st, int tt){ queue<int> Q; int i, j, a; for(i=0; i<mx; i++) dst[i]=INF; Q.push(st); dst[st] = 0; int total = 0; while(!Q.empty()){ int u = Q.front(); Q.pop(); int l = adj[u].size(); for(i=0; i<l; i++){ int v = adj[u][i]; if(dst[v]==INF){ dst[v] = dst[u]+1; Q.push(v); if(dst[v]<=tt) ++total; } } } return total; } int main(){ int t=1, n, a, b, q, i; set<int> s; while(cin>>n && n){ for(i=0; i<mx; i++) adj[i].clear(); for(i=0; i<n; i++){ cin>>a>>b; s.insert(a); s.insert(b); adj[a].pb(b); adj[b].pb(a); } while(scanf("%d %d", &a, &b)){ if(a==0 && b==0) break; if(b==0) q = s.size() - 1; else { q = BFS(a, b); q = (s.size() - q - 1); } printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n", t++, q, a, b); } s.clear(); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; #define MAX (int)1e5+7 int A[MAX], tree[MAX*4]; void build(int node, int start, int en) { if (start == en) { // Leaf node will have a single element tree[node] = A[start]; } else { int mid = (start + en) / 2; // Recurse on the left child build(2 * node, start, mid); // Recurse on the right child build(2 * node + 1, mid + 1, en); // Internal node will have the sum of both of its children tree[node] = tree[2 * node] + tree[2 * node + 1]; } } void update(int node, int start, int en, int idx, int val) { if (start == en) { // Leaf node A[idx] += val; tree[node] += val; } else { int mid = (start + en) / 2; if (start <= idx and idx <= mid) { // If idx is in the left child, recurse on the left child else right update(2 * node, start, mid, idx, val); } else { update(2 * node + 1, mid + 1, en, idx, val); } // Internal node will have the sum of both of its children tree[node] = tree[2 * node] + tree[2 * node + 1]; } } int query(int node, int start, int en, int l, int r) { if (r < start or en < l) { // range represented by a node is completely outside the given range return 0; } if (l <= start and en <= r) { // range represented by a node is completely inside the given range return tree[node]; } // range represented by a node is partially inside and partially outside the given range int mid = (start + en) / 2; int p1 = query(2 * node, start, mid, l, r); int p2 = query(2 * node + 1, mid + 1, en, l, r); return (p1 + p2); } int main() { int newer[] = {18, 17, 13, 19, 15, 11, 20}; A[0] = 0; copy(newer, newer+7, A); int n = sizeof(newer)/sizeof(newer[0]); // the original array build(1, 1, n); printf(" idx 0, 1, 2, 3, 4, 5, 6\n"); printf(" A is {18,17,13,19,15, 11,20}\n"); printf("RMQ(1, 3) = %d\n", query(1, 1, n, 1, 3)); // answer = index 2 // printf("RMQ(4, 6) = %d\n", st.rmq(4, 6)); // answer = index 5 // printf("RMQ(3, 4) = %d\n", st.rmq(3, 4)); // answer = index 4 // printf("RMQ(0, 0) = %d\n", st.rmq(0, 0)); // answer = index 0 // printf("RMQ(0, 1) = %d\n", st.rmq(0, 1)); // answer = index 1 // printf("RMQ(0, 6) = %d\n", st.rmq(0, 6)); // answer = index 5 } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; LL n, k, t, a, b, cnt; cin>>n; for(t=1; t<=n; t++){ cin>>a>>b; if(a<0 && b<0){ } k = b/3LL; cnt = 0LL; if(k>=a && k>0LL){ do{ ++cnt; cnt += (b - k*3LL); b/=3LL; k = b/3LL; }while(k>=a && k>0LL); cnt += (b - a); } else{ cnt = abs(b - a); } cout<<"Case "<<t<<": "<<cnt<<endl; } return 0; } <file_sep>//complexity between (n-1) and n(n-1)/2 #include<bits/stdc++.h> using namespace std; int main() { int n,k,x,j; cin>>n; int count_comparison = 0; int ara[n+1]; for(int i=1;i<=n;i++) cin>>ara[i]; for(int i=2;i<=n;i++){ x = ara[i]; j = i-1; while(j>0 && ara[j]>x){ ara[j+1] = ara[j]; j = j-1; } ara[j+1]= x; } for(int i=1;i<=n;i++) cout<<ara[i]<<" "; cout<<endl; } <file_sep>#include<bits/stdc++.h> using namespace std; vector< pair<int,int> > v; int n; int lo, hi, mid, ans, save=-1; int can(int rating){ for(int i=0; i<n; i++){ if(v[i].second==1 && rating<1900){ lo = mid+1; return 0;} else if(v[i].second==2 && rating>1899){hi = mid-1; return 0;} rating += v[i].first; } return rating; } int main() { cin>>n; int flag = 0, c, d, i; for(i=0; i<n; i++){ cin>>c>>d; v.push_back(make_pair(c,d)); if(d==2) flag = 1; } if(flag== 0) cout<<"Infinity"<<endl; else{ if(v[0].second==1) { lo = 1900; hi = 2e8; } else{ lo = -2e8; hi = 1899;} while(lo<=hi){ mid = (lo+hi)/2; ans = can(mid); if(ans){ save = ans; lo = mid+1; } } if(save==-1) cout<<"Impossible"<<endl; else cout<<save<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int n; vector< pair<string, int> > v; string binary; while(cin>>n){ binary = bitset<32>(n).to_string(); //to binary cout<<n<<" "<<binary<<endl; } unsigned long decimal = bitset<32>(binary).to_ulong(); cout<<decimal<<"\n"; return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int n,m, r, i, j, a; cin>>n>>m>>r; int Min = 2000, Sell = 0; for(i=0; i<n; i++){ cin>>a; Min = min(Min, a); } for(i=0; i<m; i++){ cin>>a; Sell = max(Sell, a); } int d = r/Min; int R = r - (d*Min); int Max = R + (Sell*d); if(Max>r) cout<<Max<<endl; else cout<<r<<endl; } <file_sep>/* Sift the Twos and sift the Threes, The Sieve of Eratosthenes. When the multiples sublime, The numbers that remain are Prime! */ //Sieve of Eratosthenes #include <stdio.h> #include <math.h> #include <string.h> #define Max 1000001 char primes[Max]; void sieve() { int i, j, x; memset(primes, 0, sizeof(primes)); primes[0] = primes[1] = 1; for(i=4; i<Max; i+=2) primes[i] = 1; x = sqrt(Max); for(i=3; i<=x; i+=2){ if(primes[i]==0){ for(j=i*i; j<Max; j+=i){ primes[j] = 1; } } } } int main() { sieve(); int i, n; printf("Enter the number range to generate primes(<1,000,001): "); scanf("%d", &n); for(i=0; i<=n; i++){ if(primes[i]==0){ printf("%d ", i); } } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back using namespace std; typedef long long LL; int main() { IOS; long long t, n, a, i, j; cin>>t; while(t--){ cin>>n; LL ans = 0; LL one[35] = {0}, zero[35] = {0}; vector<LL> v; for(i=0; i<n; i++){ cin>>a; v.pb(a); for(j=0; j<=30; j++){ if(a&(1<<j)){ one[j]++; } else zero[j]++; } } for(j=0; j<=30; j++){ if(one[j]>=zero[j]) ans |= (1<<j); } LL sum = 0; for(i=0; i<n; i++){ sum += (v[i]^ans); } cout<<sum<<endl; } return 0; } <file_sep>#include <stdio.h> #define Array_size 5000 //5000 is enough to calculate factorial upto 1500! //Increase the size if needed further int main() { int a[Array_size]; int N, x, temp, i, j, m; while(scanf("%d", &N)!=EOF){ a[0] = 1; m = 1; //Initializes digits Counter temp = 0; for(i=1; i<=N; i++){ for(j=0; j<m; j++){ x = a[j]*i + temp; a[j] = x%10; //storing the last digit from the product x temp = x/10; //contains the carry value } while(temp){ a[m++] = temp%10; //Here we store the digits in array from temp temp/=10; //See, only the temp portion increments the number of digits m } } printf("%d!= ", N); for(j=m-1; j>=0; j--) printf("%d", a[j]); printf("\n"); } return 0; } <file_sep># My Algorithms **The repository contains implementation of some algorithms in C/C++ that I have learned.** <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define mx 100 typedef long long ll; typedef pair<int,int> ii; vector<int> adj[mx]; bitset<mx> vis, record[mx], yup; int n, flag, x; void dfs(int u){ vis[u] = 1; int l = adj[u].size(); record[0][u] = 1; yup[u] = 1; for(int i=0; i<l; i++){ int v = adj[u][i]; if(vis[v]==0){ dfs(v); } } } void dfs2(int u, int p){ vis[u] = 1; int l = adj[u].size(); if(u==p) l = 0; else record[p][u] = 1; for(int i=0; i<l; i++){ int v = adj[u][i]; if(vis[v]==0){ dfs2(v, p); } } } void print(int k){ putchar('+'); for(int j=0; j<x; j++){ putchar('-'); } printf("+\n"); putchar('|'); for(int j=0; j<n; j++){ if(record[k][j]==flag && yup[j]==1) printf("Y|"); else printf("N|"); } putchar('\n'); record[k].reset(); vis.reset(); } int main() { int T, i, j, m; cin>>T; for(int t=1; t<=T; t++){ cin>>n; for(i=0; i<n; i++) adj[i].clear(); for(i=0; i<n; i++){ for(j=0; j<n; j++){ scanf("%d", &m); if(m==1) adj[i].pb(j); } } flag = 1; x = n*2 - 1; printf("Case %d:\n", t); dfs(0); print(0); flag = 0; for(i=1; i<n; i++){ dfs2(0, i); print(i); } putchar('+'); for(int j=0; j<x; j++){ putchar('-'); } printf("+\n"); yup.reset(); } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int price[25][25]; int M, C; int memo[210][25]; int shop(int money, int g){ if(money<0) return -100000000; if(g==C) return M - money; if(memo[money][g] != -1) { // cout<<"g = "<<g<<" money= "<<money<<endl; return memo[money][g]; } int ans = -1; for(int model=1; model<=price[g][0]; model++){ ans = max(ans, shop(money-price[g][model], g+1)); } return memo[money][g]=ans; } int main() { IOS; int i, j, T, score; cin>>T; while(T--){ cin>>M>>C; for(i=0; i<C; i++){ cin>>price[i][0]; for(j=1; j<=price[i][0]; j++) cin>>price[i][j]; } memset(memo, -1, sizeof(memo)); score = shop(M, 0); if(score<0) cout<<"no solution"<<endl; else cout<<score<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int i, j, k; cin>>n; pi arr[n]; for(i=0; i<n; i++) { cin>>arr[i].first; arr[i].second = i; } sort(arr, arr+n); i = 0; j = n-1; int Max = 0; while(i<j){ d = min(arr[j].first, arr[i].first)/abs(arr[i].second - arr[j].second); Max = max(d, Max); if(arr[i].first>arr[j].first) i++; else --j; } } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; LL i, n; vector<LL> factors; cout<<"Enter a number: "; //main function while(cin>>n){ for(i=2; i<=n; i++){ if(i*i>n) i = n; while(n%i==0){ n/=i; factors.pb(i); //recording in vector } } cout<<"Prime factors of the number is: "<<endl; for(auto p: factors) cout<<p<<" "; cout<<endl; factors.clear(); cout<<"Enter a number: "; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 #define mx 2000 typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; vector<int> adj[mx]; int dst[mx]; vector<int> v; bool BFS(int st, int en){ queue<int> Q; int i, j; int path[mx]={-1}; for(i=1; i<mx; i++) dst[i]=INF; Q.push(st); dst[st] = 0; while(!Q.empty()){ int u = Q.front(); Q.pop(); int l = adj[u].size(); for(i=0; i<l; i++){ int v = adj[u][i]; if(dst[v]==INF){ dst[v] = dst[u] + 1; path[v] = u; Q.push(v); } } } if(dst[en]==INF) return false; else{ int now = en; v.pb(now); while(now!=st){ now = path[now]; if(now<0) return false; v.pb(now); } return true; } } int main() { int n, i; bool line = false; string fm, to; map<string, int> mp; map<int, string> my; while(scanf("%d", &n)!=EOF){ int index = 0; for(i=0; i<mx; i++) adj[i].clear(); for(i=0; i<n; i++){ cin>>fm>>to; if(mp.find(fm)==mp.end()){ mp[fm]=++index; my[index] = fm; } if(mp.find(to)==mp.end()){ mp[to]=++index; my[index] = to; } adj[mp[fm]].pb(mp[to]); adj[mp[to]].pb(mp[fm]); } cin>>fm>>to; if(line) printf("\n"); if(mp.find(fm)==mp.end() || mp.find(to)==mp.end()) cout<<"No route"<<endl; else{ int st = mp[fm]; int en = mp[to]; if(BFS(st, en)){ int s = v.size(); for(i=s-1; i>0; i--){ cout<<my[v[i]]<<" "<<my[v[i-1]]<<endl; } } else cout<<"No route"<<endl; } line = true; v.clear(); mp.clear(); my.clear(); } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; #define Max 1000001 //Sieve maximum size is 10^6 in bitset<Max> isPrime; vi prime; void sieve() { int i, j, x; isPrime.reset(); isPrime[0] = isPrime[1] = 1; //Non prime numbers will be set to 1 for(i=4; i<Max; i+=2 ) isPrime[i] = 1; prime.push_back(2); for(i=3; i*i<Max; i+=2){ if(isPrime[i]==0){ prime.push_back(i); for(j=i*i; j<Max; j+=i){ //if i==prime then i+i !=prime isPrime[j] = 1; } } } } //Prime factors Generation of a given number N vi factorization(int N){ vi factors; int id = 0, PF = prime[id]; while(PF*PF <= N){ while(N % PF == 0){ N/=PF; factors.push_back(PF); } PF = prime[++id]; } if(N!=1) factors.push_back(N); //at this point, if N is not 1 then N itself is a prime factor return factors; } int main() { sieve(); int i, len = prime.size(); printf("Total Prime Number founds in range(1 - %d) is: %d\n", Max, len); for(i=0; i<len; i++){ printf("%d ", prime[i]); } cout<<endl; //Prime Factorization printf("Prime Factor Test\n Enter a number: "); scanf("%d", &i); vi factors = factorization(i); for(auto i=factors.begin(); i!=factors.end(); i++) printf("%d ", *i); } <file_sep>#include <stdio.h> int main() { int arr[100]; int i, j, N, swap; printf("Enter the number of Elements: "); scanf("%d", &N); printf("\nInput the elements need to sort: "); for(i=0; i<N; i++) scanf("%d", &arr[i]); for(i=0; i<N-2; i++){ for(j=N-1; j>=i; j--){ if(arr[j]<arr[i]){ swap = arr[i]; arr[i] = arr[j]; arr[j] = swap; } } } printf("Ascending order after sorting: "); for(i=0; i<N; i++) printf("%d ", arr[i]); printf("\n"); return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define all(x) x.begin(), x.end() #define rsort(x) x.begin(), x.end(), greater<int>() using namespace std; const double pi = acos(-1.0); const double EPS = 1e-6; const int MOD = (int)1e9+7; int main() { vector<int> v = {1, 2, 3, 4, 5}; cout<<"\nPrint Using iterator"<<endl; for(vector< int >::iterator it = v.begin(); it != v.end(); it++) cout<<*it<<" "; cout<<"\nUsing auto iterator"<<endl; for(auto it: v) cout<<it<<" "; cout<<"\nSorting usring macro"<<endl; sort(all(v)); for(auto it: v) cout<<it+1<<" "; cout<<"\nReverse sorting using macro"<<endl; sort(rsort(v)); for(auto it: v) cout<<it<<" "; cout<<endl; map<string, int> mymap{{"Santho", 48}, {"Shawon", 25}, {"Shuvo", 32}, {"Akid", 33}}; cout<<"Map store the elements in the sorted order of keys: "<<endl; for(auto it: mymap) { cout<<it.first<<endl; } cout<<endl; for(auto it=mymap.begin(); it!=mymap.end(); it++){ cout<<(*it).second<<endl; } } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ll long long //priority_queue <int, vector<int>, greater<int> > pq; //min heap using namespace std; int main() { IOS int x,n,y,ans=0; cin>>n>>x>>y; string str; cin>>str; bool flg=false; int kep=n-y-1; if(str[n-y-1]=='0') { ans++; str[n-y-1]='1'; flg=true; } n--; for(int i=1;i<=x;i++) { if(kep==n) { n--; continue; } if(str[n]=='1') ans++; n--; } cout<<ans<<endl; } <file_sep> #include <bits/stdc++.h> using namespace std; void build(int node, int start, int en){ if (start == en) tree[node] = A[start]; else { int mid = (start + en) / 2; build(2 * node, start, mid); build(2 * node + 1, mid + 1, en); tree[node] = tree[2 * node] + tree[2 * node + 1]; } } void update(int node, int start, int en, int idx, int val){ if (start == en) { // Leaf node A[idx] += val; tree[node] += val; } else { int mid = (start + en) / 2; if (start <= idx and idx <= mid){ update(2 * node, start, mid, idx, val); } else { update(2 * node + 1, mid + 1, en, idx, val); } tree[node] = tree[2 * node] + tree[2 * node + 1]; } } int query(int node, int start, int en, int l, int r) { if (r < start or en < l) { // range represented by a node is completely outside the given range return 0; } if (l <= start and en <= r) { // range represented by a node is completely inside the given range return tree[node]; } // range represented by a node is partially inside and partially outside the given range int mid = (start + en) / 2; int p1 = query(2 * node, start, mid, l, r); int p2 = query(2 * node + 1, mid + 1, en, l, r); return (p1 + p2); } int main() { } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e6+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int T, n, i, j, cnt, ans; cin>>T; while(T--){ cin>>n; vector<int> v(n), fq(MAX, 0); int Max = 0; for(i=0; i<n; i++){ cin>>v[i]; Max = max(Max, v[i]); fq[v[i]]++; } ans = 0; for(i=Max; i>=1; i--){ cnt = 0; j = i; for(j=i; j<=Max; j+=i){ if(fq[j]>0) cnt+=fq[j]; } if(cnt>1) { ans=i; break;} } cout<<ans<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define EPS 1e-9 int main() { cout<<EPS<<endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define Mx 10000 #define UNVISITED 0 #define VISITED 1 #define EXPLORED 2 typedef vector<int> vi; vi vis, parent, adj[Mx]; void graphCheck(int u){ vis[u] = EXPLORED; for(int i=0; i<(int)adj[u].size(); i++){ int v = adj[u][i]; if(vis[v]==UNVISITED){ parent[v] = u; graphCheck(v); } else if(vis[v]==EXPLORED){ if(v==parent[u]) printf("Two ways (%d, %d)-(%d, %d)\n", u, v, v, u); else printf(" Back edge (%d, %d) (cycle)\n", u, v); } else if(vis[v]==VISITED) printf(" Forward/Cross Edge (%d, %d)\n", u, v); } vis[u] = VISITED; cout<<"visited hoise"<<u<<endl; } int main() { int i, j,E, a, b, V; cin>>V>>E; //V is number of nodes & E is number of edges vis.assign(V, UNVISITED); parent.assign(V, 0); for(i=0; i<E; i++){ cin>>a>>b; adj[a].pb(b); adj[b].pb(a); } int index = 0; for(i=0; i<V; i++){ if(vis[i]== UNVISITED) printf("Component %d:\n", ++index), graphCheck(i); } } <file_sep> #include<bits/stdc++.h> using namespace std; #define Max 100005 int BIT[Max], A[Max], n; void update(int x, int val) //Adding value in index x { for(; x <=n; x += x&-x){ BIT[x] += val; } } int query(int x) { int sum = 0; for(; x>0; x -= x&-x) sum += BIT[x]; return sum; } //Bit Algo finishes here int main() { int T, t, q, i, j, v; scanf("%d", &T); for(t=1; t<=T; t++){ scanf("%d %d", &n, &q); for(i=1; i<=n; i++){ scanf("%d", &A[i]); update(i, A[i]); } printf("Case %d:\n", t); while(q--){ int type; scanf("%d", &type); switch(type){ case 1: scanf("%d", &i); ++i; printf("%d\n", A[i]); update(i, -A[i]); A[i] = 0; break; case 2: scanf("%d %d", &i, &v); ++i; update(i, v); A[i] += v; break; case 3: scanf("%d %d", &i, &j); ++i; ++j; printf("%d\n", query(j) - query(i-1)); break; } } memset(BIT, 0, sizeof(BIT)); memset(A, 0, sizeof(A));; } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; LL n, i, j, k, a, b; cin>>n>>k; vector<pill> v; for(i=0; i<n; i++){ cin>>a>>b; v.pb({b, a}); } sort(rall(v)); multiset<LL> s; LL Max = 0, pl = 0; for(i=0; i<n; i++){ pl += v[i].second; if(s.size()>k-1){ auto it = s.begin(); pl -= (*it); s.erase(it); } s.insert(v[i].second); Max = max(Max, pl*v[i].first); } cout<<Max<<endl; } <file_sep>#include<iostream> #include<bits/stdc++.h> using namespace std; /* V[]->adjacency matrix for storing graph indegree[] -> array for storing dependancies of vertices ans ->vector to store result visited ->to keep track of vertices entered in the ans Also One may point out that why are we decreasing indegree of all the adjacent vertice to u simulateneously ans then calling Recursion??? Answer is we are removing the dependency of all the vertices on current vertex.. That's It!!!! */ void allTopo(vector<int>V[],int indegree[],int n,vector<int>&ans,bool visited[]) { if(ans.size()==n) { for(int i=0;i<ans.size();i++) cout<<ans[i]<<" "; cout<<endl; return; } for(int i=0;i<n;i++) if(indegree[i]==0 && visited[i]==false) { visited[i]=true; ans.push_back(i); for(int k=0;k<V[i].size();k++) indegree[V[i][k]]--; allTopo(V,indegree,n,ans,visited); for(int k=0;k<V[i].size();k++) indegree[V[i][k]]++; visited[i]=false; ans.pop_back(); } return; } int main(void) { int n; cin>>n; vector<int>V[n+6]; int e; int x,y; int indegree[n]={}; cin>>e; for(int i=0;i<e;i++) { cin>>x>>y; V[x].push_back(y); indegree[y]++; } vector<int>ans; bool visited[n]={}; allTopo(V,indegree,n,ans,visited); return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define mx 200 vector<int> adj[mx]; bitset<mx> vis; int cnt; int dfs(int u){ vis[u] = 1; int l = adj[u].size(); for(int i=0; i<l; i++){ int v = adj[u][i]; if(vis[v]==0){ dfs(v); ++cnt; } } return cnt; } int main() { int n, i; char ch; bool flag = false; cin>>n; while(n--){ if(flag) cout<<endl; cin>>ch; for(i=65; i<97; i++) adj[i].clear(); string s; cin.ignore(); while(getline(cin, s) && s!=""){ if(s[0]!=s[1]){ adj[s[0]].pb(s[1]); adj[s[1]].pb(s[0]); } } int sub = 0; for(i=65; i<=ch; i++){ cnt = 0; if(adj[i].size()==0) ++sub; else{ int r = dfs(i); if(r>0) ++sub; } } printf("%d\n", sub); vis.reset(); flag = true; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define EPS 1e-9 vector< pair<int, string> > events; vector<double> liter; bool can(double f){ int s = events.size(); int j = 0; double rate=0.0, leak=0.0, dis=0.0, flag=0; double cap = f; for(int i=0; i<s; i++){ int index = events[i].first; string s = events[i].second; dis = index - flag; cap = cap - (dis*rate) - (leak*dis); flag = index; if(cap<0.0) return false; if(s=="Fuel"){ rate = liter[j]/100.00; j++; } else if(s=="Leak") leak+=1.0; else if(s=="Mechanic") leak = 0.0; else if(s=="Gas") cap = f; } if(cap>=0.0) return true; else return false; } int main() { string s; int d; double t; while(1){ cin>>d>>s; events.push_back(make_pair(d, s)); if(s=="Fuel"){ cin>>s>>t; if(d==0 && t==0.0) return 0;; liter.push_back(t); } else if(s=="Gas") cin>>s; else if(s=="Goal"){ double lo=0.0, hi=10000.0, mid = 0.0, ans = 0.0; while(fabs(hi-lo)>EPS){ mid = (lo+hi)/2.0; if(can(mid)){ ans = mid; hi = mid; } else lo = mid; } printf("%.3lf\n", ans); events.clear(); liter.clear(); } } } <file_sep>// * Prime Factorilization of a number // This program finds all prime factors of a ginven numbets #include <stdio.h> #include <string.h> int prime[100]; void prime_factor(int n, int arr[]) { int i, j=0; // find the number of 2's that divide n while(n%2==0){ arr[j++] = 2; n/=2; } // n must be odd at this point, so we can skip even i's(i+=2) for(i=3; i<=sqrt(n); i+=2){ while(n%i==0){ arr[j++] = i; n/=i; } } // at this point if n is greater than 2, than n itself is a prime number if(n>2) arr[j++] = n; for(i=0; i<j; i++) printf("%d ", arr[i]); } int main() { int n; char ch; do{ printf("Enter the number: "); scanf("%d", &n); printf("Prime factors of %d is: \n", n); prime_factor(n, prime); getchar(); printf("\nDo you wish to continue?(y/n): "); ch = getche(); printf("\n"); }while(ch=='y'); return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int BinarySearch(int arr [100], int lo, int hi, int x) { while(lo<=hi){ int mid = lo + (hi-lo)/2; if(arr[mid]==x) return mid; else if(arr[mid]<x) lo = mid+1; else hi = mid-1; } return -1; } int main() { int arr[10] = {11, 12, 13, 14, 15, 15, 17, 18, 19, 20}; int lo = 0, hi = (sizeof(arr)/sizeof(arr[0])) - 1; cout<<BinarySearch(arr, lo, hi, 15)<<endl; int i = lower_bound(arr, arr+10, 15) - arr; int j = upper_bound(arr, arr+10, 15) - arr; cout<<i<<" "<<j<<endl; cout<<j-i<<endl; if (binary_search(arr, arr+10, 15)) cout<<"found"<<endl; else cout<<"Not found"<<endl; int r = lower_bound(arr, arr+10, 15) - arr; //print 4 cout<<r<<endl; r = lower_bound(arr, arr+10, 25) - arr; //print 10 cout<<r<<endl; int p = upper_bound(arr, arr+10, 20) - arr; // print 6 : “position of next higher number than num” cout<<p<<endl; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e3+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int lcs[MAX][MAX]; //array dimension should be n*m string ans, a, b; void printlcs(int i, int j){ if(i==0 || j==0) ans=""; else if(a[i]==b[j]) { printlcs(i-1, j-1); //recurse to diagonal ans+=a[i]; //add result after recursion } else if(lcs[i][j]==lcs[i-1][j]) printlcs(i-1, j); else printlcs(i, j-1); } int LCS(string &a, string &b){ int n = a.length(); int m = b.length(); for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(i==0 || j == 0) lcs[i][j] = 0; else if(a[i]==b[j]) lcs[i][j] = 1 + lcs[i-1][j-1]; else lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1]); } } return lcs[n-1][m-1]; } int main() { IOS; /* a = AGGTAB b = GXTXAYB */ cin>>a>>b; a = "#"+a; //added extra character to make 0 based indexing b = "."+b; int Max_lcs = LCS(a, b); cout<<Max_lcs<<endl; int n = a.length(); int m = b.length(); printlcs(n, m); cout<<ans<<endl; //lcs table for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cout<<lcs[i][j]<<" "; } cout<<endl; } } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define mx 110 typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; bitset<mx> vis; vi adj[mx], ts; void dfs2(int u){ vis[u] = 1; int l = adj[u].size(); for(int j=0; j<l; j++){ int v = adj[u][j]; if(vis[v]==0) dfs2(v); } ts.pb(u); //this is the only change } int main() { //setting all node visiting status to 0 int n, m, i, j, a, b; while(cin>>n>>m){ ts.clear(); vis.reset(); if(n==0 && m==0) break; for(i=0; i<n; i++) adj[i].clear(); for(i=0; i<m; i++){ cin>>a>>b; adj[a].pb(b); } for(i=1; i<=n; i++){ if(vis[i]==0) dfs2(i); //calling dfs for every node } for(i=(int)ts.size() - 1; i>=0; i--){ printf("%d ", ts[i]); } printf("\n"); } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); #define pb push_back #define mkp make_pair #define All(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; bitset<8> bs(5); int result = bs.count(); //count number of on bits string s = bs.to_string(); cout<<s<<" "<<result<<endl; s = bs.to_string('X', '*'); //replace 0 and 1 with X and * cout<<s<<endl; int num = (int) bs.to_ulong(); cout<<num<<endl<<endl; bs.reset(); cout<<bs.any()<<endl; //returns true if at lest one bit is set bs = bitset<8>(255); cout<<"255 = "<<bs.to_string()<<endl; cout<<bs.all()<<endl; //returns true if all the bits are set } <file_sep>//complexity n(n-1)/2 #include<bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n; int count_comparison = 0; int ara[n+1]; for(int i=1;i<=n;i++) cin>>ara[i]; for(int i=1;i<=n-1;i++){ k = i; for(int j=i+1;j<=n;j++){ if(ara[j]<ara[k]) k = j; } if(i!=k) swap(ara[i], ara[k]); } for(int i=1;i<=n;i++) cout<<ara[i]<<" "; cout<<endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define Mx 100000 typedef vector<int> vi; vi num, low, parent, ap, adj[Mx]; int root, childs, cnt; void allAPB(int u){ num[u] = low[u] = cnt++; //iteration counter when vertex u is visited for the 1st time if(u==5) cout<<u<<" "<<num[u]<<" "<<low[u]<<endl; for(int i=0; i<(int)adj[u].size(); i++){ int v = adj[u][i]; if(num[v]==0 ){ // 0 means unvisited parent[v] = u; if(u==root) childs++; //special case if u is a root if(u==4) cout<<u<<" "<<v<<endl; allAPB(v); // if(v==5) printf("low[%d] = %d & low[%d] = %d\n", u, low[u], v, low[v]); low[u] = min(low[u], low[v]); if(low[v]>=num[u]) ap[u] = true; if(low[v]> num[u]) printf(" Edge (%d, %d) is a bridge low[%d] = %d & num[%d]=%d\n", u, v, v, low[v], u, num[u]); } else if(v != parent[u]) // a back edge not a direct cycle low[u] = min(low[u], num[v]); //low[u]<vis[u] only when there is a cycle/back edge } } int main() { int V, E, i, a, b; cin>>V>>E; //V is number of vertex from 0 and E is number of edges num.assign(V, 0); low.assign(V, 0); parent.assign(V, 0); ap.assign(V, 0); for(i=1; i<=E; i++){ //graph input cin>>a>>b; adj[a].pb(b); adj[b].pb(a); } printf("Bridges: \n"); cnt = 0; for(i=0; i<V; i++){ if(num[i]==0){ root = i; childs = 0; allAPB(i); ap[root] = (childs > 1); //a root is an ap if childs>1 } } printf("Articulation Points: \n"); for(i=0; i<V; i++){ if(ap[i]) printf(" Vertex %d\n", i); } } <file_sep>/* Problem link: https://www.hackerrank.com/contests/w34/challenges/maximum-gcd-and-sum/problem */ #include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e6+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int n, a, b, Max1=0, Max2=0, Max, i, j, ans; cin>>n; vector<int> A(n), B(n); bitset<MAX> bs1, bs2; for(i=0; i<n; i++){ cin>>A[i]; bs1[A[i]] = 1; Max1 = max(Max1, A[i]); } for(i=0; i<n; i++){ cin>>B[i]; bs2[B[i]] =1; Max2 = max(Max2, B[i]); } Max = max(Max1, Max2); for(i=Max; i>1; i--){ j = i; a = 0, b = 0; for(j=i; j<=Max; j+=i){ if(bs1[j]) a = i; if(bs2[j]) b = j; } if(a&&b) { ans = a+b; break; } } if(i==1) ans = Max1 + Max2; cout<<ans<<endl; return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define mx 200 int f(int i) { int cnt = 0; for(int j=1; j<=10; j++) ++cnt; return cnt; } int main() { for(int v=1; v<=10; v++){ cout<<f(v)<<endl; } } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { int t; char str[100]; scanf("%d",&t); getchar(); while(t--){ scanf("%[]",str); getchar(); printf("%s\n",str); // gets(str); } } <file_sep>//Implementation of EUCLID algorithm for finding GCD... // GCD(a*b) x LCM(a*b) = |a*b| #include <stdio.h> #include <math.h> int main() { int a, b, gcd, lcm; printf("Enter the two numbers: \n"); while(scanf("%d %d", &a, &b)==2){ gcd = GCD(a, b); printf("GCD of %d & %d is: %d\n", a, b, gcd); lcm = abs(a*b)/gcd; printf("LCM of %d & %d is: %d\n", a, b, lcm); } } int GCD(int a, int b) { int temp, r; if(a<b){ temp = a; a = b; b = temp; } while(a % b !=0){ temp = a%b; a = b; b = temp; } return b; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int t; cin>>t; for(int i=1; i<=t; i++){ LL A,B; cin>>A>>B; LL num,step = 0LL; if(A%3==0) num = A; else if((A+1)%3==0) num = A+1; else num = A+2; step = num - A; LL rem = B%3; if((B-1)%num==0) --B; else if((B-2)%num==0) B-=2; B/=num; LL k = 0; while(num!=B){ B/=3; ++k; } cout<<"Case "<<i<<": "<<step+k+1+rem<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int n; void SIFT_DOWN(int ara[],int i,int nn) { bool done = false; if(2*i>nn) return ; do{ i = 2*i; if(i+1<=nn && ara[i+1]>ara[i]) i++; if(ara[i/2]<ara[i]) swap(ara[i],ara[i/2]); else done = true; } while(2*i<nn && done==false); } void MAKEHEAP(int ara[]) { for(int i=n/2;i>=1;i--) SIFT_DOWN(ara,i,n); } void HEAPSORT(int ara[]) { MAKEHEAP(ara); for(int i=1;i<=n;i++) cout<<ara[i]<<" "; cout<<endl; for(int j=n;j>=2;j--){ swap(ara[j],ara[1]); SIFT_DOWN(ara,1,j-1); } } int main() { cin>>n; int ara[15]; for(int i=1;i<=n;i++) cin>>ara[i]; HEAPSORT(ara); for(int i=1;i<=n;i++) cout<<ara[i]<<" "; } <file_sep>#include<bits/stdc++.h> using namespace std; int k,ara[100],n; void Sort(int i) { if(i<n){ k = i; for(int j=i+1;j<=n;j++){ if(ara[j]<ara[k]) k = j; if(k!=i){ swap(ara[i],ara[k]); } } Sort(i+1); } } int main() { cin>>n; int count_comparison = 0; for(int i=1;i<=n;i++) cin>>ara[i]; Sort(1); for(int i=1;i<=n;i++) cout<<ara[i]<<" "; } <file_sep>/* This program Efficiently Convert a binary number into its Decimal Equivalent. Input taken as Strings */ #include <stdio.h> #include <string.h> int main() { long long int dec, i, len; char bin[100]; printf("Enter the number in Binary: \n"); scanf("%s", bin); len = strlen(bin); dec = 0; printf("Number of Binary digits: %lld\n", len); for(i=0; i<len; i++){ if(bin[i]=='1') dec = dec*2 +1; //bitweise dec = (dec<<1) + 1; else if(bin[i]=='0') dec = dec*2; //bitweise dec = dec<<1; } printf("Decimal Equivalent: %lld\n", dec); return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define maxn 100005 typedef long long ll; ll n, m, w; vector<ll> a(maxn), res(maxn); bool can(ll x, ll rest) { fill(res.begin(), res.end(), 0); for(ll i=1; i<=n; i++){ res[i]+=res[i-1]; ll need = x - a[i] - res[i]; if(need>0){ rest -= need; res[i]+=need; if(i+w<=n) res[i+w]-=need; } if(rest<0) return 0; } return 1; } int main() { cin>>n>>m>>w; for(ll i=1; i<=n; i++) scanf("%d", &a[i]); ll lo = *min_element(a.begin(), a.end()); ll hi = 1e15, ans; while(lo<=hi){ ll mid = lo + (hi-lo)/2; if(can(mid, m)){ lo = mid + 1; ans = mid; } else hi = mid - 1; } cout<<ans<<endl; return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)20 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; int vis[MAX][MAX], moves[MAX][MAX]; inline bool valid(int &row, int &col){ return (row>=1 && row<=8 && col>=1 && col<=8); } int BFS(int x, int y, int mov){ memset(vis, 0, sizeof(vis)); memset(moves, 0, sizeof(moves)); queue<pi> Q; Q.push({x, y}); vis[x][y] = 1; int visited = 1; while(!Q.empty()){ pi u = Q.front(); Q.pop(); for(int k=0; k<8; k++){ int tx = u.first + fx[k]; int ty = u.second + fy[k]; if(valid(tx,ty) && vis[tx][ty]==0){ vis[tx][ty] = 1; Q.push({tx, ty}); moves[tx][ty] = moves[u.first][u.second] + 1; if(moves[tx][ty]<=mov) visited++; } } } return visited; } int main() { IOS; int n, t, r, c, k; cin>>t; while(t--){ cin>>r>>c>>k; int ans = BFS(r, c, k); cout<<ans<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define N 200000 int main() { int ans[N] ,n,min,sub,j; char str[N+1]; scanf("%d",&n); scanf("%s",&str); min =0; for(int i=0;i<n;i++){ scanf("%d",&num); if(str[i]=='R') j= num; if(str[i]=='L' && num>j) sub = (num - j)/2; if(sub<min) min = sub; } printf("%d\n",min); } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int pos[MAX]; void print_lis(int index, int A[]){ stack<int> st; //LIFO st.push(A[index]); while(pos[index]!=-1){ index = pos[index]; st.push(A[index]); } while(!st.empty()){ cout<<st.top()<<" "; st.pop(); } cout<<endl; } int main() { IOS; int i, n, A[] = {-7, 10, 9, 2, 3, 8, 1, 2, 9, 5 , 2 , 4}; n = (sizeof(A)/sizeof(A[0])); int lis[MAX]; for(i=0; i<n; i++){ lis[i] = 1; pos[i] = -1; } //initialization int Max = 1, index; for(int i=1; i<n; i++){ for(int j=i-1; j>=0; j--){ if(A[j]<A[i] && lis[i]<lis[j]+1) { //lis[8]<lis[7] + 1 so lis[8] = 3; again lis[8] < lis[5] + 1; so lis[8] = 4 +1; lis[i] = lis[j] + 1; pos[i] = j; if(lis[i]>Max) { Max = lis[i]; index = i; } } } } cout<<"LIS = "<<Max<<endl; cout<<"Printing Sequence: "<<endl; print_lis(index, A); } <file_sep>#include<bits/stdc++.h> using namespace std; int getMostWork(vector<int> folders, int workers){ int n = folders.size(); int lo = *max_element(folders.begin(), folders.end()); int hi = accumulate(folders.begin(), folders.end(), 0); while(lo<hi){ int x = lo + (hi-lo)/2; int required=1, current_load = 0; for(int i=0; i<n; i++){ if(current_load+folders[i]<=x) current_load+=folders[i]; else{ ++required; current_load = folders[i]; } } if(required<=workers) hi = x; else lo = x+1; } return lo; } int main() { int n, m, i; vector<int> folders; cin>>n; for(i=0; i<n; i++){ cin>>m; folders.push_back(m); } cin>>m; int result = getMostWork(folders, m); cout<<result<<endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define all(c) c.begin(), c.end() typedef pair<string , int> psi; bool cmp(psi &a, psi &b){ return a.second<b.second; } int main() { map<string, int> mymap{{"Santho", 48}, {"Shawon", 25}, {"Shuvo", 32}, {"Akid", 33}}; mymap.insert({"Moshiur",53}); cout<<"Map is sorted by keys:\n"<<endl; for(auto it: mymap) cout<<it.first<<" "<<it.second<<endl; cout<<endl<<"Now we sort it using values:\n"<<endl; vector<psi> v(all(mymap)); //copy map to a vector sort(all(v), cmp); //sort vector using cmp function for(auto it: v) cout<<it.first<<" "<<it.second<<endl; return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define mx 10000 vector<int> Rank(mx), p(mx); void makeset(int n){ for(int i=0; i<n; i++) p[i] = i; Rank.assign(n, 0); } int Find(int x){ if(p[x]==x) return x; else return p[x] = Find(p[x]); } void Union(int a, int b){ int u = Find(a); int v = Find(b); if(u!=v){ if(Rank[u]>Rank[v]) p[v] = u; else{ p[u] = v; if(Rank[u]==Rank[v]) Rank[v]++; } } } int main() { makeset(mx); printf("=======Before Union======\n"); for(int i=0; i<5; i++){ printf("Find(%d) = %d\t Rank[%d] = %d\n", i, Find(i), i, Rank[i]); } Union(0,1); Union(2,3); Union(4,3); printf("=======After Union======\n"); for(int i=0; i<5; i++){ printf("Find(%d) = %d\t Rank[%d] = %d\n", i, Find(i), i, Rank[i]); } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; LL memo[MAX]; LL Fibonacci(LL n){ if (n == 1) memo[1]; else if (n == 2) memo[2]; if(memo[n] != -1) return memo[n]; return memo[n] = Fibonacci(n-1) + Fibonacci(n-2); } int main() { IOS; LL i, n; memset(memo, -1, sizeof(memo)); memo[1] = 1; memo[2] = 1; while(1){ cout<<"Number of memonacci Numbers to generate:"; cin>>n; Fibonacci(n); for(i=1; i<=n; i++){ cout<<memo[i]<<" "; } cout<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int n = 9, A[] = { 4, -5, 2, -3, 4, 4, -4, 4, -5 }; int sum = 0, ans = 0; for (int i = 0; i < n; i++) { sum += A[i]; ans = max(ans, sum); if (sum < 0) sum = 0; // we reset the running sum } printf("Max 1D Range Sum = %d\n", ans); } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)1e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; LL n, b, k, cnt, cnt2, ans, i, m; while(cin>>m>>b){ ans = (LL)1e18; for(i=2; i<=b; i++){ if(i*i>b) i = b; cnt = 0; while(b%i==0){ b/=i; cnt++; } if(cnt==0) continue; cnt2 = 0; n = m; while(n>1){ cnt2 += (n/i); n/=i; } ans = min(ans, cnt2/cnt); } cout<<ans<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 #define mx 100 typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; vector<int> adj[mx]; int path[mx], dst[mx]; int BFS(int st, int en){ queue<int> Q; int i, j; for(i=1; i<mx; i++) dst[i]=INF; Q.push(st); dst[st] = 0; while(!Q.empty()){ int u = Q.front(); Q.pop(); int l = adj[u].size(); for(i=0; i<l; i++){ int v = adj[u][i]; if(dst[v]==INF){ dst[v] = dst[u] + 1; path[v] = u; Q.push(v); } } } /*If i want to print the path of st to en: */ // int now = en; // cout<<"path: "<<now<<" "; // while(now!=st){ // now = path[now]; // cout<<now<<" "; // } // cout<<endl; return dst[en]; } int main(){ int i, j, x, f, t=1; while(scanf("%d",&x)==1){ for(i=1; i<=20; i++) adj[i].clear(); for(j=1; j<=x; j++){ scanf("%d", &f); adj[1].push_back(f); adj[f].push_back(1); } for(i=2; i<=19; i++){ scanf("%d", &x); for(j=1; j<=x; j++){ scanf("%d", &f); adj[i].push_back(f); adj[f].push_back(i); } } int n, st, en; vector<iii> result; scanf("%d", &n); for(i=1; i<=n; i++){ scanf("%d %d", &st, &en); result.push_back(make_tuple(st, en, BFS(st,en))); } printf("Test Set #%d\n", t++); for(auto &it: result){ printf("%2d to %2d: %d\n", get<0>(it), get<1>(it), get<2>(it)); } printf("\n"); result.clear(); } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; #define pb push_back #define INF 1000000000 #define mx 1005 #define valid(tx,ty) tx>=0 && tx<row && ty>=0 && ty<col typedef long long ll; typedef pair<int, int> ii; typedef tuple<int, int, int> iii; typedef vector <int> i; i a; a.push_back(2); a.push_back(3); a[1] int fx[] = {1,-1,0,0}; int fy[] = {0,0,1,-1}; int row, col; int dis[mx][mx], vis[mx][mx], cell[mx][mx]; int BFS(int x1, int y1, int x2, int y2){ memset(dis, 0, sizeof(dis)); memset(vis, 0, sizeof(vis)); queue<ii> Q; Q.push(ii(x1,y1)); vis[x1][y1] = 1; while(!Q.empty()){ ii u = Q.front(); Q.pop(); for(int k=0; k<4; k++){ int tx = u.first + fx[k]; int ty = u.second + fy[k]; if(valid(tx,ty) && cell[tx][ty]!=-1 && vis[tx][ty]==0){ vis[tx][ty] = 1; dis[tx][ty] = dis[u.first][u.second] + 1; Q.push(ii(tx,ty)); } } } return dis[x2][y2]; } int main() { int n, x, m, y, r1, c1, r2, c2; while(scanf("%d %d", &row, &col)){ if(row==0 && col==0) break; cin>>n; memset(cell, 0, sizeof(cell)); for(int i=0; i<n; i++){ scanf("%d %d", &x, &m); for(int j=0; j<m; j++){ scanf("%d", &y); cell[x][y] = -1; } } scanf("%d %d", &r1, &c1); scanf("%d %d", &r2, &c2); cout<<BFS(r1,c1,r2,c2)<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; //complete later int main() { IOS; maxSubRect = -127*100*100; // the lowest possible value for this problem for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // start coordinate for (int k = i; k < n; k++) for (int l=j;l<n;l++) { // end coord subRect = 0; // sum the items in this sub-rectangle for (int a = i; a <= k; a++) for (int b = j; b <= l; b++) subRect += A[a][b]; maxSubRect = max(maxSubRect, subRect); } // the answer is here } <file_sep>/* * Implementation of Evaluating Ackermann funtion by recursive function * Procedure : 1. if m=0 , Ackermann(m,n)=n+1 2. if m!=0 but n=0, then Ackermann (m,n)= Ackermann(m-1,1) 3. if m!=0 and n!=0 , then Ackermann(m,n) = Ackermann(m-1,Ackermann(m,n-1)) */ #include <stdio.h> int Ackerman(int m, int n); int main() { int m, n; printf("Enter the variables of ackerman functions(m & n): "); scanf("%d %d", &m, &n); printf("The value of A(%d,%d): %d\n", m, n, Ackerman(m,n)); return 0; } int Ackerman(int m, int n) { if(m==0) return n+1; else if(m && n==0) Ackerman(m-1, 1); else if(m && n) Ackerman(m-1, Ackerman(m, n-1)); } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)5e5+7 #define sieve_size 10000010 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; int n, i, j, a; cin>>n; queue<int> o, t; for(i=0; i<n; i++){ cin>>a; if(a==1) o.push(1); else t.push(2); } if(!t.empty()){ cout<<t.front()<<" "; t.pop(); } if(!o.empty()){ cout<<o.front()<<" "; o.pop(); } while(!t.empty()){ cout<<t.front()<<" "; t.pop(); } while(!o.empty()){ cout<<o.front()<<" "; o.pop(); } cout<<endl; } <file_sep>#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define mkp make_pair #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define maximum(a) *max_element(all(a)) #define minimum(a) *min_element(all(a)) #define MAX (int)2e5+7 using namespace std; typedef long long LL; typedef pair<int, int> pi; typedef pair<LL, LL> pill; int main() { IOS; LL t, n, i, j, a, m; cin>>t; while(t--){ cin>>m; vector<LL> ans; double mm = double(m); for(a=m+1; ;a++){ if((a-m)>m) break; double aa = double(a); double d = (aa*mm/(aa-mm)); double intpart; if(modf(d, &intpart) == 0.0) ans.pb(a); } cout<<ans.size()<<endl; for(auto it: ans) cout<<it<<endl; } return 0; }
0961b310518d2d5c42036587a4059c4cbed63145
[ "Markdown", "C", "C++" ]
79
C++
Santho07/My-Algorithms
e53f671c3403a583a619e1cb1be1a2ca5096b030
309c93bcf6869f6f71fac94fe3ff99ecbceba442
refs/heads/master
<file_sep> OMIT('_EndOfInclude_',_UltimateStringCLClass_) _UltimateStringCLClass_ EQUATE(1) ! Generic string handling class definition. !***************************************************************************************************************** !Copyright (C) 2007-2011 <NAME>, <EMAIL> !This software is provided 'as-is', without any express or implied warranty. In no event will the authors !be held liable for any damages arising from the use of this software. !Permission is granted to anyone to use this software for any purpose, !including commercial applications, subject to the following restrictions: !1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. ! If you use this software in a product, an acknowledgment in the product documentation would be appreciated ! but is not required. !2. You may not use this software in a commerical product whose primary purpose is string manipluation. !3. This notice may not be removed or altered from any source distribution. !***************************************************************************************************************** SplitStringQType Queue,TYPE Line &STRING SortValue STRING(50) END UltimateStringCL CLASS,TYPE,MODULE('UltimateStringCL.CLW'),LINK('UltimateStringCL.CLW') ! ,_RSMCLASSESLINKMode_),DLL(_RSMCLASSESDllMode_) Value &STRING,PRIVATE Lines &SplitStringQType,PRIVATE !Public Methods Append PROCEDURE(STRING pNewValue) Assign PROCEDURE(STRING pNewValue) Contains PROCEDURE(STRING pTestValue, LONG pNoCase=0, LONG pStartPos=1),LONG Count PROCEDURE(STRING pSearchValue, <LONG pStartPos>, <LONG pEndPos>, BYTE pNoCase=0),LONG Destruct PROCEDURE() Get PROCEDURE(),STRING GetLine PROCEDURE(LONG pLineNumber),STRING GetStrPos PROCEDURE(STRING pFindString, LONG pNullValue=0),LONG Length PROCEDURE(),LONG PreAppend PROCEDURE(STRING pNewValue) Records PROCEDURE(),LONG Replace PROCEDURE(STRING pOldValue, STRING pNewValue,<LONG pCount>) Split PROCEDURE(STRING pSplitStr) SubString PROCEDURE(LONG pStart, LONG pStop),STRING !Private Methods DisposeLines PROCEDURE(),PRIVATE DisposeStr PROCEDURE(),PRIVATE END _EndOfInclude_
adc4206e55144d3c4243be13f37cae8d1685337c
[ "PHP" ]
1
PHP
msarson/UltimateUtilities
f89385f76e95091ac27313cc604f027d2eb18582
5db2fd295ae329b163f3739712cd365f0de8e2d8
refs/heads/master
<file_sep>const XlsxPopulate = require('xlsx-populate'); const newA1Val = "REPLACE TEST" // Load an existing workbook XlsxPopulate.fromFileAsync("./TEMPLATE_XLSX.xlsx") .then(workbook => { // Modify the workbook. const value = workbook.sheet("DSHSL1").cell("A1").value(); workbook.sheet("DSHSL1").cell("A1").find(value, newA1Val); // Log the value. console.log(value); return workbook.toFileAsync("./out.xlsx"); });
4fb3b280397ff6ced4dd963087ba0c9cacd7d612
[ "JavaScript" ]
1
JavaScript
namndwebdev/excel-fill-template
e7e5cd112d3eafb8e406a5c50ccb3a31d983b412
4b6e7bf162afba64cd04548ff981c27aa8df6697
refs/heads/master
<repo_name>sayedsaddam/performance_appraisals<file_sep>/application/controllers/Export_excel.php <?php defined('BASEPATH') OR exit('No direct script access allowed!'); use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; class Export_excel extends CI_Controller{ public function __construct(){ parent::__construct(); $this->load->model('Performance_appraisal_model'); } // Export to Excel (TCSP's) public function createExcel() { $fileName = 'tcsps.xlsx'; $tcsps_data = $this->Performance_appraisal_model->export_excel(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Emp ID'); $sheet->setCellValue('B1', 'Name'); $sheet->setCellValue('C1', 'Position'); $sheet->setCellValue('D1', 'Province'); $sheet->setCellValue('E1', 'District'); $sheet->setCellValue('F1', 'Tehsil'); $sheet->setCellValue('G1', 'UC'); $sheet->setCellValue('H1', 'CNIC'); $sheet->setCellValue('I1', 'UC/Area level Micro-plans development and desk revision'); $sheet->setCellValue('J1', 'UC/Area level Micro-plans field validation'); $sheet->setCellValue('K1', 'Status of selection of the house to house vaccination teams'); $sheet->setCellValue('L1', '% of teams training attended'); $sheet->setCellValue('M1', 'Training of the UC supervisors (Area In-charges)'); $sheet->setCellValue('N1', 'Pre campaign data collection, collation and timely transmission to the next level % timeliness and % completeness'); $sheet->setCellValue('O1', 'Data collection, collation and timely transmission to the next level during the campaign % timeliness and % completeness'); $sheet->setCellValue('P1', 'Corrective measures following the identification of the gaps. Number of critical siuation handled'); $sheet->setCellValue('Q1', 'Ensure data collection from the field with more than 95% Post Campaign coverages through extensive monitoring in the field by doing LQAS & Market Surveys'); $sheet->setCellValue('R1', 'To establish the community AFP Surveillance in his area of assignment through regular health facility visits and ensure that the zero reports are timely been submitted'); $sheet->setCellValue('S1', 'Reliability'); $sheet->setCellValue('T1', 'Work independently with minimal supervision'); $sheet->setCellValue('U1', 'Punctuality'); $sheet->setCellValue('V1', 'Initiative'); $sheet->setCellValue('W1', 'Good team player'); $sheet->setCellValue('X1', 'Fimiliarity with WHO required procedures'); $sheet->setCellValue('Y1', 'Overall Assessment'); $sheet->setCellValue('Z1', 'TCSP Remarks'); $sheet->setCellValue('AA1', 'AC Remarks'); $rows = 2; foreach ($tcsps_data as $val){ $sheet->setCellValue('A' . $rows, $val['id']); $sheet->setCellValue('B' . $rows, $val['name']); $sheet->setCellValue('C' . $rows, $val['position']); $sheet->setCellValue('D' . $rows, $val['province']); $sheet->setCellValue('E' . $rows, $val['district']); $sheet->setCellValue('F' . $rows, $val['tehsil']); $sheet->setCellValue('G' . $rows, $val['uc']); $sheet->setCellValue('H' . $rows, $val['cnic_name']); $sheet->setCellValue('I' . $rows, $val['que_one']); $sheet->setCellValue('J' . $rows, $val['que_two']); $sheet->setCellValue('K' . $rows, $val['que_three']); $sheet->setCellValue('L' . $rows, $val['que_four']); $sheet->setCellValue('M' . $rows, $val['que_five']); $sheet->setCellValue('N' . $rows, $val['que_six']); $sheet->setCellValue('O' . $rows, $val['que_seven']); $sheet->setCellValue('P' . $rows, $val['que_eight']); $sheet->setCellValue('Q' . $rows, $val['que_nine']); $sheet->setCellValue('R' . $rows, $val['que_ten']); $sheet->setCellValue('S' . $rows, $val['attrib_1']); $sheet->setCellValue('T' . $rows, $val['attrib_2']); $sheet->setCellValue('U' . $rows, $val['attrib_3']); $sheet->setCellValue('V' . $rows, $val['attrib_4']); $sheet->setCellValue('W' . $rows, $val['attrib_5']); $sheet->setCellValue('X' . $rows, $val['attrib_6']); $sheet->setCellValue('Y' . $rows, $val['comment_2']); $sheet->setCellValue('Z' . $rows, $val['comment']); $sheet->setCellValue('AA' . $rows, $val['assessment_result']); $rows++; } $writer = new Xlsx($spreadsheet); $writer->save("upload/".$fileName); header("Content-Type: application/vnd.ms-excel"); redirect(base_url()."/upload/".$fileName); } // --------------------------------------- Export excel UCPO's ------------------------------------- // // Export to Excel (UCPO's). public function exportExcel() { $fileName = 'ucpos.xlsx'; $ucpos_data = $this->Performance_appraisal_model->export_excel_ucpos(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Emp ID'); $sheet->setCellValue('B1', 'Name'); $sheet->setCellValue('C1', 'Position'); $sheet->setCellValue('D1', 'Province'); $sheet->setCellValue('E1', 'District'); $sheet->setCellValue('F1', 'Tehsil'); $sheet->setCellValue('G1', 'UC'); $sheet->setCellValue('H1', 'CNIC'); $sheet->setCellValue('I1', 'UC/Area level Micro-plans development and desk revision'); $sheet->setCellValue('J1', 'UC/Area level Micro-plans field validation'); $sheet->setCellValue('K1', 'Status of selection of the house to house vaccination teams'); $sheet->setCellValue('L1', 'Training of the vaccination teams'); $sheet->setCellValue('M1', 'Training of the UC supervisors (Area In-charges)'); $sheet->setCellValue('N1', 'Pre campaign data collection, collation and timely transmission to the next level'); $sheet->setCellValue('O1', 'Data collection, collation and timely transmission to the next level during the campaign'); $sheet->setCellValue('P1', 'Corrective measures following the identification of the gaps'); $sheet->setCellValue('Q1', 'Reliability'); $sheet->setCellValue('R1', 'Work independently with minimal supervision'); $sheet->setCellValue('S1', 'Punctuality'); $sheet->setCellValue('T1', 'Initiative'); $sheet->setCellValue('U1', 'Good team player'); $sheet->setCellValue('V1', 'Familiarity with WHO required procedures'); $sheet->setCellValue('W1', 'Overall Assessment'); $sheet->setCellValue('X1', 'UCPO Remarks'); $sheet->setCellValue('Y1', 'AC Remarks'); $rows = 2; foreach ($ucpos_data as $val){ $sheet->setCellValue('A' . $rows, $val['id']); $sheet->setCellValue('B' . $rows, $val['name']); $sheet->setCellValue('C' . $rows, $val['position']); $sheet->setCellValue('D' . $rows, $val['province']); $sheet->setCellValue('E' . $rows, $val['district']); $sheet->setCellValue('F' . $rows, $val['tehsil']); $sheet->setCellValue('G' . $rows, $val['uc']); $sheet->setCellValue('H' . $rows, $val['cnic_name']); $sheet->setCellValue('I' . $rows, $val['que_one']); $sheet->setCellValue('J' . $rows, $val['que_two']); $sheet->setCellValue('K' . $rows, $val['que_three']); $sheet->setCellValue('L' . $rows, $val['que_four']); $sheet->setCellValue('M' . $rows, $val['que_five']); $sheet->setCellValue('N' . $rows, $val['que_six']); $sheet->setCellValue('O' . $rows, $val['que_seven']); $sheet->setCellValue('P' . $rows, $val['que_eight']); $sheet->setCellValue('Q' . $rows, $val['attrib_1']); $sheet->setCellValue('R' . $rows, $val['attrib_2']); $sheet->setCellValue('S' . $rows, $val['attrib_3']); $sheet->setCellValue('T' . $rows, $val['attrib_4']); $sheet->setCellValue('U' . $rows, $val['attrib_5']); $sheet->setCellValue('V' . $rows, $val['attrib_6']); $sheet->setCellValue('W' . $rows, $val['comment_2']); $sheet->setCellValue('X' . $rows, $val['comment']); $sheet->setCellValue('Y' . $rows, $val['assessment_result']); $rows++; } $writer = new Xlsx($spreadsheet); $writer->save("upload/".$fileName); header("Content-Type: application/vnd.ms-excel"); redirect(base_url()."/upload/".$fileName); } // ------------------------- Export to excel the pending UCPO's reports --------------------------- // // UCPO's public function ucpos_report() { $fileName = 'ucpos_report.xlsx'; $tcsps_data = $this->Performance_appraisal_model->ucpos_report(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Province'); $sheet->setCellValue('B1', 'District'); $sheet->setCellValue('C1', 'UC'); $sheet->setCellValue('D1', 'UCPO Name'); $sheet->setCellValue('E1', 'UCPO CNIC'); $sheet->setCellValue('F1', 'PEO Name'); $sheet->setCellValue('G1', 'PEO CNIC'); $sheet->setCellValue('H1', 'AC Name'); $sheet->setCellValue('I1', 'AC CNIC'); $rows = 2; foreach ($tcsps_data as $val){ $sheet->setCellValue('A' . $rows, $val['province']); $sheet->setCellValue('B' . $rows, $val['district']); $sheet->setCellValue('C' . $rows, $val['uc']); $sheet->setCellValue('D' . $rows, $val['name']); $sheet->setCellValue('E' . $rows, $val['cnic_name']); $sheet->setCellValue('F' . $rows, $val['peo_name']); $sheet->setCellValue('G' . $rows, $val['peo_cnic']); $sheet->setCellValue('H' . $rows, $val['ac_name']); $sheet->setCellValue('I' . $rows, $val['ac_cnic']); $rows++; } $writer = new Xlsx($spreadsheet); $writer->save("upload/".$fileName); header("Content-Type: application/vnd.ms-excel"); redirect(base_url()."/upload/".$fileName); } // TCSP's public function tcsps_report() { $fileName = 'tcsps_report.xlsx'; $tcsps_data = $this->Performance_appraisal_model->tcsps_report(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Province'); $sheet->setCellValue('B1', 'District'); $sheet->setCellValue('C1', 'UC'); $sheet->setCellValue('D1', 'TCSP Name'); $sheet->setCellValue('E1', 'TCSP CNIC'); $sheet->setCellValue('F1', 'PEO Name'); $sheet->setCellValue('G1', 'PEO CNIC'); $sheet->setCellValue('H1', 'AC Name'); $sheet->setCellValue('I1', 'AC CNIC'); $rows = 2; foreach ($tcsps_data as $val){ $sheet->setCellValue('A' . $rows, $val['province']); $sheet->setCellValue('B' . $rows, $val['district']); $sheet->setCellValue('C' . $rows, $val['uc']); $sheet->setCellValue('D' . $rows, $val['name']); $sheet->setCellValue('E' . $rows, $val['cnic_name']); $sheet->setCellValue('F' . $rows, $val['peo_name']); $sheet->setCellValue('G' . $rows, $val['peo_cnic']); $sheet->setCellValue('H' . $rows, $val['ac_name']); $sheet->setCellValue('I' . $rows, $val['ac_cnic']); $rows++; } $writer = new Xlsx($spreadsheet); $writer->save("upload/".$fileName); header("Content-Type: application/vnd.ms-excel"); redirect(base_url()."/upload/".$fileName); } } ?><file_sep>/application/controllers/Admin_dashboard.php <?php defined("BASEPATH") OR exit('No direct script access allowed !'); /** * summary */ class Admin_dashboard extends CI_Controller { /** * summary */ public function __construct() { parent::__construct(); $this->load->model('Performance_appraisal_model'); } // Get summary of all the data. public function index($offset = NULL){ $limit = 20; if(!empty($offset)){ $this->uri->segment(3); } $data['pen_ucpos'] = $this->Performance_appraisal_model->get_summary_ucpos($limit, $offset); $data['pen_tcsps'] = $this->Performance_appraisal_model->get_summary_tcsps($limit, $offset); $data['title'] = 'Dashboard | Performance Appraisals'; $data['content'] = 'performance_evaluation/admin_dashboard'; $this->load->view('components/template', $data); } // View all UCPO's statistics... public function all_ucpos($offset = NULl){ $limit = 20; if(!empty($offset)){ $this->uri->segment(3); } $this->load->library('pagination'); $config['uri_segment'] = 3; $config['base_url'] = base_url('Admin_dashboard/all_ucpos'); $config['total_rows'] = $this->Performance_appraisal_model->ucpos_pending(); $config['per_page'] = $limit; $config['num_links'] = 3; $config["full_tag_open"] = '<ul class="pagination">'; $config["full_tag_close"] = '</ul>'; $config["first_tag_open"] = '<li>'; $config["first_tag_close"] = '</li>'; $config["last_tag_open"] = '<li>'; $config["last_tag_close"] = '</li>'; $config['next_link'] = 'next &raquo;'; $config["next_tag_open"] = '<li>'; $config["next_tag_close"] = '</li>'; $config["prev_link"] = "prev &laquo;"; $config["prev_tag_open"] = "<li>"; $config["prev_tag_close"] = "</li>"; $config["cur_tag_open"] = "<li class='active'><a href='javascript:void(0);'>"; $config["cur_tag_close"] = "</a></li>"; $config["num_tag_open"] = "<li>"; $config["num_tag_close"] = "</li>"; $this->pagination->initialize($config); $data['title'] = "UCPO's List"; $data['content'] = 'performance_evaluation/list_ucpos'; $data['pending_ucpos'] = $this->Performance_appraisal_model->get_summary_ucpos($limit, $offset); $this->load->view('components/template', $data); } // Search for specific record. public function search_ucpos(){ $search = $this->input->get('search_record'); $data['title'] = 'Search Results | Admin Dashboard'; $data['content'] = 'performance_evaluation/list_ucpos'; $data['search_results'] = $this->Performance_appraisal_model->search_ucpos($search); $this->load->view('components/template', $data); } // -----------------------------------------------------------------------------------------// // TCSP's.. // Show all TCSPs. public function all_tcsps($offset = NULL){ $limit = 20; if(!empty($offset)){ $this->uri->segment(3); } $this->load->library('pagination'); $config['uri_segment'] = 3; $config['base_url'] = base_url('Admin_dashboard/all_tcsps'); $config['total_rows'] = $this->Performance_appraisal_model->tcsps_pending(); $config['per_page'] = $limit; $config['num_links'] = 3; $config["full_tag_open"] = '<ul class="pagination">'; $config["full_tag_close"] = '</ul>'; $config["first_tag_open"] = '<li>'; $config["first_tag_close"] = '</li>'; $config["last_tag_open"] = '<li>'; $config["last_tag_close"] = '</li>'; $config['next_link'] = 'next &raquo;'; $config["next_tag_open"] = '<li>'; $config["next_tag_close"] = '</li>'; $config["prev_link"] = "prev &laquo;"; $config["prev_tag_open"] = "<li>"; $config["prev_tag_close"] = "</li>"; $config["cur_tag_open"] = "<li class='active'><a href='javascript:void(0);'>"; $config["cur_tag_close"] = "</a></li>"; $config["num_tag_open"] = "<li>"; $config["num_tag_close"] = "</li>"; $this->pagination->initialize($config); $data['title'] = "TCSP's List"; $data['content'] = 'performance_evaluation/list_tcsps'; $data['pending_tcsps'] = $this->Performance_appraisal_model->get_summary_tcsps($limit, $offset); $this->load->view('components/template', $data); } // Search for specific record. public function search_tcsps(){ $search = $this->input->get('search_record'); $data['title'] = 'Search Results | Admin Dashboard'; $data['content'] = 'performance_evaluation/list_tcsps'; $data['search_results'] = $this->Performance_appraisal_model->search_tcsps($search); $this->load->view('components/template', $data); } // -----------------------------------------------------------------------------------------// // Add new UCPO's. public function add_ucpos(){ $data['title'] = 'Add UCPOs | Performance Appraisal'; $data['content'] = 'performance_evaluation/add_ucpos'; $data['peos'] = $this->Performance_appraisal_model->get_peos(); $data['acs'] = $this->Performance_appraisal_model->get_acs(); $this->load->view('components/template', $data); } // Add new TCSP's. public function add_tcsps(){ $data['title'] = 'Add TCSPs | Performance Appraisal'; $data['content'] = 'performance_evaluation/add_tcsps'; $data['peos'] = $this->Performance_appraisal_model->get_peos(); $data['acs'] = $this->Performance_appraisal_model->get_acs(); $this->load->view('components/template', $data); } // Add new PEO's and AC's. public function add_peos(){ $data['title'] = 'Add PEOs | Performance Appraisal'; $data['content'] = 'performance_evaluation/add_peos'; $this->load->view('components/template', $data); } // Save PEO's to the database. public function save_peos(){ $data = array( 'peo_name' => $this->input->post('peo_name'), 'peo_cnic' => $this->input->post('peo_cnic'), 'peo_password' => $this->input->post('peo_<PASSWORD>') ); $this->Performance_appraisal_model->add_peos($data); $this->session->set_flashdata('success_peo', '<strong>Success! </strong> PEO has been saved successfully!'); redirect('admin_dashboard/add_peos'); } // Save AC's to the database. public function save_acs(){ $data = array( 'ac_name' => $this->input->post('ac_name'), 'ac_cnic' => $this->input->post('ac_cnic'), 'ac_password' => $this->input->post('ac_pass') ); $this->Performance_appraisal_model->add_acs($data); $this->session->set_flashdata('success_ac', '<strong>Success !</strong> AC has been added successfully!'); redirect('admin_dashboard/add_peos'); } // Save UCPO's to the database. public function save_ucpos(){ $data = array( 'position' => 'UCPO', 'name' => $this->input->post('ucpo_name'), 'cnic_name' => $this->input->post('ucpo_cnic'), 'province' => $this->input->post('ucpo_prov'), 'district' => $this->input->post('ucpo_distt'), 'tehsil' => $this->input->post('ucpo_tehsil'), 'uc' => $this->input->post('ucpo_uc'), 'cnic_peo' => $this->input->post('ucpo_peo'), 'cnic_ac' => $this->input->post('ucpo_ac'), 'ucpo_password' => $this->input->post('ucpo_pass'), 'join_date' => date('d-M-y', strtotime($this->input->post('join_date'))) ); $this->Performance_appraisal_model->add_ucpos($data); $this->session->set_flashdata('success', '<strong>Success !</strong> UCPO has been added successfully!'); redirect('admin_dashboard/add_ucpos'); } // Save TCSP's to the database. public function save_tcsps(){ $data = array( 'position' => 'TCSP', 'name' => $this->input->post('tcsp_name'), 'cnic_name' => $this->input->post('tcsp_cnic'), 'province' => $this->input->post('tcsp_prov'), 'district' => $this->input->post('tcsp_distt'), 'tehsil' => $this->input->post('tcsp_tehsil'), 'uc' => $this->input->post('tcsp_uc'), 'cnic_peo' => $this->input->post('tcsp_peo'), 'cnic_ac' => $this->input->post('tcsp_ac'), 'tcsp_password' => $this->input->post('tcsp_pass'), 'join_date' => date('d-M-y', strtotime($this->input->post('join_date'))) ); $this->Performance_appraisal_model->add_tcsps($data); $this->session->set_flashdata('success', '<strong>Success !</strong> UCPO has been added successfully!'); redirect('admin_dashboard/add_tcsps'); } // ------------------------------ Edit, update, and delete operations ------------------------ // // Edit UCPO. public function edit_ucpo($id){ $data['title'] = 'Update | Performance Appraisals'; $data['content'] = 'performance_evaluation/add_ucpos'; $data['peos'] = $this->Performance_appraisal_model->get_peos(); $data['acs'] = $this->Performance_appraisal_model->get_acs(); $data['edit'] = $this->Performance_appraisal_model->edit_ucpo($id); // Model call. $this->load->view('components/template', $data); } // Update UCPO. public function update_ucpo(){ $id = $this->input->post('emp_id'); $data = array( 'position' => 'UCPO', 'name' => $this->input->post('ucpo_name'), 'cnic_name' => $this->input->post('ucpo_cnic'), 'province' => $this->input->post('ucpo_prov'), 'district' => $this->input->post('ucpo_distt'), 'tehsil' => $this->input->post('ucpo_tehsil'), 'uc' => $this->input->post('ucpo_uc'), 'cnic_peo' => $this->input->post('ucpo_peo'), 'cnic_ac' => $this->input->post('ucpo_ac') // 'ucpo_password' => $this->input->post('ucpo_pass'), //'join_date' => date('d-M-y', strtotime($this->input->post('join_date'))) ); $this->Performance_appraisal_model->update_ucpo($id, $data); $this->session->set_flashdata('success', '<strong>Success !</strong> UCPO has been updated successfully'); redirect('admin_dashboard/all_ucpos'); } // Delete UCPO. public function delete_ucpo($id){ if($this->Performance_appraisal_model->delete_ucpo($id)){ $this->session->set_flashdata('success', '<strong>Success !</strong> The delete operation was successful.'); redirect('admin_dashboard/all_ucpos'); }else{ echo "The operation wasn't successful !"; } } // Edit TCSP. public function edit_tcsp($id){ $data['title'] = 'Update | Performance Appraisals'; $data['content'] = 'performance_evaluation/add_tcsps'; $data['peos'] = $this->Performance_appraisal_model->get_peos(); $data['acs'] = $this->Performance_appraisal_model->get_acs(); $data['edit'] = $this->Performance_appraisal_model->edit_tcsp($id); // Model call. $this->load->view('components/template', $data); } // Update TCSP public function update_tcsp(){ $id = $this->input->post('emp_id'); $data = array( 'position' => 'TCSP', 'name' => $this->input->post('tcsp_name'), 'cnic_name' => $this->input->post('tcsp_cnic'), 'province' => $this->input->post('tcsp_prov'), 'district' => $this->input->post('tcsp_distt'), 'tehsil' => $this->input->post('tcsp_tehsil'), 'uc' => $this->input->post('tcsp_uc'), 'cnic_peo' => $this->input->post('tcsp_peo'), 'cnic_ac' => $this->input->post('tcsp_ac') // 'tcsp_password' => $this->input->post('tcsp_pass'), //'join_date' => date('d-M-y', strtotime($this->input->post('join_date'))) ); $this->Performance_appraisal_model->update_tcsp($id, $data); $this->session->set_flashdata('success', '<strong>Success ! </strong>TCSP has been updated successfully!'); redirect('admin_dashboard/all_tcsps'); } // Delete TCSP. public function delete_tcsp($id){ if($this->Performance_appraisal_model->delete_tcsp($id)){ $this->session->set_flashdata('success', '<strong>Success ! </strong>The delete operation was successful!'); redirect('admin_dashboard/all_tcsps'); }else{ echo "The operation wasn't successful !"; } } } ?><file_sep>/application/views/performance_evaluation/add_peos.php <section class="secMainWidthFilter" style="padding: 0px;margin-top: -40px;"> <section class="secIndexTable margint-top-0"> <section class="secIndexTable"> <div class="col-lg-6"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-12"> <div class="tabelHeading"> <h3>add PEO's | <small>Enter the detail and press the "SAVE" button.</small></h3> </div> </div> </div> <div class="row"> <div class="col-md-10 col-md-offset-1"> <?php if($success_peo = $this->session->flashdata('success_peo')): ?> <div class="alert alert-success"><?php echo $success_peo; ?></div> <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-10"> <div class="tableMain"> <div class="table-responsive"> <form action="<?php echo base_url('admin_dashboard/save_peos'); ?>" method="post"> <table class="table table-responsive"> <tbody> <tr> <td> <label>Name</label> </td> <td> <input type="text" name="peo_name" class="form-control" placeholder="PEO name..." required> </td> </tr> <tr> <td> <label>CNIC</label> </td> <td> <input type="text" name="peo_cnic" class="form-control" placeholder="PEO cnic..." required=""> </td> </tr> <tr> <td> <label>Password</label> </td> <td> <input type="password" name="peo_pass" class="form-control" placeholder="PEO password..." required=""> <small>The default password would be "<PASSWORD>", then the PEO can change it anytime.</small> </td> </tr> <tr> <td> <input type="submit" name="submit" class="btn btn-primary btn-block" value="Save"> </td> <td> <input type="reset" name="reset" class="btn btn-warning btn-block" value="Reset"> </td> </tr> </tbody> </table> </form> </div> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-12"> <div class="tabelHeading"> <h3>add AC's | <small>Enter the detail and press the "SAVE" button.</small></h3> </div> </div> </div> <div class="row"> <div class="col-md-10 col-md-offset-1"> <?php if($success_ac = $this->session->flashdata('success_ac')): ?> <div class="alert alert-success"><?php echo $success_ac; ?></div> <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-10"> <div class="tableMain"> <div class="table-responsive"> <form action="<?php echo base_url('admin_dashboard/save_acs'); ?>" method="post"> <table class="table table-responsive"> <tbody> <tr> <td> <label>Name</label> </td> <td> <input type="text" name="ac_name" class="form-control" placeholder="AC name..." required=""> </td> </tr> <tr> <td> <label>CNIC</label> </td> <td> <input type="text" name="ac_cnic" class="form-control" placeholder="AC cnic..." required=""> </td> </tr> <tr> <td> <label>Password</label> </td> <td> <input type="password" name="ac_pass" class="form-control" placeholder="AC password..." required=""> <small>The default password would be "<PASSWORD>", then the PEO can change it anytime.</small> </td> </tr> <tr> <td> <input type="submit" name="submit" class="btn btn-primary btn-block" value="Save"> </td> <td> <input type="reset" name="reset" class="btn btn-warning btn-block" value="Reset"> </td> </tr> </tbody> </table> </form> </div> </div> </div> </div> </div> </div> </section> </section> </section><file_sep>/application/views/components/head.php <?php /* * Filename: head.php * Filepath: views / components / head.php * Author: Saddam */ ?> <!DOCTYPE html> <html> <head> <title><?php echo $title; ?></title> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,900|Open+Sans:400,700,800|Roboto:400,700,900" rel="stylesheet"> <link rel="stylesheet" href="<?php echo base_url('assets/css/font-awesome.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/select2/dist/css/select2.min.css'); ?>"> <script src="<?php echo base_url('assets/js/jquery.js'); ?>"></script> <script src="<?php echo base_url('assets/DataTables/js/jquery.dataTables.min'); ?>"></script> </head> <body> <!-- Navbar --> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php if($this->session->userdata('admin_cnic')){ echo base_url('admin_dashboard'); }else{ ?>javascript:void(0);<?php } ?>">Performance Appraisals</a> </div> <?php $ucpo_session = $this->session->userdata('ucpo_cnic'); ?> <?php $tcsp_session = $this->session->userdata('tcsp_cnic'); ?> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li <?php if($tcsp_session OR $ucpo_session): ?> class="disabled" <?php endif; ?>> <a href="<?php if(!$tcsp_session){ echo base_url('performance_evaluation/get_previous'); } ?>">UCPO Evaluation</a> </li> <li <?php if($ucpo_session OR $tcsp_session): ?> class="disabled" <?php endif; ?>> <a href="<?php if(!$ucpo_session){ echo base_url('performance_evaluation/tcsp_previous'); } ?>">TCSP Evaluation</a> </li> <?php if($this->session->userdata('admin_cnic')): ?> <li> <a href="<?php echo base_url('admin_dashboard'); ?>">Summary</a> </li> <?php endif; ?> </ul> <ul class="nav navbar-nav navbar-right"> <?php if($this->session->userdata('peo_cnic') OR $this->session->userdata('ac_cnic') OR $this->session->userdata('ucpo_cnic') OR $this->session->userdata('tcsp_cnic') OR $this->session->userdata('admin_cnic')): ?> <li> <a href="<?php echo base_url('Perf_login/change_password'); ?>">Change Password</a> </li> <li> <a href="<?php echo base_url('Perf_login/logout'); ?>">Logout <span class="glyphicon glyphicon-log-out"></span></a> </li> <?php endif; ?> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <file_sep>/application/views/performance_evaluation/admin_dashboard.php <?php $count_ucpos = $this->Performance_appraisal_model->all_ucpos(); ?> <?php $count_ucpos_pending = $this->Performance_appraisal_model->count_ucpos_pending(); ?> <?php $count_tcsps = $this->Performance_appraisal_model->count_tcsps_pending(); ?> <?php $count_tcsps_pending = $this->Performance_appraisal_model->all_tcsps(); ?> <?php $count_ac_ucpos = $this->Performance_appraisal_model->count_ac_ucpos_pending(); ?> <?php $count_ac_tcsps = $this->Performance_appraisal_model->count_ac_tcsps_pending(); ?> <?php $completed_ucpos = $this->Performance_appraisal_model->completed_ucpos(); ?> <?php $completed_tcsps = $this->Performance_appraisal_model->completed_tcsps(); ?> <?php $pen_from_ucpos = $this->Performance_appraisal_model->count_pending_from_ucpos(); ?> <?php $pen_from_tcsps = $this->Performance_appraisal_model->count_pending_from_tcsps(); ?> <section class="secMainWidthFilter" style="padding: 0px;margin-top: -40px;"> <section class="secIndexTable margint-top-0"> <section class="secIndexTable"> <div class="col-lg-6"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-8"> <div class="tabelHeading"> <h3>statistics for UCPO's</h3> </div> </div> <div class="col-md-4"> <div class="tabelTopBtn"> <div class="input-group-btn"> <a href="<?php echo base_url('admin_dashboard/add_ucpos'); ?>" class="btn btn-default"><i class="fa fa-plus"></i> add ucpo's</a> <a class="btn btn-default" href="javascript:void(0);"><<< <i class="fa fa-refresh"></i> >>></a> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="tableMain"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Total no. of UCPO's</th> <th>pending from UCPO</th> <th>Pending from PEO</th> <th>pending from AC</th> <th>Completed</th> </tr> </thead> <tbody> <tr> <td><?php echo $count_ucpos; ?></td> <td><?php echo $pen_from_ucpos; ?></td> <td><?php echo $count_ucpos_pending; ?></td> <td><?php echo $count_ac_ucpos; ?></td> <td><?php echo $completed_ucpos; ?></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-8"> <div class="tabelHeading"> <h3>statistics for TCSP's</h3> </div> </div> <div class="col-md-4"> <div class="tabelTopBtn"> <div class="input-group-btn"> <a href="<?php echo base_url('admin_dashboard/add_tcsps'); ?>" class="btn btn-default"><i class="fa fa-plus"></i> add tcsp's</a> <a class="btn btn-default" href="javascript:void(0);"><<< <i class="fa fa-refresh"></i> >>></a> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="tableMain"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>total no. of TCSP's</th> <th>pending from TCSP</th> <th>pending TCSP's</th> <th>pending from AC</th> <th>completed</th> </tr> </thead> <tbody> <tr> <td><?php echo $count_tcsps_pending; ?></td> <td><?php echo $pen_from_tcsps; ?></td> <td><?php echo $count_tcsps; ?></td> <td><?php echo $count_ac_tcsps; ?></td> <td><?php echo $completed_tcsps; ?></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-8"> <div class="tabelHeading"> <h3>UCPO's pending from PEO</h3> </div> </div> <div class="col-md-4"> <div class="tabelTopBtn"> <div class="input-group-btn"> <a class="btn btn-defaul" href="<?= base_url('admin_dashboard/all_ucpos'); ?>">view all</a> <a class="btn btn-defaul" href="<?= base_url('admin_dashboard/add_peos'); ?>"><i class="fa fa-plus"></i> add peo's</a> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="tableMain"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>UCPO name</th> <th>PEO name</th> <th>AC name</th> <th>status</th> </tr> </thead> <tbody> <?php foreach ($pen_ucpos as $pending): ?> <tr> <td><?php echo $pending->name; ?></td> <td><?php echo $pending->peo_name; ?></td> <td><?php echo $pending->ac_name; ?></td> <td><div class="label label-info">Pending...</div></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-8"> <div class="tabelHeading"> <h3>TCSP's pending from PEO</h3> </div> </div> <div class="col-md-4"> <div class="tabelTopBtn"> <div class="input-group-btn"> <a class="btn btn-defaul" href="<?= base_url('admin_dashboard/all_tcsps'); ?>">view all</a> <a class="btn btn-defaul" href="<?= base_url('admin_dashboard/add_peos'); ?>"><i class="fa fa-plus"></i> add ac's</a> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="tableMain"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>TCSP name</th> <th>PEO name</th> <th>AC name</th> <th>status</th> </tr> </thead> <tbody> <?php foreach($pen_tcsps as $pending): ?> <tr> <td><?php echo $pending->name; ?></td> <td><?php echo $pending->peo_name; ?></td> <td><?php echo $pending->ac_name; ?></td> <td><div class="label label-info">Pending...</div></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </section> </section> </section><file_sep>/application/views/change_password.php <?php /* Filename: exam_login.php * Location: views/test-system/exam_login.php * Author: Saddam */ ?> <!DOCTYPE html> <html> <head> <title>Login | Performance Appraisal</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="" /> <meta property="og:description" content="" /> <meta property="og:url" content="" /> <meta property="og:site_name" content="" /> <meta name="og:card" content="" /> <meta name="og:description" content="" /> <meta name="og:title" content="" /> <meta name="og:image" content="" /> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,900|Open+Sans:400,700,800|Roboto:400,700,900" rel="stylesheet"> <link rel="stylesheet" href="<?php echo base_url('assets/css/font-awesome.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>"> <script src="<?php echo base_url('assets/js/jquery.js'); ?>"></script> </head> <body> <section class="secLogin"> <div class="container"> <div class="loginWhite"> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8"> <form action="<?php echo base_url('Perf_login/password_change'); ?>" method="post"> <div class="rightLoginMain"> <div class="aligmentWrap"> <h3 style="margin-bottom: 4px;">Change Password</h3> <small>Please enter your new password. You can update your password just once.</small> <div class="loginInput"> <input type="hidden" name="eval_date" value="<?php echo date('Y-m-d'); ?>"> <input name="pass" type="password" class="form-control" placeholder="Enter your new password here..." required> </div> <div class="loginInput"> <button type="submit" class="btn btn-block"> Change </button> </div> </div> </div> </form> </div> <div class="col-md-2"></div> </div> </div> </div> </section> <script src="<?php echo base_url('assets/js/bootstrap.min.js'); ?>"></script> <script src="<?php echo base_url('assets/js/custom.js'); ?>"></script> </body> </html><file_sep>/application/views/perf_login.php <?php /* Filename: exam_login.php * Location: views/test-system/exam_login.php * Author: Saddam */ ?> <!DOCTYPE html> <html> <head> <title>Login | Performance Appraisal</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="" /> <meta property="og:description" content="" /> <meta property="og:url" content="" /> <meta property="og:site_name" content="" /> <meta name="og:card" content="" /> <meta name="og:description" content="" /> <meta name="og:title" content="" /> <meta name="og:image" content="" /> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,900|Open+Sans:400,700,800|Roboto:400,700,900" rel="stylesheet"> <link rel="stylesheet" href="<?php echo base_url('assets/css/font-awesome.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>"> <script src="<?php echo base_url('assets/js/jquery.js'); ?>"></script> </head> <body> <section class="secLogin"> <div class="container"> <div class="loginWhite"> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8"> <form action="<?php echo base_url('Perf_login/validate'); ?>" method="post"> <div class="rightLoginMain"> <div class="aligmentWrap"> <h3 style="margin-bottom: 4px;">Appraisal's Login</h3> <small>Enter your CNIC & Password to proceed.</small> <div class="loginInput"> <input name="peo_cnic" type="text" class="form-control" placeholder="Enter your cnic here..." required><br> <input name="password" type="password" class="form-control" placeholder="Enter your password here..." required> </div> <div class="loginInput"> <button type="submit" class="btn btn-block"> Login </button> </div> <?php if($failed = $this->session->flashdata('failed')): ?> <div class="alert alert-danger alert-dismissable text-center"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <p><?php echo $failed; // Login attempt failed. ?></p> </div> <?php endif; ?> <?php if($logged_out = $this->session->flashdata('logged_out')): ?> <div class="alert alert-danger alert-dismissable text-center"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <p><?php echo $logged_out; // Logout successful. ?></p> </div> <?php endif; ?> <?php if($success = $this->session->flashdata('success')): ?> <div class="alert alert-success"> <?php echo $success; // Password change. ?> </div> <?php endif; ?> </div> </div> </form> </div> <div class="col-md-2"></div> </div> </div> </div> </section> <script src="<?php echo base_url('assets/js/bootstrap.min.js'); ?>"></script> <script src="<?php echo base_url('assets/js/custom.js'); ?>"></script> </body> </html><file_sep>/application/controllers/Performance_evaluation.php <?php defined('BASEPATH') OR exit('No direct script access allowed!'); /* * Filename: Performance_evaluation.php * Filepath: controllers / Performane_evaluation.php * Author: Saddam */ class Performance_evaluation extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->library('session'); $this->load->helper('form'); $this->load->helper('url'); $this->load->helper('html'); $this->load->database(); $this->load->library('form_validation'); //load the model $this->load->model("Performance_appraisal_model"); $this->load->model("Perf_login_model"); } /*Function to set JSON output*/ public function output($Return=array()){ /*Set response header*/ header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); /*Final JSON response*/ exit(json_encode($Return)); } // Load the form view. For UCPO. public function index(){ if($this->session->userdata('tcsp_cnic')){ redirect('performance_evaluation/tcsp_evaluation'); } $data['previously_added'] = $this->Performance_appraisal_model->get_previously_added(); $data['ptpp_employees'] = $this->Performance_appraisal_model->ptpp_employees(); $data['ac_employees'] = $this->Performance_appraisal_model->get_ptpp(); if($this->session->userdata('peo_cnic')){ $data['ucpos'] = $this->Perf_login_model->get_ucpos(); }else{ $data['ucpos'] = $this->Perf_login_model->get_ac_ucpos(); } $data['title'] = 'UCPO | Performance Appraisals'; $data['content'] ='performance_evaluation/performance_eval'; $this->load->view('components/template', $data); } // Get the previously added evaluations. public function get_previous($offset = NULL, $id = ''){ if($this->session->userdata('ucpo_cnic')){ redirect('performance_evaluation'); } $limit = 10; if(!empty($offset)){ $this->uri->segment(3); } $this->load->library('pagination'); $config['uri_segment'] = 3; $config['base_url'] = base_url('Performance_evaluation/get_previous'); $config['total_rows'] = $this->Performance_appraisal_model->count_evaluations(); $config['per_page'] = $limit; $config['num_links'] = 3; $config["full_tag_open"] = '<ul class="pagination">'; $config["full_tag_close"] = '</ul>'; $config["first_tag_open"] = '<li>'; $config["first_tag_close"] = '</li>'; $config["last_tag_open"] = '<li>'; $config["last_tag_close"] = '</li>'; $config['next_link'] = 'next &raquo;'; $config["next_tag_open"] = '<li>'; $config["next_tag_close"] = '</li>'; $config["prev_link"] = "prev &laquo;"; $config["prev_tag_open"] = "<li>"; $config["prev_tag_close"] = "</li>"; $config["cur_tag_open"] = "<li class='active'><a href='javascript:void(0);'>"; $config["cur_tag_close"] = "</a></li>"; $config["num_tag_open"] = "<li>"; $config["num_tag_close"] = "</li>"; $this->pagination->initialize($config); $data['title'] = 'Previous Evaluations'; if(!$this->session->userdata('admin_cnic')){ $data['recents'] = $this->Performance_appraisal_model->get_performance_evaluation($limit, $offset); }else{ $data['recents'] = $this->Performance_appraisal_model->get_performance_evaluation_admin($limit, $offset); } $data['content'] = 'performance_evaluation/recent_evals'; $this->load->view('components/template', $data); } // Save form data to the database, by first level supervisor. (Forward to UCPO). public function save_evaluation(){ $data = array( 'employee_id' => $this->input->post('emp_name'), 'start_date' => date('Y-m-d', strtotime($this->input->post('app_start_date'))), 'end_date' => date('Y-m-d', strtotime($this->input->post('app_end_date'))), 'que_one' => $this->input->post('remark'), 'que_two' => $this->input->post('remark1'), 'que_three' => $this->input->post('remark2'), 'que_four' => $this->input->post('remark3'), 'que_five' => $this->input->post('remark4'), 'que_six' => $this->input->post('remark5'), 'que_seven' => $this->input->post('remark6'), 'que_eight' => $this->input->post('remark7'), 'attrib_1' => $this->input->post('attribute'), 'attrib_2' => $this->input->post('attribute1'), 'attrib_3' => $this->input->post('attribute2'), 'attrib_4' => $this->input->post('attribute3'), 'attrib_5' => $this->input->post('attribute4'), 'attrib_6' => $this->input->post('attribute5'), 'comment_1' => $this->input->post('others_a'), 'comment_2' => $this->input->post('others_b'), 'signature' => $this->input->post('1st_signature'), 'created_at' => $this->input->post('1st_date') ); $this->Performance_appraisal_model->add($data); $this->session->set_flashdata('success', 'Evaluation has successfully been forwarded to UCPO!'); redirect('performance_evaluation/get_previous'); } // Update UCPO evaluation if rolled back. public function update_rolledback(){ $employee_id = $this->input->post('rollback_update'); $data = array( 'start_date' => date('Y-m-d', strtotime($this->input->post('app_start_date'))), 'end_date' => date('Y-m-d', strtotime($this->input->post('app_end_date'))), 'que_one' => $this->input->post('remark'), 'que_two' => $this->input->post('remark1'), 'que_three' => $this->input->post('remark2'), 'que_four' => $this->input->post('remark3'), 'que_five' => $this->input->post('remark4'), 'que_six' => $this->input->post('remark5'), 'que_seven' => $this->input->post('remark6'), 'que_eight' => $this->input->post('remark7'), 'attrib_1' => $this->input->post('attribute'), 'attrib_2' => $this->input->post('attribute1'), 'attrib_3' => $this->input->post('attribute2'), 'attrib_4' => $this->input->post('attribute3'), 'attrib_5' => $this->input->post('attribute4'), 'attrib_6' => $this->input->post('attribute5'), 'comment_1' => $this->input->post('others_a'), 'comment_2' => $this->input->post('others_b'), 'signature' => $this->input->post('1st_signature'), 'status' => 0, 'created_at' => $this->input->post('1st_date') ); $this->Performance_appraisal_model->update_rolled_back($employee_id, $data); $this->db->where('employee_id', $_POST['rollback_update']); $this->db->delete('ptpp_remarks'); $this->session->set_flashdata('success', '<strong>Success !</strong> Record has been updated successfully !'); redirect('performance_evaluation/get_previous'); } // Save the remarks by PTPP to the database. public function remarks_by_ptpp(){ $emp_id = $_POST['ptpp_employee']; $data = array( 'employee_id' => $emp_id, 'remarks' => $this->input->post('ptpp_remarks'), 'comment' => $this->input->post('remarks_by_ucpo'), 'signature' => $this->input->post('ptpp_holder_sign'), 'created_at' => $this->input->post('ptpp_date') ); $this->Performance_appraisal_model->add_ptpp_remarks($data); $this->db->select('status')->from('performance_evaluation')->get()->row(); $this->db->where('employee_id', $_POST['ptpp_employee']); $this->db->update('performance_evaluation', array('status' => '1')); $this->session->set_flashdata('success', 'PTPP Remarks have been saved successfully!'); redirect('performance_evaluation/get_previous'); } // Save the remarks by the second level supervisor to the database. public function remarks_by_sec_level_sup(){ $data = array( 'employee_id' => $this->input->post('sec_level'), 'assessment_result' => $this->input->post('sec_level_remarks'), 'signature' => $this->input->post('sec_level_sign'), 'created_at' => date('Y-m-d', strtotime($this->input->post('sec_level_date'))) ); $this->Performance_appraisal_model->add_sec_level_remarks($data); $this->db->select('status')->from('performance_evaluation')->get()->row(); $this->db->where('employee_id', $_POST['sec_level']); if(isset($_POST['submit_1'])){ $this->db->update('performance_evaluation', array('status' => '3', 'rollback_comment' => $this->input->post('rollback_comment'))); $this->db->where('employee_id', $_POST['sec_level']); $this->db->delete('sec_level_sup_remarks'); $this->session->set_flashdata('success', '<strong>Sucess !</strong> The rollback operation was successful.'); }else{ $this->db->update('performance_evaluation', array('status' => '2')); $this->session->set_flashdata('success', 'Remarks by the Second level supervisor have been saved successfully!'); } redirect('performance_evaluation/get_previous'); } // Get province, district, tehsil for selected employee in the dropdown. public function get_address_ucpos($id = ''){ $ucpo_address = $this->Performance_appraisal_model->get_address_ucpos($id); echo json_encode($ucpo_address); } /* ------------------------------------------------------------------------------------- */ // Performance evaluation form for TCSP (Tehsil Campaign Support Person). public function tcsp_evaluation(){ if($this->session->userdata('ucpo_cnic')){ redirect('performance_evaluation'); } $data['prev_added_tcsps'] = $this->Performance_appraisal_model->get_previously_added_tcsps(); $data['title'] = 'TCSP | Performance Appraisals'; if($this->session->userdata('peo_cnic')){ $data['tcsps'] = $this->Perf_login_model->get_tcsps(); }else{ $data['tcsps'] = $this->Perf_login_model->get_ac_tcsps(); } $data['tcsp_employees'] = $this->Performance_appraisal_model->get_tcsps(); $data['ac_tcsps'] = $this->Performance_appraisal_model->get_tcsps_for_ac(); $data['content'] = 'performance_evaluation/tcsp_evaluation'; $this->load->view('components/template', $data); } // Get the saved evaluations by TCSP. public function tcsp_previous($offset = NULL){ if($this->session->userdata('tcsp_cnic')){ redirect('performance_evaluation/tcsp_evaluation'); } $limit = 10; if(!empty($offset)){ $this->uri->segment(3); } $this->load->library('pagination'); $config['uri_segment'] = 3; $config['base_url'] = base_url('Performance_evaluation/tcsp_previous'); $config['total_rows'] = $this->Performance_appraisal_model->count_tcsp(); $config['per_page'] = $limit; $config['num_links'] = 3; $config["full_tag_open"] = '<ul class="pagination">'; $config["full_tag_close"] = '</ul>'; $config["first_tag_open"] = '<li>'; $config["first_tag_close"] = '</li>'; $config["last_tag_open"] = '<li>'; $config["last_tag_close"] = '</li>'; $config['next_link'] = 'next &raquo;'; $config["next_tag_open"] = '<li>'; $config["next_tag_close"] = '</li>'; $config["prev_link"] = "prev &laquo;"; $config["prev_tag_open"] = "<li>"; $config["prev_tag_close"] = "</li>"; $config["cur_tag_open"] = "<li class='active'><a href='javascript:void(0);'>"; $config["cur_tag_close"] = "</a></li>"; $config["num_tag_open"] = "<li>"; $config["num_tag_close"] = "</li>"; $this->pagination->initialize($config); $data['title'] = 'TCSP Evaluations | Rcently Added'; if(!$this->session->userdata('admin_cnic')){ $data['recent_tcsp'] = $this->Performance_appraisal_model->get_tcsp_evaluations($limit, $offset); }else{ $data['recent_tcsp'] = $this->Performance_appraisal_model->get_tcsp_evaluations_admin($limit, $offset); } $data['content'] = 'performance_evaluation/recent_tcsp'; $this->load->view('components/template', $data); } // Save the TCSP form data into the database. public function save_tcsp_evaluation(){ $data = array( 'employee_id' => $this->input->post('emp_name'), 'start_date' => date('Y-m-d', strtotime($this->input->post('app_start_date'))), 'end_date' => date('Y-m-d', strtotime($this->input->post('app_end_date'))), 'que_one' => $this->input->post('remark'), 'que_two' => $this->input->post('remark1'), 'que_three' => $this->input->post('remark2'), 'que_four' => $this->input->post('remark3'), 'que_five' => $this->input->post('remark4'), 'que_six' => $this->input->post('remark5'), 'que_seven' => $this->input->post('remark6'), 'que_eight' => $this->input->post('remark7'), 'que_nine' => $this->input->post('remark8'), 'que_ten' => $this->input->post('remark9'), 'attrib_1' => $this->input->post('attribute'), 'attrib_2' => $this->input->post('attribute1'), 'attrib_3' => $this->input->post('attribute2'), 'attrib_4' => $this->input->post('attribute3'), 'attrib_5' => $this->input->post('attribute4'), 'attrib_6' => $this->input->post('attribute5'), 'comment_1' => $this->input->post('others_a'), 'comment_2' => $this->input->post('others_b'), 'signature' => $this->input->post('1st_signature'), 'created_at' => $this->input->post('1st_date') ); $this->Performance_appraisal_model->insert_tcsp_evaluations($data); $this->session->set_flashdata('success', 'Evaluation saved successfully!'); redirect('Performance_evaluation/get_tcsp_data'); } // Update rolled back TCSP Evaluations. public function update_rolledback_tcsp(){ $employee_id = $this->input->post('rolledback_tcsp'); $data = array( 'start_date' => date('Y-m-d', strtotime($this->input->post('app_start_date'))), 'end_date' => date('Y-m-d', strtotime($this->input->post('app_end_date'))), 'que_one' => $this->input->post('remark'), 'que_two' => $this->input->post('remark1'), 'que_three' => $this->input->post('remark2'), 'que_four' => $this->input->post('remark3'), 'que_five' => $this->input->post('remark4'), 'que_six' => $this->input->post('remark5'), 'que_seven' => $this->input->post('remark6'), 'que_eight' => $this->input->post('remark7'), 'que_nine' => $this->input->post('remark8'), 'que_ten' => $this->input->post('remark9'), 'attrib_1' => $this->input->post('attribute'), 'attrib_2' => $this->input->post('attribute1'), 'attrib_3' => $this->input->post('attribute2'), 'attrib_4' => $this->input->post('attribute3'), 'attrib_5' => $this->input->post('attribute4'), 'attrib_6' => $this->input->post('attribute5'), 'comment_1' => $this->input->post('others_a'), 'comment_2' => $this->input->post('others_b'), 'signature' => $this->input->post('1st_signature'), 'status' => 0, 'created_at' => $this->input->post('1st_date') ); var_dump($data); exit; } // Save TCSP remarks. public function remarks_by_tcsp(){ $data = array( 'employee_id' => $this->input->post('employee_tcsp'), 'remarks' => $this->input->post('tcsp_remarks'), 'signature' => $this->input->post('apw_holder_sign'), 'comment' => $this->input->post('remarks_by_tcsp'), 'created_at' => date('Y-m-d', strtotime($this->input->post('apw_date'))) ); $this->Performance_appraisal_model->add_tcsp_remarks($data); $this->db->select('status')->from('tcsp_evaluations')->get()->row(); $this->db->where('employee_id', $_POST['employee_tcsp']); $this->db->update('tcsp_evaluations', array('status' => '1')); $this->session->set_flashdata('success', 'Remarks by TCSP have been saved successfully!'); redirect('Performance_evaluation/tcsp_previous'); } // Save Second level TCSP remarks to the database. public function sec_level_tcsp_rem(){ $data = array( 'employee_id' => $this->input->post('sec_level_tcsp'), 'assessment_result' => $this->input->post('sec_level_tcsp_remarks'), 'signature' => $this->input->post('sec_level_sign'), 'created_at' => date('Y-m-d', strtotime($this->input->post('sec_level_date'))) ); $this->Performance_appraisal_model->add_sec_level_tcsp($data); $this->db->select('status')->from('tcsp_evaluations')->get()->row(); $this->db->where('employee_id', $_POST['sec_level_tcsp']); if(isset($_POST['submit_1'])){ $this->db->update('tcsp_evaluations', array('status' => '3', 'rollback_comment' => $this->input->post('rollback_comment'))); $this->db->where('employee_id', $_POST['sec_level_tcsp']); $this->db->delete('sec_level_tcsp_remarks'); $this->session->set_flashdata('success', '<strong>Success ! </strong> The Roll back operation was successful !'); }else{ $this->db->update('tcsp_evaluations', array('status' => '2')); $this->session->set_flashdata('success', 'Overall Assessment by the CTC staff has been saved successfully.'); } redirect('Performance_evaluation/tcsp_previous'); } // Get province, district, tehsil for selected employee in the dropdown list. public function get_address_tcsps($id = ''){ $tcsp_address = $this->Performance_appraisal_model->get_address_tcsps($id); echo json_encode($tcsp_address); } // -------------------------- Generate PDF --------------------------------------// // Generate PDF, UCPO report. public function print_appraisal($eval_id){ $this->load->library('Pdf'); $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false); $pdf->SetTitle('Performance Appraisal UCPO'); $pdf->SetHeaderMargin(30); $pdf->SetTopMargin(20); $pdf->setFooterMargin(20); $pdf->SetAutoPageBreak(true); $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('Saddam'); $pdf->SetDisplayMode('real', 'default'); $pdf->SetCreator(PDF_CREATOR); $pdf->setFontSubsetting(true); $pdf->setFont('times', '', 12); $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); // Add a page $data['emp'] = $this->Performance_appraisal_model->appraisal_print($eval_id); ob_start(); $pdf->AddPage(); // Data will be loaded to the page here. $html = $this->load->view('generate_pdf', $data, true); $pdf->writeHTML($html, true, false, true, false, ''); ob_clean(); $pdf->Output(md5(time()).'.pdf', 'I'); } // Generate PDF, TCSP report. public function print_appraisal_tcsp($evalu_id){ $this->load->library('Pdf'); $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false); $pdf->SetTitle('Performance Appraisal TCSP'); $pdf->SetHeaderMargin(30); $pdf->SetTopMargin(20); $pdf->setFooterMargin(20); $pdf->SetAutoPageBreak(true); $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('Saddam'); $pdf->SetDisplayMode('real', 'default'); $pdf->SetCreator(PDF_CREATOR); $pdf->setFontSubsetting(true); $pdf->setFont('times', '', 12); $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); // Add a page $data['emp'] = $this->Performance_appraisal_model->appraisal_print_tcsp($evalu_id); ob_start(); $pdf->AddPage(); // Data will be loaded to the page here. $html = $this->load->view('generate_pdf_tcsp', $data, true); $pdf->writeHTML($html, true, false, true, false, ''); ob_clean(); $pdf->Output(md5(time()).'.pdf', 'I'); } } ?><file_sep>/application/views/performance_evaluation/add_ucpos.php <?php /* * Filename: add_ucpos.php * Author: Saddam */ ?> <style type="text/css"> .para p{ padding-top: 12px; color: #ff8d00; } .para{ background: #d6dad282; } </style> <script type="text/javascript"> $(document).ready(function(){ $('.select2').select2(); // Searchable dropdown lists/select boxes. }); </script> <section class="secMainWidth"> <section class="secFormLayout"> <div class="mainInputBg"> <div class="row"> <div class="col-lg-12"> <h3>Add UCPO's | Assign PEO's and AC's</h3> <?php if($success = $this->session->flashdata('success')): ?> <div class="alert alert-success text-center"> <?php echo $success; ?> </div> <?php endif; ?> <form action="<?php if(empty($edit)){ echo base_url('admin_dashboard/save_ucpos'); }else{ echo base_url('admin_dashboard/update_ucpo'); } ?>" method="post"> <input type="hidden" name="emp_id" value="<?php echo $this->uri->segment(3); ?>"> <div class="row"> <div class="col-lg-12"> <table class="table table-responsive"> <tbody> <tr> <td> <label>UCPO Name</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="text" name="ucpo_name" class="form-control" placeholder="UCPO name here..." value="<?php if(!empty($edit)){ echo $edit->name; } ?>"> </div> </div> </td> </tr> <tr> <td> <label>UCPO CNIC</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="text" name="ucpo_cnic" class="form-control" placeholder="UCPO cnic here..." value="<?php if(!empty($edit)){ echo $edit->cnic_name; } ?>"> </div> </div> </td> </tr> <tr> <td> <label>Province</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <select name="ucpo_prov" class="form-control select2"> <option value="<?php if(!empty(@$edit)){ echo $edit->province; ?>" selected> <?php echo $edit->province; } ?></option> <option value="">Select Province...</option> <option value="KP">KP</option> <option value="KP-TD">KP-TD</option> <option value="AJK">AJK</option> <option value="Islamabad">Islamabad</option> <option value="Punjab">Punjab</option> <option value="Balochistan">Balochistan</option> <option value="Sindh">Sindh</option> <option value="Gilgit Baltistan">GBaltistan</option> </select> </div> </div> </td> </tr> <tr> <td> <label>District</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="text" name="ucpo_distt" class="form-control" placeholder="UCPO district here..." value="<?php if(!empty($edit)){ echo $edit->district; } ?>"> </div> </div> </td> </tr> <tr> <td> <label>Tehsil</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="text" name="ucpo_tehsil" class="form-control" placeholder="UCPO tehsil here..." value="<?php if(!empty($edit)){ echo $edit->tehsil; } ?>"> </div> </div> </td> </tr> <tr> <td> <label>UC</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="text" name="ucpo_uc" class="form-control" placeholder="UCPO cnic here..." value="<?php if(!empty($edit)){ echo $edit->uc; } ?>"> </div> </div> </td> </tr> <tr> <td> <label>Assign PEO</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <select name="ucpo_peo" class="form-control select2"> <option value="<?php if(!empty(@$edit)){ echo $edit->cnic_peo; ?>" selected> <?php echo $edit->cnic_peo; } ?></option> <option value="">Select PEO...</option> <?php foreach ($peos as $peo): ?> <option value="<?php echo $peo->peo_cnic; ?>"><?php echo $peo->peo_name; ?></option> <?php endforeach; ?> </select> </div> </div> </td> </tr> <tr> <td> <label>Assign AC</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <select name="ucpo_ac" class="form-control select2"> <option value="<?php if(!empty($edit)){ echo $edit->cnic_ac; ?>" selected> <?php echo $edit->cnic_ac; } ?></option> <option value="">Select AC...</option> <?php foreach ($acs as $ac): ?> <option value="<?php echo $ac->ac_cnic; ?>"><?php echo $ac->ac_name; ?></option> <?php endforeach; ?> </select> </div> </div> </td> </tr> <tr> <td> <label>Password</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="password" name="ucpo_pass" class="form-control" placeholder="UCPO password here..." value="<PASSWORD>"> </div> </div> </td> </tr> <tr> <td> <label>Joining Date</label> </td> <td> <div class="row"> <div class="col-md-offset-3"> <input type="date" name="join_date" class="form-control" value="<?php if(!empty($edit)){ echo date('d-M-y', strtotime($edit->join_date)); } ?>"> </div> </div> </td> </tr> </tbody> </table> </div> </div> <div class="row"> <div class="col-lg-12 text-right"> <a href="javascript:history.go(-1);" class="btn btn-default">Back</a> <?php if(empty($edit)): ?> <button type="submit" class="btn btn-default">Next</button> <?php else: ?> <button type="submit" class="btn btn-default">Update</button> <?php endif; ?> </div> </div> </form> </div> </div> </div> </section> </section><file_sep>/application/models/Performance_appraisal_model.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); /* * Filename: Performance_appraisal_model.php * Filepath: models / performance_appraisal_model.php * Edited by: Saddam */ class Performance_appraisal_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } // Get all performance evaluations, recently added. public function get_performance_evaluation($limit, $offset) { $this->db->select('performance_evaluation.*, ucpo_data.id, ucpo_data.name, ucpo_data.position, ucpo_data.cnic_name, ucpo_data.province, ucpo_data.district, ucpo_data.tehsil, ucpo_data.uc, ucpo_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic'); $this->db->from('performance_evaluation'); $this->db->join('ucpo_data', 'performance_evaluation.employee_id = ucpo_data.id', 'left'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('ucpo_data.cnic_peo', $this->session->userdata('peo_cnic')); $this->db->or_where('ucpo_data.cnic_ac', $this->session->userdata('ac_cnic')); $this->db->limit($limit, $offset); $query = $this->db->get(); return $query->result(); } // Get data for admin. public function get_performance_evaluation_admin($limit, $offset) { $this->db->select('performance_evaluation.*, ucpo_data.id, ucpo_data.name, ucpo_data.position, ucpo_data.cnic_name, ucpo_data.province, ucpo_data.district, ucpo_data.tehsil, ucpo_data.uc, ucpo_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic'); $this->db->from('performance_evaluation'); $this->db->join('ucpo_data', 'performance_evaluation.employee_id = ucpo_data.id'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->limit($limit, $offset); $query = $this->db->get(); return $query->result(); } // Count evaluations. public function count_evaluations(){ return $this->db->from('performance_evaluation')->count_all_results(); } // Get UCPO's by ID. public function get_by_id($eval_id){ $this->db->select('rollback_comment'); $this->db->from('performance_evaluation'); $this->db->where('eval_id', $eval_id); return $this->db->get()->row(); } // Add performance evaluation data to the database, general and PTPP holder's different skills. public function add($data){ $this->db->insert('performance_evaluation', $data); if ($this->db->affected_rows() > 0) { return true; } else { return false; } } // Update performance evaluation if Rolled back. public function update_rolled_back($employee_id = '', $data = ''){ $this->db->where('employee_id', $employee_id); $this->db->update('performance_evaluation', $data); return true; } // Get employees for UCPO's recently evaluated. public function ptpp_employees(){ $this->db->select('performance_evaluation.eval_id, performance_evaluation.employee_id as emp_id, performance_evaluation.created_at, ucpo_data.id, ucpo_data.name, ucpo_data.cnic_name'); $this->db->from('performance_evaluation'); $this->db->join('ucpo_data', 'performance_evaluation.employee_id = ucpo_data.id', 'left'); $this->db->where('ucpo_data.cnic_name', $this->session->userdata('ucpo_cnic')); $this->db->where('employee_id NOT IN(SELECT employee_id FROM ptpp_remarks)'); $query = $this->db->get(); return $query->result(); } // Get employees for AC to evaluate. (UCPO's.) public function get_ptpp(){ $this->db->select('ptpp_remarks.remark_id, ptpp_remarks.employee_id, ucpo_data.id, ucpo_data.name, ucpo_data.cnic_name, ac_data.ac_id, ac_data.ac_cnic'); $this->db->from('ptpp_remarks'); $this->db->join('ucpo_data', 'ptpp_remarks.employee_id = ucpo_data.id', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('ucpo_data.cnic_ac', $this->session->userdata('ac_cnic')); $this->db->where('employee_id NOT IN(SELECT employee_id FROM sec_level_sup_remarks)'); $this->db->group_by('ucpo_data.id'); $query = $this->db->get(); return $query->result(); } // Add data to the database, remarks by the PTPP holder. public function add_ptpp_remarks($data){ $this->db->insert('ptpp_remarks', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Display PTPP holders' remarks public function get_ptpp_remarks($id=''){ $this->db->select('ptpp_remarks.remark_id, ptpp_remarks.employee_id, ptpp_remarks.remarks, ptpp_remarks.signature, ptpp_remarks.comment, ptpp_remarks.created_at'); $this->db->from('ptpp_remarks'); $this->db->where('ptpp_remarks.employee_id', $id); return $this->db->get()->row(); } // Add data to database, remarks the second level supervisor. (Assessment result). public function add_sec_level_remarks($data){ $this->db->insert('sec_level_sup_remarks', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Display second level supervisors' remarks. (Assessment result). public function get_sec_level_remarks($id = ''){ $this->db->select('sec_level_sup_remarks.sec_remark_id, sec_level_sup_remarks.employee_id, sec_level_sup_remarks.assessment_result, sec_level_sup_remarks.signature, sec_level_sup_remarks.created_at'); $this->db->from('sec_level_sup_remarks'); // $this->db->join('xin_employees', 'sec_level_sup_remarks.employee_id = xin_employees.employee_id'); $this->db->where('sec_level_sup_remarks.employee_id', $id); return $this->db->get()->row(); } // Get address for the selected employee (On Change function). [UCPO's]. public function get_address_ucpos($id){ $this->db->select('id, province, district, tehsil, uc'); $this->db->from('ucpo_data'); $this->db->where('id', $id); return $this->db->get()->row(); } // Get address the selected employee (On change function). [TCSP's]. public function get_address_tcsps($id){ $this->db->select('id, province, district, tehsil, uc, cnic_name'); $this->db->from('tcsp_data'); $this->db->where('id', $id); return $this->db->get()->row(); } // Get previously added UCPO's form attributes. public function get_previously_added($id = ''){ // UCPO's data... $this->db->select('*'); $this->db->from('performance_evaluation'); $this->db->where('employee_id', $this->uri->segment(3)); $this->db->limit(1); return $this->db->get()->row(); } // Get previously added TCSP's form attributes. public function get_previously_added_tcsps($id = ''){ // TCSP's data... $this->db->select('*'); $this->db->from('tcsp_evaluations'); $this->db->where('employee_id', $this->uri->segment(3)); $this->db->limit(1); return $this->db->get()->row(); } // Function to Delete selected record from table public function delete_record($id){ $this->db->where('eval_id', $id); $this->db->delete('performance_evaluation'); } // Function to update record in table public function update_record($data, $id){ $this->db->where('eval_id', $id); if( $this->db->update('performance_evaluation',$data)) { return true; } else { return false; } } /* ------------------------------------------------------------------------------- */ // Form data submission for TCSP. // Count all evaluations. public function count_tcsp(){ return $this->db->from('tcsp_evaluations')->count_all_results(); } // Get all evaluations previously made. public function get_tcsp_evaluations($limit = '', $offset = ''){ $this->db->select('tcsp_evaluations.*, tcsp_data.id, tcsp_data.name, tcsp_data.position, tcsp_data.cnic_name, tcsp_data.province, tcsp_data.district, tcsp_data.tehsil, tcsp_data.uc, tcsp_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic'); $this->db->from('tcsp_evaluations'); $this->db->join('tcsp_data', 'tcsp_evaluations.employee_id = tcsp_data.id', 'left'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where(array('tcsp_data.cnic_peo'=> $this->session->userdata('peo_cnic'))); $this->db->or_where(array('tcsp_data.cnic_ac'=> $this->session->userdata('ac_cnic'))); $this->db->limit($limit, $offset); $query = $this->db->get(); return $query->result(); } // Get for admin public function get_tcsp_evaluations_admin($limit = '', $offset = ''){ $this->db->select('tcsp_evaluations.*, tcsp_data.id, tcsp_data.name, tcsp_data.position, tcsp_data.cnic_name, tcsp_data.province, tcsp_data.district, tcsp_data.tehsil, tcsp_data.uc, tcsp_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic'); $this->db->from('tcsp_evaluations'); $this->db->join('tcsp_data', 'tcsp_evaluations.employee_id = tcsp_data.id', 'left'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->limit($limit, $offset); $query = $this->db->get(); return $query->result(); } // Insert data into the database, TCSP form data. public function insert_tcsp_evaluations($data){ $this->db->insert('tcsp_evaluations', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Get TCSP's by ID. public function get_tcsp_by_id($evalu_id){ $this->db->select('evalu_id, rollback_comment'); $this->db->from('tcsp_evaluations'); $this->db->where('evalu_id', $evalu_id); return $this->db->get()->row(); } // Update TCSP evaluations if rolled back. public function update_tcsp_rolled_back($employee_id = '', $data = ''){ $this->db->where('employee_id', $employee_id); $this->db->update('tcsp_evaluations', $data); return true; } // Get TCSP employees to list them in the dropdown for TCSP remarks. public function tcsp_employees(){ $this->db->select('tcsp_evaluations.evalu_id, tcsp_evaluations.employee_id as empl_id, tcsp_evaluations.created_at, ucpo_data.id, ucpo_data.name, ucpo_data.cnic_name, ucpo_data.cnic_ac'); $this->db->from('tcsp_evaluations'); $this->db->join('ucpo_data', 'tcsp_evaluations.employee_id = ucpo_data.id'); $this->db->where('ucpo_data.cnic_ac', $this->session->userdata('ac_cnic')); $this->db->where('employee_id NOT IN(SELECT employee_id FROM tcspp_remarks)'); return $this->db->get()->result(); } // Get employees for AC to evaluate. (TCSP's.) public function get_tcsps(){ $this->db->select('tcsp_evaluations.evalu_id, tcsp_evaluations.employee_id, tcsp_data.id, tcsp_data.name, tcsp_data.cnic_name'); $this->db->from('tcsp_evaluations'); $this->db->join('tcsp_data', 'tcsp_evaluations.employee_id = tcsp_data.id', 'left'); $this->db->where('tcsp_data.cnic_name', $this->session->userdata('tcsp_cnic')); $this->db->where('employee_id NOT IN(SELECT employee_id FROM tcsp_remarks)'); return $this->db->get()->result(); } // Get for AC. public function get_tcsps_for_ac(){ $this->db->select('tcsp_evaluations.evalu_id, tcsp_evaluations.employee_id, tcsp_data.id, tcsp_data.name, tcsp_data.cnic_ac'); $this->db->from('tcsp_evaluations'); $this->db->join('tcsp_data', 'tcsp_evaluations.employee_id = tcsp_data.id', 'left'); $this->db->where('tcsp_data.cnic_ac', $this->session->userdata('ac_cnic')); $this->db->where('employee_id NOT IN(SELECT employee_id FROM sec_level_tcsp_remarks)'); return $this->db->get()->result(); } // Get remarks by TCSP. public function get_tcsp_remarks($id=''){ $this->db->select('tcsp_remarks.remarks_id, tcsp_remarks.employee_id, tcsp_remarks.remarks, tcsp_remarks.signature, tcsp_remarks.comment, tcsp_remarks.created_at'); $this->db->from('tcsp_remarks'); $this->db->where('employee_id', $id); return $this->db->get()->row(); } // Save TCSP remarks to the database. public function add_tcsp_remarks($data){ $this->db->insert('tcsp_remarks', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Get Second level TCSP remarks. public function get_sec_level_tcsp($id=''){ $this->db->select('sec_level_tcsp_remarks.sec_tcsp_rem_id, sec_level_tcsp_remarks.employee_id, sec_level_tcsp_remarks.assessment_result, sec_level_tcsp_remarks.signature, sec_level_tcsp_remarks.created_at'); $this->db->from('sec_level_tcsp_remarks'); // $this->db->join('xin_employees', 'sec_level_tcsp_remarks.employee_id = xin_employees.employee_id'); $this->db->where('employee_id', $id); return $this->db->get()->row(); } // Save second level tcsp remarks to the database. public function add_sec_level_tcsp($data){ $this->db->insert('sec_level_tcsp_remarks', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // --------------------------------------------------------------------------- // Export to Excel.. // Export to excel using Codeigniter's library phpSpreadsheet. [TCSP's data]. public function export_excel(){ $this->db->select('tcsp_evaluations.*, tcsp_data.id, tcsp_data.name, tcsp_data.position, tcsp_data.cnic_name, tcsp_data.province, tcsp_data.district, tcsp_data.tehsil, tcsp_data.uc, tcsp_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic, tcsp_remarks.employee_id as tcsp_id, tcsp_remarks.comment, sec_level_tcsp_remarks.employee_id as sec_tcsp_id, sec_level_tcsp_remarks.assessment_result'); $this->db->from('tcsp_evaluations'); // $this->db->limit(10); $this->db->join('tcsp_data', 'tcsp_evaluations.employee_id = tcsp_data.id'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->join('tcsp_remarks', 'tcsp_data.id = tcsp_remarks.employee_id', 'left'); $this->db->join('sec_level_tcsp_remarks', 'tcsp_data.id = sec_level_tcsp_remarks.employee_id', 'left'); $this->db->group_by('tcsp_data.id'); $this->db->query('SET SQL_BIG_SELECTS=1'); return $this->db->get()->result_array(); } // Export to Excel [UCPO's data]. public function export_excel_ucpos() { $this->db->select('performance_evaluation.*, ucpo_data.id, ucpo_data.name, ucpo_data.position, ucpo_data.cnic_name, ucpo_data.province, ucpo_data.district, ucpo_data.tehsil, ucpo_data.uc, ucpo_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic, ptpp_remarks.employee_id as ptpp_id, ptpp_remarks.comment, sec_level_sup_remarks.employee_id as sup_id, sec_level_sup_remarks.assessment_result'); $this->db->from('performance_evaluation'); // $this->db->limit(10); $this->db->join('ucpo_data', 'performance_evaluation.employee_id = ucpo_data.id', 'left'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->join('ptpp_remarks', 'ucpo_data.id = ptpp_remarks.employee_id', 'left'); $this->db->join('sec_level_sup_remarks', 'ucpo_data.id = sec_level_sup_remarks.employee_id', 'left'); $this->db->group_by('ucpo_data.id'); $this->db->query('SET SQL_BIG_SELECTS=1'); return $this->db->get()->result_array(); } // --------------------------------------------------------------------------------- // Summary dashboard. For Administrators... // count number of all the ucpo's in the database. public function all_ucpos(){ return $this->db->from('ucpo_data')->count_all_results(); // Count all TCSP's. } // count number of all the tcsp's in the database. public function all_tcsps(){ return $this->db->from('tcsp_data')->count_all_results(); // Count all UCPO's. } // Count no. of UCPO's pending from UCPOS. public function count_pending_from_ucpos(){ return $this->db->where('employee_id NOT IN(SELECT employee_id FROM ptpp_remarks)')->from('performance_evaluation')->count_all_results(); } // Count no. of TCSP's pending from TCSP's. public function count_pending_from_tcsps(){ return $this->db->where('employee_id NOT IN(SELECT employee_id FROM tcsp_remarks)')->from('tcsp_evaluations')->count_all_results(); } // Count number of all UCPO's evaluated by PEO. public function count_ucpos_pending(){ return $this->db->where('id NOT IN(SELECT employee_id FROM ptpp_remarks)')->from('ucpo_data')->count_all_results(); // returns no. of ucpo's of which id not in PTPP remarks table. } // Count number of UCPO's pending for AC. public function count_ac_ucpos_pending(){ return $this->db->where('employee_id NOT IN(SELECT employee_id FROM sec_level_sup_remarks)')->from('ptpp_remarks')->count_all_results(); // returns no. of ucpo not evaluated by AC. } // Count no. of UCPO's completed. public function completed_ucpos(){ return $this->db->from('sec_level_sup_remarks')->count_all_results(); } // Count no. of TCSP's completed. public function completed_tcsps(){ return $this->db->from('sec_level_tcsp_remarks')->count_all_results(); } // Count number of all TCSP's. public function count_tcsps_pending(){ return $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_remarks)')->from('tcsp_data')->count_all_results(); } // Count number of TCSP's pending for AC. public function count_ac_tcsps_pending(){ return $this->db->where('employee_id NOT IN(SELECT employee_id FROM sec_level_tcsp_remarks)')->from('tcsp_remarks')->count_all_results(); } // Count UCPO's pending in list TCSPs. public function ucpos_pending(){ return $this->db->where('id NOT IN(SELECT employee_id FROM performance_evaluation)')->from('ucpo_data')->count_all_results(); } // Get summary UCPO's. public function get_summary_ucpos($limit, $offset){ $this->db->select('ucpo_data.id, ucpo_data.name, ucpo_data.cnic_name, ucpo_data.cnic_peo, ucpo_data.cnic_ac, ucpo_data.province, peo_data.peo_cnic, peo_data.peo_name, ac_data.ac_cnic, ac_data.ac_name'); $this->db->from('ucpo_data'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('id NOT IN(SELECT employee_id FROM performance_evaluation)'); $this->db->where('id NOT IN(SELECT employee_id FROM ptpp_remarks)'); $this->db->where('ucpo_data.status', 0); $this->db->order_by('ucpo_data.id', 'DESC'); $this->db->limit($limit, $offset); return $this->db->get()->result(); } // Count TCSPs pending in list TCSPs. public function tcsps_pending(){ return $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_evaluations)')->from('tcsp_data')->count_all_results(); } // Get summary TCSP's. public function get_summary_tcsps($limit, $offset){ $this->db->select('tcsp_data.id, tcsp_data.name, tcsp_data.cnic_name, tcsp_data.cnic_peo, tcsp_data.cnic_ac, tcsp_data.province, peo_data.peo_cnic, peo_data.peo_name, ac_data.ac_cnic, ac_data.ac_name'); $this->db->from('tcsp_data'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_evaluations)'); $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_remarks)'); $this->db->where('tcsp_data.status', 0); $this->db->order_by('tcsp_data.id', 'DESC'); $this->db->limit($limit, $offset); return $this->db->get()->result(); } // Search for UCPO's public function search_ucpos($search = ''){ $this->db->select('ucpo_data.id, ucpo_data.name, ucpo_data.cnic_name, ucpo_data.cnic_peo, ucpo_data.cnic_ac, ucpo_data.province, peo_data.peo_cnic, peo_data.peo_name, ac_data.ac_cnic, ac_data.ac_name'); $this->db->from('ucpo_data'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->like('peo_data.peo_name', $search); $this->db->or_like('ac_data.ac_name', $search); $this->db->where('id NOT IN(SELECT employee_id FROM performance_evaluation)'); $this->db->where('id NOT IN(SELECT employee_id FROM ptpp_remarks)'); $this->db->where('ucpo_data.status', 0); return $this->db->get()->result(); } // Search for TCSP's. public function search_tcsps($search = ''){ $this->db->select('tcsp_data.id, tcsp_data.name, tcsp_data.cnic_name, tcsp_data.cnic_peo, tcsp_data.cnic_ac, tcsp_data.province, peo_data.peo_cnic, peo_data.peo_name, ac_data.ac_cnic, ac_data.ac_name'); $this->db->from('tcsp_data'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->like('peo_data.peo_name', $search); $this->db->or_like('ac_data.ac_name', $search); $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_evaluations)'); $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_remarks)'); $this->db->where('tcsp_data.status', 0); return $this->db->get()->result(); } // ------- Get all PEO's & AC's to list them in the UCPO's addtion form -----------------// public function get_peos(){ $this->db->select('peo_id, peo_name, peo_cnic'); $this->db->from('peo_data'); return $this->db->get()->result(); } public function get_acs(){ $this->db->select('ac_id, ac_name, ac_cnic'); $this->db->from('ac_data'); return $this->db->get()->result(); } //--------------------- Add PEO's, AC's, UCPO's and TCSP's -------------------------------// // Add PEO's public function add_peos($data){ $this->db->insert('peo_data', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Add AC's public function add_acs($data){ $this->db->insert('ac_data', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Add UCPO's. public function add_ucpos($data){ $this->db->insert('ucpo_data', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Add TCSP's. public function add_tcsps($data){ $this->db->insert('tcsp_data', $data); if($this->db->affected_rows() > 0){ return true; }else{ return false; } } // Edit UCPO. public function edit_ucpo($id){ $this->db->select('*'); $this->db->from('ucpo_data'); $this->db->where('id', $id); return $this->db->get()->row(); } // Update UCPO. public function update_ucpo($id = '', $data = ''){ $this->db->where('id', $id); $this->db->update('ucpo_data', $data); return true; } // Delete UCPO. public function delete_ucpo($id){ $this->db->where('id', $id); $this->db->delete('ucpo_data'); return true; } // Edit TCSP. public function edit_tcsp($id){ $this->db->select('*'); $this->db->from('tcsp_data'); $this->db->where('id', $id); return $this->db->get()->row(); } // Update TCSP. public function update_tcsp($id = '', $data = ''){ $this->db->where('id', $id); $this->db->update('tcsp_data', $data); return true; } // Delete TCSP public function delete_tcsp($id){ $this->db->where('id', $id); $this->db->delete('tcsp_data'); return true; } // ---------------------------------- Get data for PDF --------------------------------- // // Print appraisal, UCPO. public function appraisal_print($eval_id){ $this->db->select('performance_evaluation.*, ucpo_data.id, ucpo_data.name, ucpo_data.position, ucpo_data.cnic_name, ucpo_data.province, ucpo_data.district, ucpo_data.tehsil, ucpo_data.uc, ucpo_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic'); $this->db->from('performance_evaluation'); $this->db->join('ucpo_data', 'performance_evaluation.employee_id = ucpo_data.id'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('eval_id', $eval_id); // $this->db->or_where('ucpo_data.cnic_ac', $this->session->userdata('ac_cnic')); $query = $this->db->get(); return $query->row(); } // Print appraisal report, TCSP. public function appraisal_print_tcsp($evalu_id){ $this->db->select('tcsp_evaluations.*, tcsp_data.id, tcsp_data.name, tcsp_data.position, tcsp_data.cnic_name, tcsp_data.province, tcsp_data.district, tcsp_data.tehsil, tcsp_data.uc, tcsp_data.join_date, peo_data.peo_id, peo_data.peo_name, peo_data.peo_cnic, ac_data.ac_id, ac_data.ac_name, ac_data.ac_cnic'); $this->db->from('tcsp_evaluations'); $this->db->join('tcsp_data', 'tcsp_evaluations.employee_id = tcsp_data.id'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('evalu_id', $evalu_id); $query = $this->db->get(); return $query->row(); } // ----------------------- Export report to Excel ---------------------- // // UCPOs. public function ucpos_report(){ $this->db->select('ucpo_data.id, ucpo_data.name, ucpo_data.cnic_name, ucpo_data.cnic_peo, ucpo_data.cnic_ac, ucpo_data.province, ucpo_data.district, ucpo_data.uc, peo_data.peo_cnic, peo_data.peo_name, ac_data.ac_cnic, ac_data.ac_name'); $this->db->from('ucpo_data'); $this->db->join('peo_data', 'ucpo_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'ucpo_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('id NOT IN(SELECT employee_id FROM performance_evaluation)'); $this->db->where('id NOT IN(SELECT employee_id FROM ptpp_remarks)'); return $this->db->get()->result_array(); } // TCSPs. public function tcsps_report(){ $this->db->select('tcsp_data.id, tcsp_data.name, tcsp_data.cnic_name, tcsp_data.cnic_peo, tcsp_data.cnic_ac, tcsp_data.province, tcsp_data.district, tcsp_data.uc, peo_data.peo_cnic, peo_data.peo_name, ac_data.ac_cnic, ac_data.ac_name'); $this->db->from('tcsp_data'); $this->db->join('peo_data', 'tcsp_data.cnic_peo = peo_data.peo_cnic', 'left'); $this->db->join('ac_data', 'tcsp_data.cnic_ac = ac_data.ac_cnic', 'left'); $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_evaluations)'); $this->db->where('id NOT IN(SELECT employee_id FROM tcsp_remarks)'); return $this->db->get()->result_array(); } } ?><file_sep>/application/views/performance_evaluation/list_tcsps.php <section class="secMainWidthFilter" style="padding: 0px;margin-top: -40px;"> <section class="secIndexTable margint-top-0"> <section class="secIndexTable"> <div class="col-lg-12"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-8"> <div class="tabelHeading"> <h3> <?php if(empty($search_results)): ?> list of TCSPs | <a href="javascript:history.go(-1);" class="btn btn-primary btn-xs"> <i class="fa fa-angle-double-left"></i> Back</a> <a href="<?php echo base_url('export_excel/tcsps_report'); ?>" class="btn btn-success btn-xs">Export Excel</a> <?php elseif(!empty($search_results)): ?> search results | <a href="javascript:history.go(-1);" class="btn btn-primary btn-xs"> <i class="fa fa-angle-double-left"></i> Back</a> <?php endif; ?> </h3> </div> </div> <div class="col-md-4"> <form action="<?php echo base_url('admin_dashboard/search_tcsps'); ?>" method="get" style="margin-top: 14px; padding-right: 12px;"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search by PEO / AC name" autocomplete="off" required="" name="search_record"> <div class="input-group-btn"> <button class="btn btn-default" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> </form> </div> </div> <?php if($success = $this->session->flashdata('success')): ?> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="alert alert-success text-center"> <?php echo $success; ?> </div> </div> </div> <?php endif; ?> <div class="row"> <div class="col-md-12"> <div class="tableMain"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>name of TCSP</th> <th>TCSP CNIC</th> <th>province</th> <th>name of PEO</th> <th>PEO CNIC</th> <th>name of AC</th> <th>AC CNIC</th> <th>status | Actions</th> </tr> </thead> <?php if(empty($search_results)): ?> <tbody> <?php if(!empty($pending_tcsps)): foreach ($pending_tcsps as $pending): ?> <tr> <td><?php echo $pending->name; ?></td> <td><?php echo $pending->cnic_name; ?></td> <td><?php echo $pending->province; ?></td> <td><?php echo $pending->peo_name; ?></td> <td><?php echo $pending->cnic_peo; ?></td> <td><?php echo $pending->ac_name; ?></td> <td><?php echo $pending->cnic_ac; ?></td> <td> <button class="btn btn-info btn-xs">Pending...</button> <a href="<?php echo base_url(); ?>admin_dashboard/edit_tcsp/<?php echo $pending->id; ?>" class="btn btn-primary btn-xs">Edit</a> <a href="<?php echo base_url(); ?>admin_dashboard/delete_tcsp/<?php echo $pending->id; ?>" class="btn btn-danger btn-xs" onclick="javascript:return confirm('Are you sure to delete ?');">Delete</a> </td> </tr> <?php endforeach; endif; ?> </tbody> <?php elseif(!empty($search_results)): ?> <tbody> <?php foreach ($search_results as $result): ?> <tr> <td><?php echo $result->name; ?></td> <td><?php echo $result->cnic_name; ?></td> <td><?php echo $result->province; ?></td> <td><?php echo $result->peo_name; ?></td> <td><?php echo $result->cnic_peo; ?></td> <td><?php echo $result->ac_name; ?></td> <td><?php echo $result->cnic_ac; ?></td> <td> <button class="btn btn-info btn-xs">Pending...</button> <a href="<?php echo base_url(); ?>admin_dashboard/edit_tcsp/<?php echo $result->id; ?>" class="btn btn-primary btn-xs">Edit</a> <a href="<?php echo base_url(); ?>admin_dashboard/delete_tcsp/<?php echo $result->id; ?>" class="btn btn-danger btn-xs" onclick="javascript:return confirm('Are you sure to delete ?');">Delete</a> </td> </tr> <?php endforeach; endif; ?> <?php if(empty($search_results) AND empty($pending_tcsps)): ?> <div class="alert alert-danger text-center col-md-10 col-md-offset-1"> <strong>Aww snap! </strong> We couldn't find what you need right now! </div> <?php endif; ?> </tbody> </table> </div> </div> </div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-10 text-center"> <?php if(empty($search_results) AND !empty($pending_tcsps)){ echo $this->pagination->create_links(); } ?> </div> <div class="col-md-1"></div> </div> </div> </div> </section> </section> </section><file_sep>/README.md # performance_appraisals This repository has been created for the project titled "Performance Appraisals" where employees will be evlauated by their supervisors. Besides the employees will also be able to review all the comments and thoughts given by their supervisors and forward it to the team lead where their three months performance will be evaluated and decision will be taken for them to extend their contracts. If the employees fulfills the requirements and complete their tasks in time, then they'll surely be given contract extension otherwise not. This system is basically created for such purpose. Suggestions and contributions are welcome. Besides, this is an open-source project, you can download and modify the code according to your requirements. -Contact me for further detail. <file_sep>/application/views/generate_pdf.php <!DOCTYPE html> <html> <head> <title>Generate PDF</title> <style type="text/css"> table#skills{ text-align: center; } table#attributes{ text-align: center; } </style> </head> <body> <p align="center"><strong>Performance Evaluation Form</strong></p> <strong>I. General</strong><br> <table border="1"> <tbody> <tr> <td>Name</td> <td><?php echo $emp->name; ?></td> </tr> <tr> <td>Position</td> <td><?php echo $emp->position; ?></td> </tr> <tr> <td>CNIC</td> <td><?php echo $emp->cnic_name; ?></td> </tr> <tr> <td>Duty station (UC / District / Province)</td> <td><?php echo $emp->uc.', '.$emp->district.', '.$emp->province; ?></td> </tr> <tr> <td>Evaluation Period</td> <td> <?php echo date('M d, Y', strtotime($emp->start_date)); ?> <strong>Till</strong> <?php echo date('M d, Y', strtotime($emp->end_date)); ?> </td> </tr> </tbody> </table><br><br> <strong>II. PTPP Technical Skills:-</strong><br> <table border="1" id="skills"> <thead> <tr> <th>S No.</th> <th>Description</th> <th>Job being done to the best of ability; desired results obtained</th> <th>Job being done to the best/good of ability; with mixed results (needs improvement)</th> <th>Work inadequately done; results unsatisfactory</th> </tr> </thead> <tbody> <tr> <td>1)</td> <td>UC/Area level Micro-plans development and desk revision</td> <td><?php if($emp->que_one == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_one == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_one == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>2)</td> <td>UC / Area level Micro-plans field validation</td> <td><?php if($emp->que_two == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_two == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_two == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>3)</td> <td>Status of selection of the house to house vaccination teams</td> <td><?php if($emp->que_three == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_three == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_three == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>4)</td> <td>Training of the vaccination teams</td> <td><?php if($emp->que_four == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_four == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_four == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>5)</td> <td>Training of the UC supervisors (Area In-charges)</td> <td><?php if($emp->que_five == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_five == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_five == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>6)</td> <td>Pre campaign data collection, collation and timely transmission to the next level</td> <td><?php if($emp->que_six == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_six == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_six == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>7)</td> <td>Data collection, collation and timely transmission to the next level during the campaign</td> <td><?php if($emp->que_seven == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_seven == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_seven == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td>8)</td> <td>Corrective measures following the identification of the gaps</td> <td><?php if($emp->que_eight == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->que_eight == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->que_eight == '1'){ echo "Yes"; } ?></td> </tr> </tbody> </table><br><br><br><br><br><br><br><br> <strong>III. PTPP Holder's Attributes</strong><br> <table border="1" id="attributes"> <thead> <tr> <th></th> <th>Satisfactory</th> <th>Needs Improvement</th> <th>Unsatisfactory</th> </tr> </thead> <tbody> <tr> <td align="left">Reliability</td> <td><?php if($emp->attrib_1 == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_1 == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_1 == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td align="left">Work independently with minimal supervision</td> <td><?php if($emp->attrib_2 == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_2 == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_2 == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td align="left">Punctuality</td> <td><?php if($emp->attrib_3 == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_3 == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_3 == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td align="left">Initiative</td> <td><?php if($emp->attrib_4 == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_4 == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_4 == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td align="left">Good team player</td> <td><?php if($emp->attrib_5 == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_5 == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_5 == '1'){ echo "Yes"; } ?></td> </tr> <tr> <td align="left">Familiarity with WHO required procedures</td> <td><?php if($emp->attrib_6 == '3'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_6 == '2'){ echo "Yes"; } ?></td> <td><?php if($emp->attrib_6 == '1'){ echo "Yes"; } ?></td> </tr> </tbody> </table><br><br><hr> <strong>IV. Others</strong><br> <p>Exceptional accomplishment: <br><?php echo $emp->comment_1; ?></p><br> <p>Overall assessment: <br><?php echo $emp->comment_2; ?></p><hr> <?php if(!empty($ptpp_remarks = $this->Performance_appraisal_model->get_ptpp_remarks($emp->employee_id))): ?> <strong>PTPP Remarks</strong> <p><?php echo $ptpp_remarks->remarks; ?></p> <strong>PTPP Comments</strong> <p><?php echo $ptpp_remarks->comment.'</p>'; endif; ?><hr> <?php if(!empty($sup_remarks = $this->Performance_appraisal_model->get_sec_level_remarks($emp->employee_id))): ?> <strong>Second Level Supervisor Remarks</strong> <p><?php echo $sup_remarks->assessment_result; endif; ?></p> </body> </html><file_sep>/application/views/performance_evaluation/recent_tcsp.php <?php /* * Filename: recent_tcsp.php * Filepath: views / performance_evaluation / recent_tcsp.php * Author: Saddam */ ?> <style type="text/css"> .ui-datepicker { display: none !important; } .form-control.ddfield { height: 36px !important; width: 300px; border: 1px solid #ccc; } .inputfield { width: 300px; margin-top: -6px; padding: 10px; line-height: 1rem; background-color: #f6f7f8; border: 1px solid #e1e4e7; } .datefldset { background: none !important; border: 0px !important; } .lablewidth { width: 180px; text-align: right; font-size: 15px; } </style> <style type="text/css"> .breadcrumb.no-bg { display: none; } h4 { display: none; } </style> <script type="text/javascript"> $(document).ready(function() { $('#contact_list1').DataTable(); }); $(document).ready(function() { $('#contact_list2').DataTable(); }); </script> <br><br> <div class="container-fluid"> <section class="secMainWidth" style="padding: 0px;margin-top: -40px;"> <section class="secIndexTable"> <div class="mainTableWhite"> <div class="row"> <div class="col-md-10"> <div class="tabelHeading"> <?php $peo_session = $this->session->userdata('peo_cnic'); $ac_session = $this->session->userdata('ac_cnic'); $ucpo_session = $this->session->userdata('ucpo_cnic'); $tcsp_session = $this->session->userdata('tcsp_cnic'); $admin_session = $this->session->userdata('admin_cnic'); ?> <h3>performance evaluation by first supervisor - PEO</small> | <small>Now Logged in: <strong> <?php if($peo_session){ echo $peo_session .' | PEO'; } ?> <?php if($ac_session){ echo $ac_session .' | AC'; } ?> <?php if($ucpo_session){ echo $ucpo_session .' | UCPO'; } ?> <?php if($tcsp_session){ echo $tcsp_session .' | TCSP'; } ?> <?php if($admin_session){ echo $admin_session .' | Admin'; } ?> </strong> </small> | <small> <a href="javascript:history.go(-1);"> <div class="label label-warning"> <i class="fa fa-angle-double-left"></i> back </div> </a>&nbsp; <a href="<?= base_url('Performance_evaluation/tcsp_evaluation'); ?>"> <div class="label label-primary"> <i class="fa fa-plus"></i> add new evaluation </div> </a>&nbsp; <a href="<?php echo base_url('Export_excel/createExcel'); ?>"> <div class="label label-success">Export to Excel</div> </a> </small> </h3> </div> </div> <div class="col-md-1"> <div class="tabelHeading"> </div> </div> </div> <?php if($success = $this->session->flashdata('success')): ?> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="alert alert-success alert-dismissible"> <a href="#" class="close" aria-lable="close" data-dismiss="alert">&times;</a> <p class="text-center"><?php echo $success; ?></p> </div> </div> </div> <?php endif; ?> <div class="row"> <div class="col-md-12"> <div class="tableMain"> <div class="table-responsive"> <table class="table table-condensed"> <thead> <tr> <th>emp iD</th> <th>name</th> <th>position</th> <th>province</th> <th>district</th> <th>tehsil</th> <th>union council</th> <th>CNIC</th> <th>Joining date</th> <th>PEO</th> <th>AC</th> <th>evaluation date</th> <th>status</th> </tr> </thead> <tbody id="filter_results"> <?php foreach($recent_tcsp as $rec_evals): ?> <?php $rollback_comment = $this->Performance_appraisal_model->get_tcsp_by_id($rec_evals->evalu_id); ?> <tr> <td> <a href="<?php if($rec_evals->status == 3 AND $peo_session){ echo base_url("performance_evaluation/tcsp_evaluation/{$rec_evals->employee_id}"); } ?>">CTC-0<?php echo $rec_evals->employee_id; ?></a> </td> <td> <a href="#" data-toggle="modal" data-target="#evaluationDetail<?= $rec_evals->evalu_id; ?>"> <?php echo $rec_evals->name; ?> </a> <div class="modal fade" id="evaluationDetail<?= $rec_evals->evalu_id; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <!--Header--> <div class="modal-header"> <h4 style="display: inline-block;" class="modal-title" id="myModalLabel">Evaluation Form made for <strong><?php echo $rec_evals->name; ?></strong></h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <!--Body--> <div class="modal-body"> <div class="row"> <div class="col-md-7"> <strong>PTPP holder's Technical Skills</strong><hr> <div class="row"> <div class="col-md-10"> <strong>Questions provided.</strong> </div> <div class="col-md-2"> <strong>Remarks</strong> </div> </div><br> <div class="row"> <div class="col-md-10"> <small>1. UC/Area level Micro-plans development and desk revision</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_one == 3){ echo 'Best'; }elseif($rec_evals->que_one == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>2. UC / Area level Micro-plans field validation</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_two == 3){ echo 'Best'; }elseif($rec_evals->que_two == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>3. Status of selection of the house to house vaccination teams</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_three == 3){ echo 'Best'; }elseif($rec_evals->que_three == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>4. % of teams training attended</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_four == 3){ echo 'Best'; }elseif($rec_evals->que_four == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>5. Training of the UC supervisors (Area In-charges)</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_five == 3){ echo 'Best'; }elseif($rec_evals->que_five == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>6. Pre campaign data collection, collation and timely transmission to the next level % timeliness and % completeness</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_six == 3){ echo 'Best'; }elseif($rec_evals->que_six == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>7. Data collection, collation and timely transmission to the next level during the campaign % timeliness and % completeness</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_seven == 3){ echo 'Best'; }elseif($rec_evals->que_seven == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>8. Corrective measures following the identification of the gaps. Number of critical situations handled</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_eight == 3){ echo 'Best'; }elseif($rec_evals->que_eight == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>9. Ensure data collection from the field with more than 95% Post Campaign coverages through extensive monitoring in the field by doing LQAS & Market Surveys</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_nine == 3){ echo 'Best'; }elseif($rec_evals->que_nine == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> <div class="row"> <div class="col-md-10"> <small>10. To establish the community AFP Surveillance in his area of assignment through regular health facility visits and ensure that the zero reports are timely been submitted</small> </div> <div class="col-md-2"> <?php if($rec_evals->que_ten == 3){ echo 'Best'; }elseif($rec_evals->que_ten == 2){ echo 'Fair'; }else{ echo 'Bad'; } ?> </div> </div> </div> <div class="col-md-5"> <strong>PTPP holder's Attributes</strong><hr> <div class="row"> <div class="col-md-8"> <strong>Attributes provided</strong> </div> <div class="col-md-4"> <strong>Remarks</strong> </div> </div><br> <div class="row"> <div class="col-md-8"> <small>Reliability</small> </div> <div class="col-md-4"> <?php if($rec_evals->attrib_1 == '3'){ echo 'Satisfactory'; }elseif($rec_evals->attrib_1 == '2'){ echo 'Needs Improvement'; }else{ echo 'Unsatisfactory'; } ?> </div> </div> <div class="row"> <div class="col-md-8"> <small>Work independently with minimal supervision</small> </div> <div class="col-md-4"> <?php if($rec_evals->attrib_2 == '3'){ echo 'Satisfactory'; }elseif($rec_evals->attrib_2 == '2'){ echo 'Needs Improvement'; }else{ echo 'Unsatisfactory'; } ?> </div> </div> <div class="row"> <div class="col-md-8"> <small>Punctuality</small> </div> <div class="col-md-4"> <?php if($rec_evals->attrib_3 == '3'){ echo 'Satisfactory'; }elseif($rec_evals->attrib_3 == '2'){ echo 'Needs Improvement'; }else{ echo 'Unsatisfactory'; } ?> </div> </div> <div class="row"> <div class="col-md-8"> <small>Initiative</small> </div> <div class="col-md-4"> <?php if($rec_evals->attrib_4 == '3'){ echo 'Satisfactory'; }elseif($rec_evals->attrib_4 == '2'){ echo 'Needs Improvement'; }else{ echo 'Unsatisfactory'; } ?> </div> </div> <div class="row"> <div class="col-md-8"> <small>Good team player</small> </div> <div class="col-md-4"> <?php if($rec_evals->attrib_5 == '3'){ echo 'Satisfactory'; }elseif($rec_evals->attrib_5 == '2'){ echo 'Needs Improvement'; }else{ echo 'Unsatisfactory'; } ?> </div> </div> <div class="row"> <div class="col-md-8"> <small>Familiarity with WHO required procedures</small> </div> <div class="col-md-4"> <?php if($rec_evals->attrib_6 == '3'){ echo 'Satisfactory'; }elseif($rec_evals->attrib_6 == '2'){ echo 'Needs Improvement'; }else{ echo 'Unsatisfactory'; } ?> </div> </div> </div> </div><hr> <div class="row"> <div class="col-md-12"> <h3>Others</h3> </div> </div> <div class="row"> <div class="col-md-6"> <strong>Exceptional Accomplishment</strong> <p><?php echo $rec_evals->comment_1; ?></p> <strong>Overall Assessment</strong> <p><?php echo $rec_evals->comment_2; ?></p> </div> <div class="col-md-6 text-right"> <strong>Supervisor's Detail</strong><br><br> <strong>Name: </strong><?= $rec_evals->signature; ?><br> <strong>Title: </strong> Polio Eradication Officer <br> <strong>Signature: </strong><?= $rec_evals->signature; ?><br> <strong>Date: </strong><?= date('M d, Y', strtotime($rec_evals->created_at)); ?> </div> </div><hr> <div class="row"> <div class="col-md-6"> <?php if(!empty($recent_tcsp = $this->Performance_appraisal_model->get_tcsp_remarks($rec_evals->employee_id))): ?> <strong>APW Remarks</strong><br><br> <?= $recent_tcsp->remarks; ?><br> <strong>Comment: </strong><?= $recent_tcsp->comment; ?> </div> <div class="col-md-6 text-right"> <strong>APW Holder's Detail</strong><br><br> <strong>Name: </strong><?= $recent_tcsp->signature; ?><br> <strong>Signature: </strong><?= $recent_tcsp->signature; ?><br> <strong>Date: </strong><?= date('M d, Y', strtotime($recent_tcsp->created_at)); else: ?> </div> <div class="col-md-12"> <div class="alert alert-danger"> <p class="text-center"><strong>Oops! </strong> APW Holder haven't evaluated the employee "<strong><?= $rec_evals->name; ?></strong>" yet. </p> </div> <?php endif; ?> </div> </div><hr> <div class="row"> <div class="col-md-6"> <?php if(!empty($recent_sec_level = $this->Performance_appraisal_model->get_sec_level_tcsp($rec_evals->employee_id))): ?> <strong>Remarks by Second Level Supervisor</strong><br><br> <?= $recent_sec_level->assessment_result; ?> <?php if($recent_sec_level->assessment_result == 'Satisfactory'): ?> - Contract recommended for extension. <?php elseif($recent_sec_level->assessment_result == 'Unsatisfactory'): ?> - Contract to be terminated. <?php elseif($recent_sec_level->assessment_result == 'Needs Improvement'): ?> - Contract to be re-evaluated after 3 months. <?php elseif($recent_sec_level->assessment_result == 'Work performed inadequately'): ?> - PTPP holder to be issued a warning/advice. <?php endif; ?> </div> <div class="col-md-6 text-right"> <strong>Second level supervisor detail</strong><br><br> <strong>Name: </strong><?= $recent_sec_level->signature; ?><br> <strong>Title: </strong>Area Coordinator<br> <strong>Signature: </strong> <?= $recent_sec_level->signature; ?><br> <strong>Date: </strong><?= date('M d, Y', strtotime($recent_sec_level->created_at)).'<br><br>'; else: ?> </div> <div class="col-md-12"> <div class="alert alert-danger"> <p class="text-center"><strong>Oops! </strong> Second level supervisor haven't evaluated the employee "<strong><?= $rec_evals->name; ?></strong>" yet. </p> </div> </div> <?php endif; ?> </div><br> </div> <!--Footer--> <div class="modal-footer"> <a target="blank" href="<?= base_url();?>Performance_evaluation/print_appraisal_tcsp/<?= $rec_evals->evalu_id; ?>" class="btn btn-primary">Print</a> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </td> <td> <?php echo $rec_evals->position; ?> </td> <td> <?php echo $rec_evals->province; ?> </td> <td> <?php echo $rec_evals->district; ?> </td> <td> <?php echo $rec_evals->tehsil; ?> </td> <td> <?php echo $rec_evals->uc; ?> </td> <td> <?php echo $rec_evals->cnic_name; ?> </td> <td> <?php echo date('M d, Y', strtotime($rec_evals->join_date)); ?> </td> <td> <?php echo $rec_evals->peo_name; ?> </td> <td> <?php echo $rec_evals->ac_name; ?> </td> <td> <?php echo date('M d, Y', strtotime($rec_evals->created_at)); ?> </td> <td> <?php if($rec_evals->status == 0){ ?> <div class="label label-primary">TCSP pending</div> <?php }elseif($rec_evals->status == 1){ ?> <div class="label label-primary">AC pending</div> <?php }elseif($rec_evals->status == 2){ ?> <div class="label label-success">Completed</div> <?php }else{ ?> <a href="#" data-toggle="modal" data-target="#commentModal<?php echo $rec_evals->evalu_id; ?>"> <div class="label label-danger">Rolled Back</div> </a> <div id="commentModal<?php echo $rec_evals->evalu_id; ?>" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <strong>Roll Back comment...</strong> <p><?php echo $rollback_comment->rollback_comment; ?></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <?php } ?> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8 text-center"> <?php echo $this->pagination->create_links(); ?> </div> <div class="col-md-2"></div> </div> </div> </section> </section> </div> <file_sep>/application/views/performance_evaluation/tcsp_evaluation.php <?php /* * Filename: tcsp_evaluation.php * Filepath: views / performance_evalauation / tcsp_evaluation.php * Author: Saddam */ ?> <style type="text/css"> table th{ text-align: center; } </style> <script type="text/javascript"> $(document).ready(function(){ $('.select2').select2(); }); </script> <section class="secMainWidth"> <section class="secFormLayout"> <div class="mainInputBg"> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-8"> <strong>Performance Evaluation Form [TCSP]</strong> | <small>Now Logged in: <?php $peo_session = $this->session->userdata('peo_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <?php $ucpo_session = $this->session->userdata('ucpo_cnic'); ?> <?php $tcsp_session = $this->session->userdata('tcsp_cnic'); ?> <?php $admin_session = $this->session->userdata('admin_cnic'); ?> <strong> <?php if($peo_session){ echo $peo_session.' | PEO'; } elseif($ac_session){ echo $ac_session.' | AC'; } elseif($ucpo_session){ echo $ucpo_session.' | UCPO'; } elseif($tcsp_session){ echo $tcsp_session.' | TCSP'; } elseif($admin_session){ echo $admin_session.' | Admin'; } ?> </strong> | </small> <a href="<?php echo base_url('Perf_login/logout'); ?>" class="btn btn-warning btn-xs">Logout</a> </div> <div class="col-md-4 text-right"> <strong><a href="<?= base_url('Performance_evaluation/tcsp_previous'); ?>">Recently Added <i class="fa fa-angle-double-right"></i></a></strong> </div> </div> </div> <div class="panel-body"> <!-- General and PTPP holder's different skills, starts here... --> <form action="<?php if($this->uri->segment(3)){ echo base_url('performance_evaluation/update_rolledback_tcsp'); }else{ echo base_url('performance_evaluation/save_tcsp_evaluation');} ?>" method="post"> <input type="hidden" name="rolledback_tcsp" value="<?php echo $this->uri->segment(3); ?>"> <strong>I. General</strong> <table class="table table-condensed"> <tbody> <tr> <td>1.</td> <td>TCSP Name</td> <td colspan="2"> <div class="inputFormMain"> <select name="emp_name" class="form-control select2"> <option value="">Select Employee</option> <?php if($peo_session): foreach($tcsps as $emp): ?> <option value="<?= $emp->id; ?>"><?= $emp->position.' - '.$emp->name; ?></option> <?php endforeach; endif; ?> </select> </div> </td> </tr> <tr> <td>2.</td> <td>Title</td> <td colspan="2"><strong>Tehsil Campaign Support Person (TCSP)</strong></td> </tr> <tr> <td>3.</td> <td>Contract Type/Position</td> <td colspan="2"><strong>PTPP</strong></td> </tr> <tr> <td>4.</td> <td>Duty Station <br> (UC/District/Province)</td> <td colspan="2"> <div class="row"> <div class="col-sm-4"> <div class="inputFormMain"> <select name="duty_province" class="form-control select2"> </select> </div> </div> <div class="col-sm-4"> <div class="inputFormMain"> <select name="duty_distt" class="form-control select2"> </select> </div> </div> <div class="col-sm-4"> <div class="inputFormMain"> <select name="duty_tehsil" class="form-control select2"> </select> </div> </div> </div> </td> </tr> <tr> <td>5.</td> <td>Evaluation Period</td> <td> <div class="inputFormMain"> <input type="text" name="app_start_date" class="form-control date" value="08-01-2019" autocomplete="off"> </div> </td> <td> <div class="inputFormMain"> <input type="text" name="app_end_date" class="form-control date" value="31-10-2019" autocomplete="off"> </div> </td> </tr> </tbody> </table> <strong>II. Rate PTPP holder's Technical Skills:- </strong><hr> <div class="table"> <table class="table table-condensed"> <thead> <tr> <th></th> <th></th> <th>Job being done to the best of ability; desired results obtained</th> <th>Job being done to the best / good of ability; with mixed results (needs improvement)</th> <th>Work inadequately done; results unsatisfactory</th> </tr> </thead> <tbody> <tr> <td>1)</td> <td>UC / Area level Micro-plans development and desk revision</td> <td align="center"><input type="radio" name="remark" value="3" <?php if(@$prev_added_tcsps->que_one == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark" value="2" <?php if(@$prev_added_tcsps->que_one == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark" value="1" <?php if(@$prev_added_tcsps->que_one == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>2)</td> <td>UC / Area level Micro-plans field validation</td> <td align="center"><input type="radio" name="remark1" value="3" <?php if(@$prev_added_tcsps->que_two == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark1" value="2" <?php if(@$prev_added_tcsps->que_two == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark1" value="1" <?php if(@$prev_added_tcsps->que_two == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>3)</td> <td>Status of selection of the house to house vaccination teams</td> <td align="center"><input type="radio" name="remark2" value="3" <?php if(@$prev_added_tcsps->que_three == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark2" value="2" <?php if(@$prev_added_tcsps->que_three == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark2" value="1" <?php if(@$prev_added_tcsps->que_three == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>4)</td> <td>% of teams training attended</td> <td align="center"><input type="radio" name="remark3" value="3" <?php if(@$prev_added_tcsps->que_four == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark3" value="2" <?php if(@$prev_added_tcsps->que_four == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark3" value="1" <?php if(@$prev_added_tcsps->que_four == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>5)</td> <td>Training of the UC supervisors (Area In-charges)</td> <td align="center"><input type="radio" name="remark4" value="3" <?php if(@$prev_added_tcsps->que_five == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark4" value="2" <?php if(@$prev_added_tcsps->que_five == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark4" value="1" <?php if(@$prev_added_tcsps->que_five == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>6)</td> <td>Pre campaign data collection, collation and timely transmission to the next level % timeliness and % completeness</td> <td align="center"><input type="radio" name="remark5" value="3" <?php if(@$prev_added_tcsps->que_six == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark5" value="2" <?php if(@$prev_added_tcsps->que_six == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark5" value="1" <?php if(@$prev_added_tcsps->que_six == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>7)</td> <td>Data collection, collation and timely transmission to the next level during the campaign % timeliness and % completeness</td> <td align="center"><input type="radio" name="remark6" value="3" <?php if(@$prev_added_tcsps->que_seven == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark6" value="2" <?php if(@$prev_added_tcsps->que_seven == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark6" value="1" <?php if(@$prev_added_tcsps->que_seven == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>8)</td> <td>Corrective measures following the identification of the gaps. Number of critical siuation handled</td> <td align="center"><input type="radio" name="remark7" value="3" <?php if(@$prev_added_tcsps->que_eight == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark7" value="2" <?php if(@$prev_added_tcsps->que_eight == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark7" value="1" <?php if(@$prev_added_tcsps->que_eight == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>9)</td> <td>Ensure data collection from the field with more than 95% Post Campaign coverages through extensive monitoring in the field by doing LQAS & Market Surveys</td> <td align="center"><input type="radio" name="remark8" value="3" <?php if(@$prev_added_tcsps->que_nine == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark8" value="2" <?php if(@$prev_added_tcsps->que_nine == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark8" value="1" <?php if(@$prev_added_tcsps->que_nine == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>10)</td> <td>To establish the community AFP Surveillance in his area of assignment through regular health facility visits and ensure that the zero reports are timely been submitted</td> <td align="center"><input type="radio" name="remark9" value="3" <?php if(@$prev_added_tcsps->que_ten == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark9" value="2" <?php if(@$prev_added_tcsps->que_ten == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark9" value="1" <?php if(@$prev_added_tcsps->que_ten == '1'){ ?> checked <?php } ?>></td> </tr> </tbody> </table> </div> <strong>III. Rate PTPP holder's Following Attributes:-</strong><hr> <div class="table"> <table class="table table-condensed"> <thead> <tr> <th></th> <th>Satisfactory</th> <th>Needs Improvement</th> <th>Unsatisfactory</th> </tr> </thead> <tbody> <tr> <td>Reliability</td> <td align="center"><input type="radio" name="attribute" value="3" <?php if(@$prev_added_tcsps->attrib_1 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute" value="2" <?php if(@$prev_added_tcsps->attrib_1 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute" value="1" <?php if(@$prev_added_tcsps->attrib_1 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Work independently with minimal supervision</td> <td align="center"><input type="radio" name="attribute1" value="3" <?php if(@$prev_added_tcsps->attrib_2 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute1" value="2" <?php if(@$prev_added_tcsps->attrib_2 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute1" value="1" <?php if(@$prev_added_tcsps->attrib_2 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Punctuality</td> <td align="center"><input type="radio" name="attribute2" value="3" <?php if(@$prev_added_tcsps->attrib_3 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute2" value="2" <?php if(@$prev_added_tcsps->attrib_3 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute2" value="1" <?php if(@$prev_added_tcsps->attrib_3 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Initiative</td> <td align="center"><input type="radio" name="attribute3" value="3" <?php if(@$prev_added_tcsps->attrib_4 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute3" value="2" <?php if(@$prev_added_tcsps->attrib_4 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute3" value="1" <?php if(@$prev_added_tcsps->attrib_4 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Good team player</td> <td align="center"><input type="radio" name="attribute4" value="3" <?php if(@$prev_added_tcsps->attrib_5 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute4" value="2" <?php if(@$prev_added_tcsps->attrib_5 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute4" value="1" <?php if(@$prev_added_tcsps->attrib_5 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Fimiliarity with WHO required procedures</td> <td align="center"><input type="radio" name="attribute5" value="3" <?php if(@$prev_added_tcsps->attrib_6 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute5" value="2" <?php if(@$prev_added_tcsps->attrib_6 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute5" value="1" <?php if(@$prev_added_tcsps->attrib_6 == '1'){ ?> checked <?php } ?>></td> </tr> </tbody> </table> </div> <strong>IV. Others:-</strong><br><br> a)&nbsp; &nbsp;Describe any exceptional accoplishment for which the PTPP staff deserves a special recommendation or recognition <br><br> <div class="inputFormMain"> <textarea name="others_a" class="form-control" rows="5" placeholder="Start typing here..."><?php if(!empty($prev_added_tcsps)){ echo $prev_added_tcsps->comment_1; } ?></textarea><br> </div> b)&nbsp; &nbsp; Overall Assessment <br><br> <div class="inputFormMain"> <textarea name="others_b" class="form-control" rows="5" placeholder="Start typing here..."><?php if(!empty($prev_added_tcsps)){ echo $prev_added_tcsps->comment_2; } ?></textarea> </div> <br><br><br> <div class="row"> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="name" class="form-control" placeholder="Name..." value="<?php if(!empty($prev_added_tcsps)){ echo $prev_added_tcsps->signature; } ?>">1<sup>st</sup> level spervisor (Name) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="title" class="form-control" placeholder="Title..." value="<?php if(!empty($prev_added_tcsps)){ echo "PEO"; } ?>">1<sup>st</sup> level supervisor (Title: PEO) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="1st_signature" class="form-control" placeholder="Write your name as a signature..." value="<?php if(!empty($prev_added_tcsps)){ echo $prev_added_tcsps->signature; } ?>">1<sup>st</sup> level supervisor (Signature) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="1st_date" class="form-control date" placeholder="Date" autocomplete="off" value="<?php if(!empty($prev_added_tcsps)){ echo date('m-d-Y', strtotime($prev_added_tcsps->created_at)); } ?>">Date </div> </div> </div><br> <div class="submitBtn"> <?php $tcsp_session = $this->session->userdata('tcsp_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <button type="submit" class="btn btn-primary" <?php if($tcsp_session OR $ac_session): ?>disabled="" <?php endif; ?>>Forward to TCSP</button> <button type="reset" class="btn btn-default" <?php if($tcsp_session OR $ac_session): ?> disabled="" <?php endif; ?>>Reset</button> | <small><strong>Note: </strong> Form once submitted, can't be edited. So be careful while filling it.</small> </div> </form> <!-- General and PTPP holder's different skills, ends here... --> <hr> <!-- Remarks by the PTPP holder, 2nd form starts here... --> <center><strong>For TCSP</strong></center> <form action="<?= base_url('Performance_evaluation/remarks_by_tcsp'); ?>" method="post"> Remarks by the PTPP holder at the end of evaluation <br><br> <?php $peo_session = $this->session->userdata('peo_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <div class="row"> <div class="col-md-4"> <div class="inputFormMain"> <select name="employee_tcsp" class="form-control select2" <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>> <option value="">Select an Employee</option> <?php foreach($tcsp_employees as $tcsp): ?> <option value="<?= $tcsp->employee_id; ?>" <?php if($this->session->userdata('tcsp_cnic')): ?> selected="selected" <?php endif; ?>> <?= $tcsp->name; ?> </option> <?php endforeach; ?> </select> </div> </div> <div class="col-md-8"> <div class="inputFormMain"> <textarea name="tcsp_remarks" class="form-control" rows="5" placeholder="Start typing here. There's no returning back, once you save your data can't be changed, so be careful while filling the form. We didn't add an option to edit." <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>></textarea> </div><br> </div> </div> <div class="row"> <div class="col-md-8"> I have discussed and reviewed the performance evaluation with my supervisor: </div> <div class="col-md-2"> <input type="radio" name="remarks_by_tcsp" value="Agree"> <strong>Agree</strong> </div> <div class="col-md-2"> <input type="radio" name="remarks_by_tcsp" value="Disagree"> <strong>Disagree</strong> </div> </div> <br><br><br> <div class="row"> <div class="col-md-4"> <div class="inputFormMain"> <input type="text" name="apw_holder_name" class="form-control" placeholder="Name..." <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>PTPP holder (Name) </div> </div> <div class="col-md-4"> <div class="inputFormMain"> <input type="text" name="apw_holder_sign" class="form-control" placeholder="Write your names as a signature..." <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>PTPP holder (Signature) </div> </div> <div class="col-md-4"> <div class="inputFormMain"> <input type="text" name="apw_date" class="form-control" <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?> value="<?php echo date('Y-m-d'); ?>">Date </div> </div> </div><br> <div class="submitBtn"> <?php $peo_sess = $this->session->userdata('peo_cnic'); ?> <?php $ac_sess = $this->session->userdata('ac_cnic'); ?> <button type="submit" class="btn btn-primary" <?php if($peo_sess OR $ac_sess): ?> disabled <?php endif; ?>>Forward to AC</button> <button type="reset" class="btn btn-default" <?php if($peo_sess OR $ac_sess): ?> disabled <?php endif; ?>>Reset</button> | <small><strong>Note: </strong> Form once submitted, can't be edited. So be careful while filling it.</small> </div> </form><hr> <!-- PTPP holder's form ends here... --> <center><strong>For Second level Supervisor</strong></center><br> &nbsp; &nbsp;&nbsp;Overall assessment by Second level supervisor according to CTC staff accountability framework:- <br><br> <!-- Second level supervisor's assessment. --> <form action="<?= base_url('Performance_evaluation/sec_level_tcsp_rem'); ?>" method="post"> <div class="row"> <div class="col-md-5"> <div class="inputFormMain"> <select name="sec_level_tcsp" class="form-control select2"> <option value="">Select an Employee</option> <?php if($ac_session): foreach($ac_tcsps as $emps): ?> <option value="<?= $emps->employee_id; ?>"> <?= $emps->name; ?> </option> <?php endforeach; endif; ?> </select> </div> </div> </div><br> <div class="row"> <div class="col-md-6"> <input type="radio" name="sec_level_tcsp_remarks" value="Satisfactory"> a. Satisfactory <br> <input type="radio" name="sec_level_tcsp_remarks" value="Needs Improvement"> b. Needs improvement <br> <input type="radio" name="sec_level_tcsp_remarks" value="Work performed inadequately"> c. Work performed inadequately <br> <input type="radio" name="sec_level_tcsp_remarks" value="Unsatisfactory"> d. Unsatisfactory <i>(no improvement in quality after receiving 3 warning/advice for previous inadequate performance).</i> </div> <div class="col-md-6"> - contract recommended of extension <br> - contract to be re-evaluated after 3 months <br> - APW holder to be issued a warning/advice <br><br> - contract to be terminated </div> </div><br><br><br> <div class="row"> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_name" class="form-control" placeholder="Name">2<sup>nd</sup> level supervisor (Name) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_title" class="form-control" placeholder="Title: Area Coordinator">2<sup>nd</sup> level supervisor (Title: AC) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_sign" class="form-control" placeholder="Write your name as a signature">2<sup>nd</sup> level supervisor (Signature) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">Date </div> </div> </div><br> <div class="submitBtn"> <button type="submit" class="btn btn-primary" <?php if($peo_session OR $tcsp_session): ?> disabled="disabled" <?php endif; ?>>Finalise</button> <button data-toggle="modal" data-target="#rollback" type="button" class="btn btn-default" <?php if($peo_session OR $tcsp_session): ?> disabled="disabled" <?php endif; ?>>Roll Back</button> | <small><strong>Note: </strong> Form once submitted, can't be edited. So be careful while filling it.</small> <div id="rollback" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Roll Back Comment...</h4> </div> <div class="modal-body"> <textarea name="rollback_comment" class="form-control" placeholder="Type some words why do you want to Roll back ?"></textarea><br> <input type="submit" name="submit_1" class="btn btn-primary" value="Roll Back"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </form> <!-- Second level supervisor's form ends here... --> <hr> </div> <!-- <div class="panel-footer"></div> --> </div> </div> </div> </div> </section> </section> <!-- Select employee and his/her address will populate itself in the dropdown list. --> <script type="text/javascript"> $(document).ready(function(){ $('select[name="emp_name"]').on('change', function(){ var empID = $(this).val(); if(empID){ $.ajax({ url: '<?php echo base_url("Performance_evaluation/get_address_tcsps/"); ?>'+empID, type: 'post', dataType: 'json', success: function(data){ console.log(data); // Log data to the console. $('select[name="duty_province"]').empty(); $('select[name="duty_distt"]').empty(); $('select[name="duty_tehsil"]').empty(); $('select[name="duty_province"]').append('<option value="'+ data.province +'">'+ data.province +'</option>'); $('select[name="duty_distt"]').append('<option value="'+ data.district +'" selected>'+ data.district +'</option>'); $('select[name="duty_tehsil"]').append('<option value="'+ data.uc +'" selected>'+ data.uc +'</option>'); } }); }else{ $('select[name="duty_province"]').empty(); $('select[name="duty_distt"]').empty(); $('select[name="duty_tehsil"]').empty(); } }); }); </script><file_sep>/application/views/performance_evaluation/performance_eval.php <?php /* * Filename: performance_eval.php * Filepath: views / performance_evaluation / performance_eval.php * Author: Saddam */ ?> <style type="text/css"> table th{ text-align: center; } </style> <script type="text/javascript"> $(document).ready(function(){ $('.select2').select2(); // Searchable dropdown lists/select boxes. }); </script> <section class="secMainWidth"> <section class="secFormLayout"> <div class="mainInputBg"> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-8"> <strong>Performance Evaluation Form [UCPO]</strong> | <small>Welcome : <?php $peo_session = $this->session->userdata('peo_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <?php $ucpo_session = $this->session->userdata('ucpo_cnic'); ?> <?php $tcsp_session = $this->session->userdata('tcsp_cnic'); ?> <?php $admin_session = $this->session->userdata('admin_cnic'); ?> <strong> <?php if($peo_session){ echo $peo_session .' | PEO'; } elseif($ac_session){ echo $ac_session . ' | AC'; } elseif($ucpo_session){ echo $ucpo_session.' | UCPO'; } elseif($tcsp_session){ echo $tcsp_session.' | TCSP'; } elseif($admin_session){ echo $admin_session.' | Admin'; } ?> </strong> | </small> <a href="<?php echo base_url('Perf_login/logout'); ?>" class="btn btn-warning btn-xs">Logout</a> </div> <div class="col-md-4 text-right"> <strong><a href="<?= base_url('Performance_evaluation/get_previous'); ?>">Recently Added <i class="fa fa-angle-double-right"></i></a></strong> </div> </div> </div> <div class="panel-body"> <?php //if(!empty($this->uri->segment(3))): ?> <!-- General and PTPP holder's different skills, starts here... --> <form action="<?php if($this->uri->segment(3)){ echo base_url('performance_evaluation/update_rolledback'); }else{ echo base_url('performance_evaluation/save_evaluation'); } ?>" method="post"> <input type="hidden" name="rollback_update" value="<?php echo $this->uri->segment(3); ?>"> <strong>I. General</strong> <table class="table table-condensed"> <tbody> <tr> <td>1.</td> <td>UCPO Name</td> <td colspan="2"> <div class="inputFormMain"> <select name="emp_name" class="form-control select2"> <option value="">Select an Employee</option> <?php if($peo_session AND !$this->uri->segment(3)): foreach($ucpos as $emp): ?> <option value="<?= $emp->id; ?>"><?= $emp->position.' - '. $emp->name; ?></option> <?php endforeach; endif; ?> </select> </div> </td> </tr> <tr> <td>2.</td> <td>Title</td> <td colspan="2"><strong>Union Council Polio Officer (UCPO)</strong></td> </tr> <tr> <td>3.</td> <td>Contract Type/Position</td> <td colspan="2"><strong>PTPP</strong></td> </tr> <tr> <td>4.</td> <td>Duty Station <br> (UC/District/Province)</td> <td colspan="2"> <div class="row"> <div class="col-sm-4"> <div class="inputFormMain"> <select name="duty_province" class="form-control select2"> </select> </div> </div> <div class="col-sm-4"> <div class="inputFormMain"> <select name="duty_distt" class="form-control select2"> </select> </div> </div> <div class="col-sm-4"> <div class="inputFormMain"> <select name="duty_tehsil" class="form-control select2" id="tehsil"> </select> </div> </div> </div> </td> </tr> <tr> <td>5.</td> <td>Evaluation Period</td> <td> <div class="inputFormMain"> <input type="text" name="app_start_date" class="form-control date" placeholder="Start date..." autocomplete="off" value="01-11-2019"> </div> </td> <td> <div class="inputFormMain"> <input type="text" name="app_end_date" class="form-control date" placeholder="End date..." autocomplete="off" value="31-12-2019"> </div> </td> </tr> </tbody> </table> <strong>II. Rate PTPP holder's Technical Skills:- </strong><hr> <div class="table"> <table class="table table-condensed"> <thead> <tr> <th></th> <th></th> <th>Job being done to the best of ability; desired results obtained</th> <th>Job being done to the best / good of ability; with mixed results (needs improvement)</th> <th>Work inadequately done; results unsatisfactory</th> </tr> </thead> <tbody> <tr> <td>1)</td> <td>UC / Area level Micro-plans development and desk revision</td> <td align="center"><input type="radio" name="remark" value="3" <?php if(@$previously_added->que_one == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark" value="2" <?php if(@$previously_added->que_one == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark" value="1" <?php if(@$previously_added->que_one == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>2)</td> <td>UC / Area level Micro-plans field validation</td> <td align="center"><input type="radio" name="remark1" value="3" <?php if(@$previously_added->que_two == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark1" value="2" <?php if(@$previously_added->que_two == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark1" value="1" <?php if(@$previously_added->que_two == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>3)</td> <td>Status of selection of the house to house vaccination teams</td> <td align="center"><input type="radio" name="remark2" value="3" <?php if(@$previously_added->que_three == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark2" value="2" <?php if(@$previously_added->que_three == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark2" value="1" <?php if(@$previously_added->que_three == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>4)</td> <td>Training of the vaccination teams</td> <td align="center"><input type="radio" name="remark3" value="3" <?php if(@$previously_added->que_four == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark3" value="2" <?php if(@$previously_added->que_four == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark3" value="1" <?php if(@$previously_added->que_four == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>5)</td> <td>Training of the UC supervisors (Area In-charges)</td> <td align="center"><input type="radio" name="remark4" value="3" <?php if(@$previously_added->que_five == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark4" value="2" <?php if(@$previously_added->que_five == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark4" value="1" <?php if(@$previously_added->que_five == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>6)</td> <td>Pre campaign data collection, collation and timely transmission to the next level</td> <td align="center"><input type="radio" name="remark5" value="3" <?php if(@$previously_added->que_six == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark5" value="2" <?php if(@$previously_added->que_six == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark5" value="1" <?php if(@$previously_added->que_six == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>7)</td> <td>Data collection, collation and timely transmission to the next level during the campaign</td> <td align="center"><input type="radio" name="remark6" value="3" <?php if(@$previously_added->que_seven == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark6" value="2" <?php if(@$previously_added->que_seven == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark6" value="1" <?php if(@$previously_added->que_seven == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>8)</td> <td>Corrective measures following the identification of the gaps</td> <td align="center"><input type="radio" name="remark7" value="3" <?php if(@$previously_added->que_eight == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark7" value="2" <?php if(@$previously_added->que_eight == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="remark7" value="1" <?php if(@$previously_added->que_eight == '1'){ ?> checked <?php } ?>></td> </tr> </tbody> </table> </div> <strong>III. Rate PTPP holder's Following Attributes:- </strong><hr> <div class="table"> <table class="table table-condensed"> <thead> <tr> <th></th> <th>Satisfactory</th> <th>Needs Improvement</th> <th>Unsatisfactory</th> </tr> </thead> <tbody> <tr> <td>Reliability</td> <td align="center"><input type="radio" name="attribute" value="3" <?php if(@$previously_added->attrib_1 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute" value="2" <?php if(@$previously_added->attrib_1 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute" value="1" <?php if(@$previously_added->attrib_1 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Work independently with minimal supervision</td> <td align="center"><input type="radio" name="attribute1" value="3" <?php if(@$previously_added->attrib_2 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute1" value="2" <?php if(@$previously_added->attrib_2 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute1" value="1" <?php if(@$previously_added->attrib_2 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Punctuality</td> <td align="center"><input type="radio" name="attribute2" value="3" <?php if(@$previously_added->attrib_3 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute2" value="2" <?php if(@$previously_added->attrib_3 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute2" value="1" <?php if(@$previously_added->attrib_3 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Initiative</td> <td align="center"><input type="radio" name="attribute3" value="3" <?php if(@$previously_added->attrib_4 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute3" value="2" <?php if(@$previously_added->attrib_4 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute3" value="1" <?php if(@$previously_added->attrib_4 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Good team player</td> <td align="center"><input type="radio" name="attribute4" value="3" <?php if(@$previously_added->attrib_5 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute4" value="2" <?php if(@$previously_added->attrib_5 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute4" value="1" <?php if(@$previously_added->attrib_5 == '1'){ ?> checked <?php } ?>></td> </tr> <tr> <td>Fimiliarity with WHO required procedures</td> <td align="center"><input type="radio" name="attribute5" value="3" <?php if(@$previously_added->attrib_6 == '3'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute5" value="2" <?php if(@$previously_added->attrib_6 == '2'){ ?> checked <?php } ?>></td> <td align="center"><input type="radio" name="attribute5" value="1" <?php if(@$previously_added->attrib_6 == '1'){ ?> checked <?php } ?>></td> </tr> </tbody> </table> </div> <strong>IV. Others:-</strong><br><br> a)&nbsp; &nbsp;Describe any exceptional accoplishment for which the PTPP staff deserves a special recommendation or recognition <br><br> <div class="inputFormMain"> <textarea name="others_a" class="form-control" rows="5" placeholder="Start typing here..."><?php if(!empty($previously_added)){ echo $previously_added->comment_1; } ?></textarea> </div><br> b)&nbsp; &nbsp; Overall Assessment <br><br> <div class="inputFormMain"> <textarea name="others_b" class="form-control" rows="5" placeholder="Start typing here..."><?php if(!empty($previously_added)){ echo $previously_added->comment_2; } ?></textarea> </div> <br><br><br> <div class="row"> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="name" class="form-control" placeholder="Name..." value="<?php if(!empty($previously_added)){ echo $previously_added->signature; } ?>">1<sup>st</sup> level spervisor (Name) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="title" class="form-control" placeholder="Title..." value="<?php if(!empty($previously_added)){ echo "PEO"; } ?>">1<sup>st</sup> level supervisor (Title: PEO) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="1st_signature" class="form-control" placeholder="Write your name as a signature..." value="<?php if(!empty($previously_added)){ echo $previously_added->signature; } ?>">1<sup>st</sup> level supervisor (Signature) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="1st_date" class="form-control date" placeholder="Date" autocomplete="off"value="<?php if(!empty($previously_added)){ echo date('Y-m-d', strtotime($previously_added->created_at)); }else{ echo date('Y-m-d'); } ?>">Date </div> </div> </div><br> <div class="submitBtn"> <?php $ucpo_session = $this->session->userdata('ucpo_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <button type="submit" class="btn btn-primary" <?php if($ucpo_session OR $ac_session): ?> disabled="" <?php endif; ?>>Forward to UCPO</button> <button type="reset" class="btn btn-default" <?php if($ucpo_session OR $ac_session): ?> disabled="" <?php endif; ?>>Reset</button> | <small><strong>Note: </strong> Form once submitted, can't be edited. So be careful while filling it.</small> </div> </form> <!-- General and PTPP holder's different skills, ends here... --> <?php //endif; ?> <hr> <!-- Remarks by the PTPP holder, 2nd form starts here... --> <form action="<?= base_url('Performance_evaluation/remarks_by_ptpp'); ?>" method="post"> Remarks by the PTPP holder at the end of evaluation <br><br> <div class="row"> <div class="col-md-4"> <div class="inputFormMain"> <?php $peo_session = $this->session->userdata('peo_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <select name="ptpp_employee" class="form-control select2" <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>> <option value="">Select an Employee</option> <?php foreach($ptpp_employees as $employee): ?> <option value="<?= $employee->emp_id; ?>" <?php if($this->session->userdata('ucpo_cnic')): ?> selected="selected" <?php endif; ?>> <?= $employee->name; ?> </option> <?php endforeach; ?> </select> </div> </div> <div class="col-md-8"> <div class="inputFormMain"> <textarea name="ptpp_remarks" class="form-control" rows="5" placeholder="Start typing here... There's no returning back, once you save your data can't be changed, so be careful while filling the form. We didn't add an option to edit." <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>></textarea> </div><br> </div> </div> <div class="row"> <div class="col-md-8"> I have discussed and reviewed the performance evaluation with my supervisor: </div> <div class="col-md-2"> <input type="radio" name="remarks_by_ucpo" value="Agree"> <strong>Agree</strong> </div> <div class="col-md-2"> <input type="radio" name="remarks_by_ucpo" value="Disagree"> <strong>Disagree</strong> </div> </div> <br><br><br> <div class="row"> <div class="col-md-4"> <div class="inputFormMain"> <input type="text" name="ptpp_holder_name" class="form-control" placeholder="Name..." <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>PTPP holder (Name) </div> </div> <div class="col-md-4"> <div class="inputFormMain"> <input type="text" name="ptpp_holder_sign" class="form-control" placeholder="Write your names as a signature..." <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>PTPP holder (Signature) </div> </div> <div class="col-md-4"> <div class="inputFormMain"> <input type="text" name="ptpp_date" class="form-control date" placeholder="Date" autocomplete="off" value="<?php echo date('Y-m-d'); ?>" <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>Date </div> </div> </div><br> <div class="submitBtn"> <?php $peo_session = $this->session->userdata('peo_cnic'); ?> <?php $ac_session = $this->session->userdata('ac_cnic'); ?> <button type="submit" class="btn btn-primary" <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>Forward to AC</button> <button type="reset" class="btn btn-default" <?php if($peo_session OR $ac_session): ?> disabled <?php endif; ?>>Reset</button> | <small><strong>Note: </strong> Form once submitted, can't be edited. So be careful while filling it.</small> </div> </form><hr> <!-- PTPP holder's form ends here... --> <center><strong>For Second level Supervisor</strong></center><br> &nbsp; &nbsp;&nbsp;Overall assessment by Second level supervisor according to CTC staff accountability framework:- <br><br> <!-- Second level supervisor's assessment. --> <form action="<?= base_url('Performance_evaluation/remarks_by_sec_level_sup'); ?>" method="post"> <div class="row"> <div class="col-md-5"> <div class="inputFormMain"> <select name="sec_level" class="form-control select2"> <option value="">Select an Employee</option> <?php if($ac_session): foreach($ac_employees as $ac): ?> <option value="<?php echo $ac->employee_id; ?>"> <?php echo $ac->name; ?> </option> <?php endforeach; endif; ?> </select> </div> </div> </div><br> <div class="row"> <div class="col-md-6"> <input type="radio" name="sec_level_remarks" value="Satisfactory"> a. Satisfactory <br> <input type="radio" name="sec_level_remarks" value="Needs Improvement"> b. Needs improvement <br> <input type="radio" name="sec_level_remarks" value="Work performed inadequately"> c. Work performed inadequately <br> <input type="radio" name="sec_level_remarks" value="Unsatisfactory"> d. Unsatisfactory <i>(no improvement in quality after receiving 3 warning/advice for previous inadequate performance).</i> </div> <div class="col-md-6"> - contract recommended of extension <br> - contract to be re-evaluated after 3 months <br> - PTPP holder to be issued a warning/advice <br><br> - contract to be terminated </div> </div><br><br><br> <div class="row"> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_name" class="form-control" placeholder="Name"> 2<sup>nd</sup> level supervisor (Name) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_title" class="form-control" placeholder="Title: Area Coordinator">2<sup>nd</sup> level supervisor (Title: AC) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_sign" class="form-control" placeholder="Write your name as a signature">2<sup>nd</sup> level supervisor (Signature) </div> </div> <div class="col-md-3"> <div class="inputFormMain"> <input type="text" name="sec_level_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">Date </div> </div> </div><br> <div class="submitBtn"> <?php $ucpo_session = $this->session->userdata('ucpo_cnic'); ?> <button type="submit" name="submit" class="btn btn-primary" <?php if($ucpo_session OR $peo_session): ?> disabled="disabled" <?php endif; ?>>Finalise</button> <button type="button" data-toggle="modal" data-target="#rollback" class="btn btn-default" <?php if($ucpo_session OR $peo_session): ?> disabled="disabled" <?php endif; ?>>Roll Back</button> | <small><strong>Note: </strong> Form once submitted, can't be edited. So be careful while filling it.</small> <div id="rollback" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Roll Back Comment...</h4> </div> <div class="modal-body"> <textarea name="rollback_comment" class="form-control" placeholder="Type some words why do you want to Roll back ?"></textarea><br> <input type="submit" name="submit_1" class="btn btn-primary" value="Roll Back"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </form> <!-- Second level supervisor's form ends here... --> <hr> </div> <!-- <div class="panel-footer"></div> --> </div> </div> </div> </div> </section> </section> <!-- Select employee and his/her address will populate itself in the dropdown list. --> <script type="text/javascript"> $(document).ready(function(){ $('select[name="emp_name"]').on('change', function(){ var empID = $(this).val(); if(empID){ $.ajax({ url: '<?php echo base_url("Performance_evaluation/get_address_ucpos/"); ?>'+empID, type: 'post', dataType: 'json', success: function(data){ console.log(data); // Log data to the console. $('select[name="duty_province"]').empty(); $('select[name="duty_distt"]').empty(); $('select[name="duty_tehsil"]').empty(); $('select[name="duty_province"]').append('<option value="'+ data.province +'">'+ data.province +'</option>'); $('select[name="duty_distt"]').append('<option value="'+ data.district +'" selected>'+ data.district +'</option>'); $('select[name="duty_tehsil"]').append('<option value="'+ data.uc +'" selected>'+ data.uc +'</option>'); } }); }else{ $('select[name="duty_province"]').empty(); $('select[name="duty_distt"]').empty(); $('select[name="duty_tehsil"]').empty(); } }); }); </script><file_sep>/application/controllers/Perf_login.php <?php defined('BASEPATH') OR exit('No direct script access allowed!'); /** * Filename: Perf_login.php * Filepath: controllers / Perf_login.php * Author: Saddam */ class Perf_login extends CI_Controller { /** * */ public function __construct() { parent::__construct(); $this->load->model('Perf_login_model'); } // Index function to load the main page. public function index() { $this->load->view('perf_login'); } // Validate user to make an appraisal, for all designations. public function validate() { // PEO login. $peo_cnic = $this->input->post('peo_cnic'); $password = $this-><PASSWORD>->post('<PASSWORD>'); // AC login. $ac_cnic = $this->input->post('peo_cnic'); $password = $this-><PASSWORD>('password'); // UCPO Login. $ucpo_cnic = $this->input->post('peo_cnic'); $password = $this-><PASSWORD>->post('<PASSWORD>'); // TCSP login. $tcsp_cnic = $this->input->post('peo_cnic'); $password = $<PASSWORD>('<PASSWORD>'); // Administrators login. $admin_name = $this->input->post('peo_cnic'); $admin_cnic = $this->input->post('password'); $peo_signin = $this->Perf_login_model->validate_user($peo_cnic, $password); $ac_signin = $this->Perf_login_model->validate_ac($ac_cnic, $password); $ucpo_signin = $this->Perf_login_model->validate_ucpo($ucpo_cnic, $password); $tcsp_signin = $this->Perf_login_model->validate_tcsp($tcsp_cnic, $password); $admin_signin = $this->Perf_login_model->validate_admin($admin_cnic); // Admin login. if($peo_signin){ $this->session->set_userdata(array('peo_cnic' => $peo_cnic)); redirect('performance_evaluation/get_previous'); }elseif($ac_signin){ $this->session->set_userdata(array('ac_cnic' => $ac_cnic)); redirect('performance_evaluation/get_previous'); }elseif($ucpo_signin){ $this->session->set_userdata(array('ucpo_cnic' => $ucpo_cnic)); $this->db->select('id'); $this->db->from('ucpo_data'); $this->db->where('cnic_name', $this->session->userdata('ucpo_cnic')); $ucpo_id = $this->db->get()->row(); $test = $ucpo_id->id; redirect("performance_evaluation/index/".$test); }elseif($tcsp_signin){ $this->session->set_userdata(array('tcsp_cnic' => $tcsp_cnic)); $this->db->select('id'); $this->db->from('tcsp_data'); $this->db->where('cnic_name', $this->session->userdata('tcsp_cnic')); $tcsp_id = $this->db->get()->row(); $test1 = $tcsp_id->id; redirect("performance_evaluation/tcsp_evaluation/".$test1); }elseif($admin_signin){ $this->session->set_userdata(array('admin_cnic' => $admin_cnic)); redirect('performance_evaluation/get_previous'); }else{ $this->session->set_flashdata('failed', '<strong>Aww snap! </strong> Looks like you do not have the permission to make an appraisal, contact your supervisor for further detail.'); $this->index(); } } // Change password, this method will redirect the user to the change password page. public function change_password(){ $this->load->view('change_password'); } // Update password. public function password_change(){ if($this->session->userdata('peo_cnic')){ $this->db->where('peo_cnic', $this->session->userdata('peo_cnic')); $this->db->update('peo_data', array('peo_password' => $this->input->post('pass'))); }elseif($this->session->userdata('ac_cnic')){ $this->db->where('ac_cnic', $this->session->userdata('ac_cnic')); $this->db->update('ac_data', array('ac_password' => $this->input->post('pass'))); }elseif($this->session->userdata('ucpo_cnic')){ $this->db->where('ucpo_cnic', $this->session->userdata('ucpo_cnic')); $this->db->update('ucpo_data', array('ucpo_password' => $this->input->post('pass'))); }elseif($this->session->userdata('tcsp_cnic')){ $this->db->where('tcsp_cnic', $this->session->userdata('tcsp_cnic')); $this->db->update('tcsp_data', array('tcsp_password' => $this->input->post('pass'))); }else{ echo 'Failed to update your password!'; } $this->session->set_flashdata('success', '<strong>Success !</strong> Password change has been successful !'); redirect('Perf_login'); } // Terminate the session and log the user out. public function logout(){ $this->session->sess_destroy(array('peo_cnic')); $this->session->set_flashdata('logged_out', '<strong>Hooray !</strong> You have been logged out successfully, Login again .'); $this->index(); } } ?>
5d0abf7c2884389fd7b065b8d7f8606fc91053fc
[ "Markdown", "PHP" ]
17
PHP
sayedsaddam/performance_appraisals
bf5d98049f7ba214ceb372d3066d97739cbf43d1
392405f207115662cc3369eb0b12f0e6be64355a
refs/heads/master
<file_sep># 非极大值抑制算法 ## 简介 非极大值抑制算法(Non-Maximum Suppression,NMS),首次在论文 Efficient non-maximum suppression 被提出,多年之后被广泛用于目标检测领域,用于消除多余的检测框。 ## NMS 介绍 目标检测算法(主流的有 RCNN 系、YOLO 系、SSD 等)在进行目标检测任务时,可能对同一目标有多次预测得到不同的检测框,NMS 算法则可以确保对每个对象只得到一个检测,简单来说就是“消除冗余检测”。 ## IOU 交并比(Intersection over Union,IOU)是目标检测领域常用的一个指标,用于衡量两个边界框的重叠程度,顾名思义利用两个边界框的交集面积除以两个边界框的并集面积即可。当 IOU 为 0 的时候表示无重叠,为 1 的时候表示完全重叠,在 0 到 1 之间的数值表示重叠程度。 ![](./assets/iou.png) ## NMS 算法流程 ![](./assets/raw_img.png) NMS 的工作流程如下,其实非常简单粗暴: 1. 按照一定的置信度阈值,删除置信度过低的检测框,对检测框进行初步筛选,如设置为 0.5,上图中没有检测框会被初步过滤掉; 2. 从当前边界框列表中选取置信度最大的边界框,加入结果列表,同时计算其他边界框与它的 IOU,若 IOU 超过设定的 IOU 阈值,则删除该检测框; 3. 重复上面的第二步,直到边界框列表为空,得到结果列表。 上图中,显然,左侧目标只保留 0.95 的置信度的检测结果,右侧目标只保留 0.9 的检测结果。 **此外,还有一个问题就是当目标为很多类别时(上图只有一个行人类别),按照吴恩达的思路这里应该不引入其他变量,简单来说就是一个类别一个类别地进行 NMS。** ## 代码实现 利用 Python 实现 NMS 是非常简单的,有兴趣可以查看 Fast R-CNN 的实现源码,下文代码参考其完成(代码中没有进行第一步的按置信度过滤)。 ```python import numpy as np import cv2 from draw_bbox import draw_box def nms(bboxes, scores, iou_thresh): """ :param bboxes: 检测框列表 :param scores: 置信度列表 :param iou_thresh: IOU阈值 :return: """ x1 = bboxes[:, 0] y1 = bboxes[:, 1] x2 = bboxes[:, 2] y2 = bboxes[:, 3] areas = (y2 - y1) * (x2 - x1) # 结果列表 result = [] index = scores.argsort()[::-1] # 对检测框按照置信度进行从高到低的排序,并获取索引 # 下面的操作为了安全,都是对索引处理 while index.size > 0: # 当检测框不为空一直循环 i = index[0] result.append(i) # 将置信度最高的加入结果列表 # 计算其他边界框与该边界框的IOU x11 = np.maximum(x1[i], x1[index[1:]]) y11 = np.maximum(y1[i], y1[index[1:]]) x22 = np.minimum(x2[i], x2[index[1:]]) y22 = np.minimum(y2[i], y2[index[1:]]) w = np.maximum(0, x22 - x11 + 1) h = np.maximum(0, y22 - y11 + 1) overlaps = w * h ious = overlaps / (areas[i] + areas[index[1:]] - overlaps) # 只保留满足IOU阈值的索引 idx = np.where(ious <= iou_thresh)[0] index = index[idx + 1] # 处理剩余的边框 bboxes, scores = bboxes[result], scores[result] return bboxes, scores if __name__ == '__main__': raw_img = cv2.imread('test.png') # 这里为了编码方便,将检测的结果直接作为变量 bboxes = [[183, 625, 269, 865], [197, 603, 296, 853], [190, 579, 295, 864], [537, 507, 618, 713], [535, 523, 606, 687]] confidences = [0.7, 0.9, 0.95, 0.9, 0.6] # 未经过nms的原始检测结果 img = raw_img.copy() for x, y in zip(bboxes, confidences): img = draw_box(img, x, y) cv2.imwrite("../assets/raw_img.png", img) # 进行nms处理 bboxes, scores = nms(np.array(bboxes), np.array(confidences), 0.5) img = raw_img.copy() for x, y in zip(list(bboxes), list(scores)): img = draw_box(img, x, y) cv2.imwrite("../assets/img_nms.png", img) ``` 在上一节的检测结果基础上进行 NMS 后的检测结果如下图,可以看到,成功过滤掉很多冗余的检测。 ![](./assets/img_nms.png) ## 补充说明 本文主要讲解并实现了目标检测算法中常用的 NMS 算法,该算法对检测结果进行筛选上有着姣好的效果,本文理论部分参考吴恩达的深度学习课程,设计的源码可以在我的 Github 找到,欢迎 star 或者 fork。 <file_sep>""" Author: <NAME> Date: 2020/4/30 Desc: Numpy实现nms """ import numpy as np import cv2 from draw_bbox import draw_box def nms(bboxes, scores, iou_thresh): """ :param bboxes: 检测框列表 :param scores: 置信度列表 :param iou_thresh: IOU阈值 :return: """ x1 = bboxes[:, 0] y1 = bboxes[:, 1] x2 = bboxes[:, 2] y2 = bboxes[:, 3] areas = (y2 - y1) * (x2 - x1) # 结果列表 result = [] index = scores.argsort()[::-1] # 对检测框按照置信度进行从高到低的排序,并获取索引 # 下面的操作为了安全,都是对索引处理 while index.size > 0: # 当检测框不为空一直循环 i = index[0] result.append(i) # 将置信度最高的加入结果列表 # 计算其他边界框与该边界框的IOU x11 = np.maximum(x1[i], x1[index[1:]]) y11 = np.maximum(y1[i], y1[index[1:]]) x22 = np.minimum(x2[i], x2[index[1:]]) y22 = np.minimum(y2[i], y2[index[1:]]) w = np.maximum(0, x22 - x11 + 1) h = np.maximum(0, y22 - y11 + 1) overlaps = w * h ious = overlaps / (areas[i] + areas[index[1:]] - overlaps) # 只保留满足IOU阈值的索引 idx = np.where(ious <= iou_thresh)[0] index = index[idx + 1] # 处理剩余的边框 bboxes, scores = bboxes[result], scores[result] return bboxes, scores if __name__ == '__main__': raw_img = cv2.imread('test.png') # 这里为了编码方便,将检测的结果直接作为变量 bboxes = [[183, 625, 269, 865], [197, 603, 296, 853], [190, 579, 295, 864], [537, 507, 618, 713], [535, 523, 606, 687]] confidences = [0.7, 0.9, 0.95, 0.9, 0.6] # 未经过nms的原始检测结果 img = raw_img.copy() for x, y in zip(bboxes, confidences): img = draw_box(img, x, y) cv2.imwrite("../assets/raw_img.png", img) # 进行nms处理 bboxes, scores = nms(np.array(bboxes), np.array(confidences), 0.5) img = raw_img.copy() for x, y in zip(list(bboxes), list(scores)): img = draw_box(img, x, y) cv2.imwrite("../assets/img_nms.png", img)<file_sep>import cv2 def draw_box(img, bbox, confidence=None, offset=(0, 0)): """ 图上绘制一个边界框 :param img: :param bbox: 必须是(xmin, ymin, xmax, ymax)的格式 :param confidence: 该边界框的置信度 :param offset: :return: """ x1, y1, x2, y2 = [int(i) for i in bbox] x1 += offset[0] x2 += offset[0] y1 += offset[1] y2 += offset[1] # box text and bar color = 0.5 label = str(confidence) t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 1, 2)[0] cv2.rectangle(img, (x1, y1), (x2, y2), color, 3) cv2.rectangle(img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1) cv2.putText(img, label, (x1, y1 + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 2, [255, 255, 255], 2) return img
da14e46fa60260ecf40c3a07d2fb53b288194e1a
[ "Markdown", "Python" ]
3
Markdown
sqiangcao/NMS
72b4fe37da85d10daa033fc1a93f2e4fa267cda0
8852094dd03e203912a319595ddcc719d448d8d0
refs/heads/main
<repo_name>peasy90/zc_plugin_expenses<file_sep>/resources/js/components/view/commitandSubmit.js import './App.css'; function App() { return( <div className="form-group"> <label class="font-weight-bold display-4" htmlFor="title">Status</label> <input readonly type="text" className="form-control-plaintext text-success lead" id="title" placeholder="Expense Title" value="Approved" /> <pre><button><h3>SUBMIT</h3></button> <button><h3>CANCEL</h3></button></pre> </div> ); } export default App;
3df78ccae8b548d44b8688b6fff9f0feaf5761fc
[ "JavaScript" ]
1
JavaScript
peasy90/zc_plugin_expenses
d4ddc2137b4955907fbd17dd6fc63a2832b90b17
55ba21d13516a045122f9cd47090f52c023c24f3
refs/heads/master
<repo_name>a18simongv/GestionRestaurant<file_sep>/src/resources/Stacks.java package resources; import java.util.LinkedList; public class Stacks { private static int numToCook = 0, numCooked = 0; private LinkedList<Order> toCook; private LinkedList<Order> cooked; //variables to control access private boolean takenCooked, takenToCook; public Stacks() { toCook = new LinkedList<>(); cooked = new LinkedList<>(); takenCooked = false; takenToCook = false; } public synchronized void putToCook(Order order) throws Exception{ while(takenToCook) { wait(); } takenToCook = true; Utils.goSleep(2); toCook.add(order); numToCook++; takenToCook = false; notify(); } public synchronized Order getToCook() throws Exception{ while(takenToCook) { wait(); } takenToCook = true; Utils.goSleep(2); Order order = toCook.poll(); numToCook--; takenToCook = false; notify(); return order; } public synchronized void putCooked(Order order) throws Exception{ while(takenCooked) { wait(); } takenCooked = true; Utils.goSleep(2); cooked.add(order); numCooked++; takenCooked = false; notify(); } public synchronized Order getCooked() throws Exception{ while(takenCooked) { wait(); } takenCooked = true; Utils.goSleep(2); Order order = cooked.poll(); numCooked--; takenCooked = false; notify(); return order; } public synchronized int getNumToCook() { return numToCook;} public synchronized int getNumCooked() { return numCooked;} } <file_sep>/src/personal/Waiter.java package personal; import places.*; import resources.*; public class Waiter extends Thread { private String name; private Order order; private Restaurant rest; private Stacks stacks; public Waiter(String name, Restaurant rest, Stacks stk) { this.name = name; this.rest = rest; stacks = stk; } public String getWtrName() {return name;} public void setOrder(Order order) { this.order = order; } @Override public void run() { while (true) { int cont = 0; try { int posTakeNote = rest.posTakeNote(); if (posTakeNote != -1) { Utils.goSleep(3); rest.takeNote(posTakeNote, this); stacks.putToCook(order); } else { cont++; } } catch (Exception ex) { ex.printStackTrace(); } try { if (stacks.getNumCooked() > 0) { order = stacks.getCooked(); rest.serve(order, this); } else { cont++; } } catch (Exception ex) { ex.printStackTrace(); } if(cont==2) { System.out.println(name + " is seeping and looking to the clients"); Utils.goSleep(8); } cont = 0; } } } <file_sep>/src/resources/Utils.java package resources; public class Utils { // public int randomNumb(int sec) { // return (int) (Math.random()*1000*sec); // } public static void goSleep(int sec) { try { Thread.sleep((int) (Math.random()*1000*sec)); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>/src/personal/Client.java package personal; import resources.*; import places.Restaurant; public class Client extends Thread { private String name; private Order order; private boolean waiting; private Restaurant rest; public Client(String name, String order, Restaurant rest) { this.name = name; this.order = new Order(order); this.rest = rest; } public void putDesk(int desk) { order.setDesk(desk); } public void setWaiting(boolean wait) { waiting = wait; } public Order getOrder() { return order; } public String getCltName() { return name; } @Override public void run() { try { rest.sitDown(this); // wait to be attend while (waiting) Utils.goSleep(1); // eat menu System.out.println(name + " starts to have lunch"); Utils.goSleep(5); // finish and stand up System.out.println(name + " finish and go home"); rest.standUp(this); } catch (Exception ex) { ex.printStackTrace(); } } } <file_sep>/src/places/Kitchen.java package places; import java.util.concurrent.Semaphore; import personal.Cooker; import resources.Utils; public class Kitchen { private Semaphore cookers = new Semaphore(2); public int cook(Cooker cooker) { if (cookers.tryAcquire()) { System.out.println(cooker.getCkName() +" starts to cook"); Utils.goSleep(8); cookers.release(); return 1; } else { System.out.println(cooker.getCkName() +" is peeling potatoes and cutting vegetables"); Utils.goSleep(3); return 0; } } } <file_sep>/src/Program.java import personal.*; import places.*; import resources.Stacks; public class Program { public static void main(String[] args) { Restaurant rest = new Restaurant(10); Stacks stacks = new Stacks(); Kitchen kitchen = new Kitchen(); // Client clt = new Client("pepe","azucar",rest); Client[] clt = new Client[20]; Waiter[] waitrs = new Waiter[5]; Cooker[] cookrs = new Cooker[3]; for(int i=0; i<clt.length; i++) { clt[i] = new Client("Client-"+i,"order-"+i,rest); clt[i].start(); } for(int i=0; i<waitrs.length; i++) { waitrs[i] = new Waiter("Waiter-"+i,rest,stacks); waitrs[i].start(); } for(int i=0; i<cookrs.length; i++) { cookrs[i] = new Cooker("Cooker-"+i,kitchen,stacks); cookrs[i].start(); } } }
1660e372085d1c251bd432cf702b542fae41b439
[ "Java" ]
6
Java
a18simongv/GestionRestaurant
09021259f43085c3de26e5a5ee4e806f9441476d
142d6698dd8ad5a36955d9d89902cb19e62faadb
refs/heads/master
<repo_name>malkaviano/fleet-front<file_sep>/src/app/components/form/form.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ActivatedRoute, convertToParamMap } from '@angular/router'; import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing'; import { FormsModule } from '@angular/forms'; import { mock, instance } from 'ts-mockito'; import { ToastrService } from 'ngx-toastr'; import { of } from 'rxjs'; import { FormComponent } from './form.component'; describe('FormComponent', () => { let component: FormComponent; let fixture: ComponentFixture<FormComponent>; const mockedToast = mock(ToastrService); beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [FormComponent], imports: [HttpClientTestingModule, FormsModule], providers: [ { provide: 'VEHICLE_URL', useValue: 'testeUrl' }, { provide: ToastrService, useValue: instance(mockedToast) }, { provide: ActivatedRoute, useValue: { params: of({ update: 'false' }) } }, ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FormComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/components/fleet/fleet.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { BsModalService, BsModalRef } from 'ngx-bootstrap'; import { faEdit, faEraser } from '@fortawesome/free-solid-svg-icons'; import { Vehicle } from '../../models/vehicle.model'; import { DialogComponent } from '../dialog/dialog.component'; @Component({ selector: 'app-fleet', templateUrl: './fleet.component.html', styleUrls: ['./fleet.component.css'] }) export class FleetComponent implements OnInit { public faEdit = faEdit; public faEraser = faEraser; public title = 'Fleet'; public dialogRef: BsModalRef; public fleet: Vehicle[]; constructor( private router: Router, private modalService: BsModalService, private http: HttpClient, @Inject('VEHICLE_URL') private url: string ) { } ngOnInit(): void { this.load(); } load() { this.http.get(this.url).subscribe( done => { const r: Vehicle[] = []; for (const obj of (done as any[])) { r.push({ series: obj['chassisId']['series'], number: obj['chassisId']['number'], type: obj['type'], color: obj['color'], passengers: obj['passengers'] }); } this.fleet = r; }, err => console.error(err) ); } create() { this.router.navigate(['/form']); } edit(series: string, number: number) { this.router.navigate(['/form', { update: true, series, number }]); } delete(series: string, number: number) { this.http.delete(`${this.url}/${series}/${number}`).subscribe( done => this.load(), err => console.error(err) ); } openDialog(series: string, number: number) { this.dialogRef = this.modalService.show(DialogComponent); this.dialogRef.content.notifyParent.subscribe((result) => { if (result) { this.delete(series, number); } }); } } <file_sep>/src/app/models/vehicle.model.ts export class Vehicle { series: string; number: number; type: string; passengers: number; color: string; }<file_sep>/src/app/components/form/form.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent implements OnInit { public title = 'Vehicle'; public update: boolean; public form: any; constructor( private http: HttpClient, @Inject('VEHICLE_URL') private url: string, private route: ActivatedRoute, private toastr: ToastrService ) { this.form = { series: '', number: '', type: '', color: '', passengers: '' } } ngOnInit(): void { this.route.params.subscribe( params => { this.update = !!params['update']; if (this.update) { const series = params['series']; const number = params['number']; this.http.get(`${this.url}/${series}/${number}`).subscribe( done => this.form = { series: done['chassisId']['series'], number: done['chassisId']['number'], type: done['type'], color: done['color'], passengers: done['passengers'] }, err => this.toastr.error("Error loading the vehicle") ); } } ); } submit(values: any) { if (this.update) { this.http.put( this.url, { "series": this.form['series'], "number": this.form['number'], "color": values['color'] } ).subscribe( done => this.toastr.success("Vehicle color changed"), err => this.toastr.error("Error changing vehicle color") ); } else { this.http.post( this.url, { "series": values['series'], "number": values['number'], "color": values['color'], "type": values['type'] } ).subscribe( done => this.toastr.success("Vehicle created"), err => this.toastr.error("Error creating vehicle") ); } } }
f03ec06d13a7c0093c19b64ad4c21568287efe24
[ "TypeScript" ]
4
TypeScript
malkaviano/fleet-front
9a715e4419abe2f04ba33ae9a56802791f9ccb72
01f346e28f15d2a808cf11e72975cfb489c89b6c
refs/heads/master
<repo_name>JoaoPedroBSantana/projeto-teste<file_sep>/projeto01/src/br/com/joao/git/simounao.java package br.com.joao.git; public class simounao { public static void main (String[] args) { System.out.println("voce ta bem?"); } } <file_sep>/projeto01/src/br/com/joao/git/olamundo.java package br.com.joao.git; public class olamundo { public static void main(String[] args) { System.out.println("ola mundo"); System.out.println("tudo bem?"); } }
1d77d352603a03477ff0a0f77be10828e3479fca
[ "Java" ]
2
Java
JoaoPedroBSantana/projeto-teste
6ea12c2bd6d8754c2895afe1f31b1cc940dc55d2
345e238480de7bbaa62ede00305fc615530663ab
refs/heads/master
<repo_name>pituganov/reinforcement-learning<file_sep>/main.py """ Основной модуль """ # pylint: disable=C0321 # pylint: disable=E1101 import random import pygame import player import wall import settings import world #Инициализация окна pygame.init() CRASHED = False P = player.Player(450, 550) EPS = 20 #Основной цикл игры while not CRASHED: for event in pygame.event.get(): if event.type == pygame.QUIT: CRASHED = True settings.GAME_DISPLAY.fill(settings.WHITE) PREVIOUS_X, PREVIOUS_Y = P.x, P.y P.controller_polar() #Обрабатывает цели for i in range(len(world.GAME_WORLD.target)): (x, y) = world.GAME_WORLD.target[i] #обрабатывает попадание в цель if abs(P.x - x) <= EPS and abs(P.y - y) <= EPS: P.score += 1 world.GAME_WORLD.target[i] = (random.randint(0, settings.DISPLAY_WIDTH-25), random.randint(0, settings.DISPLAY_HEIGHT-25)) pygame.draw.circle(settings.GAME_DISPLAY, settings.BLACK, (x, y), 22) pygame.draw.circle(settings.GAME_DISPLAY, settings.GREEN, (x, y), 20) #Обрабатывает столкновение со стенами for wall in world.GAME_WORLD.walls: wall.draw() if wall.is_collide(P, 30): P.x, P.y = PREVIOUS_X, PREVIOUS_Y PREVIOUS_X, PREVIOUS_Y = P.x, P.y for i in range(len(world.GAME_WORLD.falseTarget)): (x, y) = world.GAME_WORLD.falseTarget[i] #обрабатывает попадание в цель if abs(P.x - x) <= EPS and abs(P.y - y) <= EPS: P.score += -1 world.GAME_WORLD.falseTarget[i] = (random.randint(0, settings.DISPLAY_WIDTH-25), random.randint(0, settings.DISPLAY_HEIGHT-25)) pygame.draw.circle(settings.GAME_DISPLAY, settings.BLACK, (x, y), 22) pygame.draw.circle(settings.GAME_DISPLAY, settings.RED, (x, y), 20) settings.message_display(str(P.score)) P.draw() #Отрисовывает кадр pygame.display.update() #FPS settings.CLOCK.tick(30) pygame.quit() quit() <file_sep>/README.md # reinforcement-learning Обучение алгоритма с подкреплением на примере простой игры. <file_sep>/settings.py """ Модуль, в котором записаны основные настройки и функции, используемые для pygame """ import pygame #Цвета RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) DISPLAY_WIDTH = 800 DISPLAY_HEIGHT = 600 GAME_DISPLAY = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT)) pygame.display.set_caption('Игра') CLOCK = pygame.time.Clock() def text_objects(text, font): "Преобразует строку text в объект" _text_surface = font.render(text, True, BLACK) return _text_surface, _text_surface.get_rect() #Рисует текст def message_display(text): "Отображает text на экране" _large_text = pygame.font.Font('freesansbold.ttf', 115) _text_surf, _text_rect = text_objects(text, _large_text) _text_rect.center = (100, 50) GAME_DISPLAY.blit(_text_surf, _text_rect) <file_sep>/wall.py """ Модуль в котором описан Класс стены """ import math import pygame import settings import point class Wall: """Класс стены""" start = point.Point(0, 0) end = point.Point(0, 0) def __init__(self, a, b): "Конструктор" self.start = a self.end = b def lagrange(self, x_value): """возвращает значение интерполяционной функции Лагранжа для двух точек""" constanta0 = self.start.y/(self.start.x-self.end[0]) constanta1 = self.end[1]/(-self.start.x+self.end[0]) first = (x_value-self.start.x)*(x_value-self.end[0])*constanta0 second = (x_value-self.start.x)*(x_value-self.end[0])*constanta1 return first + second def formula(self, point_a): "Я не помню, что она делает" first = (self.end.y - self.start.y)*point_a.x second = (self.end.x - self.start.x)*point_a.y third = (self.start.x*self.end.y-self.end.x*self.start.y) return first + second + third def cross(self, point_a, point_b): "true, если отрезок АВ пересекает стену" return self.formula(point_a) * self.formula(point_b) <= 0 def draw(self): """ Рисует стену """ pygame.draw.line(settings.GAME_DISPLAY, settings.BLACK, self.start, self.end, 1) def is_collide_point(self, obj): """ true, если объект obj соприкасается со стеной """ #если стена горизонтальная if abs(obj[1]-self.start[1]) <= 1 and abs(obj[1]-self.end[1]) <= 1: return self.start[0] <= obj[0] and self.end[0] >= obj[0] if abs(obj[0]-self.start[0]) <= 1 and abs(obj[0]-self.end[0]) <= 1: return self.start[1] <= obj[1] and self.end[1] >= obj[1] return False def is_collide(self, obj, epsilon): """true, если объект obj соприкасается со стеной""" res = False if math.fabs(self.start[0]-obj.x) <= 5 and math.fabs(self.end[0]-obj.x) <= epsilon: if self.start[1] <= obj.y and self.end[1] >= obj.y: res = True elif math.fabs(self.start[1]-obj.y) <= 5 and math.fabs(self.end[1]-obj.y) <= epsilon: if self.start[0] <= obj.x and self.end[0] >= obj.x: res = True return res <file_sep>/world.py """ Модуль в котором описан Класс со всеми объектами """ import random import wall import settings class World: "Класс со всеми объектами" target = list() # Зеленые цели falseTarget = list() # Красные цели walls = [wall.Wall((0, 0), (settings.DISPLAY_WIDTH, 0)), wall.Wall((0, 0), (0, settings.DISPLAY_HEIGHT)), wall.Wall((0, settings.DISPLAY_HEIGHT), (settings.DISPLAY_WIDTH, settings.DISPLAY_HEIGHT)), wall.Wall((settings.DISPLAY_WIDTH, 0), (settings.DISPLAY_WIDTH, settings.DISPLAY_HEIGHT)), wall.Wall((150, 150), (350, 150)), wall.Wall((350, 150), (350, 450)), wall.Wall((150, 450), (350, 450)), wall.Wall((150+300, 150), (350+300, 150)), wall.Wall((350+300, 150), (350+300, 450)), wall.Wall((150+300, 450), (350+300, 450))] def __init__(self): "Конструктор" for i in range(5): i += 0 self.target.append((random.randint(0, settings.DISPLAY_WIDTH-25), random.randint(0, settings.DISPLAY_HEIGHT-25)) ) self.falseTarget.append((random.randint(0, settings.DISPLAY_WIDTH-25), random.randint(0, settings.DISPLAY_HEIGHT-25)) ) def is_collide_target(self, obj): "true, если obj соприкасается с одной из точек" for i in enumerate(self.target): (_coordinate_x, _coordinate_y) = i[1] #обрабатывает попадание в цель if ((obj[0] - _coordinate_x)**2 + (obj[1] - _coordinate_y)**2) <= 21**2: return True return False def is_collide_false_target(self, obj): "true, если obj соприкасается с одной из красных точек" for i in enumerate(self.falseTarget): (_coordinate_x, _coordinate_y) = i[1] #обрабатывает попадание в цель if ((obj[0] - _coordinate_x)**2 + (obj[1] - _coordinate_y)**2) <= 21**2: return True return False def is_collide_wall(self, obj): """true - если obj попадает хотя бы на одну стену""" for iteration_wall in self.walls: if iteration_wall.is_collide_point(obj): return True return False GAME_WORLD = World() <file_sep>/point.py """ Модуль, описывающий класс точка """ class Point: "Класс, описывающий точку" def __init__(self, x0, y0): "Конструктор" self.x = x0 self.y = y0 def distance_to_line(self, point_1, point_2): "Возвращает расстояние до отрезка [p1, p2]" first = (point_2.y-point_1.y)*self.x - (point_2.x-point_1.x)*self.y second = point_2.x*point_1.y-point_2.y*point_1*self.x numerator = (first + second)**2 denominator = ((point_2.y - point_1.y)**2+(point_2.x - point_1.x)**2) return numerator/denominator class Target(Point): "Класс, описывающий цель" radius = 10 def distance_to(self, point): "Расстояние между целью и точкой point" _distance_x = self.x-point.x _distance_y = self.y-point.y _distance_to_center = (_distance_x**2+_distance_y**2)**0.5 return abs(_distance_to_center - self.radius) <file_sep>/player.py """ Модуль, описывающий класс игрока """ # pylint: disable=C0321 # pylint: disable=E1101 import math import pygame import settings import point import world #Класс для игрока class Player(point.Point): "Класс, описывающий игрока" velocity = 10 angle = 0 score = 0 lines = list() def __init__(self, x0, y0): "Конструктор" point.Point.__init__(self, x0, y0) self.x = x0 self.y = y0 self.score = 0 for _ in range(7): self.lines.append((0, settings.BLACK)) def update_lines(self): "Обновляет линии" for i in range(len(self.lines)): collide_wall = False collide_target = False collide_false_target = False collide = collide_wall or collide_target or collide_false_target while self.lines[i][0] < 100 and not collide: #увеличивает длину луча self.lines[i] = (self.lines[i][0] + 2, self.lines[i][1]) #x и y координаты конца i-го луча angle = self.angle-math.pi/2+math.pi*(i+1)/8 x_coordinate = self.x + self.lines[i][0]*math.cos(angle) y_coordinate = self.y + self.lines[i][0]*math.sin(angle) #определияет сталикивается ли конец луча хотя бы с одной из стен collide_wall = world.GAME_WORLD.is_collide_wall((int(x_coordinate), int(y_coordinate))) collide_target = world.GAME_WORLD.is_collide_target((int(x_coordinate), int(y_coordinate))) collide_false_target = world.GAME_WORLD.is_collide_false_target((int(x_coordinate), int(y_coordinate))) collide = collide_wall or collide_target or collide_false_target #если сталкивается if collide_wall: #меняет цвет луча self.lines[i] = (self.lines[i][0], settings.GREEN) if collide_target: self.lines[i] = (self.lines[i][0], settings.RED) if collide_false_target: self.lines[i] = (self.lines[i][0], settings.BLUE) def draw(self): """Рисует игрока""" #Обновляет линии """for i in range(len((self.lines)): angle = self.angle-math.pi/2+math.pi*(i+1)/8 # Начало и конец луча A, B = point.Point(self.x, self.y), point.Point(100*cos(angle),100*sin(angle)) min_wall = 100 #Расстояние до ближайшей стены for wall in GAME_WORLD.walls: if wall.cross(A, B): d = self.distance_to_line(wall.start, wall.end) if d < min_wall: min_wall = d min_target = 100 #Расстояние до ближайшей точки for interation_point in GAME_WORLD.target: d = iteration_point.distance_to(self)#Реализовать if d < min_target: min_target = d if min_wall < min_target: self.lines[i] = (self.lines[i][0], green) if min_wall > min_target: #Столкновение с целью if min_wall == min_target and min_wall == 100: self.lines[i] = (100, black)""" #Рисует линии i = 0 for line in self.lines: i += 1 pygame.draw.line(settings.GAME_DISPLAY, line[1], (self.x, self.y), (int(self.x + line[0]*math.cos(self.angle-math.pi/2+math.pi*i/8)), int(self.y + line[0]*math.sin(self.angle-math.pi/2+math.pi*i/8))), 2) self.clear_lines() #Рисует точку pygame.draw.circle(settings.GAME_DISPLAY, settings.BLACK, (self.x, self.y), 22) pygame.draw.circle(settings.GAME_DISPLAY, settings.WHITE, (self.x, self.y), 20) def clear_lines(self): "Обнуляет линии" self.lines = list() for _ in range(7): self.lines.append((0, settings.BLACK)) def move(self, delpha_x, delpha_y): """Передвигает игрока""" self.x += delpha_x self.y += delpha_y def controller_polar(self): """Обрабатывает нажатие клавиатуры элементов управления""" delpha = 0 key_states = pygame.key.get_pressed() if key_states[pygame.K_LEFT]: self.angle += -math.pi/10 elif key_states[pygame.K_RIGHT]: self.angle += +math.pi/10 if key_states[pygame.K_UP]: delpha = self.velocity elif key_states[pygame.K_DOWN]: delpha = -self.velocity else: delpha = 0 self.move(int(delpha * math.cos(self.angle)), int(delpha * math.sin(self.angle))) self.update_lines()
ff3bb933ed210310587e03db7249fa59b6c083c9
[ "Markdown", "Python" ]
7
Python
pituganov/reinforcement-learning
3e448e3a32fb710fbed36579d747fba86f169acb
172ab53d0b32dd752cf7362c72217232e49eaf57
refs/heads/master
<repo_name>dgrnbrg/lapack<file_sep>/README.md # LAPACK [![Package][package-img]][package-url] [![Documentation][documentation-img]][documentation-url] [![Build][build-img]][build-url] The package provides an interface to the [Linear Algebra PACKage][lapack]. ## Configuration The underlying implementation of LAPACK to compile, if needed, and link to can be chosen among the following options: * Apple’s [Accelerate framework][accelerate] (macOS only), * Netlib’s [reference implementation][netlib], and * [OpenBLAS][openblas] (default). An implementation can be chosen using the package’s features as follows: ```toml [dependencies] # Apple’s Accelerate framework lapack = { version = "0.13", default-features = false, features = ["accelerate"] } # Netlib’s reference implementation lapack = { version = "0.13", default-features = false, features = ["netlib"] } # OpenBLAS lapack = { version = "0.13", default-features = false, features = ["openblas"] } # OpenBLAS lapack = { version = "0.13" } ``` ## Example (C) ```rust use lapack::c::*; let n = 3; let mut a = vec![3.0, 1.0, 1.0, 1.0, 3.0, 1.0, 1.0, 1.0, 3.0]; let mut w = vec![0.0; n as usize]; let info; unsafe { info = dsyev(Layout::ColumnMajor, b'V', b'U', n, &mut a, n, &mut w); } assert_eq!(info, 0); for (one, another) in w.iter().zip(&[2.0, 2.0, 5.0]) { assert!((one - another).abs() < 1e-14); } ``` ## Example (Fortran) ```rust use lapack::fortran::*; let n = 3; let mut a = vec![3.0, 1.0, 1.0, 1.0, 3.0, 1.0, 1.0, 1.0, 3.0]; let mut w = vec![0.0; n as usize]; let mut work = vec![0.0; 4 * n as usize]; let lwork = 4 * n; let mut info = 0; unsafe { dsyev(b'V', b'U', n, &mut a, n, &mut w, &mut work, lwork, &mut info); } assert_eq!(info, 0); for (one, another) in w.iter().zip(&[2.0, 2.0, 5.0]) { assert!((one - another).abs() < 1e-14); } ``` ## Contribution Your contribution is highly appreciated. Do not hesitate to open an issue or a pull request. Note that any contribution submitted for inclusion in the project will be licensed according to the terms given in [LICENSE.md](LICENSE.md). [accelerate]: https://developer.apple.com/reference/accelerate [lapack]: https://en.wikipedia.org/wiki/LAPACK [netlib]: http://www.netlib.org/lapack [openblas]: http://www.openblas.net [build-img]: https://travis-ci.org/stainless-steel/lapack.svg?branch=master [build-url]: https://travis-ci.org/stainless-steel/lapack [documentation-img]: https://docs.rs/lapack/badge.svg [documentation-url]: https://docs.rs/lapack [package-img]: https://img.shields.io/crates/v/lapack.svg [package-url]: https://crates.io/crates/lapack <file_sep>/src/lib.rs //! Interface to the [Linear Algebra PACKage][lapack]. //! //! ## Configuration //! //! The underlying implementation of LAPACK to compile, if needed, and link to //! can be chosen among the following options: //! //! * Apple’s [Accelerate framework][accelerate] (macOS only), //! * Netlib’s [reference implementation][netlib], and //! * [OpenBLAS][openblas] (default). //! //! An implementation can be chosen using the package’s features as follows: //! //! ```toml //! [dependencies] //! # Apple’s Accelerate framework //! lapack = { version = "0.13", default-features = false, features = ["accelerate"] } //! # Netlib’s reference implementation //! lapack = { version = "0.13", default-features = false, features = ["netlib"] } //! # OpenBLAS //! lapack = { version = "0.13", default-features = false, features = ["openblas"] } //! # OpenBLAS //! lapack = { version = "0.13" } //! ``` //! //! [accelerate]: https://developer.apple.com/reference/accelerate //! [lapack]: https://en.wikipedia.org/wiki/LAPACK //! [netlib]: http://www.netlib.org/lapack //! [openblas]: http://www.openblas.net extern crate lapack_sys; extern crate libc; extern crate num_complex as num; /// A complex number with 32-bit parts. #[allow(non_camel_case_types)] pub type c32 = num::Complex<f32>; /// A complex number with 64-bit parts. #[allow(non_camel_case_types)] pub type c64 = num::Complex<f64>; #[cfg(not(feature = "accelerate"))] pub mod c; pub mod fortran; <file_sep>/Cargo.toml [package] name = "lapack" version = "0.13.2" license = "Apache-2.0/MIT" authors = [ "<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>", ] description = "The package provides an interface to the Linear Algebra PACKage." documentation = "https://docs.rs/lapack" homepage = "https://github.com/stainless-steel/lapack" repository = "https://github.com/stainless-steel/lapack" readme = "README.md" categories = ["api-bindings", "science"] keywords = ["linear-algebra"] exclude = ["bin/*"] [features] default = ["openblas"] accelerate = ["lapack-sys/accelerate"] netlib = ["lapack-sys/netlib"] openblas = ["lapack-sys/openblas"] [dependencies] libc = "0.2" [dependencies.num-complex] version = "0.1" default-features = false [dependencies.lapack-sys] version = "0.11" default-features = false <file_sep>/src/common.rs use libc::c_char; use std::mem::transmute; use {c32, c64}; pub type Select2F32 = Option<extern "C" fn(*const f32, *const f32) -> i32>; pub type Select3F32 = Option<extern "C" fn(*const f32, *const f32, *const f32) -> i32>; pub type Select2F64 = Option<extern "C" fn(*const f64, *const f64) -> i32>; pub type Select3F64 = Option<extern "C" fn(*const f64, *const f64, *const f64) -> i32>; pub type Select1C32 = Option<extern "C" fn(*const c32) -> i32>; pub type Select2C32 = Option<extern "C" fn(*const c32, *const c32) -> i32>; pub type Select1C64 = Option<extern "C" fn(*const c64) -> i32>; pub type Select2C64 = Option<extern "C" fn(*const c64, *const c64) -> i32>;
4abb8b310ed593ed2c3ba3da7e154325edd25121
[ "Markdown", "Rust", "TOML" ]
4
Markdown
dgrnbrg/lapack
252fca2f5fa4e8a27ab2d39dee70d9858c6070cf
a5e3bf73a17b375f212809ee879fb3311baf8e81
refs/heads/master
<repo_name>MoDawod/javascript-test<file_sep>/site/main.js // adding tasks var tname, tdate, ttime, testimated ,tArea; function addtask(){ tname = document.getElementById("newtask").value; tdate= document.getElementById("startdate").value; ttime = document.getElementById("stime").value; testimated= document.getElementById("estimated").value; tArea= document.getElementById("notices").value; (function(){ if(tname == ""|| tdate == "" || ttime == "" || testimated== ""){ alert('Please fill in all fields') } else { var slcTable= document.getElementsByTagName('table')[0]; var newRow= slcTable.insertRow(slcTable.rows.length); var cel1=newRow.insertCell(0); var cel2=newRow.insertCell(1); var cel3=newRow.insertCell(2); var cel4=newRow.insertCell(3); cel1.innerHTML=tname; cel2.innerHTML=tdate; cel3.innerHTML=ttime; cel4.innerHTML=testimated; // saving in local storage var taskObject = { name : tname, date : tdate, time : ttime, duration : testimated, notice : tArea } myjson = localStorage.setItem(tname,JSON.stringify(taskObject)); // resetting the form document.getElementById("newtask").value = " "; document.getElementById("startdate").value = " "; document.getElementById("stime").value = ""; document.getElementById("estimated").value = ""; document.getElementById("notices").value = ""; } })(); } // about button function About(){ alert(" Task Manager V 1.0.0\n Designed By <NAME> \n <EMAIL>") } // retrieving from local Storage window.onload = function allStorage() { for (var i = 0; i < localStorage.length; i++) { // set iteration key name var key = localStorage.key(i); // use key name to retrieve the corresponding value var value = localStorage.getItem(key); // console.log the iteration key and value var obj = JSON.parse(value); var slcTable= document.getElementsByTagName('table')[0]; var newRow= slcTable.insertRow(slcTable.rows.length); var cel1=newRow.insertCell(0); var cel2=newRow.insertCell(1); var cel3=newRow.insertCell(2); var cel4=newRow.insertCell(3); cel1.innerHTML=obj.name; cel2.innerHTML=obj.date; cel3.innerHTML=obj.time; cel4.innerHTML=obj.duration; } } <file_sep>/README.md # javascript-test ## Quick start Run the project with the following command: ```javascript npm install npm start ```
773d40488c23882b009f616c2ca261a3d4533cf5
[ "JavaScript", "Markdown" ]
2
JavaScript
MoDawod/javascript-test
4f2dd8a9065676b28c7249980f2a65b487cd63b6
61537a846fa90dcfcc61822e9390d4749b612557
refs/heads/master
<file_sep>/* * @lc app=leetcode.cn id=71 lang=javascript * * [71] 简化路径 */ // @lc code=start /** * @param {string} path * @return {string} */ var simplifyPath = function(path) { let stark = [] path = path.split('/') path.forEach(dir => { if (!dir) return; if (dir === '..') { stark.pop() } else if (dir !== '.') { stark.push(dir); } }) return `/${stark.join('/')}` }; // @lc code=end <file_sep>/* * @lc app=leetcode.cn id=509 lang=javascript * * [509] 斐波那契数 */ // @lc code=start /** * @param {number} N * @return {number} */ var fib = function(N) { if(N === 0 || N=== 1) return N; let preNum = 0,currNum = 1,index = 1,result; while (index !== N) { result = preNum + currNum; preNum = currNum; currNum = result; index ++; } return currNum; }; // @lc code=end <file_sep>/* * @lc app=leetcode.cn id=1 lang=javascript * * [1] 两数之和 */ // @lc code=start /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let res = {}; for (let i = 0; i < nums.length; i++) { const num = nums[i]; const diff = target - num; if (num in res) { return [res[num], i]; } else { res[diff] = i; } } }; // @lc code=end <file_sep>/* * @lc app=leetcode.cn id=15 lang=javascript * * [15] 三数之和 */ // @lc code=start /** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { if (nums.length < 3) return []; const target = 0; let result = []; // 最终返回的结果 nums = nums.sort((a,b) => a-b) // nums = [ -4, -1, -1, 0, 1, 2 ] // 0 // i => -4 // left => -1 // right => 2 // 1 // i => -4 // left => 0 // right => 2 // 2 // i => -4 // left => 1 // right => 2 // 3 // i => -1 // left => -1 // right => 2 // 4 // i => -1 // left => 0 // right => 1 for (let i = 0; i<nums.length ; i ++) { if (nums[i] > target) break // 3个值都大于目标值时 相加不可能等于目标 if (nums[i] === nums[i - 1]) continue; // 去重 let left = i + 1; let right = nums.length - 1; while (left < right) { const first = nums[i] const second = nums[left] const third = nums[right] const sum = first + second + third if ( sum === target) { result.push([first, second ,third]) while (left<right && nums[left] == nums[left+1]) left++; // 去重 当下一个left的值与当前相等时,则直接跳过 while (left<right && nums[right] == nums[right-1]) right--; // 去重 当下一个right的值与当前相等时,则直接跳过 left++ right--; } else if (sum < target) left++; else if (sum > target) right--; } } return result; }; // @lc code=end
664ef4cd0e6de24ea32f5ec46a0293d171bb2670
[ "JavaScript" ]
4
JavaScript
aniu2016/leetcode-javascript
6e1029a05a4670bcfe7abac571b87993b01d80ff
e7fa03dfa96b0f8b0132e69c3b995f981c38e764
refs/heads/master
<file_sep> import React, {Component} from 'react'; class ChatBar extends Component { render() { const { currentUser } = this.props; return ( <footer className='chatbar'> <input className='chatbar-username' placeholder='<NAME> (Optional)' defaultValue={ this.props.currentUser } onKeyPress={ this.props.changeUser } /> <input className='chatbar-message' placeholder='Type a message and hit ENTER' onKeyPress={ this.props.onMessage } /> </footer> ); } } export default ChatBar; <file_sep> import React, { Component } from 'react'; class Message extends Component { parseType() { let styles = { color: this.props.color } switch(this.props.type) { case 'incomingMessage': return ( <div className='message'> <span className='message-username' style={ styles }>{ this.props.username }</span> <span className='message-content'>{ this.props.content }</span> </div> ) break; case 'incomingNotification': return ( <div className='message system'> { this.props.content } </div> ) break; case 'incomingImage': return ( <div> <span className='message-username' style={ styles }>{ this.props.username }</span> <span><img src={this.props.content} /></span> </div> ) break; } } render() { return ( <div className='messages'> {this.parseType()} </div> ) } } export default Message; <file_sep># Chatty Full stack, real time web app that allows users to communicate with each other without having to register accounts. ## Screenshots Home Page - The Room ![Home](https://github.com/marshalldanel/chatty/blob/master/client/docs/homepg.png?raw=true) ## Project Stack - [React](https://facebook.github.io/react/) - [Webpack](https://webpack.github.io/) with [babel](https://github.com/babel/babel-loader), [JSX](https://facebook.github.io/react/docs/jsx-in-depth.html), ES6 and [webpack-dev-server](https://github.com/webpack/webpack-dev-server) - Websockets using [Node](https://www.npmjs.com/package/websocket) on the server side, and native WebSocket on the client side ## Versioning * 0.1.0 * LHL Project # 4 * More features on the horizon ## Getting Started 1. Fork this repository, then clone your fork of this repository. 2. Install dependencies using the `npm install` command. 3. Start the web server using the `npm run local` command. The app will be served at <http://localhost:8080/>. 4. Go to <http://localhost:8080/> in your browser. 5. Fantastic. Go send some events to your friends, or your parents, or some strangers. ### Contributing 1. Fork it (<https://github.com/yourname/yourproject/fork>) 2. Create your feature branch (`git checkout -b feature/stuff`) 3. Commit your changes (`git commit -am 'Add some stuff'`) 4. Push to the branch (`git push origin feature/stuff`) 5. Create a new Pull Request ### Authors - [<NAME>](https://github.com/marshalldanel/) ### Acknowledgments - The folks at [Lighthouse Labs](https://www.lighthouselabs.ca/) for their free and typically fast wifi
a23044b6eada3e3fd64fa0004761f34592094edb
[ "JavaScript", "Markdown" ]
3
JavaScript
marshalldanel/chatty
1e5d929b05de7d9d175e70aa50c360ac0f1cd01c
d0f30211b801ae70333bb56762735802bfbe8742
refs/heads/main
<file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.functions['*'].included_files[1] = 'two' }, } <file_sep>'use strict' const { exit } = require('process') module.exports = { onPreBuild() { exit(1) }, onBuild() { console.log('test') }, } <file_sep>'use strict' module.exports = { onPreBuild({ utils: { cache } }) { console.log(Object.keys(cache).sort().join(' ')) }, } <file_sep>import isPlainObj from 'is-plain-obj' import data from './data.json' export const onRequest = function (event) { return [isPlainObj({}), data.a, event] } <file_sep>'use strict' module.exports = () => 'one' <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig: { headers } }) { console.log(headers) }, onBuild({ netlifyConfig: { headers } }) { console.log(headers) }, } <file_sep>[[edge_handlers]] path = "/src" handler = "log" [[context.production.edge_handlers]] path = "/srcTest" handler = "logTest" <file_sep>'use strict' const mathAvg = require('math-avg') module.exports = () => mathAvg([]) <file_sep>'use strict' module.exports = { onBuild({ netlifyConfig }) { console.log(netlifyConfig.functionsDirectory) }, } <file_sep>'use strict' const { env, kill } = require('process') const { promisify } = require('util') const processExists = require('process-exists') // TODO: replace with `timers/promises` after dropping Node < 15.0.0 const pSetTimeout = promisify(setTimeout) // 100ms const PROCESS_TIMEOUT = 1e2 module.exports = { async onBuild() { kill(env.TEST_PID) // Signals are async, so we need to wait for the child process to exit // The while loop is required due to `await` // eslint-disable-next-line fp/no-loops, no-await-in-loop while (await processExists(env.TEST_PID)) { // eslint-disable-next-line no-await-in-loop await pSetTimeout(PROCESS_TIMEOUT) } }, } <file_sep>'use strict' const { createServer } = require('net') const { promisify } = require('util') const getPort = require('get-port') const { tmpName } = require('tmp-promise') // Start a TCP server to mock calls. const startTcpServer = async function ({ response = '', useUnixSocket = true } = {}) { const requests = [] const { connectionOpts, address } = await getConnectionOpts({ useUnixSocket }) const server = createServer(onConnection.bind(null, { response, requests })) await promisify(server.listen.bind(server))(connectionOpts) const stopServer = promisify(server.close.bind(server)) return { address, requests, stopServer } } const getConnectionOpts = async function ({ useUnixSocket }) { if (useUnixSocket) { const path = await tmpName({ template: 'netlify-test-socket-XXXXXX' }) return { connectionOpts: { path }, address: path } } const host = 'localhost' const port = await getPort() return { connectionOpts: { host, port }, address: `${host}:${port}` } } const onConnection = function ({ response, requests }, socket) { socket.on('data', onNewRequest.bind(null, { response, requests, socket })) } const onNewRequest = function ({ response, requests, socket }, data) { const json = typeof response !== 'string' const dataString = data.toString() const parsedData = json ? JSON.parse(dataString) : dataString requests.push(parsedData) const serializedResponse = json ? JSON.stringify(response, null, 2) : response socket.write(serializedResponse) } module.exports = { startTcpServer } <file_sep>'use strict' const { cwd, version } = require('process') const test = require('ava') const hasAnsi = require('has-ansi') const { runFixture } = require('../helpers/main') const { startServer } = require('../helpers/server') const CANCEL_PATH = '/api/v1/deploys/test/cancel' test('build.failBuild()', async (t) => { await runFixture(t, 'fail_build') }) test('build.failBuild() error option', async (t) => { await runFixture(t, 'fail_build_error_option') }) test('build.failBuild() inside a callback', async (t) => { await runFixture(t, 'fail_build_callback') }) test('build.failBuild() is not available within post-deploy events', async (t) => { await runFixture(t, 'fail_build_post_deploy') }) test('build.failPlugin()', async (t) => { await runFixture(t, 'fail_plugin') }) test('build.failPlugin() inside a callback', async (t) => { await runFixture(t, 'fail_plugin_callback') }) test('build.failPlugin() error option', async (t) => { await runFixture(t, 'fail_plugin_error_option') }) test('build.cancelBuild()', async (t) => { await runFixture(t, 'cancel') }) test('build.cancelBuild() inside a callback', async (t) => { await runFixture(t, 'cancel_callback') }) test('build.cancelBuild() error option', async (t) => { await runFixture(t, 'cancel_error_option') }) const runWithApiMock = async function (t, flags) { const { scheme, host, requests, stopServer } = await startServer({ path: CANCEL_PATH }) try { await runFixture(t, 'cancel', { flags: { testOpts: { scheme, host }, ...flags } }) } finally { await stopServer() } return requests } test('build.cancelBuild() API call', async (t) => { const requests = await runWithApiMock(t, { token: 'test', deployId: 'test' }) t.snapshot(requests) }) test('build.cancelBuild() API call no DEPLOY_ID', async (t) => { const requests = await runWithApiMock(t, { token: 'test' }) t.is(requests.length, 0) }) test('build.cancelBuild() API call no token', async (t) => { const requests = await runWithApiMock(t, { deployId: 'test' }) t.is(requests.length, 0) }) // Node `util.inspect()` output is different from Node 10, leading to // inconsistent test snapshots // @todo: remove once dropping Node 10 if (!version.startsWith('v10.')) { test('build.cancelBuild() API call failure', async (t) => { await runFixture(t, 'cancel', { flags: { token: 'test', deployId: 'test', testOpts: { host: '...', env: false } }, }) }) } test('build.cancelBuild() is not available within post-deploy events', async (t) => { await runFixture(t, 'cancel_post_deploy') }) test('exception', async (t) => { await runFixture(t, 'exception') }) test('exception with static properties', async (t) => { await runFixture(t, 'exception_props') }) test('exception with circular references', async (t) => { await runFixture(t, 'exception_circular') }) test('exception that are strings', async (t) => { await runFixture(t, 'exception_string') }) test('exception that are arrays', async (t) => { await runFixture(t, 'exception_array') }) test('Clean stack traces of build.command', async (t) => { const { returnValue } = await runFixture(t, 'build_command', { flags: { debug: false }, snapshot: false, normalize: false, }) const count = getStackLinesCount(returnValue) t.is(count, 0) }) test('Clean stack traces of plugin event handlers', async (t) => { const { returnValue } = await runFixture(t, 'plugin', { flags: { debug: false }, snapshot: false, normalize: false }) const count = getStackLinesCount(returnValue) t.is(count, 1) }) test('Do not clean stack traces in debug mode', async (t) => { const { returnValue } = await runFixture(t, 'plugin', { flags: { debug: true }, snapshot: false, normalize: false }) const count = getStackLinesCount(returnValue) t.not(count, 1) }) test('Does not clean stack traces of exceptions', async (t) => { const { returnValue } = await runFixture(t, 'stack_exception', { flags: { debug: false }, snapshot: false, normalize: false, }) const count = getStackLinesCount(returnValue) t.not(count, 1) }) test('Clean stack traces of config validation', async (t) => { const { returnValue } = await runFixture(t, 'config_validation', { false: { debug: false }, snapshot: false, normalize: false, }) const count = getStackLinesCount(returnValue) t.is(count, 0) }) const getStackLinesCount = function (returnValue) { return returnValue.split('\n').filter(isStackLine).length } const isStackLine = function (line) { return line.trim().startsWith('at ') } test('Clean stack traces from cwd', async (t) => { const { returnValue } = await runFixture(t, 'plugin', { flags: { debug: false }, snapshot: false, normalize: false }) t.false(returnValue.includes(`onPreBuild (${cwd()}`)) }) test('Clean stack traces but keep error message', async (t) => { const { returnValue } = await runFixture(t, 'plugin', { flags: { debug: false }, snapshot: false, normalize: false }) t.true(returnValue.includes('Error: test')) }) test('Do not log secret values on build errors', async (t) => { await runFixture(t, 'log_secret') }) const BUGSNAG_TEST_KEY = '00000000000000000000000000000000' const flags = { testOpts: { errorMonitor: true }, bugsnagKey: BUGSNAG_TEST_KEY } test('Report build.command failure', async (t) => { await runFixture(t, 'command', { flags }) }) test('Report configuration user error', async (t) => { await runFixture(t, 'config', { flags }) }) test('Report plugin input error', async (t) => { await runFixture(t, 'plugin_input', { flags }) }) test('Report plugin validation error', async (t) => { await runFixture(t, 'plugin_validation', { flags }) }) test('Report plugin internal error', async (t) => { await runFixture(t, 'plugin_internal', { flags }) }) test('Report utils.build.failBuild()', async (t) => { await runFixture(t, 'monitor_fail_build', { flags }) }) test('Report utils.build.failPlugin()', async (t) => { await runFixture(t, 'monitor_fail_plugin', { flags }) }) test('Report utils.build.cancelBuild()', async (t) => { await runFixture(t, 'cancel_build', { flags }) }) test('Report IPC error', async (t) => { await runFixture(t, 'ipc', { flags }) }) test.serial('Report API error', async (t) => { await runFixture(t, 'cancel_build', { flags: { ...flags, token: 'test', deployId: 'test', testOpts: { ...flags.testOpts, env: false } }, }) }) // Node v10 uses a different error message format // TODO: remove once dropping Node 10 if (!version.startsWith('v10.')) { test('Report dependencies error', async (t) => { await runFixture(t, 'dependencies', { flags }) }) } test('Report buildbot mode as releaseStage', async (t) => { await runFixture(t, 'command', { flags: { ...flags, mode: 'buildbot' }, useBinary: true }) }) test('Report CLI mode as releaseStage', async (t) => { await runFixture(t, 'command', { flags: { ...flags, mode: 'cli' }, useBinary: true }) }) test('Report programmatic mode as releaseStage', async (t) => { await runFixture(t, 'command', { flags: { ...flags, mode: 'require' }, useBinary: true }) }) test('Remove colors in error.message', async (t) => { const { returnValue } = await runFixture(t, 'colors', { flags, snapshot: false }) const lines = returnValue.split('\n').filter((line) => line.includes('ColorTest')) t.true(lines.every((line) => !hasAnsi(line))) }) test('Report BUILD_ID', async (t) => { await runFixture(t, 'command', { flags, env: { BUILD_ID: 'test' }, useBinary: true }) }) test('Report plugin homepage', async (t) => { await runFixture(t, 'plugin_homepage', { flags }) }) test('Report plugin homepage without a repository', async (t) => { await runFixture(t, 'plugin_homepage_no_repo', { flags }) }) test('Report plugin origin', async (t) => { const defaultConfig = { plugins: [{ package: './plugin.js' }] } await runFixture(t, 'plugin_origin', { flags: { ...flags, defaultConfig } }) }) test('Report build logs URLs', async (t) => { await runFixture(t, 'command', { flags, env: { DEPLOY_ID: 'testDeployId', SITE_NAME: 'testSiteName' }, useBinary: true, }) }) test('Top-level errors', async (t) => { await runFixture(t, 'top') }) test('Top function errors local', async (t) => { await runFixture(t, 'function') }) test('Node module all fields', async (t) => { await runFixture(t, 'full') }) test('Node module partial fields', async (t) => { await runFixture(t, 'partial') }) test('No repository root', async (t) => { await runFixture(t, 'no_root', { copyRoot: { git: false } }) }) test('Process warnings', async (t) => { await runFixture(t, 'warning') }) test('Uncaught exception', async (t) => { await runFixture(t, 'uncaught') }) test('Unhandled promises', async (t) => { await runFixture(t, 'unhandled_promise') }) test('Exits in plugins', async (t) => { await runFixture(t, 'plugin_exit') }) test('Plugin errors can have a toJSON() method', async (t) => { await runFixture(t, 'plugin_error_to_json') }) // Process exit is different on Windows // @todo: re-enable. This test is currently randomly failing. // @todo: uncomment after upgrading to Ava v4. // See https://github.com/netlify/build/issues/3615 // if (platform !== 'win32') { // test.skip('Early exit', async (t) => { // await runFixture(t, 'early_exit') // }) // } test('Print stack trace of plugin errors', async (t) => { await runFixture(t, 'plugin_stack') }) test('Print stack trace of plugin errors during load', async (t) => { await runFixture(t, 'plugin_load') }) test('Print stack trace of build.command errors', async (t) => { await runFixture(t, 'command_stack') }) test('Print stack trace of build.command errors with stack traces', async (t) => { await runFixture(t, 'command_full_stack') }) test('Print stack trace of Build command UI settings', async (t) => { const defaultConfig = { build: { command: 'node --invalid' } } await runFixture(t, 'none', { flags: { defaultConfig } }) }) test('Print stack trace of validation errors', async (t) => { await runFixture(t, '', { flags: { config: '/invalid' } }) }) // Node `util.inspect()` output is different from Node 10, leading to // inconsistent test snapshots // TODO: remove once dropping Node 10 if (!version.startsWith('v10.')) { test('Redact API token on errors', async (t) => { await runFixture(t, 'api_token_redact', { flags: { token: '<KEY>', deployId: 'test', mode: 'buildbot', testOpts: { host: '...' } }, }) }) } <file_sep># Snapshot report for `packages/build/tests/log/tests.js` The actual snapshot is saved in `tests.js.snap`. Generated by [AVA](https://avajs.dev). ## Logs whether the build commands came from the UI > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/log/fixtures/empty␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/log/fixtures/empty␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: ui␊ publish: packages/build/tests/log/fixtures/empty␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Build command from Netlify app ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In Build command from Netlify app:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: ui␊ publish: packages/build/tests/log/fixtures/empty␊ publishOrigin: default␊ ␊ node: bad option: --invalid` <file_sep>'use strict' const { writeFile, readFile, readdir } = require('fs') const { join, basename } = require('path') const { promisify } = require('util') const del = require('del') const { dir: getTmpDir, tmpName } = require('tmp-promise') // TODO: replace with `timers/promises` after dropping Node < 15.0.0 const pSetTimeout = promisify(setTimeout) const pWriteFile = promisify(writeFile) const pReadFile = promisify(readFile) const pReaddir = promisify(readdir) const createTmpDir = async function (opts) { const { path } = await getTmpDir({ ...opts, prefix: PREFIX }) return path } // Utility method to create a single temporary file and directory const createTmpFile = async function ({ name, ...opts } = {}) { const [[tmpFile], tmpDir] = await createTmpFiles([{ name }], opts) return [tmpFile, tmpDir] } // Create multiple temporary files with a particular or random name, i.e. // createTmpFiles([{name: 'test'}, {} {}]) => creates 3 files, one of them named test, under the same temporary dir const createTmpFiles = async function (files, opts) { const tmpDir = await createTmpDir(opts) const tmpFiles = await Promise.all( files.map(async ({ name }) => { const filename = name || basename(await tmpName()) const tmpFile = join(tmpDir, filename) await pWriteFile(tmpFile, '') return tmpFile }), ) return [tmpFiles, tmpDir] } const PREFIX = 'test-cache-utils-' const removeFiles = function (paths) { return del(paths, { force: true }) } module.exports = { pSetTimeout, pWriteFile, pReadFile, pReaddir, createTmpDir, createTmpFile, createTmpFiles, removeFiles, } <file_sep>'use strict' module.exports = { onPreBuild({ inputs: { test } }) { console.log(test) }, } <file_sep>'use strict' const moduleName = 'test' // eslint-disable-next-line import/no-dynamic-require module.exports = require(moduleName) <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.build.environment.TEST_TWO = 'two' }, onBuild({ netlifyConfig: { build: { environment }, }, }) { console.log(environment) }, } <file_sep>'use strict' const { writeFile } = require('fs') const { promisify } = require('util') const pWriteFile = promisify(writeFile) module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.build.publish = 'test' }, async onBuild({ netlifyConfig: { headers }, constants: { PUBLISH_DIR } }) { console.log(headers) console.log(PUBLISH_DIR) await pWriteFile(`${PUBLISH_DIR}/_headers`, '/path\n test: one') }, onPostBuild({ netlifyConfig: { headers } }) { console.log(headers) }, } <file_sep>'use strict' module.exports = { onPreBuild({ inputs: { one } }) { console.log(one) }, } <file_sep>'use strict' const { stableStringify } = require('fast-safe-stringify') const { getBinPath } = require('get-bin-path') // Tests require the full monorepo to be present at the moment // TODO: split tests utility into its own package const resolveConfig = require('../..') const { runFixtureCommon, FIXTURES_DIR, startServer } = require('../../../build/tests/helpers/common') const ROOT_DIR = `${__dirname}/../..` const getFixtureConfig = async function (t, fixtureName, opts) { const { returnValue } = await runFixture(t, fixtureName, { snapshot: false, ...opts }) try { return JSON.parse(returnValue) } catch (error) { return returnValue } } const runFixture = async function (t, fixtureName, { flags = {}, env, ...opts } = {}) { const binaryPath = await BINARY_PATH const flagsA = { stable: true, buffer: true, branch: 'branch', featureFlags: { ...DEFAULT_TEST_FEATURE_FLAGS, ...flags.featureFlags }, ...flags, } // Ensure local environment variables aren't used during development const envA = { NETLIFY_AUTH_TOKEN: '', ...env } return runFixtureCommon(t, fixtureName, { ...opts, flags: flagsA, env: envA, mainFunc, binaryPath }) } const DEFAULT_TEST_FEATURE_FLAGS = {} // In tests, make the return value stable so it can be snapshot const mainFunc = async function (flags) { const { logs: { stdout = [], stderr = [] } = {}, ...result } = await resolveConfig(flags) const resultA = serializeApi(result) const resultB = stableStringify(resultA, null, 2) const resultC = [stdout.join('\n'), stderr.join('\n'), resultB].filter(Boolean).join('\n\n') return resultC } const serializeApi = function ({ api, ...result }) { if (api === undefined) { return result } return { ...result, hasApi: true } } // Use a top-level promise so it's only performed once at load time const BINARY_PATH = getBinPath({ cwd: ROOT_DIR }) module.exports = { getFixtureConfig, runFixture, FIXTURES_DIR, startServer } <file_sep>'use strict' const { spawn } = require('child_process') module.exports = { onPreBuild() { const { pid } = spawn('node', [`${__dirname}/forever.js`], { detached: true, stdio: 'ignore' }) console.log(`PID: ${pid}`) }, } <file_sep>'use strict' const isNetlifyMagic = true module.exports = () => isNetlifyMagic <file_sep>'use strict' // From CLI `--featureFlags=a,b,c` to programmatic `{ a: true, b: true, c: true }` const normalizeCliFeatureFlags = function (cliFeatureFlags) { return Object.assign({}, ...cliFeatureFlags.split(',').filter(isNotEmpty).map(getFeatureFlag)) } const isNotEmpty = function (name) { return name.trim() !== '' } const getFeatureFlag = function (name) { return { [name]: true } } // Default values for feature flags const DEFAULT_FEATURE_FLAGS = { netlify_config_toml_backslash: false, } module.exports = { normalizeCliFeatureFlags, DEFAULT_FEATURE_FLAGS } <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.edge_handlers = [{ path: '/two', handler: 'two' }] }, onBuild({ netlifyConfig }) { console.log(netlifyConfig.edge_handlers) }, } <file_sep># Changelog ### [2.0.4](https://www.github.com/netlify/build/compare/cache-utils-v2.0.3...cache-utils-v2.0.4) (2021-10-01) ### Bug Fixes * **deps:** update dependency globby to v11 ([#3487](https://www.github.com/netlify/build/issues/3487)) ([6776522](https://www.github.com/netlify/build/commit/677652284d345b5d0db4344a93c92546559735c1)) ### [2.0.3](https://www.github.com/netlify/build/compare/cache-utils-v2.0.2...cache-utils-v2.0.3) (2021-08-18) ### Bug Fixes * **cache-utils:** don't cache junk files nor list them as cached ([#3516](https://www.github.com/netlify/build/issues/3516)) ([2aa9641](https://www.github.com/netlify/build/commit/2aa96413cdd3daf8fa73a9ac26ee2f6c85fc89b7)) ### [2.0.2](https://www.github.com/netlify/build/compare/cache-utils-v2.0.1...cache-utils-v2.0.2) (2021-08-16) ### Bug Fixes * **deps:** update dependency locate-path to v6 ([#3490](https://www.github.com/netlify/build/issues/3490)) ([523b049](https://www.github.com/netlify/build/commit/523b0496c90e4c80fcabd406022a2423b12d0a90)) * **deps:** update dependency move-file to v2 ([#3492](https://www.github.com/netlify/build/issues/3492)) ([9a71aab](https://www.github.com/netlify/build/commit/9a71aab0b9fdddbc56718b8956ecc0c6e427a8a0)) ### [2.0.1](https://www.github.com/netlify/build/compare/cache-utils-v2.0.0...cache-utils-v2.0.1) (2021-08-13) ### Bug Fixes * **deps:** update dependency get-stream to v6 ([#3456](https://www.github.com/netlify/build/issues/3456)) ([478a039](https://www.github.com/netlify/build/commit/478a03946579729a5796eb1a395389eafcc9168e)) ## [2.0.0](https://www.github.com/netlify/build/compare/cache-utils-v1.0.7...cache-utils-v2.0.0) (2021-07-23) ### ⚠ BREAKING CHANGES * deprecate Node 8 (#3322) ### Miscellaneous Chores * deprecate Node 8 ([#3322](https://www.github.com/netlify/build/issues/3322)) ([9cc108a](https://www.github.com/netlify/build/commit/9cc108aab825558204ffef6b8034f456d8d11879)) ### [1.0.7](https://www.github.com/netlify/build/compare/cache-utils-v1.0.6...v1.0.7) (2021-02-18) ### Bug Fixes * fix `files` in `package.json` with `npm@7` ([#2278](https://www.github.com/netlify/build/issues/2278)) ([e9df064](https://www.github.com/netlify/build/commit/e9df0645f3083a0bb141c8b5b6e474ed4e27dbe9)) <file_sep># Changelog ### [18.13.9](https://www.github.com/netlify/build/compare/build-v18.13.8...build-v18.13.9) (2021-10-06) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.5 ([#3693](https://www.github.com/netlify/build/issues/3693)) ([3f417f4](https://www.github.com/netlify/build/commit/3f417f4088baa7c6090d86440c06a2df8a66b1cd)) ### [18.13.8](https://www.github.com/netlify/build/compare/build-v18.13.7...build-v18.13.8) (2021-10-05) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.4 ([#3687](https://www.github.com/netlify/build/issues/3687)) ([a6ab7b9](https://www.github.com/netlify/build/commit/a6ab7b9dbfebd21bcedcb5dbada4d1620cd6192a)) * simplify plugin's Node.js version in local builds ([#3691](https://www.github.com/netlify/build/issues/3691)) ([bd0b102](https://www.github.com/netlify/build/commit/bd0b1024d3e7bb6c69493e12eb0f75876f11c9ec)) ### [18.13.7](https://www.github.com/netlify/build/compare/build-v18.13.6...build-v18.13.7) (2021-10-04) ### Bug Fixes * warn when using odd backslash sequences in netlify.toml ([#3677](https://www.github.com/netlify/build/issues/3677)) ([d3029ac](https://www.github.com/netlify/build/commit/d3029ac8de1e270c2fc2717ed24786506cd112cc)) ### [18.13.6](https://www.github.com/netlify/build/compare/build-v18.13.5...build-v18.13.6) (2021-09-30) ### Bug Fixes * check for functionsSrc in "module not found" error ([#3674](https://www.github.com/netlify/build/issues/3674)) ([34f771f](https://www.github.com/netlify/build/commit/34f771f384234fa5dfd50f605c8c4dfa2c7d7656)) ### [18.13.5](https://www.github.com/netlify/build/compare/build-v18.13.4...build-v18.13.5) (2021-09-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.3 ([#3669](https://www.github.com/netlify/build/issues/3669)) ([cb3fa5f](https://www.github.com/netlify/build/commit/cb3fa5fba1b9e3dd1d7c712d343d3c5adb6db599)) ### [18.13.4](https://www.github.com/netlify/build/compare/build-v18.13.3...build-v18.13.4) (2021-09-27) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to v4 ([#3668](https://www.github.com/netlify/build/issues/3668)) ([098c109](https://www.github.com/netlify/build/commit/098c1092ec3dfa1930ffdaa0e8e8a59703d01930)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.2 ([#3665](https://www.github.com/netlify/build/issues/3665)) ([adc1c43](https://www.github.com/netlify/build/commit/adc1c43fcfb381b79655cddca407d2965a21b61a)) ### [18.13.3](https://www.github.com/netlify/build/compare/build-v18.13.2...build-v18.13.3) (2021-09-27) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.6.2 ([#3664](https://www.github.com/netlify/build/issues/3664)) ([99e472c](https://www.github.com/netlify/build/commit/99e472c2be55764bd0459232dce29b5c8401ffed)) ### [18.13.2](https://www.github.com/netlify/build/compare/build-v18.13.1...build-v18.13.2) (2021-09-27) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.6.1 ([#3656](https://www.github.com/netlify/build/issues/3656)) ([b8f89da](https://www.github.com/netlify/build/commit/b8f89da94ea515e63ffa0babaece6430b00fca7b)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.1 ([#3663](https://www.github.com/netlify/build/issues/3663)) ([64cf36d](https://www.github.com/netlify/build/commit/64cf36db8dc441e1670c4b73fa4e74c6d526f4cc)) ### [18.13.1](https://www.github.com/netlify/build/compare/build-v18.13.0...build-v18.13.1) (2021-09-23) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.0 ([#3653](https://www.github.com/netlify/build/issues/3653)) ([8d36249](https://www.github.com/netlify/build/commit/8d362492ffb2e73d0edfb29968dff8f97319b935)) ## [18.13.0](https://www.github.com/netlify/build/compare/build-v18.12.0...build-v18.13.0) (2021-09-23) ### Features * add support for `parseWithEsbuild` feature flag ([#3632](https://www.github.com/netlify/build/issues/3632)) ([7f2b4dd](https://www.github.com/netlify/build/commit/7f2b4ddce79e69ab08aa2dc7493cc14e2a0c651f)) ## [18.12.0](https://www.github.com/netlify/build/compare/build-v18.11.2...build-v18.12.0) (2021-09-21) ### Features * use internal functions directory in functions utils ([#3630](https://www.github.com/netlify/build/issues/3630)) ([7a17b00](https://www.github.com/netlify/build/commit/7a17b007852436b5e259c2fffde58f90abb7ab2c)) ### [18.11.2](https://www.github.com/netlify/build/compare/build-v18.11.1...build-v18.11.2) (2021-09-21) ### Bug Fixes * remove zisiEsbuildDynamicImports feature flag ([#3638](https://www.github.com/netlify/build/issues/3638)) ([c7a139d](https://www.github.com/netlify/build/commit/c7a139dcdbac344b5501b8c742163c3ab188ed34)) ### [18.11.1](https://www.github.com/netlify/build/compare/build-v18.11.0...build-v18.11.1) (2021-09-21) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.22.0 ([#3634](https://www.github.com/netlify/build/issues/3634)) ([e1175a3](https://www.github.com/netlify/build/commit/e1175a37c5d1af72bf3298a1060cfd1bf2d4cf07)) ## [18.11.0](https://www.github.com/netlify/build/compare/build-v18.10.0...build-v18.11.0) (2021-09-20) ### Features * **build:** pass ES module feature flag to zisi ([#3619](https://www.github.com/netlify/build/issues/3619)) ([5002fc4](https://www.github.com/netlify/build/commit/5002fc4ed0ec63ae89dbd2f43e21446097226afc)) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.21.1 ([#3633](https://www.github.com/netlify/build/issues/3633)) ([5f70b85](https://www.github.com/netlify/build/commit/5f70b850f470c18d8b015b0e150b598fe8c8a571)) ## [18.10.0](https://www.github.com/netlify/build/compare/build-v18.9.1...build-v18.10.0) (2021-09-15) ### Features * remove `netlify_build_warning_missing_headers` feature flag ([#3612](https://www.github.com/netlify/build/issues/3612)) ([fd255b0](https://www.github.com/netlify/build/commit/fd255b0029cc40b0bf99782228b9c78892c2b550)) ### [18.9.1](https://www.github.com/netlify/build/compare/build-v18.9.0...build-v18.9.1) (2021-09-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.21.0 ([#3614](https://www.github.com/netlify/build/issues/3614)) ([541da43](https://www.github.com/netlify/build/commit/541da43fd57b1d0413a649d0b948c4f4ff7aba3d)) ## [18.9.0](https://www.github.com/netlify/build/compare/build-v18.8.0...build-v18.9.0) (2021-09-14) ### Features * warn when `_headers`/`_redirects` file is missing ([#3608](https://www.github.com/netlify/build/issues/3608)) ([254a03b](https://www.github.com/netlify/build/commit/254a03b17bbeed7bc14a27b3be384357c1f72216)) ## [18.8.0](https://www.github.com/netlify/build/compare/build-v18.7.4...build-v18.8.0) (2021-09-07) ### Features * remove `builders` and `buildersDistDir` ([#3581](https://www.github.com/netlify/build/issues/3581)) ([d27906b](https://www.github.com/netlify/build/commit/d27906bc1390dbeb6ebc64279ce7475d418a8514)) ### [18.7.4](https://www.github.com/netlify/build/compare/build-v18.7.3...build-v18.7.4) (2021-09-06) ### Bug Fixes * **deps:** update dependency got to v10 ([#3488](https://www.github.com/netlify/build/issues/3488)) ([6be8f2b](https://www.github.com/netlify/build/commit/6be8f2bd3b48c18c5ce58d1a2f2189c9c0c9b3c2)) ### [18.7.3](https://www.github.com/netlify/build/compare/build-v18.7.2...build-v18.7.3) (2021-09-01) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.6.0 ([#3582](https://www.github.com/netlify/build/issues/3582)) ([a7bdb43](https://www.github.com/netlify/build/commit/a7bdb433242791fb3bb6bb4f32ce9c5c2eb0f907)) * error handling of syntax errors in plugin configuration changes ([#3586](https://www.github.com/netlify/build/issues/3586)) ([56d902d](https://www.github.com/netlify/build/commit/56d902d88353b5b836ca4124b94532fb744470fc)) ### [18.7.2](https://www.github.com/netlify/build/compare/build-v18.7.1...build-v18.7.2) (2021-08-27) ### Bug Fixes * internal functions directory ([#3564](https://www.github.com/netlify/build/issues/3564)) ([11144f4](https://www.github.com/netlify/build/commit/11144f4728147fe59a4ffef7e0fc18274e48d913)) * revert `utils.functions.add()` fix ([#3570](https://www.github.com/netlify/build/issues/3570)) ([4f247d1](https://www.github.com/netlify/build/commit/4f247d15c0e06783332736a98757eb575113123b)) ### [18.7.1](https://www.github.com/netlify/build/compare/build-v18.7.0...build-v18.7.1) (2021-08-27) ### Bug Fixes * file path resolution of `INTERNAL_BUILDERS_SRC` ([#3566](https://www.github.com/netlify/build/issues/3566)) ([2b614b2](https://www.github.com/netlify/build/commit/2b614b2fd5ed5bed7e753b6e16b90135033e2de3)) ## [18.7.0](https://www.github.com/netlify/build/compare/build-v18.6.0...build-v18.7.0) (2021-08-27) ### Features * add `builders` configuration to `@netlify/build` ([#3563](https://www.github.com/netlify/build/issues/3563)) ([daecb3b](https://www.github.com/netlify/build/commit/daecb3b2f95a690f9454ca8ab6e76d2d671ea574)) ## [18.6.0](https://www.github.com/netlify/build/compare/build-v18.5.0...build-v18.6.0) (2021-08-26) ### Features * add `builders.*` and `builders.directory` configuration properties to `@netlify/config` ([#3560](https://www.github.com/netlify/build/issues/3560)) ([4e9b757](https://www.github.com/netlify/build/commit/4e9b757efcdeec5477cd278ec57feb02dbe49248)) ## [18.5.0](https://www.github.com/netlify/build/compare/build-v18.4.3...build-v18.5.0) (2021-08-24) ### Features * add `--buildersDistDir` flag ([#3552](https://www.github.com/netlify/build/issues/3552)) ([49037dd](https://www.github.com/netlify/build/commit/49037dd01e29094255a11ae78ba330c0166348fe)) ### [18.4.3](https://www.github.com/netlify/build/compare/build-v18.4.2...build-v18.4.3) (2021-08-24) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.4.0 ([#3544](https://www.github.com/netlify/build/issues/3544)) ([978f4d1](https://www.github.com/netlify/build/commit/978f4d19723cad958c3a293cc875bc8cf33c5692)) * **deps:** update dependency @netlify/plugins-list to ^3.5.0 ([#3546](https://www.github.com/netlify/build/issues/3546)) ([72c067a](https://www.github.com/netlify/build/commit/72c067a7eed0b2ccb0cdc6b1b34cb8618e4afef4)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.20.0 ([#3551](https://www.github.com/netlify/build/issues/3551)) ([fd2d891](https://www.github.com/netlify/build/commit/fd2d89196ad01882c396894d8f968310bb6bc172)) ### [18.4.2](https://www.github.com/netlify/build/compare/build-v18.4.1...build-v18.4.2) (2021-08-20) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.19.0 ([#3535](https://www.github.com/netlify/build/issues/3535)) ([eb11110](https://www.github.com/netlify/build/commit/eb11110b9fc6a54f8f063b2db63c47757b2a3c11)) ### [18.4.1](https://www.github.com/netlify/build/compare/build-v18.4.0...build-v18.4.1) (2021-08-19) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.18.0 ([#3530](https://www.github.com/netlify/build/issues/3530)) ([7addb52](https://www.github.com/netlify/build/commit/7addb5290e11065282dc91692ed0c4b5f66990d8)) ## [18.4.0](https://www.github.com/netlify/build/compare/build-v18.3.0...build-v18.4.0) (2021-08-18) ### Features * **build-id:** add a `build-id` flag and expose `BUILD_ID` based on said flag ([#3527](https://www.github.com/netlify/build/issues/3527)) ([94a4a03](https://www.github.com/netlify/build/commit/94a4a03f337d3c2195f4b4a1912f778893ebf485)) ## [18.3.0](https://www.github.com/netlify/build/compare/build-v18.2.12...build-v18.3.0) (2021-08-18) ### Features * **telemetry:** report both build and deploy ids ([#3520](https://www.github.com/netlify/build/issues/3520)) ([97e36bd](https://www.github.com/netlify/build/commit/97e36bd5c93753fb958ea3e9e7829a7ca3d1e54b)) ### [18.2.12](https://www.github.com/netlify/build/compare/build-v18.2.11...build-v18.2.12) (2021-08-17) ### Bug Fixes * **deps:** update dependency os-name to v5 ([#3493](https://www.github.com/netlify/build/issues/3493)) ([47b724b](https://www.github.com/netlify/build/commit/47b724b9a5c6b724356ccfc4106257c1fbe2a69e)) ### [18.2.11](https://www.github.com/netlify/build/compare/build-v18.2.10...build-v18.2.11) (2021-08-17) ### Bug Fixes * **deps:** update dependency log-process-errors to v6 ([#3491](https://www.github.com/netlify/build/issues/3491)) ([c7f1dd4](https://www.github.com/netlify/build/commit/c7f1dd4d4ded87e39cc97b3cb8f53e825e4b4f8b)) ### [18.2.10](https://www.github.com/netlify/build/compare/build-v18.2.9...build-v18.2.10) (2021-08-16) ### Bug Fixes * **deps:** update dependency is-plain-obj to v3 ([#3489](https://www.github.com/netlify/build/issues/3489)) ([b353eec](https://www.github.com/netlify/build/commit/b353eece861296ef18de8e19855a6b2e30ac4fba)) * **deps:** update dependency locate-path to v6 ([#3490](https://www.github.com/netlify/build/issues/3490)) ([523b049](https://www.github.com/netlify/build/commit/523b0496c90e4c80fcabd406022a2423b12d0a90)) * **deps:** update dependency pkg-dir to v5 ([#3497](https://www.github.com/netlify/build/issues/3497)) ([7a0ec32](https://www.github.com/netlify/build/commit/7a0ec3273e486956fae3be63c8808062569cee50)) ### [18.2.9](https://www.github.com/netlify/build/compare/build-v18.2.8...build-v18.2.9) (2021-08-16) ### Bug Fixes * **deps:** update dependency p-locate to v5 ([#3495](https://www.github.com/netlify/build/issues/3495)) ([ce07fbc](https://www.github.com/netlify/build/commit/ce07fbccc5e93224e7adab5dc039f9534a49f06b)) * **deps:** update dependency pretty-ms to v7 ([#3498](https://www.github.com/netlify/build/issues/3498)) ([435629a](https://www.github.com/netlify/build/commit/435629a8f2368582cc1b01b12298911ccb548a70)) ### [18.2.8](https://www.github.com/netlify/build/compare/build-v18.2.7...build-v18.2.8) (2021-08-13) ### Bug Fixes * **deps:** update dependency supports-color to v8 ([#3466](https://www.github.com/netlify/build/issues/3466)) ([2cdf370](https://www.github.com/netlify/build/commit/2cdf370a5347772ec6437b41679bec5eceb3311f)) * **deps:** update dependency update-notifier to v5 ([#3467](https://www.github.com/netlify/build/issues/3467)) ([d34a0d7](https://www.github.com/netlify/build/commit/d34a0d76721d551d1a3bf6dc8a77ea123c92b3e5)) * rely on `package.engines.node` for plugin version support instead of a hardcoded var ([#3474](https://www.github.com/netlify/build/issues/3474)) ([3c8c7b2](https://www.github.com/netlify/build/commit/3c8c7b2714f65755ec14ca2d19396a7f6836ca66)) * **utils:** remove condition around `require.resolve` invocation ([#3480](https://www.github.com/netlify/build/issues/3480)) ([f29d7c1](https://www.github.com/netlify/build/commit/f29d7c1badd2467fef8d13920d1199e7988abde2)) ### [18.2.7](https://www.github.com/netlify/build/compare/build-v18.2.6...build-v18.2.7) (2021-08-13) ### Bug Fixes * **deps:** update dependency ps-list to v7 ([#3465](https://www.github.com/netlify/build/issues/3465)) ([05398cc](https://www.github.com/netlify/build/commit/05398ccb97c986e4c7ec88df4ac108c8ec17142c)) ### [18.2.6](https://www.github.com/netlify/build/compare/build-v18.2.5...build-v18.2.6) (2021-08-13) ### Bug Fixes * **deps:** remove cp-file usage ([#3470](https://www.github.com/netlify/build/issues/3470)) ([5b98fb4](https://www.github.com/netlify/build/commit/5b98fb494478cc0e7676856ce38f980b406306b9)) ### [18.2.5](https://www.github.com/netlify/build/compare/build-v18.2.4...build-v18.2.5) (2021-08-13) ### Bug Fixes * **deps:** update dependency get-stream to v6 ([#3456](https://www.github.com/netlify/build/issues/3456)) ([478a039](https://www.github.com/netlify/build/commit/478a03946579729a5796eb1a395389eafcc9168e)) ### [18.2.4](https://www.github.com/netlify/build/compare/build-v18.2.3...build-v18.2.4) (2021-08-12) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to v2 ([#3448](https://www.github.com/netlify/build/issues/3448)) ([3d83dce](https://www.github.com/netlify/build/commit/3d83dce6efa68df5ef090e57958eff6f78c8f065)) ### [18.2.3](https://www.github.com/netlify/build/compare/build-v18.2.2...build-v18.2.3) (2021-08-12) ### Bug Fixes * delete `_redirects`/`_headers` when persisted to `netlify.toml` ([#3446](https://www.github.com/netlify/build/issues/3446)) ([4bdf2cc](https://www.github.com/netlify/build/commit/4bdf2ccb64edae4254a9b7832f46e2cbeeb322eb)) ### [18.2.2](https://www.github.com/netlify/build/compare/build-v18.2.1...build-v18.2.2) (2021-08-12) ### Bug Fixes * **deps:** bump execa to the latest version (5.x) ([#3440](https://www.github.com/netlify/build/issues/3440)) ([3e8bd01](https://www.github.com/netlify/build/commit/3e8bd019eddca738a664af9590c313dd5fcd20df)) ### [18.2.1](https://www.github.com/netlify/build/compare/build-v18.2.0...build-v18.2.1) (2021-08-12) ### Bug Fixes * avoid debug mode to be too verbose ([#3437](https://www.github.com/netlify/build/issues/3437)) ([23dc159](https://www.github.com/netlify/build/commit/23dc1591d8a2de3ffb2b2e1f54e5068ea361c681)) ## [18.2.0](https://www.github.com/netlify/build/compare/build-v18.1.0...build-v18.2.0) (2021-08-12) ### Features * improve warning messages shown with invalid redirects/headers ([#3426](https://www.github.com/netlify/build/issues/3426)) ([6eb42ce](https://www.github.com/netlify/build/commit/6eb42ced66873e3bd95226d6ad6937cdb71536d6)) ## [18.1.0](https://www.github.com/netlify/build/compare/build-v18.0.3...build-v18.1.0) (2021-08-12) ### Features * remove some double newlines in the build logs ([#3425](https://www.github.com/netlify/build/issues/3425)) ([d17af96](https://www.github.com/netlify/build/commit/d17af96445a142aeb57256af33cbe854ead93a6d)) ### [18.0.3](https://www.github.com/netlify/build/compare/build-v18.0.2...build-v18.0.3) (2021-08-12) ### Bug Fixes * **deps:** bump clean-stack to 3.x ([#3429](https://www.github.com/netlify/build/issues/3429)) ([eb94887](https://www.github.com/netlify/build/commit/eb94887298428ca27c28131439cfaf5284f609f8)) ### [18.0.2](https://www.github.com/netlify/build/compare/build-v18.0.1...build-v18.0.2) (2021-08-11) ### Bug Fixes * error handling of headers and redirects ([#3422](https://www.github.com/netlify/build/issues/3422)) ([add5417](https://www.github.com/netlify/build/commit/add54178e5b046d6ec8d7cc44ac626135a25b9e6)) ### [18.0.1](https://www.github.com/netlify/build/compare/build-v18.0.0...build-v18.0.1) (2021-08-11) ### Bug Fixes * `@netlify/config` upgrade ([bd118ed](https://www.github.com/netlify/build/commit/bd118edfd083bdae19da984cb78e2a7a35335d3e)) ## [18.0.0](https://www.github.com/netlify/build/compare/build-v17.11.0...build-v18.0.0) (2021-08-11) ### ⚠ BREAKING CHANGES * add `netlifyConfig.headers` (#3407) ### Features * add `netlifyConfig.headers` ([#3407](https://www.github.com/netlify/build/issues/3407)) ([14888c7](https://www.github.com/netlify/build/commit/14888c73278b6c68538ecaa385e5ce01932b7e09)) ## [17.11.0](https://www.github.com/netlify/build/compare/build-v17.10.0...build-v17.11.0) (2021-08-11) ### Features * pass `rustTargetDirectory` to ZISI ([#3411](https://www.github.com/netlify/build/issues/3411)) ([0287d22](https://www.github.com/netlify/build/commit/0287d221d804f0cbe5036ce7d170c3f7271a32b3)) ## [17.10.0](https://www.github.com/netlify/build/compare/build-v17.9.2...build-v17.10.0) (2021-08-10) ### Features * fix log messages related to redirects upload ([#3412](https://www.github.com/netlify/build/issues/3412)) ([8a2fcc1](https://www.github.com/netlify/build/commit/8a2fcc1eb87430f3bcb5f6cfa8a7a87d952a089e)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.3.0 ([#3405](https://www.github.com/netlify/build/issues/3405)) ([64e3a62](https://www.github.com/netlify/build/commit/64e3a626881f2116a5c27571fb5110f35035c508)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.17.0 ([#3409](https://www.github.com/netlify/build/issues/3409)) ([6942dcd](https://www.github.com/netlify/build/commit/6942dcd83b7908710e994b39b5ef4323cf88f039)) ### [17.9.2](https://www.github.com/netlify/build/compare/build-v17.9.1...build-v17.9.2) (2021-08-05) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to ^8.2.0 ([#3399](https://www.github.com/netlify/build/issues/3399)) ([70911c9](https://www.github.com/netlify/build/commit/70911c91729d02475684b179febe9b07e23df293)) ### [17.9.1](https://www.github.com/netlify/build/compare/build-v17.9.0...build-v17.9.1) (2021-08-05) ### Bug Fixes * `redirects[*].status` should not be a float in `netlify.toml` ([#3396](https://www.github.com/netlify/build/issues/3396)) ([1c006ea](https://www.github.com/netlify/build/commit/1c006eae3de54e034dbcd87de5e011b6bfa843e6)) ## [17.9.0](https://www.github.com/netlify/build/compare/build-v17.8.0...build-v17.9.0) (2021-08-04) ### Features * allow modifying `build.environment` ([#3389](https://www.github.com/netlify/build/issues/3389)) ([76d3bc9](https://www.github.com/netlify/build/commit/76d3bc9c77e28cf500ada47289c01d394d6da6db)) * do not log modified `build.environment` ([#3392](https://www.github.com/netlify/build/issues/3392)) ([cb734f3](https://www.github.com/netlify/build/commit/cb734f372279ad15472b0de7e04a8dda417925e3)) * update environment variables with `netlifyConfig.build.environment` ([#3393](https://www.github.com/netlify/build/issues/3393)) ([9ef37af](https://www.github.com/netlify/build/commit/9ef37af440df8701917f68e70d104b117b8ae5c5)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.2.1 ([#3390](https://www.github.com/netlify/build/issues/3390)) ([32da36a](https://www.github.com/netlify/build/commit/32da36ad02c8e33ffcfb18a6c867be702fa858af)) ## [17.8.0](https://www.github.com/netlify/build/compare/build-v17.7.1...build-v17.8.0) (2021-08-03) ### Features * improve config simplification ([#3384](https://www.github.com/netlify/build/issues/3384)) ([b9f7d7a](https://www.github.com/netlify/build/commit/b9f7d7ad1baf063bd3919a16b961007cb94da2e2)) ### [17.7.1](https://www.github.com/netlify/build/compare/build-v17.7.0...build-v17.7.1) (2021-08-03) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^3.2.0 ([#3381](https://www.github.com/netlify/build/issues/3381)) ([b02dc7f](https://www.github.com/netlify/build/commit/b02dc7fd3fec933be3ca204508a4906a78e22b94)) ## [17.7.0](https://www.github.com/netlify/build/compare/build-v17.6.0...build-v17.7.0) (2021-08-03) ### Features * enable functions bundling manifest ([#3378](https://www.github.com/netlify/build/issues/3378)) ([c03c4ac](https://www.github.com/netlify/build/commit/c03c4ac64f79020d732488014f4cb337cb6363a7)) ## [17.6.0](https://www.github.com/netlify/build/compare/build-v17.5.0...build-v17.6.0) (2021-08-03) ### Features * **build:** return config mutations ([#3379](https://www.github.com/netlify/build/issues/3379)) ([8eb39b5](https://www.github.com/netlify/build/commit/8eb39b5ee3fae124498f87046a7776ad5574e011)) ## [17.5.0](https://www.github.com/netlify/build/compare/build-v17.4.4...build-v17.5.0) (2021-08-02) ### Features * re-add support for feature-flagging plugin versions ([#3373](https://www.github.com/netlify/build/issues/3373)) ([85b739c](https://www.github.com/netlify/build/commit/85b739c0b48d36c76429f02ddcc32e5c3c51e28d)) ### [17.4.4](https://www.github.com/netlify/build/compare/build-v17.4.3...build-v17.4.4) (2021-08-02) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.16.0 ([#3375](https://www.github.com/netlify/build/issues/3375)) ([4d1c90d](https://www.github.com/netlify/build/commit/4d1c90d5218c8d60373a50043ac6cfa6bda1aa9e)) ### [17.4.3](https://www.github.com/netlify/build/compare/build-v17.4.2...build-v17.4.3) (2021-08-02) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to v3 ([#3372](https://www.github.com/netlify/build/issues/3372)) ([c911b2d](https://www.github.com/netlify/build/commit/c911b2d3c02dddaf38183cc9499a0b0d976723da)) ### [17.4.2](https://www.github.com/netlify/build/compare/build-v17.4.1...build-v17.4.2) (2021-08-02) ### Bug Fixes * **deps:** update dependency chalk to ^4.1.1 ([#3367](https://www.github.com/netlify/build/issues/3367)) ([dd258ec](https://www.github.com/netlify/build/commit/dd258ecd758824e56b15fc5f6c73a3180ac0af66)) ### [17.4.1](https://www.github.com/netlify/build/compare/build-v17.4.0...build-v17.4.1) (2021-07-30) ### Bug Fixes * `deployDir` parameter sent to buildbot during deploys ([#3363](https://www.github.com/netlify/build/issues/3363)) ([5c39e70](https://www.github.com/netlify/build/commit/5c39e70c3a5b8ceecad448593b1095c093b093ff)) ## [17.4.0](https://www.github.com/netlify/build/compare/build-v17.3.1...build-v17.4.0) (2021-07-30) ### Features * allow adding new properties to `compatibility` ([#3361](https://www.github.com/netlify/build/issues/3361)) ([24d1541](https://www.github.com/netlify/build/commit/24d15419e64b5d7b291b154fd9363660e468416d)) ### [17.3.1](https://www.github.com/netlify/build/compare/build-v17.3.0...build-v17.3.1) (2021-07-29) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.21.0 ([#3359](https://www.github.com/netlify/build/issues/3359)) ([2b34de5](https://www.github.com/netlify/build/commit/2b34de56e7561c915c840c9070ad0fe6edbcfe2c)) * update `plugins.json` version ([#3358](https://www.github.com/netlify/build/issues/3358)) ([511da72](https://www.github.com/netlify/build/commit/511da7264f0369aebec0e5cc975164d04c736a83)) ## [17.3.0](https://www.github.com/netlify/build/compare/build-v17.2.0...build-v17.3.0) (2021-07-29) ### Features * add versioning to `plugins.json` ([#3355](https://www.github.com/netlify/build/issues/3355)) ([034ac01](https://www.github.com/netlify/build/commit/034ac0106327c2aeccc6b3358e1d3e0b25c48af5)) ## [17.2.0](https://www.github.com/netlify/build/compare/build-v17.1.1...build-v17.2.0) (2021-07-28) ### Features * add `NETLIFY_LOCAL` environment variable ([#3351](https://www.github.com/netlify/build/issues/3351)) ([c3c0716](https://www.github.com/netlify/build/commit/c3c07169ba922010d7233de868a52b6ccd6bcd20)) ### [17.1.1](https://www.github.com/netlify/build/compare/build-v17.1.0...build-v17.1.1) (2021-07-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.15.1 ([#3344](https://www.github.com/netlify/build/issues/3344)) ([9d9d52f](https://www.github.com/netlify/build/commit/9d9d52f8974a8af298dce47b089bb3c2ba3374ac)) ## [17.1.0](https://www.github.com/netlify/build/compare/build-v17.0.1...build-v17.1.0) (2021-07-27) ### Features * **telemetry:** report the framework provided ([#3328](https://www.github.com/netlify/build/issues/3328)) ([bc64b5c](https://www.github.com/netlify/build/commit/bc64b5c163ef8a4b303fa6e44491cc250a6092c8)) ### [17.0.1](https://www.github.com/netlify/build/compare/build-v17.0.0...build-v17.0.1) (2021-07-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.15.0 ([#3340](https://www.github.com/netlify/build/issues/3340)) ([3bd2099](https://www.github.com/netlify/build/commit/3bd2099526ba17c351af27d91241d37667caae6b)) ## [17.0.0](https://www.github.com/netlify/build/compare/build-v16.2.1...build-v17.0.0) (2021-07-26) ### ⚠ BREAKING CHANGES * deprecate Node 8 (#3322) ### Features * **deps:** bump @netlify/*-utils and @netlify/config to latest ([d57c7c3](https://www.github.com/netlify/build/commit/d57c7c3cadb79b96f6e96052fbd261b2a1e77f41)) ### Miscellaneous Chores * deprecate Node 8 ([#3322](https://www.github.com/netlify/build/issues/3322)) ([9cc108a](https://www.github.com/netlify/build/commit/9cc108aab825558204ffef6b8034f456d8d11879)) ### [16.2.1](https://www.github.com/netlify/build/compare/build-v16.2.0...build-v16.2.1) (2021-07-23) ### Bug Fixes * allow functions directory to be a symlink ([#3326](https://www.github.com/netlify/build/issues/3326)) ([1b98e50](https://www.github.com/netlify/build/commit/1b98e50c8bedc1a15855ab5ede42b8f5305ef263)) ## [16.2.0](https://www.github.com/netlify/build/compare/build-v16.1.1...build-v16.2.0) (2021-07-22) ### Features * add support for feature-flagging plugin versions ([#3304](https://www.github.com/netlify/build/issues/3304)) ([157c03c](https://www.github.com/netlify/build/commit/157c03c70ab33ffd4ecc659b3437a113009729dd)) * **plugins:** remove feature flag responsible plugin node version execution changes ([#3311](https://www.github.com/netlify/build/issues/3311)) ([8c94faf](https://www.github.com/netlify/build/commit/8c94faf8d1e7cbf830b1cbc722949198759f9f8c)) ### Bug Fixes * revert "feat: add support for feature-flagging plugin versions ([#3304](https://www.github.com/netlify/build/issues/3304))" ([#3318](https://www.github.com/netlify/build/issues/3318)) ([226ff8e](https://www.github.com/netlify/build/commit/226ff8ead52642961bdba8c0f445879e67b2bbaf)) ### [16.1.1](https://www.github.com/netlify/build/compare/build-v16.1.0...build-v16.1.1) (2021-07-22) ### Bug Fixes * bundle functions from internal directory if configured user dire… ([#3314](https://www.github.com/netlify/build/issues/3314)) ([b58afc3](https://www.github.com/netlify/build/commit/b58afc31fdfe4c412605e11b2f9261d2ed412c93)) ## [16.1.0](https://www.github.com/netlify/build/compare/build-v16.0.1...build-v16.1.0) (2021-07-21) ### Features * bundle functions from `.netlify/functions-internal` ([#3213](https://www.github.com/netlify/build/issues/3213)) ([9ff3b9c](https://www.github.com/netlify/build/commit/9ff3b9cec1008a117bc687ba5a55d0fb8aecd91a)) ### [16.0.1](https://www.github.com/netlify/build/compare/build-v16.0.0...build-v16.0.1) (2021-07-20) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.22 ([#3306](https://www.github.com/netlify/build/issues/3306)) ([a21dc85](https://www.github.com/netlify/build/commit/a21dc85cc3575572dfbe151d518336f88a6f7be9)) ## [16.0.0](https://www.github.com/netlify/build/compare/build-v15.11.5...build-v16.0.0) (2021-07-19) ### ⚠ BREAKING CHANGES * change edge-handler default directory (#3296) ### Features * change edge-handler default directory ([#3296](https://www.github.com/netlify/build/issues/3296)) ([86b02da](https://www.github.com/netlify/build/commit/86b02dae85bbd879f107606487853ad3cd2fc147)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.19.3 ([#3297](https://www.github.com/netlify/build/issues/3297)) ([1a9d614](https://www.github.com/netlify/build/commit/1a9d614dae066568017c882719379ceccf8118eb)) ### [15.11.5](https://www.github.com/netlify/build/compare/build-v15.11.4...build-v15.11.5) (2021-07-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.14.0 ([#3293](https://www.github.com/netlify/build/issues/3293)) ([a371a0d](https://www.github.com/netlify/build/commit/a371a0dbdb3a7c8a05674ab9d6255635cd63d727)) ### [15.11.4](https://www.github.com/netlify/build/compare/build-v15.11.3...build-v15.11.4) (2021-07-14) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.13.1 ([#3288](https://www.github.com/netlify/build/issues/3288)) ([f5e5b6b](https://www.github.com/netlify/build/commit/f5e5b6ba91a8ad9e95d4dea5c18078a8e334313a)) ### [15.11.3](https://www.github.com/netlify/build/compare/build-v15.11.2...build-v15.11.3) (2021-07-14) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.19.2 ([#3286](https://www.github.com/netlify/build/issues/3286)) ([23b323d](https://www.github.com/netlify/build/commit/23b323db25e444307c382e20b807f17fb4126d8d)) ### [15.11.2](https://www.github.com/netlify/build/compare/build-v15.11.1...build-v15.11.2) (2021-07-12) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.13.0 ([#3280](https://www.github.com/netlify/build/issues/3280)) ([8249fe1](https://www.github.com/netlify/build/commit/8249fe19d1edab64fad2362757d59d33fabe18c2)) ### [15.11.1](https://www.github.com/netlify/build/compare/build-v15.11.0...build-v15.11.1) (2021-07-12) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.21 ([#3278](https://www.github.com/netlify/build/issues/3278)) ([556706f](https://www.github.com/netlify/build/commit/556706f67688ad804e7a0694df549e7f46255c6f)) ## [15.11.0](https://www.github.com/netlify/build/compare/build-v15.10.0...build-v15.11.0) (2021-07-08) ### Features * delete `netlify.toml` after deploy if it was created due to configuration changes ([#3271](https://www.github.com/netlify/build/issues/3271)) ([444087d](https://www.github.com/netlify/build/commit/444087d528a0e8450031eda65cd5877980a5fa70)) ## [15.10.0](https://www.github.com/netlify/build/compare/build-v15.9.0...build-v15.10.0) (2021-07-08) ### Features * simplify the `netlify.toml` being saved on configuration changes ([#3268](https://www.github.com/netlify/build/issues/3268)) ([15987fe](https://www.github.com/netlify/build/commit/15987fe0d869f01110d4d97c8e8395580eb1a9f7)) ## [15.9.0](https://www.github.com/netlify/build/compare/build-v15.8.0...build-v15.9.0) (2021-07-08) ### Features * restore `netlify.toml` and `_redirects` after deploy ([#3265](https://www.github.com/netlify/build/issues/3265)) ([2441d6a](https://www.github.com/netlify/build/commit/2441d6a8b2be81212384816a0686221d4a6a2577)) ## [15.8.0](https://www.github.com/netlify/build/compare/build-v15.7.0...build-v15.8.0) (2021-07-08) ### Features * add debug logs to deploys ([#3262](https://www.github.com/netlify/build/issues/3262)) ([5748f92](https://www.github.com/netlify/build/commit/5748f92fa82efd0a892f45a015f39a03dbf41159)) ## [15.7.0](https://www.github.com/netlify/build/compare/build-v15.6.0...build-v15.7.0) (2021-07-08) ### Features * fix `_redirects` to `netlify.toml` before deploy ([#3259](https://www.github.com/netlify/build/issues/3259)) ([e32d076](https://www.github.com/netlify/build/commit/e32d076ab642b8a0df72c96d8726e161b65b182f)) ## [15.6.0](https://www.github.com/netlify/build/compare/build-v15.5.0...build-v15.6.0) (2021-07-08) ### Features * use a diff instead of a Proxy for configuration mutations ([#3254](https://www.github.com/netlify/build/issues/3254)) ([ae7f36e](https://www.github.com/netlify/build/commit/ae7f36e03fe84a512007694654cbfeb3b12c2cf3)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.19.1 ([#3255](https://www.github.com/netlify/build/issues/3255)) ([a1db0b0](https://www.github.com/netlify/build/commit/a1db0b035bfe50d2852746ed34214641a02d94f1)) ## [15.5.0](https://www.github.com/netlify/build/compare/build-v15.4.0...build-v15.5.0) (2021-07-08) ### Features * move configMutations validation logic ([#3252](https://www.github.com/netlify/build/issues/3252)) ([db11947](https://www.github.com/netlify/build/commit/db119472d6f8105409ac8b560bd51a140b84226d)) ## [15.4.0](https://www.github.com/netlify/build/compare/build-v15.3.1...build-v15.4.0) (2021-07-08) ### Features * do not validate against `preventExtensions()` nor `setPrototypeOf()` ([#3250](https://www.github.com/netlify/build/issues/3250)) ([6fed537](https://www.github.com/netlify/build/commit/6fed537e071617f7f6acbe84b8fb98d39f7e2677)) * move configMutations logging logic ([#3249](https://www.github.com/netlify/build/issues/3249)) ([8764874](https://www.github.com/netlify/build/commit/8764874f09b82a336700366b0fca6407a1dacb8c)) ### [15.3.1](https://www.github.com/netlify/build/compare/build-v15.3.0...build-v15.3.1) (2021-07-08) ### Bug Fixes * allow `netlifyConfig.redirects` to be modified before `_redirects` is added ([#3242](https://www.github.com/netlify/build/issues/3242)) ([f3330a6](https://www.github.com/netlify/build/commit/f3330a685aeb0320e1ac445bbe7a908e7a83dbda)) ## [15.3.0](https://www.github.com/netlify/build/compare/build-v15.2.2...build-v15.3.0) (2021-07-08) ### Features * add default values for `build.processing` and `build.services` ([#3235](https://www.github.com/netlify/build/issues/3235)) ([2ba263b](https://www.github.com/netlify/build/commit/2ba263ba9ebc54c38410245f021deb906b8a8aa2)) ### [15.2.2](https://www.github.com/netlify/build/compare/build-v15.2.1...build-v15.2.2) (2021-07-07) ### Bug Fixes * save the `netlify.toml` earlier ([#3233](https://www.github.com/netlify/build/issues/3233)) ([d4bfb25](https://www.github.com/netlify/build/commit/d4bfb25e362ebf3aea0ba2830d79cfc178b355a9)) ### [15.2.1](https://www.github.com/netlify/build/compare/build-v15.2.0...build-v15.2.1) (2021-07-07) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.12.0 ([#3228](https://www.github.com/netlify/build/issues/3228)) ([3c8a3c6](https://www.github.com/netlify/build/commit/3c8a3c6a4a0e3a29f984739613b6f823b1d7f38c)) ## [15.2.0](https://www.github.com/netlify/build/compare/build-v15.1.0...build-v15.2.0) (2021-07-07) ### Features * persist configuration changes to `netlify.toml` ([#3224](https://www.github.com/netlify/build/issues/3224)) ([f924661](https://www.github.com/netlify/build/commit/f924661f94d04af1e90e1023e385e35587ae301c)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.19.0 ([#3227](https://www.github.com/netlify/build/issues/3227)) ([571bcb4](https://www.github.com/netlify/build/commit/571bcb4821faece491c9f1b7392a364317e3d571)) ## [15.1.0](https://www.github.com/netlify/build/compare/build-v15.0.0...build-v15.1.0) (2021-07-06) ### Features * fix the payload sent during deploy to the buildbot ([#3218](https://www.github.com/netlify/build/issues/3218)) ([55d5fc4](https://www.github.com/netlify/build/commit/55d5fc4a71d7d7055a679371ff588d9e6c2ea200)) ## [15.0.0](https://www.github.com/netlify/build/compare/build-v14.0.0...build-v15.0.0) (2021-07-06) ### ⚠ BREAKING CHANGES * return `redirectsPath` from `@netlify/config` (#3207) ### Features * return `redirectsPath` from `@netlify/config` ([#3207](https://www.github.com/netlify/build/issues/3207)) ([35dd205](https://www.github.com/netlify/build/commit/35dd205ca35a393dbb3cff50e79ba1cdad8f8755)) ## [14.0.0](https://www.github.com/netlify/build/compare/build-v13.3.1...build-v14.0.0) (2021-07-06) ### ⚠ BREAKING CHANGES * add `configMutations` flag to `@netlify/config` (#3211) ### Features * add `configMutations` flag to `@netlify/config` ([#3211](https://www.github.com/netlify/build/issues/3211)) ([9037f03](https://www.github.com/netlify/build/commit/9037f03b6d288d136007f0c2c964c04aed3f33f7)) ### [13.3.1](https://www.github.com/netlify/build/compare/build-v13.3.0...build-v13.3.1) (2021-07-06) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.11.0 ([#3202](https://www.github.com/netlify/build/issues/3202)) ([37df6bd](https://www.github.com/netlify/build/commit/37df6bd5ce55e3176f336285e3b17b9982d8f2f2)) ## [13.3.0](https://www.github.com/netlify/build/compare/build-v13.2.0...build-v13.3.0) (2021-07-05) ### Features * move some mutation logic to `@netlify/config` ([#3203](https://www.github.com/netlify/build/issues/3203)) ([9ce4725](https://www.github.com/netlify/build/commit/9ce47250e806379db93528913c298bc57f3d23a6)) ## [13.2.0](https://www.github.com/netlify/build/compare/build-v13.1.0...build-v13.2.0) (2021-07-05) ### Features * allow mutating `edge_handlers` in plugins ([#3200](https://www.github.com/netlify/build/issues/3200)) ([896b795](https://www.github.com/netlify/build/commit/896b795e4f97186c35d76f60cbd012bf76d1d31e)) ## [13.1.0](https://www.github.com/netlify/build/compare/build-v13.0.0...build-v13.1.0) (2021-07-05) ### Features * improve `functions` configuration logic ([#3175](https://www.github.com/netlify/build/issues/3175)) ([7085d77](https://www.github.com/netlify/build/commit/7085d7720191c399d8fd9d560ce30a76b483e30a)) ## [13.0.0](https://www.github.com/netlify/build/compare/build-v12.28.0...build-v13.0.0) (2021-07-05) ### ⚠ BREAKING CHANGES * merge `priorityConfig` with `inlineConfig` (#3193) ### Features * merge `priorityConfig` with `inlineConfig` ([#3193](https://www.github.com/netlify/build/issues/3193)) ([35989ef](https://www.github.com/netlify/build/commit/35989ef8fe8196c1da2d36c2f73e4ff82efba6c5)) ## [12.28.0](https://www.github.com/netlify/build/compare/build-v12.27.0...build-v12.28.0) (2021-07-05) ### Features * change `origin` of `inlineConfig` and `priorityConfig` ([#3190](https://www.github.com/netlify/build/issues/3190)) ([5ea2439](https://www.github.com/netlify/build/commit/5ea2439ae8f7de11ba15059820466456ee8df196)) ## [12.27.0](https://www.github.com/netlify/build/compare/build-v12.26.1...build-v12.27.0) (2021-07-05) ### Features * change how `priorityConfig` interacts with contexts ([#3187](https://www.github.com/netlify/build/issues/3187)) ([736c269](https://www.github.com/netlify/build/commit/736c26993385173e37110b8e26c2cf389344de3e)) ### [12.26.1](https://www.github.com/netlify/build/compare/build-v12.26.0...build-v12.26.1) (2021-07-05) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.20 ([#3182](https://www.github.com/netlify/build/issues/3182)) ([0c19650](https://www.github.com/netlify/build/commit/0c19650bd88be78ba291dd19d9e800dbf08db1aa)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.9.0 ([#3181](https://www.github.com/netlify/build/issues/3181)) ([1d733f6](https://www.github.com/netlify/build/commit/1d733f69f30db1e06722c1e0b7cd167e1e8ddad9)) ## [12.26.0](https://www.github.com/netlify/build/compare/build-v12.25.0...build-v12.26.0) (2021-07-01) ### Features * detect when build command adds `_redirects` file ([#3171](https://www.github.com/netlify/build/issues/3171)) ([ddf93d5](https://www.github.com/netlify/build/commit/ddf93d5dea00f5f86320be8eb353b75853ba1409)) ## [12.25.0](https://www.github.com/netlify/build/compare/build-v12.24.0...build-v12.25.0) (2021-07-01) ### Features * allow mutating more configuration properties ([#3163](https://www.github.com/netlify/build/issues/3163)) ([7357fa8](https://www.github.com/netlify/build/commit/7357fa89cd2824e03ae3c1fe654537f4218d4f52)) ## [12.24.0](https://www.github.com/netlify/build/compare/build-v12.23.0...build-v12.24.0) (2021-07-01) ### Features * detect when `_redirects` are created during builds ([#3168](https://www.github.com/netlify/build/issues/3168)) ([82746f4](https://www.github.com/netlify/build/commit/82746f48c21817c41228d782db6266226cb02ba2)) ## [12.23.0](https://www.github.com/netlify/build/compare/build-v12.22.0...build-v12.23.0) (2021-07-01) ### Features * reduce verbose logs when changing `netlifyConfig` ([#3167](https://www.github.com/netlify/build/issues/3167)) ([6f3413d](https://www.github.com/netlify/build/commit/6f3413ded8c06da9a81425ee5de0f3208983d64a)) ## [12.22.0](https://www.github.com/netlify/build/compare/build-v12.21.0...build-v12.22.0) (2021-07-01) ### Features * log updated config when changed, in debug mode ([#3162](https://www.github.com/netlify/build/issues/3162)) ([83c53f8](https://www.github.com/netlify/build/commit/83c53f89d9da42e029f5f23c3b62c3e55a60c5e5)) ## [12.21.0](https://www.github.com/netlify/build/compare/build-v12.20.0...build-v12.21.0) (2021-07-01) ### Features * allow array configuration property to be modified ([#3161](https://www.github.com/netlify/build/issues/3161)) ([f4f2982](https://www.github.com/netlify/build/commit/f4f298207d27ca00c785fc0e4b4837258c1db8ff)) ## [12.20.0](https://www.github.com/netlify/build/compare/build-v12.19.1...build-v12.20.0) (2021-06-30) ### Features * allow plugins to unset configuration properties ([#3158](https://www.github.com/netlify/build/issues/3158)) ([64e1235](https://www.github.com/netlify/build/commit/64e1235079356f5936638cde812a17027e627b9f)) ### [12.19.1](https://www.github.com/netlify/build/compare/build-v12.19.0...build-v12.19.1) (2021-06-30) ### Bug Fixes * **plugins:** only rely in the system node version for plugins running Node <10 ([#3144](https://www.github.com/netlify/build/issues/3144)) ([74bbff2](https://www.github.com/netlify/build/commit/74bbff231ec49277a1900b1ac19c2390094a1d0f)) ## [12.19.0](https://www.github.com/netlify/build/compare/build-v12.18.0...build-v12.19.0) (2021-06-30) ### Features * remove redirects parsing feature flag ([#3150](https://www.github.com/netlify/build/issues/3150)) ([1f297c9](https://www.github.com/netlify/build/commit/1f297c9845bc3a1f3ba4725c9f97aadf0d541e45)) ## [12.18.0](https://www.github.com/netlify/build/compare/build-v12.17.0...build-v12.18.0) (2021-06-30) ### Features * validate and normalize config properties modified by plugins ([#3153](https://www.github.com/netlify/build/issues/3153)) ([daf5c91](https://www.github.com/netlify/build/commit/daf5c91c080e41c7c5371f6fd6ca2ffa2c965f6f)) ## [12.17.0](https://www.github.com/netlify/build/compare/build-v12.16.0...build-v12.17.0) (2021-06-29) ### Features * call `@netlify/config` when the configuration is modified ([#3147](https://www.github.com/netlify/build/issues/3147)) ([afc73a4](https://www.github.com/netlify/build/commit/afc73a4afa2f6b765bfb6043358c5e9af27314f7)) ## [12.16.0](https://www.github.com/netlify/build/compare/build-v12.15.0...build-v12.16.0) (2021-06-29) ### Features * remove zisiHandlerV2 feature flag ([#3145](https://www.github.com/netlify/build/issues/3145)) ([239fb4b](https://www.github.com/netlify/build/commit/239fb4b7ed41636f7c3814a5f61a7676d4242256)) ## [12.15.0](https://www.github.com/netlify/build/compare/build-v12.14.0...build-v12.15.0) (2021-06-29) ### Features * add `priorityConfig` to `@netlify/build` ([#3143](https://www.github.com/netlify/build/issues/3143)) ([61a5fca](https://www.github.com/netlify/build/commit/61a5fcadb2c15e62accf9e1c97e40f8e3a73170f)) ## [12.14.0](https://www.github.com/netlify/build/compare/build-v12.13.1...build-v12.14.0) (2021-06-29) ### Features * apply `netlifyConfig` modifications in the parent process ([#3135](https://www.github.com/netlify/build/issues/3135)) ([44f107f](https://www.github.com/netlify/build/commit/44f107fbc34653b97359681f1a8d763d29b81ce2)) ### [12.13.1](https://www.github.com/netlify/build/compare/build-v12.13.0...build-v12.13.1) (2021-06-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.8.0 ([#3137](https://www.github.com/netlify/build/issues/3137)) ([872db54](https://www.github.com/netlify/build/commit/872db544c2d1b798e8a93024c2c8b7fb87bf3f04)) ## [12.13.0](https://www.github.com/netlify/build/compare/build-v12.12.0...build-v12.13.0) (2021-06-28) ### Features * split mutations logic ([#3132](https://www.github.com/netlify/build/issues/3132)) ([6da5a40](https://www.github.com/netlify/build/commit/6da5a405b9d92e95edd67150f9adaf24dd06d749)) ## [12.12.0](https://www.github.com/netlify/build/compare/build-v12.11.0...build-v12.12.0) (2021-06-28) ### Features * update dependency @netlify/zip-it-and-ship-it to v4.7.0 ([#3123](https://www.github.com/netlify/build/issues/3123)) ([c70b708](https://www.github.com/netlify/build/commit/c70b70881f836693dff6994287f23bcfe3d25bb9)) ## [12.11.0](https://www.github.com/netlify/build/compare/build-v12.10.0...build-v12.11.0) (2021-06-28) ### Features * simplify proxy logic ([#3117](https://www.github.com/netlify/build/issues/3117)) ([f833a21](https://www.github.com/netlify/build/commit/f833a219eafb174786695e59691215215a3e6db6)) ## [12.10.0](https://www.github.com/netlify/build/compare/build-v12.9.0...build-v12.10.0) (2021-06-24) ### Features * move `netlifyConfig` mutations validation logic ([#3113](https://www.github.com/netlify/build/issues/3113)) ([a962fd0](https://www.github.com/netlify/build/commit/a962fd0c0a97c56199dd00d117c44f787fdbed03)) ## [12.9.0](https://www.github.com/netlify/build/compare/build-v12.8.3...build-v12.9.0) (2021-06-24) ### Features * move proxy handler logic ([#3101](https://www.github.com/netlify/build/issues/3101)) ([6773d58](https://www.github.com/netlify/build/commit/6773d58b9eece26a0b56811ea92b0a6bc59847ba)) ### [12.8.3](https://www.github.com/netlify/build/compare/build-v12.8.2...build-v12.8.3) (2021-06-24) ### Bug Fixes * dependencies ([67cae98](https://www.github.com/netlify/build/commit/67cae981597b0b2dea6ab2a1856a134705adee89)) ### [12.8.2](https://www.github.com/netlify/build/compare/build-v12.8.1...build-v12.8.2) (2021-06-24) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v4.6.0 ([#3105](https://www.github.com/netlify/build/issues/3105)) ([b2c53c7](https://www.github.com/netlify/build/commit/b2c53c789faa5c29295bb2f0209020cd0d9af7b6)) ### [12.8.1](https://www.github.com/netlify/build/compare/build-v12.8.0...build-v12.8.1) (2021-06-24) ### Bug Fixes * **plugins:** feature flag plugin execution with the system node version ([#3081](https://www.github.com/netlify/build/issues/3081)) ([d1d5b58](https://www.github.com/netlify/build/commit/d1d5b58925fbe156591de0cf7123276fb910332d)) ## [12.8.0](https://www.github.com/netlify/build/compare/build-v12.7.2...build-v12.8.0) (2021-06-23) ### Features * add `configMutations` internal variable ([#3093](https://www.github.com/netlify/build/issues/3093)) ([629d32e](https://www.github.com/netlify/build/commit/629d32e3c5205ce555de579bbe349e56355a48d4)) ### [12.7.2](https://www.github.com/netlify/build/compare/build-v12.7.1...build-v12.7.2) (2021-06-23) ### Bug Fixes * pin zip-it-and-ship-it to version 4.4.2 ([#3095](https://www.github.com/netlify/build/issues/3095)) ([86a00ce](https://www.github.com/netlify/build/commit/86a00ce3d5ee0bb5e9158ce81531459215ac0015)) ### [12.7.1](https://www.github.com/netlify/build/compare/build-v12.7.0...build-v12.7.1) (2021-06-22) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.5.1 ([#3088](https://www.github.com/netlify/build/issues/3088)) ([192d1ff](https://www.github.com/netlify/build/commit/192d1ff219ab5e091e6023d4f14933b1e7cc5230)) ## [12.7.0](https://www.github.com/netlify/build/compare/build-v12.6.0...build-v12.7.0) (2021-06-22) ### Features * do not allow deleting configuration properties ([#3067](https://www.github.com/netlify/build/issues/3067)) ([aea876a](https://www.github.com/netlify/build/commit/aea876a63bfaf483a9b74018fb68a2604b760354)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.17.0 ([#3085](https://www.github.com/netlify/build/issues/3085)) ([104aebf](https://www.github.com/netlify/build/commit/104aebf0595d1c75e860714bbc9b6b82bd7ace7a)) ## [12.6.0](https://www.github.com/netlify/build/compare/build-v12.5.2...build-v12.6.0) (2021-06-22) ### Features * add `build.publishOrigin` to `@netlify/config` ([#3078](https://www.github.com/netlify/build/issues/3078)) ([b5badfd](https://www.github.com/netlify/build/commit/b5badfdda2c7bada76d21583f6f57465b12b16cb)) ### [12.5.2](https://www.github.com/netlify/build/compare/build-v12.5.1...build-v12.5.2) (2021-06-22) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.4.2 ([#3070](https://www.github.com/netlify/build/issues/3070)) ([673f684](https://www.github.com/netlify/build/commit/673f68442849774c62969049e3f0bd7e22ed40b0)) ### [12.5.1](https://www.github.com/netlify/build/compare/build-v12.5.0...build-v12.5.1) (2021-06-22) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.19 ([#3073](https://www.github.com/netlify/build/issues/3073)) ([e5f68ab](https://www.github.com/netlify/build/commit/e5f68abbc2b3121c8866e32105ee66fb6d60d136)) ## [12.5.0](https://www.github.com/netlify/build/compare/build-v12.4.1...build-v12.5.0) (2021-06-22) ### Features * improve verbose logging ([#3066](https://www.github.com/netlify/build/issues/3066)) ([6cb567b](https://www.github.com/netlify/build/commit/6cb567b9c4ca3a5abd9cc967df1d5812b0989602)) ### [12.4.1](https://www.github.com/netlify/build/compare/build-v12.4.0...build-v12.4.1) (2021-06-17) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.16.0 ([#3064](https://www.github.com/netlify/build/issues/3064)) ([a01bea3](https://www.github.com/netlify/build/commit/a01bea386b5a2a4f60a2d1c36ed6ebb778c7ff50)) ## [12.4.0](https://www.github.com/netlify/build/compare/build-v12.3.0...build-v12.4.0) (2021-06-17) ### Features * pass `publish` directory to the buildbot during deploys ([#3056](https://www.github.com/netlify/build/issues/3056)) ([7d57080](https://www.github.com/netlify/build/commit/7d570801dc9fd469638b938e62c76433b861ff55)) ## [12.3.0](https://www.github.com/netlify/build/compare/build-v12.2.2...build-v12.3.0) (2021-06-17) ### Features * return `accounts` and `addons` from `@netlify/config` ([#3057](https://www.github.com/netlify/build/issues/3057)) ([661f79c](https://www.github.com/netlify/build/commit/661f79cf9ca6eaee03f25a24a6569bc6cc9302a3)) ### [12.2.2](https://www.github.com/netlify/build/compare/build-v12.2.1...build-v12.2.2) (2021-06-17) ### Bug Fixes * log `--cachedConfigPath` in verbose mode ([#3046](https://www.github.com/netlify/build/issues/3046)) ([dc4028f](https://www.github.com/netlify/build/commit/dc4028f1ea84435f62c461be3367015f8be75817)) ### [12.2.1](https://www.github.com/netlify/build/compare/build-v12.2.0...build-v12.2.1) (2021-06-17) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.18 ([#3044](https://www.github.com/netlify/build/issues/3044)) ([68828d6](https://www.github.com/netlify/build/commit/68828d688a25959ae37966510ae0d43c0d532e7a)) * remove `netlify_config_default_publish` feature flag ([#3047](https://www.github.com/netlify/build/issues/3047)) ([0e2c137](https://www.github.com/netlify/build/commit/0e2c137fffae8ad3d4d8243ade3e5f46c0e96e21)) ## [12.2.0](https://www.github.com/netlify/build/compare/build-v12.1.7...build-v12.2.0) (2021-06-15) ### Features * add `--cachedConfigPath` CLI flag ([#3037](https://www.github.com/netlify/build/issues/3037)) ([e317a36](https://www.github.com/netlify/build/commit/e317a36b7c7028fcab6bb0fb0d026e0da522b692)) ### [12.1.7](https://www.github.com/netlify/build/compare/build-v12.1.6...build-v12.1.7) (2021-06-15) ### Bug Fixes * do not print warning messages for plugins from the directory ([#3038](https://www.github.com/netlify/build/issues/3038)) ([12c36b2](https://www.github.com/netlify/build/commit/12c36b24cba72dbc6421c231599c073d5e04b3c7)) ### [12.1.6](https://www.github.com/netlify/build/compare/build-v12.1.5...build-v12.1.6) (2021-06-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.4.1 ([#3034](https://www.github.com/netlify/build/issues/3034)) ([034f13a](https://www.github.com/netlify/build/commit/034f13a59a7ba73b3b0c9b46752b67d971e1a8ac)) ### [12.1.5](https://www.github.com/netlify/build/compare/build-v12.1.4...build-v12.1.5) (2021-06-15) ### Bug Fixes * **plugins:** add warning message for local/package.json plugins relying on old node versions ([#2952](https://www.github.com/netlify/build/issues/2952)) ([5e9b101](https://www.github.com/netlify/build/commit/5e9b101629b5f7f261f985495c7ca17d3c17d8c1)) ### [12.1.4](https://www.github.com/netlify/build/compare/build-v12.1.3...build-v12.1.4) (2021-06-15) ### Bug Fixes * **metrics:** remove timing metrics report ([#3022](https://www.github.com/netlify/build/issues/3022)) ([12424ff](https://www.github.com/netlify/build/commit/12424fffab992497d718549ac2a19129e8281073)) ### [12.1.3](https://www.github.com/netlify/build/compare/build-v12.1.2...build-v12.1.3) (2021-06-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v4.4.0 ([#3011](https://www.github.com/netlify/build/issues/3011)) ([f49b8c3](https://www.github.com/netlify/build/commit/f49b8c3024f070187a66b3f713b1cb3a5154ab0f)) ### [12.1.2](https://www.github.com/netlify/build/compare/build-v12.1.1...build-v12.1.2) (2021-06-14) ### Bug Fixes * **feature_flags:** remove distribution metrics feature flag ([#3015](https://www.github.com/netlify/build/issues/3015)) ([36e11a2](https://www.github.com/netlify/build/commit/36e11a299a626d918a009f9d8038572bd12d19ad)) ### [12.1.1](https://www.github.com/netlify/build/compare/build-v12.1.0...build-v12.1.1) (2021-06-14) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.17 ([#3010](https://www.github.com/netlify/build/issues/3010)) ([8e35944](https://www.github.com/netlify/build/commit/8e35944e4974e026c600dfbc46758985b9d9cb2e)) * **deps:** update dependency @netlify/plugins-list to ^2.15.1 ([#3014](https://www.github.com/netlify/build/issues/3014)) ([1b7bfa6](https://www.github.com/netlify/build/commit/1b7bfa61d1c7fe689268d1a10442609dc220fa44)) * revert `redirects` parsing ([#3016](https://www.github.com/netlify/build/issues/3016)) ([39613cf](https://www.github.com/netlify/build/commit/39613cfd04281e51264ef61a75c3bd4880158a11)) ## [12.1.0](https://www.github.com/netlify/build/compare/build-v12.0.1...build-v12.1.0) (2021-06-11) ### Features * add `config.redirects` ([#3003](https://www.github.com/netlify/build/issues/3003)) ([ec3c177](https://www.github.com/netlify/build/commit/ec3c177fcc6a90a99fb7a584d2402b004704bc7e)) ### [12.0.1](https://www.github.com/netlify/build/compare/build-v12.0.0...build-v12.0.1) (2021-06-10) ### Bug Fixes * allow using no feature flags ([#2991](https://www.github.com/netlify/build/issues/2991)) ([f25ca43](https://www.github.com/netlify/build/commit/f25ca434df6bba362112d3a1c881c7391988ae58)) ## [12.0.0](https://www.github.com/netlify/build/compare/build-v11.38.0...build-v12.0.0) (2021-06-10) ### ⚠ BREAKING CHANGES * improve support for monorepo sites without a `publish` directory (#2988) ### Features * improve support for monorepo sites without a `publish` directory ([#2988](https://www.github.com/netlify/build/issues/2988)) ([1fcad8a](https://www.github.com/netlify/build/commit/1fcad8a81c35060fbc3ec8cb15ade9762579a166)) ## [11.38.0](https://www.github.com/netlify/build/compare/build-v11.37.2...build-v11.38.0) (2021-06-10) ### Features * improve feature flags logic ([#2960](https://www.github.com/netlify/build/issues/2960)) ([6df6360](https://www.github.com/netlify/build/commit/6df63603ee3822229d1504e95f4622d47387ddfb)) ### [11.37.2](https://www.github.com/netlify/build/compare/build-v11.37.1...build-v11.37.2) (2021-06-10) ### Bug Fixes * pin ZISI to v4.2.7 ([#2983](https://www.github.com/netlify/build/issues/2983)) ([29a8b19](https://www.github.com/netlify/build/commit/29a8b199b7d4db780b237a838e6495b4259bdfcc)) ### [11.37.1](https://www.github.com/netlify/build/compare/build-v11.37.0...build-v11.37.1) (2021-06-10) ### Bug Fixes * force release of Build ([#2981](https://www.github.com/netlify/build/issues/2981)) ([a64994b](https://www.github.com/netlify/build/commit/a64994b5bc296056bf9bc51a1c21fcb157c86edd)) ## [11.37.0](https://www.github.com/netlify/build/compare/build-v11.36.3...build-v11.37.0) (2021-06-09) ### Features * only monitor the duration of Netlify maintained plugins ([#2967](https://www.github.com/netlify/build/issues/2967)) ([1968e34](https://www.github.com/netlify/build/commit/1968e344512ea2ff231f18cb608f88ef37c58278)) ### [11.36.3](https://www.github.com/netlify/build/compare/build-v11.36.2...build-v11.36.3) (2021-06-09) ### Bug Fixes * do not record plugins duration if no plugins ([#2962](https://www.github.com/netlify/build/issues/2962)) ([dee54bf](https://www.github.com/netlify/build/commit/dee54bf8c0bf28aa17b37144da282ca3f4f4b637)) ### [11.36.2](https://www.github.com/netlify/build/compare/build-v11.36.1...build-v11.36.2) (2021-06-09) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.3.0 ([#2959](https://www.github.com/netlify/build/issues/2959)) ([a5f7b64](https://www.github.com/netlify/build/commit/a5f7b64c6d5a43ec330db989c3862679aa91ea0f)) ### [11.36.1](https://www.github.com/netlify/build/compare/build-v11.36.0...build-v11.36.1) (2021-06-09) ### Bug Fixes * improve error handling of plugins list fetch error ([#2957](https://www.github.com/netlify/build/issues/2957)) ([414d405](https://www.github.com/netlify/build/commit/414d405845a8fd28e9cc46b706bec4f1662ebe61)) ## [11.36.0](https://www.github.com/netlify/build/compare/build-v11.35.0...build-v11.36.0) (2021-06-08) ### Features * allow mutating `functions.*` top-level properties ([#2944](https://www.github.com/netlify/build/issues/2944)) ([0b4b58b](https://www.github.com/netlify/build/commit/0b4b58bbdd1e5a9aa82b185404920f3c353b54f5)) ## [11.35.0](https://www.github.com/netlify/build/compare/build-v11.34.0...build-v11.35.0) (2021-06-08) ### Features * log when `netlifyConfig` is mutated ([#2945](https://www.github.com/netlify/build/issues/2945)) ([fd98db3](https://www.github.com/netlify/build/commit/fd98db331096e75ef3812d6e9a901a8841aafbc4)) ## [11.34.0](https://www.github.com/netlify/build/compare/build-v11.33.0...build-v11.34.0) (2021-06-08) ### Features * fix `functions.directory` mutation ([#2940](https://www.github.com/netlify/build/issues/2940)) ([29f71be](https://www.github.com/netlify/build/commit/29f71beae04fed1b365504d3d7144618d222f720)) * handle symbols mutations on `netlifyConfig` ([#2941](https://www.github.com/netlify/build/issues/2941)) ([58f9f8f](https://www.github.com/netlify/build/commit/58f9f8f3f2f7a69441049b95159362507f7bfc40)) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.16 ([#2942](https://www.github.com/netlify/build/issues/2942)) ([29728b5](https://www.github.com/netlify/build/commit/29728b58ab2d6334d6cc2a0722ff7bff2a701c90)) ## [11.33.0](https://www.github.com/netlify/build/compare/build-v11.32.5...build-v11.33.0) (2021-06-07) ### Features * **metrics:** report distribution metrics under a feature flag ([#2933](https://www.github.com/netlify/build/issues/2933)) ([5a2e2f2](https://www.github.com/netlify/build/commit/5a2e2f2dc96112f32a31ae1dba3c46fd9f23de82)) ### [11.32.5](https://www.github.com/netlify/build/compare/build-v11.32.4...build-v11.32.5) (2021-06-07) ### Bug Fixes * correct usage of ZISI's basePath property ([#2927](https://www.github.com/netlify/build/issues/2927)) ([c354944](https://www.github.com/netlify/build/commit/c3549448740f504308ffb50d2897054f29b83d65)) ### [11.32.4](https://www.github.com/netlify/build/compare/build-v11.32.3...build-v11.32.4) (2021-06-07) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.15 ([#2929](https://www.github.com/netlify/build/issues/2929)) ([87df6cb](https://www.github.com/netlify/build/commit/87df6cb9c6855bf6506290a7099a84022d3a0e93)) * **deps:** update dependency @netlify/plugins-list to ^2.15.0 ([#2931](https://www.github.com/netlify/build/issues/2931)) ([efef14b](https://www.github.com/netlify/build/commit/efef14b09b907b08cd659de51f8e74e9c2b83b5f)) * **deps:** update dependency statsd-client to v0.4.7 ([#2920](https://www.github.com/netlify/build/issues/2920)) ([a789aec](https://www.github.com/netlify/build/commit/a789aecaa20803e81822248d56312aa2b64c1419)) ### [11.32.3](https://www.github.com/netlify/build/compare/build-v11.32.2...build-v11.32.3) (2021-06-06) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.14 ([#2917](https://www.github.com/netlify/build/issues/2917)) ([3985338](https://www.github.com/netlify/build/commit/3985338aab737255a68749a84b6c0570373be69a)) ### [11.32.2](https://www.github.com/netlify/build/compare/build-v11.32.1...build-v11.32.2) (2021-06-04) ### Bug Fixes * configuration mutation of object values ([#2915](https://www.github.com/netlify/build/issues/2915)) ([5560199](https://www.github.com/netlify/build/commit/5560199e9b47e05b6ff514af127020fed9eecaa1)) ### [11.32.1](https://www.github.com/netlify/build/compare/build-v11.32.0...build-v11.32.1) (2021-06-04) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.7 ([#2910](https://www.github.com/netlify/build/issues/2910)) ([a96240f](https://www.github.com/netlify/build/commit/a96240f54c4842634d0e2756a9891934926e71f7)) ## [11.32.0](https://www.github.com/netlify/build/compare/build-v11.31.1...build-v11.32.0) (2021-06-04) ### Features * monitor total time for user/system/plugin code ([#2911](https://www.github.com/netlify/build/issues/2911)) ([ef33e9f](https://www.github.com/netlify/build/commit/ef33e9f2cb6bafa0cc861ee7c45d52187048132a)) ### [11.31.1](https://www.github.com/netlify/build/compare/build-v11.31.0...build-v11.31.1) (2021-06-02) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.6 ([#2900](https://www.github.com/netlify/build/issues/2900)) ([6ae857d](https://www.github.com/netlify/build/commit/6ae857d99cdf69ac9f70cc96a891c9c14804b4a2)) ## [11.31.0](https://www.github.com/netlify/build/compare/build-v11.30.0...build-v11.31.0) (2021-06-02) ### Features * validate when mutating a property too late ([#2894](https://www.github.com/netlify/build/issues/2894)) ([fa2d870](https://www.github.com/netlify/build/commit/fa2d87073fed71cf0219ebac70056f4e91f67f73)) ## [11.30.0](https://www.github.com/netlify/build/compare/build-v11.29.2...build-v11.30.0) (2021-06-02) ### Features * add support for experimental ZISI v2 handler ([#2895](https://www.github.com/netlify/build/issues/2895)) ([7fea341](https://www.github.com/netlify/build/commit/7fea34122cd2ab8a1c56a177c5dffa83618542fe)) ### [11.29.2](https://www.github.com/netlify/build/compare/build-v11.29.1...build-v11.29.2) (2021-05-31) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.5 ([#2891](https://www.github.com/netlify/build/issues/2891)) ([5ccd5f5](https://www.github.com/netlify/build/commit/5ccd5f51c553fd5f588065b384a795d90837ac85)) ### [11.29.1](https://www.github.com/netlify/build/compare/build-v11.29.0...build-v11.29.1) (2021-05-31) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.13 ([#2885](https://www.github.com/netlify/build/issues/2885)) ([3a2f6ff](https://www.github.com/netlify/build/commit/3a2f6ff14013e0791ce21f51393b36c7e799cd42)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.2 ([#2886](https://www.github.com/netlify/build/issues/2886)) ([a4a0549](https://www.github.com/netlify/build/commit/a4a05497ba9809bc6420b31514f690badba4bc53)) * **deps:** update dependency uuid to v8 ([#2882](https://www.github.com/netlify/build/issues/2882)) ([1d06463](https://www.github.com/netlify/build/commit/1d06463d9e4a15bfddb14b4be271411f29ed709a)) ## [11.29.0](https://www.github.com/netlify/build/compare/build-v11.28.0...build-v11.29.0) (2021-05-28) ### Features * allow mutating `build.command` ([#2874](https://www.github.com/netlify/build/issues/2874)) ([e55dd94](https://www.github.com/netlify/build/commit/e55dd94e375c805fa923cd9bdccd184928d0790c)) ## [11.28.0](https://www.github.com/netlify/build/compare/build-v11.27.0...build-v11.28.0) (2021-05-28) ### Features * allow mutating `build.functions`, `functions.directory` and `functions.*.directory` ([#2875](https://www.github.com/netlify/build/issues/2875)) ([39804f2](https://www.github.com/netlify/build/commit/39804f214a4de40b1eb573c7b405079df528b5ec)) ## [11.27.0](https://www.github.com/netlify/build/compare/build-v11.26.1...build-v11.27.0) (2021-05-28) ### Features * make build command a core command ([#2868](https://www.github.com/netlify/build/issues/2868)) ([5149c87](https://www.github.com/netlify/build/commit/5149c87574f2dead8a4c6e8c1ef9056d35f91639)) ### [11.26.1](https://www.github.com/netlify/build/compare/build-v11.26.0...build-v11.26.1) (2021-05-28) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.1 ([#2870](https://www.github.com/netlify/build/issues/2870)) ([6e576b2](https://www.github.com/netlify/build/commit/6e576b252fb08a8e70c0f17e178ff54aede1e272)) ## [11.26.0](https://www.github.com/netlify/build/compare/build-v11.25.1...build-v11.26.0) (2021-05-27) ### Features * allow mutating `build.publish` and `build.edge_handlers` ([#2866](https://www.github.com/netlify/build/issues/2866)) ([c27557e](https://www.github.com/netlify/build/commit/c27557e0aadb8b9241358e2d5a77fc24fb7faed0)) * improve normalization of `constants` ([#2865](https://www.github.com/netlify/build/issues/2865)) ([9dc4fdd](https://www.github.com/netlify/build/commit/9dc4fddfa351e9230387316af6c8386cb63ffea2)) ### [11.25.1](https://www.github.com/netlify/build/compare/build-v11.25.0...build-v11.25.1) (2021-05-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.0 ([#2861](https://www.github.com/netlify/build/issues/2861)) ([1bd75f8](https://www.github.com/netlify/build/commit/1bd75f89509c4859cb3e31908d3ce54985142d7c)) ## [11.25.0](https://www.github.com/netlify/build/compare/build-v11.24.0...build-v11.25.0) (2021-05-27) ### Features * allow mutating `netlifyConfig.functions` ([#2857](https://www.github.com/netlify/build/issues/2857)) ([0ea57a5](https://www.github.com/netlify/build/commit/0ea57a5d868afcc7abbbd65f11e843c4938035d4)) ## [11.24.0](https://www.github.com/netlify/build/compare/build-v11.23.0...build-v11.24.0) (2021-05-26) ### Features * allow mutating `netlifyConfig.functionsDirectory` ([#2852](https://www.github.com/netlify/build/issues/2852)) ([c81904e](https://www.github.com/netlify/build/commit/c81904e9a89f0bc09f1dfda3f430e2ed14f1409b)) ## [11.23.0](https://www.github.com/netlify/build/compare/build-v11.22.0...build-v11.23.0) (2021-05-26) ### Features * allow `constants` to be mutated during builds ([#2850](https://www.github.com/netlify/build/issues/2850)) ([b7a51aa](https://www.github.com/netlify/build/commit/b7a51aa61e86e51a8b074f5472fbd578aa2ca3a0)) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.1.0 ([#2853](https://www.github.com/netlify/build/issues/2853)) ([8269428](https://www.github.com/netlify/build/commit/826942805e8b02aa2462fa547890a263d5b4fbd8)) ## [11.22.0](https://www.github.com/netlify/build/compare/build-v11.21.0...build-v11.22.0) (2021-05-25) ### Features * pass mutated `netlifyConfig` everywhere ([#2847](https://www.github.com/netlify/build/issues/2847)) ([7191b57](https://www.github.com/netlify/build/commit/7191b57e1a9cbc8d599db24b20996b568609c875)) ## [11.21.0](https://www.github.com/netlify/build/compare/build-v11.20.0...build-v11.21.0) (2021-05-25) ### Features * pass `netlifyConfig` to each event handler ([#2845](https://www.github.com/netlify/build/issues/2845)) ([16ea9e4](https://www.github.com/netlify/build/commit/16ea9e401ec7045a091d70ff3724023eab3261fc)) ## [11.20.0](https://www.github.com/netlify/build/compare/build-v11.19.1...build-v11.20.0) (2021-05-25) ### Features * make `netlifyConfig` readonly ([#2840](https://www.github.com/netlify/build/issues/2840)) ([a8e8e31](https://www.github.com/netlify/build/commit/a8e8e3173e8c58c3c0cdc2b956aa588c445c2f27)) ### [11.19.1](https://www.github.com/netlify/build/compare/build-v11.19.0...build-v11.19.1) (2021-05-25) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.12 ([#2841](https://www.github.com/netlify/build/issues/2841)) ([9933438](https://www.github.com/netlify/build/commit/99334380f0057d37680695852019f4ad0561cb61)) ## [11.19.0](https://www.github.com/netlify/build/compare/build-v11.18.1...build-v11.19.0) (2021-05-25) ### Features * add `installType` to telemetry ([#2837](https://www.github.com/netlify/build/issues/2837)) ([de0f18f](https://www.github.com/netlify/build/commit/de0f18f1b1172fb3353bbc1e325c3bf7b551e601)) ### [11.18.1](https://www.github.com/netlify/build/compare/build-v11.18.0...build-v11.18.1) (2021-05-24) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.11 ([#2835](https://www.github.com/netlify/build/issues/2835)) ([03932f6](https://www.github.com/netlify/build/commit/03932f62398f459d0e46033e5aed89462fdd9909)) * **deps:** update dependency @netlify/plugins-list to ^2.14.2 ([#2831](https://www.github.com/netlify/build/issues/2831)) ([b779b3f](https://www.github.com/netlify/build/commit/b779b3f503a9603e439d30ac305391c78675f168)) ## [11.18.0](https://www.github.com/netlify/build/compare/build-v11.17.4...build-v11.18.0) (2021-05-21) ### Features * print a warning message when `base` is set but not `publish` ([#2827](https://www.github.com/netlify/build/issues/2827)) ([a9fb807](https://www.github.com/netlify/build/commit/a9fb807be477bcd2419520b92d8a7c7d7ee03088)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.14.1 ([#2830](https://www.github.com/netlify/build/issues/2830)) ([1ee3998](https://www.github.com/netlify/build/commit/1ee3998a8aaa0d2e1cb07285e6853c37e5b64ca1)) ### [11.17.4](https://www.github.com/netlify/build/compare/build-v11.17.3...build-v11.17.4) (2021-05-19) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.10 ([#2822](https://www.github.com/netlify/build/issues/2822)) ([47c8e05](https://www.github.com/netlify/build/commit/47c8e05269f3735d1988e46ac80ddfec2ff7c930)) ### [11.17.3](https://www.github.com/netlify/build/compare/build-v11.17.2...build-v11.17.3) (2021-05-19) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.9 ([#2819](https://www.github.com/netlify/build/issues/2819)) ([0a820a2](https://www.github.com/netlify/build/commit/0a820a2cf2d370829e87e17d1e45f5c9c72be645)) * **deps:** update dependency @netlify/plugins-list to ^2.14.0 ([#2820](https://www.github.com/netlify/build/issues/2820)) ([fb55377](https://www.github.com/netlify/build/commit/fb5537770234866f23c3a441b668f0ab2dee837e)) ### [11.17.2](https://www.github.com/netlify/build/compare/build-v11.17.1...build-v11.17.2) (2021-05-17) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.0.1 ([#2814](https://www.github.com/netlify/build/issues/2814)) ([122446e](https://www.github.com/netlify/build/commit/122446edb82aa597f1882c543664fbf683744904)) ### [11.17.1](https://www.github.com/netlify/build/compare/build-v11.17.0...build-v11.17.1) (2021-05-17) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.13.0 ([#2803](https://www.github.com/netlify/build/issues/2803)) ([0d2009a](https://www.github.com/netlify/build/commit/0d2009aa3fb308f93a71425a312c2f5a8ca9aa40)) * **deps:** update dependency @netlify/zip-it-and-ship-it to v4 ([#2800](https://www.github.com/netlify/build/issues/2800)) ([5575708](https://www.github.com/netlify/build/commit/5575708ab19384103dd0e8c477e0ae672750c6cf)) ## [11.17.0](https://www.github.com/netlify/build/compare/build-v11.16.0...build-v11.17.0) (2021-05-14) ### Features * add build logs to explain how to upgrade plugins ([#2798](https://www.github.com/netlify/build/issues/2798)) ([7e054ae](https://www.github.com/netlify/build/commit/7e054ae16d815b89f6a4ea2984a4c21dc4c75a4e)) ### Bug Fixes * improve `compatibility`-related warning messages ([#2797](https://www.github.com/netlify/build/issues/2797)) ([7f34aa5](https://www.github.com/netlify/build/commit/7f34aa59909dce6fa5fa6cd7f9721c8203745da6)) ## [11.16.0](https://www.github.com/netlify/build/compare/build-v11.15.0...build-v11.16.0) (2021-05-13) ### Features * simplify version pinning logic ([#2795](https://www.github.com/netlify/build/issues/2795)) ([7c0d61b](https://www.github.com/netlify/build/commit/7c0d61b896b50be42272d489bd04b09097fbc752)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.12.0 ([#2793](https://www.github.com/netlify/build/issues/2793)) ([f2b4bad](https://www.github.com/netlify/build/commit/f2b4bad006d9185ff2ee0c09c101d69873fc0ffa)) ## [11.15.0](https://www.github.com/netlify/build/compare/build-v11.14.0...build-v11.15.0) (2021-05-13) ### Features * change shape of `compatibility` field ([#2791](https://www.github.com/netlify/build/issues/2791)) ([f43d3f6](https://www.github.com/netlify/build/commit/f43d3f6682aa46e2d442b4d94a787629507945af)) ## [11.14.0](https://www.github.com/netlify/build/compare/build-v11.13.0...build-v11.14.0) (2021-05-12) ### Features * allow commands to add tags to the metrics + `bundler` tag ([#2783](https://www.github.com/netlify/build/issues/2783)) ([345e433](https://www.github.com/netlify/build/commit/345e433244b4c27e8d9a333e52e056d7f51e4bea)) * **config:** return repository root ([#2785](https://www.github.com/netlify/build/issues/2785)) ([9a05786](https://www.github.com/netlify/build/commit/9a05786266c51031ccaef1f216f21c5821ec92fb)) ## [11.13.0](https://www.github.com/netlify/build/compare/build-v11.12.1...build-v11.13.0) (2021-05-12) ### Features * show warning about modules with dynamic imports ([#2773](https://www.github.com/netlify/build/issues/2773)) ([b49efe5](https://www.github.com/netlify/build/commit/b49efe54e81b1cd35b912b1980ba6cd1bd04539c)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.11.2 ([#2779](https://www.github.com/netlify/build/issues/2779)) ([83cfde7](https://www.github.com/netlify/build/commit/83cfde78abda0c782b3a9979d60f06d8eb07ce5f)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.10.0 ([#2776](https://www.github.com/netlify/build/issues/2776)) ([e8599eb](https://www.github.com/netlify/build/commit/e8599ebaac5828fbd143dc54bd14abeb1aee6732)) ### [11.12.1](https://www.github.com/netlify/build/compare/build-v11.12.0...build-v11.12.1) (2021-05-12) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.11.1 ([#2775](https://www.github.com/netlify/build/issues/2775)) ([982944b](https://www.github.com/netlify/build/commit/982944b5c90b39ce838c0849294d9787dc141ab9)) ## [11.12.0](https://www.github.com/netlify/build/compare/build-v11.11.0...build-v11.12.0) (2021-05-10) ### Features * improve version pinning ([#2762](https://www.github.com/netlify/build/issues/2762)) ([940b19e](https://www.github.com/netlify/build/commit/940b19eb10747f33f67d4eecec834471c0455cc0)) ## [11.11.0](https://www.github.com/netlify/build/compare/build-v11.10.0...build-v11.11.0) (2021-05-10) ### Features * fix test snapshots related to version pinning ([#2764](https://www.github.com/netlify/build/issues/2764)) ([0ce49e0](https://www.github.com/netlify/build/commit/0ce49e001e9f7fb980b3de3e22bbcc047e4f5d4e)) ## [11.10.0](https://www.github.com/netlify/build/compare/build-v11.9.4...build-v11.10.0) (2021-05-07) ### Features * add support for `0.*` versions in outdated plugins message ([#2756](https://www.github.com/netlify/build/issues/2756)) ([69a0ea1](https://www.github.com/netlify/build/commit/69a0ea13e655535c113ec37374a99a5b7b3308c3)) * add support for `0.*` versions when pinning versions ([#2758](https://www.github.com/netlify/build/issues/2758)) ([6210e36](https://www.github.com/netlify/build/commit/6210e36dafc4f7deda44d8ab3e4a76c44e3e1a5d)) ### [11.9.4](https://www.github.com/netlify/build/compare/build-v11.9.3...build-v11.9.4) (2021-05-06) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.10.0 ([#2759](https://www.github.com/netlify/build/issues/2759)) ([3cf77d9](https://www.github.com/netlify/build/commit/3cf77d941a0d83b6ba7987c95d0442dfe1a2a615)) ### [11.9.3](https://www.github.com/netlify/build/compare/build-v11.9.2...build-v11.9.3) (2021-05-06) ### Bug Fixes * simplify version pinning logic ([#2753](https://www.github.com/netlify/build/issues/2753)) ([c0c34c0](https://www.github.com/netlify/build/commit/c0c34c062349ccec92163586a69ea112f8d461e8)) ### [11.9.2](https://www.github.com/netlify/build/compare/build-v11.9.1...build-v11.9.2) (2021-05-06) ### Bug Fixes * 404 in production with `updatePlugin` ([#2749](https://www.github.com/netlify/build/issues/2749)) ([6ed8ab9](https://www.github.com/netlify/build/commit/6ed8ab9f55690981d8f6c1216ebb1b5bc0efd8c4)) ### [11.9.1](https://www.github.com/netlify/build/compare/build-v11.9.0...build-v11.9.1) (2021-05-05) ### Bug Fixes * **deps:** lock file maintenance ([#2744](https://www.github.com/netlify/build/issues/2744)) ([52f47a4](https://www.github.com/netlify/build/commit/52f47a4ff2787c5b8256bbe89e572c12c8912f84)) ## [11.9.0](https://www.github.com/netlify/build/compare/build-v11.8.0...build-v11.9.0) (2021-05-05) ### Features * pin `netlify.toml`-installed plugins versions ([#2740](https://www.github.com/netlify/build/issues/2740)) ([7ebab6b](https://www.github.com/netlify/build/commit/7ebab6bd89506d7fb0c60e8f698d07367e02822c)) ## [11.8.0](https://www.github.com/netlify/build/compare/build-v11.7.3...build-v11.8.0) (2021-05-05) ### Features * add more plugin metrics ([#2732](https://www.github.com/netlify/build/issues/2732)) ([77efcaa](https://www.github.com/netlify/build/commit/77efcaabedb0f6866dcbffc95d84d8f200942233)) ### [11.7.3](https://www.github.com/netlify/build/compare/build-v11.7.2...build-v11.7.3) (2021-05-04) ### Bug Fixes * **deps:** update netlify packages ([#2735](https://www.github.com/netlify/build/issues/2735)) ([6060bab](https://www.github.com/netlify/build/commit/6060babcee003881df46f45eda1118b7737cc4e1)) ### [11.7.2](https://www.github.com/netlify/build/compare/build-v11.7.1...build-v11.7.2) (2021-05-03) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.9.0 ([#2729](https://www.github.com/netlify/build/issues/2729)) ([a0cbfdc](https://www.github.com/netlify/build/commit/a0cbfdcccb122549ba1efb576d3c0431e8370a6f)) ### [11.7.1](https://www.github.com/netlify/build/compare/build-v11.7.0...build-v11.7.1) (2021-05-03) ### Bug Fixes * **deps:** update dependency map-obj to v4 ([#2721](https://www.github.com/netlify/build/issues/2721)) ([17559dc](https://www.github.com/netlify/build/commit/17559dcc75dd9f9a73f2a604c9f8ef3140a91b42)) ## [11.7.0](https://www.github.com/netlify/build/compare/build-v11.6.0...build-v11.7.0) (2021-05-03) ### Features * add support for `functions.included_files` config property ([#2681](https://www.github.com/netlify/build/issues/2681)) ([d75dc74](https://www.github.com/netlify/build/commit/d75dc74d9bbe9b542b17afce37419bed575c8651)) ## [11.6.0](https://www.github.com/netlify/build/compare/build-v11.5.1...build-v11.6.0) (2021-04-30) ### Features * pin plugins versions ([#2714](https://www.github.com/netlify/build/issues/2714)) ([0857f65](https://www.github.com/netlify/build/commit/0857f652ccaa8f38f5af68e7e65348e7a8e25fd8)) ### [11.5.1](https://www.github.com/netlify/build/compare/build-v11.5.0...build-v11.5.1) (2021-04-30) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.7 ([#2711](https://www.github.com/netlify/build/issues/2711)) ([66d9f53](https://www.github.com/netlify/build/commit/66d9f538dc226e569424d7c72f26c808e54e6987)) ## [11.5.0](https://www.github.com/netlify/build/compare/build-v11.4.4...build-v11.5.0) (2021-04-30) ### Features * **plugins:** expose NETLIFY_API_HOST constant to plugins ([#2709](https://www.github.com/netlify/build/issues/2709)) ([8b56399](https://www.github.com/netlify/build/commit/8b5639916f7dffba4bb74e776db060f2cc4e0993)) ### [11.4.4](https://www.github.com/netlify/build/compare/build-v11.4.3...build-v11.4.4) (2021-04-29) ### Bug Fixes * re-enable `updateSite` endpoint ([#2704](https://www.github.com/netlify/build/issues/2704)) ([aa704af](https://www.github.com/netlify/build/commit/aa704af603b21fec4d99d2163f884e0a6f776761)) ### [11.4.3](https://www.github.com/netlify/build/compare/build-v11.4.2...build-v11.4.3) (2021-04-29) ### Bug Fixes * do not run `updateSite` for `netlify.toml`-only plugins ([#2703](https://www.github.com/netlify/build/issues/2703)) ([0580c8f](https://www.github.com/netlify/build/commit/0580c8fa0b1dfcd9fe8eaac6596e84d3ab38b980)) * percent-encode the `package` parameter of the `updatePlugin` endpoint ([#2702](https://www.github.com/netlify/build/issues/2702)) ([d2edef2](https://www.github.com/netlify/build/commit/d2edef2a8ca27dc996a2c7db50d66a623fcb1d08)) ### [11.4.2](https://www.github.com/netlify/build/compare/build-v11.4.1...build-v11.4.2) (2021-04-29) ### Bug Fixes * improve temporary fix for the `updatePlugin` bug ([#2696](https://www.github.com/netlify/build/issues/2696)) ([87fde4a](https://www.github.com/netlify/build/commit/87fde4accae7dc6d4ab8a1b09ef2c4c3a7152f25)) ### [11.4.1](https://www.github.com/netlify/build/compare/build-v11.4.0...build-v11.4.1) (2021-04-29) ### Bug Fixes * use the proper conventional commit in PR title ([#2694](https://www.github.com/netlify/build/issues/2694)) ([6829fe4](https://www.github.com/netlify/build/commit/6829fe432d9a2e1288c7eb931e052c12b302b703)) ## [11.4.0](https://www.github.com/netlify/build/compare/build-v11.3.2...build-v11.4.0) (2021-04-29) ### Features * call `updatePlugin` to pin plugins' versions ([#2683](https://www.github.com/netlify/build/issues/2683)) ([1d0ce63](https://www.github.com/netlify/build/commit/1d0ce6342f6e00376be51a05d906b7867fc8f9a0)) * improve debugging of plugins versioning ([#2691](https://www.github.com/netlify/build/issues/2691)) ([4659410](https://www.github.com/netlify/build/commit/46594109dcbc713d9ba3041e7a2a1013b4e406df)) ### [11.3.2](https://www.github.com/netlify/build/compare/build-v11.3.1...build-v11.3.2) (2021-04-28) ### Bug Fixes * **telemetry:** fwd relevant `nodeVersion` information ([#2634](https://www.github.com/netlify/build/issues/2634)) ([caec0d6](https://www.github.com/netlify/build/commit/caec0d66f7649856cdad749545fdbe084b1549e8)) ### [11.3.1](https://www.github.com/netlify/build/compare/build-v11.3.0...build-v11.3.1) (2021-04-27) ### Bug Fixes * do not fail when plugin error has `toJSON()` method ([#2677](https://www.github.com/netlify/build/issues/2677)) ([6363758](https://www.github.com/netlify/build/commit/6363758cb4cc2ef232ac5ff21298126ab7318e30)) ## [11.3.0](https://www.github.com/netlify/build/compare/build-v11.2.6...build-v11.3.0) (2021-04-27) ### Features * remove `--ui-plugins` CLI flag ([#2673](https://www.github.com/netlify/build/issues/2673)) ([a1cbf78](https://www.github.com/netlify/build/commit/a1cbf789bac18a83232a29c70390691442527693)) ### [11.2.6](https://www.github.com/netlify/build/compare/build-v11.2.5...build-v11.2.6) (2021-04-26) ### Bug Fixes * **deps:** update dependency map-obj to v3.1.0 ([#2656](https://www.github.com/netlify/build/issues/2656)) ([89e497a](https://www.github.com/netlify/build/commit/89e497a37a892f203a601a510e0e24ae037ad146)) * **deps:** update dependency statsd-client to v0.4.6 ([#2658](https://www.github.com/netlify/build/issues/2658)) ([be366a2](https://www.github.com/netlify/build/commit/be366a264d1e4db2a71ee8b233d65889cee3992c)) * **deps:** update dependency uuid to v7.0.3 ([#2659](https://www.github.com/netlify/build/issues/2659)) ([e7e9ea8](https://www.github.com/netlify/build/commit/e7e9ea8d0cb0a9c3cd9e16aeda2bd300c7057509)) ### [11.2.5](https://www.github.com/netlify/build/compare/build-v11.2.4...build-v11.2.5) (2021-04-24) ### Bug Fixes * **deps:** memoize-one breaking change in exports ([#2653](https://www.github.com/netlify/build/issues/2653)) ([7a10098](https://www.github.com/netlify/build/commit/7a10098382f3a35bbe1a0dc62a6d7b7416479d53)) ### [11.2.4](https://www.github.com/netlify/build/compare/build-v11.2.3...build-v11.2.4) (2021-04-23) ### Bug Fixes * **deps:** memoize-one cjs exports breaking changes ([#2643](https://www.github.com/netlify/build/issues/2643)) ([eafdaa0](https://www.github.com/netlify/build/commit/eafdaa04b60ae1753e3752748aaa4d2b6a5994e7)) ### [11.2.3](https://www.github.com/netlify/build/compare/build-v11.2.2...build-v11.2.3) (2021-04-22) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.8.0 ([#2631](https://www.github.com/netlify/build/issues/2631)) ([fbc235e](https://www.github.com/netlify/build/commit/fbc235e407ac100957a53fe5a151c02bde58bb7f)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.7.0 ([#2633](https://www.github.com/netlify/build/issues/2633)) ([4938a1c](https://www.github.com/netlify/build/commit/4938a1ca36a8dffcec5fb2b10a4e08ac451a8ba7)) ### [11.2.2](https://www.github.com/netlify/build/compare/build-v11.2.1...build-v11.2.2) (2021-04-21) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.6.0 ([#2626](https://www.github.com/netlify/build/issues/2626)) ([63e0330](https://www.github.com/netlify/build/commit/63e033014a78229daa9b11360abd24944561ec12)) ### [11.2.1](https://www.github.com/netlify/build/compare/build-v11.2.0...build-v11.2.1) (2021-04-20) ### Bug Fixes * **deps:** update netlify packages ([#2622](https://www.github.com/netlify/build/issues/2622)) ([4d35de4](https://www.github.com/netlify/build/commit/4d35de4d4d8d49b460080480c6e5b3610e6ef023)) ## [11.2.0](https://www.github.com/netlify/build/compare/build-v11.1.0...build-v11.2.0) (2021-04-19) ### Features * split `compatibleVersion` and `expectedVersion` ([#2613](https://www.github.com/netlify/build/issues/2613)) ([ffaf4a4](https://www.github.com/netlify/build/commit/ffaf4a477ef7e88a8af55dd6070b8e939e89c740)) * start pinning plugin versions ([#2617](https://www.github.com/netlify/build/issues/2617)) ([2c8a9cb](https://www.github.com/netlify/build/commit/2c8a9cb676e92411aa709a0aeb23394c30c7e3a1)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.7.0 ([#2619](https://www.github.com/netlify/build/issues/2619)) ([ae1e4ae](https://www.github.com/netlify/build/commit/ae1e4ae4624d8510f8838d6f3a190bc515d92925)) * failing esbuild tests ([#2615](https://www.github.com/netlify/build/issues/2615)) ([6f50566](https://www.github.com/netlify/build/commit/6f505662083672975eff9f745a68c7ec6702fd6d)) ## [11.1.0](https://www.github.com/netlify/build/compare/build-v11.0.2...build-v11.1.0) (2021-04-16) ### Features * refactor incompatible/outdated plugins warnings ([#2612](https://www.github.com/netlify/build/issues/2612)) ([d2777e9](https://www.github.com/netlify/build/commit/d2777e9b97d8b509c0fd6121e0ae4c6a89a0c408)) ### [11.0.2](https://www.github.com/netlify/build/compare/build-v11.0.1...build-v11.0.2) (2021-04-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.4.0 ([#2609](https://www.github.com/netlify/build/issues/2609)) ([83da9dc](https://www.github.com/netlify/build/commit/83da9dc609296f4cd7409c923e14e6772c2e4463)) ### [11.0.1](https://www.github.com/netlify/build/compare/build-v11.0.0...build-v11.0.1) (2021-04-14) ### Bug Fixes * `@netlify/config` major release ([#2603](https://www.github.com/netlify/build/issues/2603)) ([5c53aa8](https://www.github.com/netlify/build/commit/5c53aa895d51a0b99ac8638f54b326fb7ae1a395)) ## [11.0.0](https://www.github.com/netlify/build/compare/build-v10.3.0...build-v11.0.0) (2021-04-14) ### ⚠ BREAKING CHANGES * simplify `inlineConfig`, `defaultConfig` and `cachedConfig` CLI flags (#2595) ### Features * simplify `inlineConfig`, `defaultConfig` and `cachedConfig` CLI flags ([#2595](https://www.github.com/netlify/build/issues/2595)) ([c272632](https://www.github.com/netlify/build/commit/c272632db8825f85c07bb05cd90eacb1c8ea2544)) ## [10.3.0](https://www.github.com/netlify/build/compare/build-v10.2.7...build-v10.3.0) (2021-04-14) ### Features * add `--ui-plugins` CLI flag ([#2597](https://www.github.com/netlify/build/issues/2597)) ([7c9273b](https://www.github.com/netlify/build/commit/7c9273b2ed1e2e47b25c6eed0851bc26b1da037a)) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.2.1 ([#2592](https://www.github.com/netlify/build/issues/2592)) ([3fae367](https://www.github.com/netlify/build/commit/3fae3679e78734d2dad9e199870419f22cffd9c9)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.3.0 ([#2598](https://www.github.com/netlify/build/issues/2598)) ([5eeed10](https://www.github.com/netlify/build/commit/5eeed1075e0b65aa656be065558668b451896ac7)) ### [10.2.7](https://www.github.com/netlify/build/compare/build-v10.2.6...build-v10.2.7) (2021-04-09) ### Bug Fixes * warning message link ([#2576](https://www.github.com/netlify/build/issues/2576)) ([19a6ba3](https://www.github.com/netlify/build/commit/19a6ba31bc6b2fdce96dc6b48adfc7b8489a18a9)) ### [10.2.6](https://www.github.com/netlify/build/compare/build-v10.2.5...build-v10.2.6) (2021-04-09) ### Bug Fixes * improve lingering processes warning message ([#2467](https://www.github.com/netlify/build/issues/2467)) ([d62099b](https://www.github.com/netlify/build/commit/d62099ba424a70bbcb0b7d239d94f63cc03826b5)) ### [10.2.5](https://www.github.com/netlify/build/compare/build-v10.2.4...build-v10.2.5) (2021-04-07) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.2.0 ([#2552](https://www.github.com/netlify/build/issues/2552)) ([26b379e](https://www.github.com/netlify/build/commit/26b379e10feb5ee26c3fd426df05a21c0eafb4f1)) ### [10.2.4](https://www.github.com/netlify/build/compare/build-v10.2.3...build-v10.2.4) (2021-04-06) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.1.0 ([#2536](https://www.github.com/netlify/build/issues/2536)) ([fc694be](https://www.github.com/netlify/build/commit/fc694be35a186ef362c3e1e541d0e4c65af7109d)) ### [10.2.3](https://www.github.com/netlify/build/compare/build-v10.2.2...build-v10.2.3) (2021-04-06) ### Bug Fixes * **feature_flag:** remove telemetry feature flag code ([#2535](https://www.github.com/netlify/build/issues/2535)) ([69a48b6](https://www.github.com/netlify/build/commit/69a48b669a38c5492cbd7abed13f5d3bcd832dcd)) ### [10.2.2](https://www.github.com/netlify/build/compare/build-v10.2.1...build-v10.2.2) (2021-04-02) ### Bug Fixes * do not print internal information in the build logs ([#2527](https://www.github.com/netlify/build/issues/2527)) ([8c2ca4a](https://www.github.com/netlify/build/commit/8c2ca4aa406bd7d16ecb2b9d4aabed95c22dceb3)) ### [10.2.1](https://www.github.com/netlify/build/compare/build-v10.2.0...build-v10.2.1) (2021-04-01) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.6.0 ([#2167](https://www.github.com/netlify/build/issues/2167)) ([342cc55](https://www.github.com/netlify/build/commit/342cc55e4dd559c4db41f8e475425aef225523a1)) * remove some code ([#2524](https://www.github.com/netlify/build/issues/2524)) ([536b89b](https://www.github.com/netlify/build/commit/536b89bf4f82bf4ffe3155847ef824e56b35a82d)) ## [10.2.0](https://www.github.com/netlify/build/compare/build-v10.1.0...build-v10.2.0) (2021-04-01) ### Features * improve lingering processes warning message, comments and logic ([#2514](https://www.github.com/netlify/build/issues/2514)) ([e619528](https://www.github.com/netlify/build/commit/e61952833dd27fc2bb711505f820dc54248a29b9)) ## [10.1.0](https://www.github.com/netlify/build/compare/build-v10.0.0...build-v10.1.0) (2021-04-01) ### Features * add functions config object to build output ([#2518](https://www.github.com/netlify/build/issues/2518)) ([280834c](https://www.github.com/netlify/build/commit/280834c079995ad3c3b5607f983198fba6b3ac13)) ## [10.0.0](https://www.github.com/netlify/build/compare/build-v9.19.1...build-v10.0.0) (2021-03-30) ### ⚠ BREAKING CHANGES * add functions.directory property (#2496) ### Features * add functions.directory property ([#2496](https://www.github.com/netlify/build/issues/2496)) ([d72b1d1](https://www.github.com/netlify/build/commit/d72b1d1fb91de3fa23310ed477a6658c5492aed0)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.5.1 ([#2510](https://www.github.com/netlify/build/issues/2510)) ([8614122](https://www.github.com/netlify/build/commit/8614122b8c4cb676cece0780e390ef2b98dc08a1)) * disable 2 Yarn-related tests on Node <14 ([#2511](https://www.github.com/netlify/build/issues/2511)) ([f3b3db2](https://www.github.com/netlify/build/commit/f3b3db254c6c3826ac91b68e284b403cb5bfeedb)) ### [9.19.1](https://www.github.com/netlify/build/compare/build-v9.19.0...build-v9.19.1) (2021-03-30) ### Bug Fixes * **telemetry:** report telemetry errors without impacting builds ([#2501](https://www.github.com/netlify/build/issues/2501)) ([9bc15fe](https://www.github.com/netlify/build/commit/9bc15fec1f66e30a1980e52c55701d32ecc08b2f)) ## [9.19.0](https://www.github.com/netlify/build/compare/build-v9.18.0...build-v9.19.0) (2021-03-29) ### Features * make lingering processes logic work on Windows ([#2500](https://www.github.com/netlify/build/issues/2500)) ([a23f12c](https://www.github.com/netlify/build/commit/a23f12cd25f327f2c757148195dba371702060f3)) ## [9.18.0](https://www.github.com/netlify/build/compare/build-v9.17.1...build-v9.18.0) (2021-03-29) ### Features * improve how lingering processes are filtered out ([#2488](https://www.github.com/netlify/build/issues/2488)) ([4cc25e0](https://www.github.com/netlify/build/commit/4cc25e07d48c6edc2138a2d53cb4d39f0a9f93e1)) ### [9.17.1](https://www.github.com/netlify/build/compare/build-v9.17.0...build-v9.17.1) (2021-03-26) ### Bug Fixes * do not show an empty list of lingering processes ([#2486](https://www.github.com/netlify/build/issues/2486)) ([692a043](https://www.github.com/netlify/build/commit/692a043dbfd966e9f806521a33966025bf745337)) ## [9.17.0](https://www.github.com/netlify/build/compare/build-v9.16.0...build-v9.17.0) (2021-03-26) ### Features * distinguish between warnings and errors in build logs ([#2470](https://www.github.com/netlify/build/issues/2470)) ([73e4998](https://www.github.com/netlify/build/commit/73e4998218d0c243d47e98d2856486466631062c)) ## [9.16.0](https://www.github.com/netlify/build/compare/build-v9.15.1...build-v9.16.0) (2021-03-26) ### Features * improve lingering process message to add bullet points ([#2479](https://www.github.com/netlify/build/issues/2479)) ([9376e26](https://www.github.com/netlify/build/commit/9376e2615f7dcf9db556e8305a076ee477fc5387)) ### [9.15.1](https://www.github.com/netlify/build/compare/build-v9.15.0...build-v9.15.1) (2021-03-26) ### Bug Fixes * do not fail when there are no lingering processes ([#2480](https://www.github.com/netlify/build/issues/2480)) ([0c1eff1](https://www.github.com/netlify/build/commit/0c1eff1d004feab6dbdebb000e38dc49d0093176)) ## [9.15.0](https://www.github.com/netlify/build/compare/build-v9.14.1...build-v9.15.0) (2021-03-26) ### Features * improve lingering processes list ([#2475](https://www.github.com/netlify/build/issues/2475)) ([d805361](https://www.github.com/netlify/build/commit/d805361b505d130acd7b00b3ab3bb70ba29a0ccd)) ### [9.14.1](https://www.github.com/netlify/build/compare/build-v9.14.0...build-v9.14.1) (2021-03-26) ### Bug Fixes * improve lingering processes query ([#2473](https://www.github.com/netlify/build/issues/2473)) ([c7e1c58](https://www.github.com/netlify/build/commit/c7e1c5866a56ce00c47efbc4d8a5cbd3ed896343)) ## [9.14.0](https://www.github.com/netlify/build/compare/build-v9.13.2...build-v9.14.0) (2021-03-25) ### Features * remove legacy code related to netlify-automatic-functions ([#2469](https://www.github.com/netlify/build/issues/2469)) ([88b841a](https://www.github.com/netlify/build/commit/88b841ad02bf48f000b6d6250fb519630db1a23c)) * remove unused warning message ([#2468](https://www.github.com/netlify/build/issues/2468)) ([46a4cba](https://www.github.com/netlify/build/commit/46a4cba90a67d1848655f4e27153e520a513b33f)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.5.0 ([#2465](https://www.github.com/netlify/build/issues/2465)) ([cdd82f3](https://www.github.com/netlify/build/commit/cdd82f31cf2cf7e43ba6fd0faabcccf1e454ccf1)) ### [9.13.2](https://www.github.com/netlify/build/compare/v9.13.1...v9.13.2) (2021-03-24) ### Bug Fixes * **telemetry:** s/user_id/userId/ ([#2463](https://www.github.com/netlify/build/issues/2463)) ([7793424](https://www.github.com/netlify/build/commit/77934242d563af480121372b533c8cb7de278dc7)) ### [9.13.1](https://www.github.com/netlify/build/compare/v9.13.0...v9.13.1) (2021-03-23) ### Bug Fixes * **telemetry:** set a default user_id for production builds ([#2458](https://www.github.com/netlify/build/issues/2458)) ([50bd881](https://www.github.com/netlify/build/commit/50bd881b1805bce9cda7cc676f7231f4675fd906)) ## [9.13.0](https://www.github.com/netlify/build/compare/v9.12.0...v9.13.0) (2021-03-23) ### Features * add skipped plugin_runs ([#2457](https://www.github.com/netlify/build/issues/2457)) ([0d4f3fc](https://www.github.com/netlify/build/commit/0d4f3fc2d0f961651c6671739436ea97b9d831fd)) ## [9.12.0](https://www.github.com/netlify/build/compare/v9.11.4...v9.12.0) (2021-03-23) ### Features * move core plugins logic ([#2454](https://www.github.com/netlify/build/issues/2454)) ([35e7fa2](https://www.github.com/netlify/build/commit/35e7fa26b4d4280e53dc97b35a520ed4c0219fec)) * move plugins initialization code ([#2451](https://www.github.com/netlify/build/issues/2451)) ([ffc4a8b](https://www.github.com/netlify/build/commit/ffc4a8bd23b05d6150af90b4811fabed61466a01)) ### [9.11.4](https://www.github.com/netlify/build/compare/v9.11.3...v9.11.4) (2021-03-22) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to ^1.11.6 ([#2449](https://www.github.com/netlify/build/issues/2449)) ([f7613c3](https://www.github.com/netlify/build/commit/f7613c320d223833d853c511a7d8ea3de8bdcc83)) ### [9.11.3](https://www.github.com/netlify/build/compare/v9.11.2...v9.11.3) (2021-03-22) ### Bug Fixes * **telemetry:** wait for telemetry completion ([#2438](https://www.github.com/netlify/build/issues/2438)) ([ae0b3d5](https://www.github.com/netlify/build/commit/ae0b3d5236a0b4ab341e357d8ddd47ac3491474b)) ### [9.11.2](https://www.github.com/netlify/build/compare/v9.11.1...v9.11.2) (2021-03-19) ### Bug Fixes * add exit event handler to prevent invalid exit code 0 ([#2432](https://www.github.com/netlify/build/issues/2432)) ([361ed2d](https://www.github.com/netlify/build/commit/361ed2d67b0ae05a5e71692da388f68518188b92)) ### [9.11.1](https://www.github.com/netlify/build/compare/v9.11.0...v9.11.1) (2021-03-19) ### Bug Fixes * reinstate notice about bundling errors and warnings ([#2437](https://www.github.com/netlify/build/issues/2437)) ([b8571d8](https://www.github.com/netlify/build/commit/b8571d8dd0122a90edd7f0f512c3d77505cb42ca)) ## [9.11.0](https://www.github.com/netlify/build/compare/v9.10.2...v9.11.0) (2021-03-18) ### Features * add functions configuration API to @netlify/build ([#2414](https://www.github.com/netlify/build/issues/2414)) ([7aa8173](https://www.github.com/netlify/build/commit/7aa8173f9d0bf7553ed3326c5b4aca1ba34d5cda)) * add functions configuration API to @netlify/config ([#2390](https://www.github.com/netlify/build/issues/2390)) ([654d32e](https://www.github.com/netlify/build/commit/654d32eb49bea33816b1adde02f13f0843db9cdd)) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.4.3 ([#2436](https://www.github.com/netlify/build/issues/2436)) ([1d96d65](https://www.github.com/netlify/build/commit/1d96d65c073439b5e349963e357780ced48ec59a)) ### [9.10.2](https://www.github.com/netlify/build/compare/v9.10.1...v9.10.2) (2021-03-17) ### Bug Fixes * rename internal variable ([#2425](https://www.github.com/netlify/build/issues/2425)) ([614b5c7](https://www.github.com/netlify/build/commit/614b5c73422b0ad780038c09410f5e17242d1922)) ### [9.10.1](https://www.github.com/netlify/build/compare/v9.10.0...v9.10.1) (2021-03-16) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.4.2 ([#2423](https://www.github.com/netlify/build/issues/2423)) ([475ad30](https://www.github.com/netlify/build/commit/475ad302370777741675bb31b7aaa8c62aa58a49)) ## [9.10.0](https://www.github.com/netlify/build/compare/v9.9.7...v9.10.0) (2021-03-16) ### Features * add an error type for Functions bundling user errors ([#2420](https://www.github.com/netlify/build/issues/2420)) ([9fe8911](https://www.github.com/netlify/build/commit/9fe8911f22ad88ed38e22734cbcf687b9663fa49)) * add warning messages when using plugins that are too recent and incompatible ([#2422](https://www.github.com/netlify/build/issues/2422)) ([30bc126](https://www.github.com/netlify/build/commit/30bc1264e590b25a13cb2c53133589721fe45127)) ### [9.9.7](https://www.github.com/netlify/build/compare/v9.9.6...v9.9.7) (2021-03-16) ### Bug Fixes * build process never exits ([#2415](https://www.github.com/netlify/build/issues/2415)) ([d394b24](https://www.github.com/netlify/build/commit/d394b2410bb4d52053b8a922dfc8075933a3da62)) ### [9.9.7](https://www.github.com/netlify/build/compare/v9.9.6...v9.9.7) (2021-03-15) ### Bug Fixes * fix build process never exits ([#2415](https://www.github.com/netlify/build/issues/2415)) ([d394b2410](https://www.github.com/netlify/build/commit/d394b2410bb4d52053b8a922dfc8075933a3da62)) ### [9.9.6](https://www.github.com/netlify/build/compare/v9.9.5...v9.9.6) (2021-03-15) ### Bug Fixes * **compatibility:** properly handle dependency ranges ([#2408](https://www.github.com/netlify/build/issues/2408)) ([0d14572](https://www.github.com/netlify/build/commit/0d14572d4a6c826b4289b4630b8b04507075d3f4)) * **deps:** update dependency @netlify/plugins-list to ^2.4.1 ([#2404](https://www.github.com/netlify/build/issues/2404)) ([14cee2d](https://www.github.com/netlify/build/commit/14cee2d4075c998bf41697655ac572d4e1191b14)) ### [9.9.5](https://www.github.com/netlify/build/compare/v9.9.4...v9.9.5) (2021-03-12) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.7.1 ([#2396](https://www.github.com/netlify/build/issues/2396)) ([b4c070f](https://www.github.com/netlify/build/commit/b4c070fa8ac1406b3f489e5ddb038e4ecbe1f68c)) ### [9.9.4](https://www.github.com/netlify/build/compare/v9.9.3...v9.9.4) (2021-03-11) ### Bug Fixes * fix error handling when importing a non-existing local file ([#2394](https://www.github.com/netlify/build/issues/2394)) ([881448b](https://www.github.com/netlify/build/commit/881448b9ba6460086c653e7de40e6866f709b979)) ### [9.9.3](https://www.github.com/netlify/build/compare/v9.9.2...v9.9.3) (2021-03-11) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.7.0 ([#2391](https://www.github.com/netlify/build/issues/2391)) ([0c1c1dc](https://www.github.com/netlify/build/commit/0c1c1dcce06fc511ba2c26bf2fb52b91e202b670)) ### [9.9.2](https://www.github.com/netlify/build/compare/v9.9.1...v9.9.2) (2021-03-10) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.6.0 ([#2384](https://www.github.com/netlify/build/issues/2384)) ([4311b02](https://www.github.com/netlify/build/commit/4311b02530807eee9b83f063923f0d1932c9ec85)) ### [9.9.1](https://www.github.com/netlify/build/compare/v9.9.0...v9.9.1) (2021-03-09) ### Bug Fixes * fix `host` option in `@netlify/config` ([#2379](https://www.github.com/netlify/build/issues/2379)) ([64d8386](https://www.github.com/netlify/build/commit/64d8386daf5f1f069ea95fb655a593b05f8f8107)) * fix `semver` version with Node 8 ([#2362](https://www.github.com/netlify/build/issues/2362)) ([c72ecd8](https://www.github.com/netlify/build/commit/c72ecd8c8525e269180b427489991d9ec3238022)) ## [9.9.0](https://www.github.com/netlify/build/compare/v9.8.6...v9.9.0) (2021-03-08) ### Features * allow passing Netlify API host to Netlify API client ([#2288](https://www.github.com/netlify/build/issues/2288)) ([5529b1d](https://www.github.com/netlify/build/commit/5529b1dc92eccb6a932f80b006e83acfa0034413)) ### [9.8.6](https://www.github.com/netlify/build/compare/v9.8.5...v9.8.6) (2021-03-08) ### Bug Fixes * telemetry ([#2349](https://www.github.com/netlify/build/issues/2349)) ([3ee7ebf](https://www.github.com/netlify/build/commit/3ee7ebf08a2ac9e21d19f64ff63d7ce20ec031b9)) ### [9.8.5](https://www.github.com/netlify/build/compare/v9.8.4...v9.8.5) (2021-03-08) ### Bug Fixes * add dependency error messages for esbuild ([#2361](https://www.github.com/netlify/build/issues/2361)) ([9df783a](https://www.github.com/netlify/build/commit/9df783ace59371e3ada566e713aaabe05afff733)) ### [9.8.4](https://www.github.com/netlify/build/compare/v9.8.3...v9.8.4) (2021-03-05) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.4.0 ([#2363](https://www.github.com/netlify/build/issues/2363)) ([2e5286d](https://www.github.com/netlify/build/commit/2e5286d4b68a76d4cc4235c1f8337372521ec3ef)) ### [9.8.3](https://www.github.com/netlify/build/compare/v9.8.2...v9.8.3) (2021-03-04) ### Bug Fixes * fix esbuild error reporting ([#2358](https://www.github.com/netlify/build/issues/2358)) ([348d43b](https://www.github.com/netlify/build/commit/348d43bda2698dbdbb2a441a08038e48fadf6715)) ### [9.8.2](https://www.github.com/netlify/build/compare/v9.8.1...v9.8.2) (2021-03-04) ### Bug Fixes * **deps:** update dependency @netlify/plugins-list to ^2.3.0 ([#2356](https://www.github.com/netlify/build/issues/2356)) ([e4f79e6](https://www.github.com/netlify/build/commit/e4f79e63e786db9e6a511bb4f24297dfc3e0f29d)) ### [9.8.1](https://www.github.com/netlify/build/compare/v9.8.0...v9.8.1) (2021-03-04) ### Bug Fixes * **deps:** update netlify packages ([#2352](https://www.github.com/netlify/build/issues/2352)) ([c45bdc8](https://www.github.com/netlify/build/commit/c45bdc8e6165751b4294993426ff32e366f0c55a)) ## [9.8.0](https://www.github.com/netlify/build/compare/v9.7.1...v9.8.0) (2021-03-04) ### Features * stop printing output from esbuild ([#2350](https://www.github.com/netlify/build/issues/2350)) ([d225592](https://www.github.com/netlify/build/commit/d225592203a0ebdd8e48ad54ed9da5087991f888)) ### [9.7.1](https://www.github.com/netlify/build/compare/v9.7.0...v9.7.1) (2021-03-03) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.4.3 ([#2346](https://www.github.com/netlify/build/issues/2346)) ([76607df](https://www.github.com/netlify/build/commit/76607dff6de5594d2ebbabfb824737d2ce92e902)) ## [9.7.0](https://www.github.com/netlify/build/compare/v9.6.0...v9.7.0) (2021-03-03) ### Features * add `compatibility[*].siteDependencies` ([#2322](https://www.github.com/netlify/build/issues/2322)) ([9b1bc5d](https://www.github.com/netlify/build/commit/9b1bc5d4883a5301803cc69f863f1491e92857ed)) * do not sort `compatibility` field ([#2336](https://www.github.com/netlify/build/issues/2336)) ([455477f](https://www.github.com/netlify/build/commit/455477fc4af7b9d720588d4e4b601e388303a15b)) * improve `migrationGuide` test ([#2337](https://www.github.com/netlify/build/issues/2337)) ([9776923](https://www.github.com/netlify/build/commit/9776923855ae0baa767ac92ae39786ce77d3e92b)) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.4.2 ([#2341](https://www.github.com/netlify/build/issues/2341)) ([cbba54d](https://www.github.com/netlify/build/commit/cbba54dea815e61fe40e048de664035fd06df36d)) ## [9.6.0](https://www.github.com/netlify/build/compare/build-v9.5.0...v9.6.0) (2021-03-01) ### Features * improve tests related to `compatibility` ([#2321](https://www.github.com/netlify/build/issues/2321)) ([a5bfb6b](https://www.github.com/netlify/build/commit/a5bfb6b526a4155c5d6f912b03dfff845f5cb4ab)) * print migration guides ([#2320](https://www.github.com/netlify/build/issues/2320)) ([a701222](https://www.github.com/netlify/build/commit/a7012223a0e45373cfbdb278180c88a7971324a5)) ## [9.5.0](https://www.github.com/netlify/build/compare/v9.4.0...v9.5.0) (2021-02-26) ### Features * add `compatibility[*].nodeVersion` ([#2315](https://www.github.com/netlify/build/issues/2315)) ([8df8c34](https://www.github.com/netlify/build/commit/8df8c3481b8b7009e4ed367844106913463dd0a0)) * add feature flag for esbuild rollout ([#2308](https://www.github.com/netlify/build/issues/2308)) ([eef6428](https://www.github.com/netlify/build/commit/eef64288fed481c6940dc86fec5a61cbd953d5de)) * print warnings when using `compatibility` versions ([#2319](https://www.github.com/netlify/build/issues/2319)) ([9beea68](https://www.github.com/netlify/build/commit/9beea68ad168a454b214a149a466d71fe403b74a)) * turn `compatibility` field into an array ([#2318](https://www.github.com/netlify/build/issues/2318)) ([77243ef](https://www.github.com/netlify/build/commit/77243efaf93924501d2e986267b3b53aa5475153)) ### [9.4.0](https://www.github.com/netlify/build/compare/v9.3.0...v9.4.0) (2021-02-25) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.4.0 ([#2312](https://www.github.com/netlify/build/issues/2312)) ([1dbf0a1](https://www.github.com/netlify/build/commit/1dbf0a1463e33fee4a69e90fbf5d128bfdc22081)) ## [9.3.0](https://www.github.com/netlify/build/compare/v9.2.0...v9.3.0) (2021-02-25) ### Features * add `plugin.compatibility` field ([#2310](https://www.github.com/netlify/build/issues/2310)) ([80525cb](https://www.github.com/netlify/build/commit/80525cbbc8ba38fc46daad0d40703d5a69c27dbc)) * allow `version` in `plugins.json` to be an object ([#2307](https://www.github.com/netlify/build/issues/2307)) ([ce56878](https://www.github.com/netlify/build/commit/ce5687804759539ec43840089822fb9629fbc1fd)) * move where the plugin Node.js version is resolved ([#2311](https://www.github.com/netlify/build/issues/2311)) ([5ada384](https://www.github.com/netlify/build/commit/5ada384d644661dca9b481d91b7f829acc9b7b00)) ## [9.2.0](https://www.github.com/netlify/build/compare/v9.1.4...v9.2.0) (2021-02-23) ### Features * print warnings for outdated plugins ([#2289](https://www.github.com/netlify/build/issues/2289)) ([d8fb63d](https://www.github.com/netlify/build/commit/d8fb63d73881ba5ae2e21961f07ce8e3228e7382)) ### [9.1.4](https://www.github.com/netlify/build/compare/v9.1.3...v9.1.4) (2021-02-22) ### Bug Fixes * **deps:** update netlify packages ([#2302](https://www.github.com/netlify/build/issues/2302)) ([dbbbeea](https://www.github.com/netlify/build/commit/dbbbeea693c2353d8014a3a74d6b69abfabcebe2)) ### [9.1.3](https://www.github.com/netlify/build/compare/v9.1.2...v9.1.3) (2021-02-18) ### Bug Fixes * fix `files` in `package.json` with `npm@7` ([#2278](https://www.github.com/netlify/build/issues/2278)) ([e9df064](https://www.github.com/netlify/build/commit/e9df0645f3083a0bb141c8b5b6e474ed4e27dbe9)) ### [9.1.2](https://www.github.com/netlify/build/compare/v9.1.1...v9.1.2) (2021-02-11) ### Bug Fixes * improve Bugsnag reporting of upload errors ([#2267](https://www.github.com/netlify/build/issues/2267)) ([c03985c](https://www.github.com/netlify/build/commit/c03985c83ff0f426f59a85a42f039e0522bc83d5)) ### [9.1.1](https://www.github.com/netlify/build/compare/v9.1.0...v9.1.1) (2021-02-10) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.3.0 ([#2264](https://www.github.com/netlify/build/issues/2264)) ([40d122d](https://www.github.com/netlify/build/commit/40d122d6e722e55f1925f4179999d0d7ad065999)) ## [9.1.0](https://www.github.com/netlify/build/compare/v9.0.1...v9.1.0) (2021-02-09) ### Features * pass esbuild parameters to ZISI ([#2256](https://www.github.com/netlify/build/issues/2256)) ([2483f72](https://www.github.com/netlify/build/commit/2483f72660ac2306fd817b6fa330e28e6709dfbb)) ### [9.0.1](https://www.github.com/netlify/build/compare/v9.0.0...v9.0.1) (2021-02-09) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.2.0 ([#2258](https://www.github.com/netlify/build/issues/2258)) ([6faf36b](https://www.github.com/netlify/build/commit/6faf36b24d66f88f93dc96d0190a80af459ad5f4)) ## [9.0.0](https://www.github.com/netlify/build/compare/v8.4.0...v9.0.0) (2021-02-04) ### ⚠ BREAKING CHANGES * use netlify/functions as the default functions directory (#2188) ### Features * use netlify/functions as the default functions directory ([#2188](https://www.github.com/netlify/build/issues/2188)) ([84e1e07](https://www.github.com/netlify/build/commit/84e1e075b5efd7ca26ccaf2531511e7737d97f1f)) ## [8.4.0](https://www.github.com/netlify/build/compare/v8.3.5...v8.4.0) (2021-02-03) ### Features * remove deploy feature flag ([#2246](https://www.github.com/netlify/build/issues/2246)) ([cbeac56](https://www.github.com/netlify/build/commit/cbeac5653c924265a61d84485e41c0e76427db31)) ### [8.3.5](https://www.github.com/netlify/build/compare/v8.3.4...v8.3.5) (2021-02-03) ### Bug Fixes * **deps:** force a release for [#2244](https://www.github.com/netlify/build/issues/2244) and bump zip-it-and-ship-it ([#2245](https://www.github.com/netlify/build/issues/2245)) ([25787c2](https://www.github.com/netlify/build/commit/25787c2cf134fbbd8029a142512ff314cbab1951)) ### [8.3.4](https://www.github.com/netlify/build/compare/v8.3.3...v8.3.4) (2021-02-01) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to v1.11.3 ([#2235](https://www.github.com/netlify/build/issues/2235)) ([27e2a7f](https://www.github.com/netlify/build/commit/27e2a7faf95262198ec1ae9ad2e1c14f5b5b5561)) * **deps:** update dependency moize to v6 ([#2231](https://www.github.com/netlify/build/issues/2231)) ([e34454c](https://www.github.com/netlify/build/commit/e34454c633bbc541c4074bdaa15361c84f0c8f04)) ### [8.3.3](https://www.github.com/netlify/build/compare/v8.3.2...v8.3.3) (2021-01-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.3 ([#2227](https://www.github.com/netlify/build/issues/2227)) ([301fe88](https://www.github.com/netlify/build/commit/301fe885ed1a896e7b0766fcc85386510ff9f670)) ### [8.3.2](https://www.github.com/netlify/build/compare/v8.3.1...v8.3.2) (2021-01-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.2 ([#2222](https://www.github.com/netlify/build/issues/2222)) ([47adf7a](https://www.github.com/netlify/build/commit/47adf7af089f308b9abe7709675bc84b8f179809)) ### [8.3.1](https://www.github.com/netlify/build/compare/v8.3.0...v8.3.1) (2021-01-26) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.1 ([#2215](https://www.github.com/netlify/build/issues/2215)) ([f6e191e](https://www.github.com/netlify/build/commit/f6e191edbb3bf43ac1b9d75b7e0ab62fabd2062f)) ## [8.3.0](https://www.github.com/netlify/build/compare/v8.2.0...v8.3.0) (2021-01-26) ### Features * add back `process.env` plugins communication ([#2212](https://www.github.com/netlify/build/issues/2212)) ([d815ef9](https://www.github.com/netlify/build/commit/d815ef9cfb68af90691f705b0c21abb7415fd5b9)) ## [8.2.0](https://www.github.com/netlify/build/compare/v8.1.1...v8.2.0) (2021-01-25) ### Features * run deploy logic as core instead of plugin ([#2192](https://www.github.com/netlify/build/issues/2192)) ([157767b](https://www.github.com/netlify/build/commit/157767b9e5e3857344efd16def9495e7d8bff939)) ### [8.1.1](https://www.github.com/netlify/build/compare/build-v8.1.0...v8.1.1) (2021-01-25) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.0 ([#2197](https://www.github.com/netlify/build/issues/2197)) ([8ed28f9](https://www.github.com/netlify/build/commit/8ed28f9ccbe991f98cf8dcf2acde4c19f01c246d)) ### [8.0.6](https://www.github.com/netlify/build/compare/build-v8.0.5...v8.0.6) (2021-01-15) ### Bug Fixes * **deps:** update dependency @netlify/plugin-edge-handlers to v1.11.1 ([#2178](https://www.github.com/netlify/build/issues/2178)) ([5941943](https://www.github.com/netlify/build/commit/594194390aae7e43b21e437ddd735ed9b0df55e1)) * **windows:** show windows path separator in netlify dir warning message ([#2182](https://www.github.com/netlify/build/issues/2182)) ([02b497f](https://www.github.com/netlify/build/commit/02b497fb75a1d3b4c3d10df4cbc3c137c711b5bd)) <file_sep>'use strict' module.exports = { onEnd() { throw new Error('test') }, } <file_sep>'use strict' const { execPath, env: { TEST_NODE_PATH }, } = require('process') module.exports = { onPreBuild() { console.log(`expect execPath to equal TEST_NODE_PATH. Got '${execPath === TEST_NODE_PATH}'`) }, } <file_sep>'use strict' const { delimiter, normalize } = require('path') const { env } = require('process') const { getBinPath } = require('get-bin-path') const pathKey = require('path-key') const netlifyBuild = require('../..') const { runFixtureCommon, FIXTURES_DIR } = require('./common') const ROOT_DIR = `${__dirname}/../..` const BUILD_BIN_DIR = normalize(`${ROOT_DIR}/node_modules/.bin`) const runFixture = async function ( t, fixtureName, { flags = {}, env: envOption = {}, programmatic = false, ...opts } = {}, ) { const binaryPath = await BINARY_PATH const flagsA = { debug: true, buffer: true, featureFlags: { ...DEFAULT_TEST_FEATURE_FLAGS, ...flags.featureFlags }, ...flags, testOpts: { silentLingeringProcesses: true, pluginsListUrl: 'test', ...flags.testOpts }, } const envOptionA = { // Ensure local environment variables aren't used during development BUILD_TELEMETRY_DISABLED: '', NETLIFY_AUTH_TOKEN: '', // Allows executing any locally installed Node modules inside tests, // regardless of the current directory. // This is needed for example to run `yarn` in tests in environments that // do not have a global binary of `yarn`. [pathKey()]: `${env[pathKey()]}${delimiter}${BUILD_BIN_DIR}`, ...envOption, } const mainFunc = programmatic ? netlifyBuild : getNetlifyBuildLogs return runFixtureCommon(t, fixtureName, { ...opts, flags: flagsA, env: envOptionA, mainFunc, binaryPath }) } const DEFAULT_TEST_FEATURE_FLAGS = {} const getNetlifyBuildLogs = async function (flags) { const { logs } = await netlifyBuild(flags) return [logs.stdout.join('\n'), logs.stderr.join('\n')].filter(Boolean).join('\n\n') } // Use a top-level promise so it's only performed once at load time const BINARY_PATH = getBinPath({ cwd: ROOT_DIR }) module.exports = { runFixture, FIXTURES_DIR } <file_sep>'use strict' // eslint-disable-next-line fp/no-loops, no-empty while (true) {} <file_sep>[build] base = "/base" command = "echo command" edge_handlers = "edge-handlers" publish = "publish" [functions] directory = "functions" <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig: { build } }) { // eslint-disable-next-line no-param-reassign build.command = 'node --version' }, onBuild({ netlifyConfig: { build: { command }, }, }) { console.log(command) }, } <file_sep>'use strict' module.exports = { onPreBuild({ constants: { PUBLISH_DIR } }) { console.log(PUBLISH_DIR) }, } <file_sep>'use strict' // const { version } = require('process') const test = require('ava') const pathExists = require('path-exists') // const { gte: gteVersion } = require('semver') const { removeDir } = require('../helpers/dir') const { runFixture, FIXTURES_DIR } = require('../helpers/main') // Run fixture and ensure: // - specific directories exist after run // - specific directories are removed before/after test const runInstallFixture = async function (t, fixtureName, dirs, opts) { await removeDir(dirs) try { await runFixture(t, fixtureName, opts) await Promise.all( dirs.map(async (dir) => { t.true(await pathExists(dir)) }), ) } finally { await removeDir(dirs) } } test('Functions: install dependencies nested', async (t) => { await runInstallFixture(t, 'dir', [ `${FIXTURES_DIR}/dir/.netlify/functions/`, `${FIXTURES_DIR}/dir/functions/function/node_modules/`, ]) }) test('Functions: ignore package.json inside node_modules', async (t) => { await runInstallFixture(t, 'modules', [`${FIXTURES_DIR}/modules/.netlify/functions/`]) }) test('Functions: install dependencies with npm', async (t) => { await runInstallFixture(t, 'functions_npm', [ `${FIXTURES_DIR}/functions_npm/.netlify/functions/`, `${FIXTURES_DIR}/functions_npm/functions/node_modules/`, ]) }) test('Functions: install dependencies with Yarn locally', async (t) => { await runInstallFixture( t, 'functions_yarn', [`${FIXTURES_DIR}/functions_yarn/.netlify/functions/`, `${FIXTURES_DIR}/functions_yarn/functions/node_modules/`], { useBinary: true }, ) }) test('Functions: install dependencies with Yarn in CI', async (t) => { await runInstallFixture(t, 'functions_yarn_ci', [`${FIXTURES_DIR}/functions_yarn_ci/functions/node_modules/`], { useBinary: true, flags: { mode: 'buildbot', deployId: 'functions_yarn_ci' }, }) }) test('Functions: does not install dependencies unless opting in', async (t) => { await runInstallFixture(t, 'optional', []) t.false(await pathExists(`${FIXTURES_DIR}/optional/functions/node_modules/`)) }) test('Functions: does not install dependencies unless opting in (with esbuild)', async (t) => { await runInstallFixture(t, 'optional-esbuild', []) t.false(await pathExists(`${FIXTURES_DIR}/optional-esbuild/functions/node_modules/`)) }) test('Functions: does not install dependencies unless opting in (with esbuild, many dependencies)', async (t) => { await runInstallFixture(t, 'optional-many-esbuild', []) t.false(await pathExists(`${FIXTURES_DIR}/optional-many-esbuild/functions/node_modules/`)) }) test('Functions: does not print warnings when dependency was mispelled', async (t) => { await runInstallFixture(t, 'mispelled_dep', []) t.false(await pathExists(`${FIXTURES_DIR}/mispelled_dep/functions/node_modules/`)) }) test('Functions: does not print warnings when dependency was local', async (t) => { await runInstallFixture(t, 'local_dep', []) t.false(await pathExists(`${FIXTURES_DIR}/local_dep/functions/node_modules/`)) }) test('Functions: install dependencies handles errors', async (t) => { await runInstallFixture(t, 'functions_error', []) }) test('Install local plugin dependencies: with npm', async (t) => { await runInstallFixture(t, 'npm', [`${FIXTURES_DIR}/npm/plugin/node_modules/`]) }) // @todo: enable those tests for Node <14.0.0 // @todo: uncomment after upgrading to Ava v4. // See https://github.com/netlify/build/issues/3615 // if (gteVersion(version, '14.0.0')) { // test.skip('Install local plugin dependencies: with yarn locally', async (t) => { // await runInstallFixture(t, 'yarn', [`${FIXTURES_DIR}/yarn/plugin/node_modules/`], { useBinary: true }) // }) // test.skip('Install local plugin dependencies: with yarn in CI', async (t) => { // await runInstallFixture(t, 'yarn_ci', [`${FIXTURES_DIR}/yarn_ci/plugin/node_modules/`], { // useBinary: true, // flags: { mode: 'buildbot' }, // }) // }) // } test('Install local plugin dependencies: propagate errors', async (t) => { await runFixture(t, 'error') }) test('Install local plugin dependencies: already installed', async (t) => { await runFixture(t, 'already') }) test('Install local plugin dependencies: no package.json', async (t) => { await runFixture(t, 'no_package') }) test('Install local plugin dependencies: no root package.json', async (t) => { await runFixture(t, 'no_root_package', { copyRoot: {} }) }) test('Install local plugin dependencies: missing plugin in netlify.toml', async (t) => { await runFixture(t, 'local_missing') }) <file_sep>'use strict' const { writeFile, copyFile, readdir } = require('fs') const { normalize } = require('path') const { platform, version } = require('process') const { promisify } = require('util') const { pluginsList } = require('@netlify/plugins-list') const test = require('ava') const cpy = require('cpy') const del = require('del') const pathExists = require('path-exists') const { spy } = require('sinon') const { removeDir } = require('../helpers/dir') const { runFixture, FIXTURES_DIR } = require('../helpers/main') const { startServer } = require('../helpers/server') const { startTcpServer } = require('../helpers/tcp_server') const { getTempName } = require('../helpers/temp') const pWriteFile = promisify(writeFile) const pCopyFile = promisify(copyFile) const pReaddir = promisify(readdir) test('Pass netlifyConfig to plugins', async (t) => { await runFixture(t, 'config_valid') }) test('netlifyConfig properties are readonly (set) by default', async (t) => { await runFixture(t, 'config_readonly_set') }) test('netlifyConfig properties are readonly (delete) by default', async (t) => { await runFixture(t, 'config_readonly_delete') }) test('netlifyConfig properties are readonly (defineProperty) by default', async (t) => { await runFixture(t, 'config_readonly_define') }) test('Some netlifyConfig properties can be mutated', async (t) => { await runFixture(t, 'config_mutate_general') }) test('netlifyConfig properties cannot be deleted', async (t) => { await runFixture(t, 'config_mutate_delete') }) test('netlifyConfig properties cannot be assigned to undefined', async (t) => { await runFixture(t, 'config_mutate_set_undefined') }) test('netlifyConfig properties cannot be assigned to null', async (t) => { await runFixture(t, 'config_mutate_set_null') }) test('netlifyConfig properties cannot be assigned to undefined with defineProperty', async (t) => { await runFixture(t, 'config_mutate_define_undefined') }) test('netlifyConfig properties mutations is persisted', async (t) => { await runFixture(t, 'config_mutate_persist') }) test('netlifyConfig array properties can be mutated per index', async (t) => { await runFixture(t, 'config_mutate_array_index') }) test('netlifyConfig array properties can be pushed', async (t) => { await runFixture(t, 'config_mutate_array_push') }) test('netlifyConfig.functionsDirectory mutations are used during functions bundling', async (t) => { await runFixture(t, 'config_mutate_functions_directory_bundling') }) test('netlifyConfig.functionsDirectory deletion skips functions bundling', async (t) => { await runFixture(t, 'config_mutate_functions_directory_skip') }) test('netlifyConfig.functionsDirectory mutations are used by utils.functions', async (t) => { await runFixture(t, 'config_mutate_functions_directory_utils') }) test('netlifyConfig.functionsDirectory mutations are used by constants.FUNCTIONS_SRC', async (t) => { await runFixture(t, 'config_mutate_functions_directory_constants') }) test('netlifyConfig.functionsDirectory mutations are taken into account by default constants.FUNCTIONS_SRC', async (t) => { await runFixture(t, 'config_mutate_functions_directory_default') }) test('netlifyConfig.functions.star.directory mutations work', async (t) => { await runFixture(t, 'config_mutate_functions_directory_star') }) test('netlifyConfig.functions.star.directory has priority over functions.directory', async (t) => { await runFixture(t, 'config_mutate_functions_directory_star_priority') }) test('netlifyConfig.functions.directory mutations work', async (t) => { await runFixture(t, 'config_mutate_functions_directory_nested') }) test('netlifyConfig.functions.directory has priority over functions.star.directory', async (t) => { await runFixture(t, 'config_mutate_functions_directory_nested_priority') }) test('netlifyConfig.build.functions mutations work', async (t) => { await runFixture(t, 'config_mutate_functions_directory_build') }) test('netlifyConfig.functions mutations are used during functions bundling', async (t) => { await runFixture(t, 'config_mutate_functions_bundling') }) test('netlifyConfig.functions mutations on any property can be used', async (t) => { await runFixture(t, 'config_mutate_functions_any') }) test('netlifyConfig.functions mutations can add new functions configs', async (t) => { await runFixture(t, 'config_mutate_functions_new') }) // Node 10 prints different snapshots due to change of behavior with // `util.inspect()` // @todo remove once Node 10 support is removed if (!version.startsWith('v10.')) { test('netlifyConfig properties are deeply readonly by default', async (t) => { await runFixture(t, 'config_readonly_deep') }) test('netlifyConfig is updated when headers file is created by a plugin', async (t) => { const headersFile = `${FIXTURES_DIR}/config_create_headers_plugin/_headers` await del(headersFile) try { await runFixture(t, 'config_create_headers_plugin') } finally { await del(headersFile) } }) test('netlifyConfig is updated when headers file is created by a plugin and publish was changed', async (t) => { const headersFile = `${FIXTURES_DIR}/config_create_headers_plugin_dynamic/test/_headers` await del(headersFile) try { await runFixture(t, 'config_create_headers_plugin_dynamic') } finally { await del(headersFile) } }) test('netlifyConfig is updated when headers file is created by a build command', async (t) => { const headersFile = `${FIXTURES_DIR}/config_create_headers_command/_headers` await del(headersFile) try { await runFixture(t, 'config_create_headers_command') } finally { await del(headersFile) } }) test('netlifyConfig is updated when headers file is created by a build command and publish was changed', async (t) => { const headersFile = `${FIXTURES_DIR}/config_create_headers_command_dynamic/test/_headers` await del(headersFile) try { await runFixture(t, 'config_create_headers_command_dynamic') } finally { await del(headersFile) } }) test('netlifyConfig is updated when redirects file is created by a plugin', async (t) => { const redirectsFile = `${FIXTURES_DIR}/config_create_redirects_plugin/_redirects` await del(redirectsFile) try { await runFixture(t, 'config_create_redirects_plugin') } finally { await del(redirectsFile) } }) test('netlifyConfig is updated when redirects file is created by a plugin and publish was changed', async (t) => { const redirectsFile = `${FIXTURES_DIR}/config_create_redirects_plugin_dynamic/test/_redirects` await del(redirectsFile) try { await runFixture(t, 'config_create_redirects_plugin_dynamic') } finally { await del(redirectsFile) } }) test('netlifyConfig is updated when redirects file is created by a build command', async (t) => { const redirectsFile = `${FIXTURES_DIR}/config_create_redirects_command/_redirects` await del(redirectsFile) try { await runFixture(t, 'config_create_redirects_command') } finally { await del(redirectsFile) } }) test('netlifyConfig is updated when redirects file is created by a build command and publish was changed', async (t) => { const redirectsFile = `${FIXTURES_DIR}/config_create_redirects_command_dynamic/test/_redirects` await del(redirectsFile) try { await runFixture(t, 'config_create_redirects_command_dynamic') } finally { await del(redirectsFile) } }) test('netlifyConfig.processing can be assigned all at once', async (t) => { await runFixture(t, 'config_mutate_processing_all') }) test('netlifyConfig.processing can be assigned individually', async (t) => { await runFixture(t, 'config_mutate_processing_prop') }) test('netlifyConfig.headers can be assigned all at once', async (t) => { await runFixture(t, 'config_mutate_headers_all') }) test('netlifyConfig.headers can be modified before headers file has been added', async (t) => { const headersPath = `${FIXTURES_DIR}/config_mutate_headers_before/_headers` await del(headersPath) try { await runFixture(t, 'config_mutate_headers_before') } finally { await del(headersPath) } }) test('netlifyConfig.headers can be modified after headers file has been added', async (t) => { await runFixture(t, 'config_mutate_headers_after') }) test('--saveConfig deletes headers file if headers were changed', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_headers` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` const fixtureHeadersPath = `${fixtureDir}/_headers_file` const headersPath = `${fixtureDir}/_headers` await Promise.all([pCopyFile(fixtureConfigPath, configPath), pCopyFile(fixtureHeadersPath, headersPath)]) const { address, stopServer } = await startDeployServer() try { try { await runFixture(t, 'config_save_headers', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, }) } finally { await stopServer() } } finally { await del(headersPath) } }) test('--saveConfig deletes headers file if any configuration property was changed', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_delete_headers` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` const fixtureHeadersPath = `${fixtureDir}/_headers_file` const headersPath = `${fixtureDir}/_headers` await Promise.all([pCopyFile(fixtureConfigPath, configPath), pCopyFile(fixtureHeadersPath, headersPath)]) const { address, stopServer } = await startDeployServer() try { try { await runFixture(t, 'config_delete_headers', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, }) } finally { await stopServer() } } finally { await del(headersPath) } }) test('Erroneous headers created by a build command are handled', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_create_headers_command_error` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` const headersPath = `${fixtureDir}/_headers` await pCopyFile(fixtureConfigPath, configPath) const { address, stopServer } = await startDeployServer() try { try { await runFixture(t, 'config_create_headers_command_error', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, useBinary: true, }) } finally { await stopServer() } } finally { await del(headersPath) } }) test('Erroneous headers created by a plugin are handled', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_create_headers_plugin_error` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` const headersPath = `${fixtureDir}/_headers` await pCopyFile(fixtureConfigPath, configPath) const { address, stopServer } = await startDeployServer() try { try { await runFixture(t, 'config_create_headers_plugin_error', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, useBinary: true, }) } finally { await stopServer() } } finally { await del(headersPath) } }) test('netlifyConfig.redirects can be assigned all at once', async (t) => { await runFixture(t, 'config_mutate_redirects_all') }) test('netlifyConfig.redirects can be modified before redirects file has been added', async (t) => { const redirectsPath = `${FIXTURES_DIR}/config_mutate_redirects_before/_redirects` await del(redirectsPath) try { await runFixture(t, 'config_mutate_redirects_before') } finally { await del(redirectsPath) } }) test('netlifyConfig.redirects can be modified after redirects file has been added', async (t) => { await runFixture(t, 'config_mutate_redirects_after') }) test('--saveConfig deletes redirects file if redirects were changed', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_redirects` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` const fixtureRedirectsPath = `${fixtureDir}/_redirects_file` const redirectsPath = `${fixtureDir}/_redirects` await Promise.all([pCopyFile(fixtureConfigPath, configPath), pCopyFile(fixtureRedirectsPath, redirectsPath)]) const { address, stopServer } = await startDeployServer() try { try { await runFixture(t, 'config_save_redirects', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, }) } finally { await stopServer() } } finally { await del(redirectsPath) } }) test('--saveConfig deletes redirects file if any configuration property was changed', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_delete_redirects` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` const fixtureRedirectsPath = `${fixtureDir}/_redirects_file` const redirectsPath = `${fixtureDir}/_redirects` await Promise.all([pCopyFile(fixtureConfigPath, configPath), pCopyFile(fixtureRedirectsPath, redirectsPath)]) const { address, stopServer } = await startDeployServer() try { try { await runFixture(t, 'config_delete_redirects', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, }) } finally { await stopServer() } } finally { await del(redirectsPath) } }) } test('netlifyConfig.build.command can be changed', async (t) => { await runFixture(t, 'config_mutate_build_command_change') }) test('netlifyConfig.build.command can be added', async (t) => { await runFixture(t, 'config_mutate_build_command_add') }) test('netlifyConfig.build.command can be removed', async (t) => { await runFixture(t, 'config_mutate_build_command_remove') }) test('netlifyConfig.build.environment can be assigned all at once', async (t) => { await runFixture(t, 'config_mutate_env_all') }) test('netlifyConfig.build.environment can be assigned individually', async (t) => { await runFixture(t, 'config_mutate_env_prop') }) test('netlifyConfig.build.publish mutations are used by constants.PUBLISH_DIR', async (t) => { await runFixture(t, 'config_mutate_publish_constants') }) test('netlifyConfig.build.edge_handlers mutations are used by constants.EDGE_HANDLERS_SRC', async (t) => { await runFixture(t, 'config_mutate_edge_handlers_constants') }) test('netlifyConfig.edge_handlers can be assigned all at once', async (t) => { await runFixture(t, 'config_mutate_edge_handlers_all') }) test('netlifyConfig.services can be assigned all at once', async (t) => { await runFixture(t, 'config_mutate_services_all') }) test('netlifyConfig.services can be assigned individually', async (t) => { await runFixture(t, 'config_mutate_services_prop') }) test('netlifyConfig mutations fail if done in an event that is too late', async (t) => { await runFixture(t, 'config_mutate_too_late') }) test('netlifyConfig mutations fail correctly on symbols', async (t) => { await runFixture(t, 'config_mutate_symbol') }) test('netlifyConfig mutations fail if the syntax is invalid', async (t) => { await runFixture(t, 'config_mutate_invalid_syntax') }) test('--saveConfig saves the configuration changes as netlify.toml', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_changes` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` await pCopyFile(fixtureConfigPath, configPath) const { address, stopServer } = await startDeployServer() try { await runFixture(t, 'config_save_changes', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, }) } finally { await stopServer() } }) test('--saveConfig is required to save the configuration changes as netlify.toml', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_none` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` await pCopyFile(fixtureConfigPath, configPath) const { address, stopServer } = await startDeployServer() try { await runFixture(t, 'config_save_none', { flags: { buildbotServerSocket: address, config: configPath, context: 'production', branch: 'main' }, }) } finally { await stopServer() } }) test('--saveConfig creates netlify.toml if it does not exist', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_empty` const configPath = `${fixtureDir}/netlify.toml` await del(configPath) const { address, stopServer } = await startDeployServer() try { await runFixture(t, 'config_save_empty', { flags: { buildbotServerSocket: address, saveConfig: true, context: 'production', branch: 'main', defaultConfig: { plugins: [{ package: './plugin.js' }] }, }, }) t.false(await pathExists(configPath)) } finally { await stopServer() } }) test('--saveConfig gives higher priority to configuration changes than context properties', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_context` const fixtureConfigPath = `${fixtureDir}/netlify.toml` const configPath = `${fixtureDir}/test_netlify.toml` await pCopyFile(fixtureConfigPath, configPath) const { address, stopServer } = await startDeployServer() try { await runFixture(t, 'config_save_context', { flags: { buildbotServerSocket: address, config: configPath, saveConfig: true, context: 'production', branch: 'main', }, }) } finally { await stopServer() } }) test('--saveConfig is performed before deploy', async (t) => { const fixtureDir = `${FIXTURES_DIR}/config_save_deploy` const configPath = `${fixtureDir}/netlify.toml` await del(configPath) const { address, stopServer } = await startDeployServer() try { await runFixture(t, 'config_save_deploy', { flags: { buildbotServerSocket: address, saveConfig: true, context: 'production', branch: 'main', defaultConfig: { plugins: [{ package: './plugin.js' }] }, }, }) } finally { await stopServer() } }) test('constants.CONFIG_PATH', async (t) => { await runFixture(t, 'config_path') }) test('constants.PUBLISH_DIR default value', async (t) => { await runFixture(t, 'publish_default') }) test('constants.PUBLISH_DIR default value with build.base', async (t) => { await runFixture(t, 'publish_default_base') }) test('constants.PUBLISH_DIR absolute path', async (t) => { await runFixture(t, 'publish_absolute') }) test('constants.PUBLISH_DIR relative path', async (t) => { await runFixture(t, 'publish_relative') }) test('constants.PUBLISH_DIR missing path', async (t) => { await runFixture(t, 'publish_missing') }) test('constants.FUNCTIONS_SRC default value', async (t) => { await runFixture(t, 'functions_src_default') }) test('constants.FUNCTIONS_SRC uses legacy default functions directory if it exists', async (t) => { await runFixture(t, 'functions_src_legacy') }) test('constants.FUNCTIONS_SRC ignores the legacy default functions directory if the new default directory exists', async (t) => { await runFixture(t, 'functions_src_default_and_legacy') }) test('constants.FUNCTIONS_SRC relative path', async (t) => { await runFixture(t, 'functions_src_relative') }) test('constants.FUNCTIONS_SRC dynamic is ignored if FUNCTIONS_SRC is specified', async (t) => { await runFixture(t, 'functions_src_dynamic_ignore', { copyRoot: { git: false } }) }) test('constants.FUNCTIONS_SRC dynamic should bundle Functions', async (t) => { await runFixture(t, 'functions_src_dynamic_bundle', { copyRoot: { git: false } }) }) test('constants.FUNCTIONS_SRC automatic value', async (t) => { await runFixture(t, 'functions_src_auto') }) test('constants.FUNCTIONS_SRC missing path', async (t) => { await runFixture(t, 'functions_src_missing') }) test('constants.FUNCTIONS_SRC created dynamically', async (t) => { await runFixture(t, 'functions_src_dynamic', { copyRoot: { git: false } }) }) test('constants.INTERNAL_FUNCTIONS_SRC default value', async (t) => { await runFixture(t, 'internal_functions_src_default') }) test('constants.FUNCTIONS_DIST', async (t) => { await runFixture(t, 'functions_dist') }) test('constants.CACHE_DIR local', async (t) => { await runFixture(t, 'cache') }) test('constants.CACHE_DIR CI', async (t) => { await runFixture(t, 'cache', { flags: { cacheDir: '/opt/build/cache' } }) }) test('constants.IS_LOCAL CI', async (t) => { await runFixture(t, 'is_local', { flags: { mode: 'buildbot' } }) }) test('constants.SITE_ID', async (t) => { await runFixture(t, 'site_id', { flags: { siteId: 'test' } }) }) test('constants.IS_LOCAL local', async (t) => { await runFixture(t, 'is_local') }) test('constants.NETLIFY_BUILD_VERSION', async (t) => { await runFixture(t, 'netlify_build_version') }) test('constants.NETLIFY_API_TOKEN', async (t) => { await runFixture(t, 'netlify_api_token', { flags: { token: 'test', testOpts: { env: false } } }) }) test('constants.NETLIFY_API_HOST', async (t) => { await runFixture(t, 'netlify_api_host', { flags: { apiHost: 'test.api.netlify.com' } }) }) test('constants.NETLIFY_API_HOST default value is set to api.netlify.com', async (t) => { await runFixture(t, 'netlify_api_host') }) test('Pass packageJson to plugins', async (t) => { await runFixture(t, 'package_json_valid') }) test('Pass empty packageJson to plugins if no package.json', async (t) => { await runFixture(t, 'package_json_none', { copyRoot: { git: false } }) }) test('Pass empty packageJson to plugins if package.json invalid', async (t) => { await runFixture(t, 'package_json_invalid') }) test('Functions: missing source directory', async (t) => { await runFixture(t, 'missing') }) test('Functions: must not be a regular file', async (t) => { await runFixture(t, 'regular_file') }) test('Functions: can be a symbolic link', async (t) => { await runFixture(t, 'symlink') }) test('Functions: default directory', async (t) => { await runFixture(t, 'default') }) test('Functions: simple setup', async (t) => { await removeDir(`${FIXTURES_DIR}/simple/.netlify/functions/`) await runFixture(t, 'simple') }) test('Functions: no functions', async (t) => { await runFixture(t, 'none') }) test('Functions: invalid package.json', async (t) => { const fixtureName = 'functions_package_json_invalid' const packageJsonPath = `${FIXTURES_DIR}/${fixtureName}/package.json` // We need to create that file during tests. Otherwise, ESLint fails when // detecting an invalid *.json file. await pWriteFile(packageJsonPath, '{{}') try { await runFixture(t, fixtureName) } finally { await del(packageJsonPath) } }) test('Functions: --functionsDistDir', async (t) => { const functionsDistDir = await getTempName() try { await runFixture(t, 'simple', { flags: { functionsDistDir } }) t.true(await pathExists(functionsDistDir)) const files = await pReaddir(functionsDistDir) t.is(files.length, 1) } finally { await removeDir(functionsDistDir) } }) const EDGE_HANDLERS_LOCAL_DIR = '.netlify/edge-handlers' const EDGE_HANDLERS_MANIFEST = 'manifest.json' const getEdgeHandlersPaths = function (fixtureName) { const outputDir = `${FIXTURES_DIR}/${fixtureName}/${EDGE_HANDLERS_LOCAL_DIR}` const manifestPath = `${outputDir}/${EDGE_HANDLERS_MANIFEST}` return { outputDir, manifestPath } } const loadEdgeHandlerBundle = async function ({ outputDir, manifestPath }) { const bundlePath = getEdgeHandlerBundlePath({ outputDir, manifestPath }) try { return requireEdgeHandleBundle(bundlePath) } finally { await removeDir(bundlePath) } } const getEdgeHandlerBundlePath = function ({ outputDir, manifestPath }) { // eslint-disable-next-line node/global-require, import/no-dynamic-require const { sha } = require(manifestPath) return `${outputDir}/${sha}` } const requireEdgeHandleBundle = function (bundlePath) { const set = spy() global.netlifyRegistry = { set } // eslint-disable-next-line node/global-require, import/no-dynamic-require require(bundlePath) delete global.netlifyRegistry return set.args.map(normalizeEdgeHandler) } const normalizeEdgeHandler = function ([handlerName, { onRequest }]) { return { handlerName, onRequest } } test('constants.EDGE_HANDLERS_SRC default value', async (t) => { await runFixture(t, 'edge_handlers_src_default') }) test('constants.EDGE_HANDLERS_SRC automatic value', async (t) => { await runFixture(t, 'edge_handlers_src_auto') }) test('constants.EDGE_HANDLERS_SRC relative path', async (t) => { await runFixture(t, 'edge_handlers_src_relative') }) test('constants.EDGE_HANDLERS_SRC missing path', async (t) => { await runFixture(t, 'edge_handlers_src_missing') }) test('constants.EDGE_HANDLERS_SRC created dynamically', async (t) => { await runFixture(t, 'edge_handlers_src_dynamic', { copyRoot: { git: false } }) }) test('constants.EDGE_HANDLERS_SRC dynamic is ignored if EDGE_HANDLERS_SRC is specified', async (t) => { await runFixture(t, 'edge_handlers_src_dynamic_ignore', { copyRoot: { git: false } }) }) test('Edge handlers: simple setup', async (t) => { const { outputDir, manifestPath } = getEdgeHandlersPaths('handlers_simple') await runFixture(t, 'handlers_simple') const [{ handlerName, onRequest }] = await loadEdgeHandlerBundle({ outputDir, manifestPath }) t.is(handlerName, 'test') t.deepEqual(onRequest('test'), [true, 'test', 'test']) }) test('Edge handlers: can configure directory', async (t) => { const { outputDir, manifestPath } = getEdgeHandlersPaths('handlers_custom_dir') await runFixture(t, 'handlers_custom_dir') const [{ handlerName }] = await loadEdgeHandlerBundle({ outputDir, manifestPath }) t.is(handlerName, 'test') }) test('Deploy plugin succeeds', async (t) => { const { address, requests, stopServer } = await startDeployServer() try { await runFixture(t, 'empty', { flags: { buildbotServerSocket: address } }) } finally { await stopServer() } t.true(requests.every(isValidDeployReponse)) }) test('Deploy plugin sends deployDir as a path relative to repositoryRoot', async (t) => { const { address, requests, stopServer } = await startDeployServer() try { await runFixture(t, 'deploy_dir_path', { flags: { buildbotServerSocket: address }, snapshot: false }) } finally { await stopServer() } const [{ deployDir }] = requests t.is(deployDir, normalize('base/publish')) }) test('Deploy plugin is not run unless --buildbotServerSocket is passed', async (t) => { const { requests, stopServer } = await startDeployServer() try { await runFixture(t, 'empty', { flags: {}, snapshot: false }) } finally { await stopServer() } t.is(requests.length, 0) }) test('Deploy plugin connection error', async (t) => { const { address, stopServer } = await startDeployServer() await stopServer() const { exitCode, returnValue } = await runFixture(t, 'empty', { flags: { buildbotServerSocket: address }, snapshot: false, }) t.not(exitCode, 0) t.true(returnValue.includes('Could not connect to buildbot: Error: connect')) }) test('Deploy plugin response syntax error', async (t) => { const { address, stopServer } = await startDeployServer({ response: 'test' }) try { await runFixture(t, 'empty', { flags: { buildbotServerSocket: address } }) } finally { await stopServer() } }) test('Deploy plugin response system error', async (t) => { const { address, stopServer } = await startDeployServer({ response: { succeeded: false, values: { error: 'test', error_type: 'system' } }, }) try { await runFixture(t, 'empty', { flags: { buildbotServerSocket: address } }) } finally { await stopServer() } }) test('Deploy plugin response user error', async (t) => { const { address, stopServer } = await startDeployServer({ response: { succeeded: false, values: { error: 'test', error_type: 'user' } }, }) try { await runFixture(t, 'empty', { flags: { buildbotServerSocket: address } }) } finally { await stopServer() } }) test('Deploy plugin does not wait for post-processing if not using onSuccess nor onEnd', async (t) => { const { address, requests, stopServer } = await startDeployServer() try { await runFixture(t, 'empty', { flags: { buildbotServerSocket: address }, snapshot: false }) } finally { await stopServer() } t.true(requests.every(doesNotWaitForPostProcessing)) }) test('Deploy plugin waits for post-processing if using onSuccess', async (t) => { const { address, requests, stopServer } = await startDeployServer() try { await runFixture(t, 'success', { flags: { buildbotServerSocket: address }, snapshot: false }) } finally { await stopServer() } t.true(requests.every(waitsForPostProcessing)) }) test('Deploy plugin waits for post-processing if using onEnd', async (t) => { const { address, requests, stopServer } = await startDeployServer() try { await runFixture(t, 'end', { flags: { buildbotServerSocket: address }, snapshot: false }) } finally { await stopServer() } t.true(requests.every(waitsForPostProcessing)) }) const startDeployServer = function (opts = {}) { const useUnixSocket = platform !== 'win32' return startTcpServer({ useUnixSocket, response: { succeeded: true, ...opts.response }, ...opts }) } const isValidDeployReponse = function ({ action, deployDir }) { return ['deploySite', 'deploySiteAndAwaitLive'].includes(action) && typeof deployDir === 'string' && deployDir !== '' } const doesNotWaitForPostProcessing = function (request) { return request.action === 'deploySite' } const waitsForPostProcessing = function (request) { return request.action === 'deploySiteAndAwaitLive' } test('plugin.onSuccess is triggered on success', async (t) => { await runFixture(t, 'success_ok') }) test('plugin.onSuccess is not triggered on failure', async (t) => { await runFixture(t, 'success_not_ok') }) test('plugin.onSuccess is not triggered on failPlugin()', async (t) => { await runFixture(t, 'success_fail_plugin') }) test('plugin.onSuccess is not triggered on cancelBuild()', async (t) => { await runFixture(t, 'success_cancel_build') }) test('plugin.onSuccess can fail but does not stop builds', async (t) => { await runFixture(t, 'success_fail') }) test('plugin.onError is not triggered on success', async (t) => { await runFixture(t, 'error_ok') }) test('plugin.onError is triggered on failure', async (t) => { await runFixture(t, 'error_not_ok') }) test('plugin.onError is not triggered on failPlugin()', async (t) => { await runFixture(t, 'error_fail_plugin') }) test('plugin.onError is triggered on cancelBuild()', async (t) => { await runFixture(t, 'error_cancel_build') }) test('plugin.onError can fail', async (t) => { await runFixture(t, 'error_fail') }) test('plugin.onError gets an error argument', async (t) => { await runFixture(t, 'error_argument') }) test('plugin.onError can be used in several plugins', async (t) => { await runFixture(t, 'error_several') }) test('plugin.onEnd is triggered on success', async (t) => { await runFixture(t, 'end_ok') }) test('plugin.onEnd is triggered on failure', async (t) => { await runFixture(t, 'end_not_ok') }) test('plugin.onEnd is not triggered on failPlugin()', async (t) => { await runFixture(t, 'end_fail_plugin') }) test('plugin.onEnd is triggered on cancelBuild()', async (t) => { await runFixture(t, 'end_cancel_build') }) test('plugin.onEnd can fail but it does not stop builds', async (t) => { await runFixture(t, 'end_fail') }) test('plugin.onEnd and plugin.onError can be used together', async (t) => { await runFixture(t, 'end_error') }) test('plugin.onEnd can be used in several plugins', async (t) => { await runFixture(t, 'end_several') }) test('Local plugins', async (t) => { await runFixture(t, 'local') }) test('Local plugins directory', async (t) => { await runFixture(t, 'local_dir') }) test('Local plugins absolute path', async (t) => { await runFixture(t, 'local_absolute') }) test('Local plugins invalid path', async (t) => { await runFixture(t, 'local_invalid') }) test('Node module plugins', async (t) => { await runFixture(t, 'module') }) test('UI plugins', async (t) => { const defaultConfig = { plugins: [{ package: 'netlify-plugin-test' }] } await runFixture(t, 'ui', { flags: { defaultConfig } }) }) test('Resolution is relative to the build directory', async (t) => { await runFixture(t, 'module_base', { flags: { config: `${FIXTURES_DIR}/module_base/netlify.toml` } }) }) test('Non-existing plugins', async (t) => { await runFixture(t, 'non_existing') }) test('Do not allow overriding core plugins', async (t) => { await runFixture(t, 'core_override') }) const runWithApiMock = async function ( t, fixtureName, { testPlugin, response = getPluginsList(testPlugin), ...flags } = {}, status = 200, ) { const { scheme, host, stopServer } = await startServer({ path: PLUGINS_LIST_URL, response, status, }) try { await runFixture(t, fixtureName, { flags: { testOpts: { pluginsListUrl: `${scheme}://${host}`, ...flags.testOpts }, ...flags, }, }) } finally { await stopServer() } } // We use a specific plugin in tests. We hardcode its version to keep the tests // stable even when new versions of that plugin are published. const getPluginsList = function (testPlugin = DEFAULT_TEST_PLUGIN) { return pluginsList.map((plugin) => getPlugin(plugin, testPlugin)) } const getPlugin = function (plugin, testPlugin) { if (plugin.package !== TEST_PLUGIN_NAME) { return plugin } return { ...plugin, ...testPlugin } } const TEST_PLUGIN_NAME = 'netlify-plugin-contextual-env' const TEST_PLUGIN_VERSION = '0.3.0' const PLUGINS_LIST_URL = '/' const DEFAULT_TEST_PLUGIN = { version: TEST_PLUGIN_VERSION } const DEFAULT_TEST_PLUGIN_RUNS = [{ package: TEST_PLUGIN_NAME, version: TEST_PLUGIN_VERSION }] test('Install plugins in .netlify/plugins/ when not cached', async (t) => { await removeDir(`${FIXTURES_DIR}/valid_package/.netlify`) try { await runWithApiMock(t, 'valid_package') } finally { await removeDir(`${FIXTURES_DIR}/valid_package/.netlify`) } }) test('Use plugins cached in .netlify/plugins/', async (t) => { await runWithApiMock(t, 'plugins_cache') }) test('Do not use plugins cached in .netlify/plugins/ if outdated', async (t) => { const pluginsDir = `${FIXTURES_DIR}/plugins_cache_outdated/.netlify/plugins` await removeDir(pluginsDir) await cpy('**', '../plugins', { cwd: `${pluginsDir}-old`, parents: true }) try { await runWithApiMock(t, 'plugins_cache_outdated') } finally { await removeDir(pluginsDir) } }) test('Fetches the list of plugin versions', async (t) => { await runWithApiMock(t, 'plugins_cache') }) test('Only prints the list of plugin versions in verbose mode', async (t) => { await runWithApiMock(t, 'plugins_cache', { debug: false }) }) test('Uses fallback when the plugins fetch fails', async (t) => { await runWithApiMock(t, 'plugins_cache', {}, 500) }) test('Uses fallback when the plugins fetch succeeds with an invalid response', async (t) => { await runWithApiMock(t, 'plugins_cache', { response: { error: 'test' } }) }) test('Can execute local binaries when using .netlify/plugins/', async (t) => { await runWithApiMock(t, 'plugins_cache_bin') }) test('Can require site dependencies when using .netlify/plugins/', async (t) => { await runWithApiMock(t, 'plugins_cache_site_deps') }) test('Works with .netlify being a regular file', async (t) => { const dotNetlifyFile = `${FIXTURES_DIR}/plugins_cache_regular_file/.netlify` await pWriteFile(dotNetlifyFile, '') try { await runWithApiMock(t, 'plugins_cache_regular_file') } finally { await removeDir(dotNetlifyFile) } }) test('Print a warning when using plugins not in plugins.json nor package.json', async (t) => { await runWithApiMock(t, 'invalid_package') }) test('Can use local plugins even when some plugins are cached', async (t) => { await runWithApiMock(t, 'plugins_cache_local') }) // Note: the `version` field is normalized to `1.0.0` in the test snapshots test('Prints outdated plugins installed in package.json', async (t) => { await runWithApiMock(t, 'plugins_outdated_package_json') }) test('Prints incompatible plugins installed in package.json', async (t) => { await runWithApiMock(t, 'plugins_incompatible_package_json', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', nodeVersion: '<100' }], }, }) }) test('Does not print incompatible plugins installed in package.json if major version is same', async (t) => { await runWithApiMock(t, 'plugins_incompatible_package_json_same_major', { testPlugin: { compatibility: [{ version: '0.4.0' }, { version: '0.4.1', nodeVersion: '<100' }], }, }) }) test('Does not print incompatible plugins installed in package.json if not using the compatibility field', async (t) => { await runWithApiMock(t, 'plugins_incompatible_package_json') }) // `serial()` is needed due to the potential of re-installing the dependency test.serial('Plugins can specify non-matching compatibility.nodeVersion', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [ { version: '0.3.0' }, { version: '0.2.0', nodeVersion: '100 - 120' }, { version: '0.1.0', nodeVersion: '<100' }, ], }, }) }) test.serial('Plugins ignore compatibility entries without conditions unless pinned', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0' }, { version: '0.1.0', nodeVersion: '<100' }], }, }) }) test.serial('Plugins does not ignore compatibility entries without conditions if pinned', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0' }, { version: '0.1.0' }], }, defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME, pinned_version: '0.2.0' }] }, }) }) test.serial('Plugins ignore compatibility conditions if pinned', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', nodeVersion: '100 - 200' }, { version: '0.1.0' }], }, defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME, pinned_version: '0.2.0' }] }, }) }) test.serial('Plugins can specify matching compatibility.nodeVersion', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [ { version: '0.3.0' }, { version: '0.2.0', nodeVersion: '6 - 120' }, { version: '0.1.0', nodeVersion: '<6' }, ], }, }) }) test.serial('Plugins compatibility defaults to version field', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [ { version: '0.3.0' }, { version: '0.2.0', nodeVersion: '4 - 6' }, { version: '0.1.0', nodeVersion: '<4' }, ], }, }) }) test.serial('Plugins can specify compatibility.migrationGuide', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [ { version: '0.3.0', migrationGuide: 'http://test.com' }, { version: '0.2.0', nodeVersion: '100 - 120' }, { version: '0.1.0', nodeVersion: '<100' }, ], }, }) }) test.serial('Plugins can specify matching compatibility.siteDependencies', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_site_dependencies/.netlify`) await runWithApiMock(t, 'plugins_compat_site_dependencies', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', siteDependencies: { 'ansi-styles': '<3' } }], }, }) }) test.serial('Plugins can specify non-matching compatibility.siteDependencies', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_site_dependencies/.netlify`) await runWithApiMock(t, 'plugins_compat_site_dependencies', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', siteDependencies: { 'ansi-styles': '<2' } }], }, }) }) test.serial('Plugins can specify non-existing compatibility.siteDependencies', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_site_dependencies/.netlify`) await runWithApiMock(t, 'plugins_compat_site_dependencies', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', siteDependencies: { 'does-not-exist': '<3' } }], }, }) }) test.serial('Plugins can specify multiple non-matching compatibility conditions', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_site_dependencies/.netlify`) await runWithApiMock(t, 'plugins_compat_site_dependencies', { testPlugin: { compatibility: [ { version: '0.3.0' }, { version: '0.2.0', siteDependencies: { 'ansi-styles': '<3' }, nodeVersion: '100 - 120' }, ], }, }) }) test.serial('Plugins can specify multiple matching compatibility conditions', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_site_dependencies/.netlify`) await runWithApiMock(t, 'plugins_compat_site_dependencies', { testPlugin: { compatibility: [ { version: '0.3.0' }, { version: '0.2.0', siteDependencies: { 'ansi-styles': '<3' }, nodeVersion: '<100' }, ], }, }) }) test.serial('Plugins can specify non-matching compatibility.siteDependencies range', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_site_dependencies_range/.netlify`) await runWithApiMock(t, 'plugins_compat_site_dependencies_range', { testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', siteDependencies: { 'dependency-with-range': '<10' } }], }, }) }) test.serial('Plugin versions can be feature flagged', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { featureFlags: { some_feature_flag: true }, testPlugin: { compatibility: [{ version: '0.3.0', featureFlag: 'some_feature_flag' }, { version: '0.2.0' }], }, }) }) test.serial('Plugin versions that are feature flagged are ignored if no matching feature flag', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [{ version: '0.3.0', featureFlag: 'some_feature_flag' }, { version: '0.2.0' }], }, }) }) test.serial( 'Plugin pinned versions that are feature flagged are not ignored if pinned but no matching feature flag', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { testPlugin: { compatibility: [{ version: '0.3.0', featureFlag: 'some_feature_flag' }, { version: '0.2.0' }], }, defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME, pinned_version: '0.3.0' }] }, }) }, ) test.serial('Compatibility order take precedence over the `featureFlag` property', async (t) => { await removeDir(`${FIXTURES_DIR}/plugins_compat_node_version/.netlify`) await runWithApiMock(t, 'plugins_compat_node_version', { featureFlags: { some_feature_flag: true }, testPlugin: { compatibility: [{ version: '0.3.0' }, { version: '0.2.0', featureFlag: 'some_feature_flag' }], }, }) }) const getNodePath = function (nodeVersion) { return `/home/ether/.nvm/versions/node/v${nodeVersion}/bin/node` } const runWithUpdatePluginMock = async function (t, fixture, { flags, status, sendStatus = true, testPlugin } = {}) { const { scheme, host, requests, stopServer } = await startServer([ { path: UPDATE_PLUGIN_PATH, status }, { path: PLUGINS_LIST_URL, response: getPluginsList(testPlugin), status: 200 }, ]) try { await runFixture(t, fixture, { flags: { siteId: 'test', token: '<PASSWORD>', sendStatus, testOpts: { scheme, host, pluginsListUrl: `${scheme}://${host}` }, defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME }] }, ...flags, }, }) } finally { await stopServer() } t.snapshot(requests) } const UPDATE_PLUGIN_PATH = `/api/v1/sites/test/plugins/${TEST_PLUGIN_NAME}` test('Pin plugin versions', async (t) => { await runWithUpdatePluginMock(t, 'pin_success') }) test('Report updatePlugin API error without failing the build', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { status: 400 }) }) test('Does not report 404 updatePlugin API error', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { status: 404 }) }) test('Only pin plugin versions in production', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { sendStatus: false }) }) test('Do not pin plugin versions without an API token', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { flags: { token: '' } }) }) test('Do not pin plugin versions without a siteId', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { flags: { siteId: '' } }) }) test('Do not pin plugin versions if the build failed', async (t) => { await runWithUpdatePluginMock(t, 'pin_build_failed') }) test('Do not pin plugin versions if the plugin failed', async (t) => { await runWithUpdatePluginMock(t, 'pin_plugin_failed') }) test('Do not pin plugin versions if the build was installed in package.json', async (t) => { await runWithUpdatePluginMock(t, 'pin_module', { flags: { defaultConfig: {} } }) }) test('Do not pin plugin versions if already pinned', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { flags: { defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME, pinned_version: '0' }] } }, testPlugin: { version: '1.0.0' }, }) }) test('Pinning plugin versions takes into account the compatibility field', async (t) => { await runWithUpdatePluginMock(t, 'pin_success', { flags: { defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME, pinned_version: '0' }] } }, testPlugin: { compatibility: [ { version: '1.0.0' }, { version: '100.0.0', nodeVersion: '<100' }, { version: '0.3.0', nodeVersion: '<100' }, ], }, }) }) const runWithPluginRunsMock = async function ( t, fixture, { flags, status, sendStatus = true, testPlugin, pluginRuns = DEFAULT_TEST_PLUGIN_RUNS } = {}, ) { const { scheme, host, requests, stopServer } = await startServer([ { path: PLUGIN_RUNS_PATH, response: pluginRuns, status }, { path: PLUGINS_LIST_URL, response: getPluginsList(testPlugin), status: 200 }, ]) try { await runFixture(t, fixture, { flags: { siteId: 'test', token: 'test', sendStatus, testOpts: { scheme, host, pluginsListUrl: `${scheme}://${host}` }, ...flags, }, }) } finally { await stopServer() } t.snapshot(requests) } const PLUGIN_RUNS_PATH = `/api/v1/sites/test/plugin_runs/latest` test('Pin netlify.toml-only plugin versions', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success') }) test('Does not pin netlify.toml-only plugin versions if there are no matching plugin runs', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { pluginRuns: [{ package: `${TEST_PLUGIN_NAME}-test` }] }) }) test('Does not pin netlify.toml-only plugin versions if there are no plugin runs', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { pluginRuns: [] }) }) test('Does not pin netlify.toml-only plugin versions if there are no matching plugin runs version', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { pluginRuns: [{ package: TEST_PLUGIN_NAME }] }) }) // Node 10 `util.inspect()` prints the API error differently // @todo remove after removing support for Node 10 if (!version.startsWith('v10.')) { test('Fails the build when pinning netlify.toml-only plugin versions and the API request fails', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { status: 400 }) }) } test('Does not pin netlify.toml-only plugin versions if already pinned', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { flags: { defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME, pinned_version: '0' }] } }, }) }) test('Does not pin netlify.toml-only plugin versions if installed in UI', async (t) => { await runWithPluginRunsMock(t, 'pin_config_ui', { flags: { defaultConfig: { plugins: [{ package: TEST_PLUGIN_NAME }] } }, }) }) test('Does not pin netlify.toml-only plugin versions if installed in package.json', async (t) => { await runWithPluginRunsMock(t, 'pin_config_module') }) test('Does not pin netlify.toml-only plugin versions if there are no API token', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { flags: { token: '' } }) }) test('Does not pin netlify.toml-only plugin versions if there are no site ID', async (t) => { await runWithPluginRunsMock(t, 'pin_config_success', { flags: { siteId: '' } }) }) test('Validate --node-path unsupported version does not fail when no plugins are used', async (t) => { const nodePath = getNodePath('8.2.0') await runFixture(t, 'empty', { flags: { nodePath }, }) }) test('Validate --node-path version is supported by the plugin', async (t) => { const nodePath = getNodePath('12.0.0') await runFixture(t, 'engines', { flags: { nodePath }, }) }) test('Validate --node-path exists', async (t) => { await runFixture(t, 'node_version_simple', { flags: { nodePath: '/doesNotExist' }, }) }) test('Provided --node-path version is unused in buildbot for local plugin executions if <10.18.0', async (t) => { const nodePath = getNodePath('10.17.0') await runFixture(t, 'version_greater_than_minimum', { flags: { nodePath, mode: 'buildbot' }, }) }) test('Plugins can execute local binaries', async (t) => { await runFixture(t, 'local_bin') }) test('Plugin output can interleave stdout and stderr', async (t) => { await runFixture(t, 'interleave') }) // TODO: check output length once big outputs are actually fixed test.serial('Big plugin output is not truncated', async (t) => { await runFixture(t, 'big', { snapshot: false }) t.pass() }) test('Plugins can have inputs', async (t) => { await runFixture(t, 'inputs') }) test('process.env changes are propagated to other plugins', async (t) => { await runFixture(t, 'env_changes_plugin') }) test('process.env changes are propagated to onError and onEnd', async (t) => { await runFixture(t, 'env_changes_on_error') }) test('process.env changes are propagated to build.command', async (t) => { await runFixture(t, 'env_changes_command') }) test('build.environment changes are propagated to other plugins', async (t) => { await runFixture(t, 'env_changes_build_plugin') }) test('build.environment changes are propagated to onError and onEnd', async (t) => { await runFixture(t, 'env_changes_build_on_error') }) test('build.environment changes are propagated to build.command', async (t) => { await runFixture(t, 'env_changes_build_command') }) test('build.environment and process.env changes can be mixed', async (t) => { await runFixture(t, 'env_changes_build_mix') }) test('Expose some utils', async (t) => { await runFixture(t, 'keys') }) test('Utils are defined', async (t) => { await runFixture(t, 'defined') }) test('Can run utils', async (t) => { const functionsDir = `${FIXTURES_DIR}/functions_add/.netlify/functions-internal` await removeDir(functionsDir) try { await runFixture(t, 'functions_add') } finally { await removeDir(functionsDir) } }) test('Can run list util', async (t) => { await runFixture(t, 'functions_list') }) test('Git utils fails if no root', async (t) => { await runFixture(t, 'git_no_root', { copyRoot: { git: false } }) }) test('Git utils does not fail if no root and not used', async (t) => { await runFixture(t, 'keys', { copyRoot: { git: false } }) }) test('Validate plugin is an object', async (t) => { await runFixture(t, 'object') }) test('Validate plugin event handler names', async (t) => { await runFixture(t, 'handler_name') }) test('Validate plugin event handler function', async (t) => { await runFixture(t, 'handler_function') }) <file_sep>'use strict' const { promisify } = require('util') // TODO: replace with `timers/promises` after dropping Node < 15.0.0 const pSetTimeout = promisify(setTimeout) // 100ms const LOG_TIMEOUT = 1e2 module.exports = { async onPreBuild() { console.log('one') await pSetTimeout(LOG_TIMEOUT) console.error('two') await pSetTimeout(LOG_TIMEOUT) console.log('three') }, } <file_sep>'use strict' const missing = require('./missing') module.exports = () => missing() <file_sep>'use strict' module.exports = { onPreBuild({ constants: { NETLIFY_API_HOST } }) { console.log(NETLIFY_API_HOST) }, } <file_sep>'use strict' module.exports = { onEnd() { console.log('onEnd') }, } <file_sep>[build] command = "echo commandBase" edge_handlers = "edge-handlers" publish = "publish" [functions] directory = "functions" <file_sep>'use strict' const test = require('ava') const { runFixture } = require('../helpers/main') test('plugins: not array', async (t) => { await runFixture(t, 'plugins_not_array') }) test('plugins: not array of objects', async (t) => { await runFixture(t, 'plugins_not_objects') }) test('plugins: do not allow duplicates', async (t) => { await runFixture(t, 'plugins_duplicate') }) test('plugins: do not allow duplicates in the UI', async (t) => { const defaultConfig = { plugins: [{ package: 'test' }, { package: 'test' }] } await runFixture(t, 'empty', { flags: { defaultConfig } }) }) test('plugins.any: unknown property', async (t) => { await runFixture(t, 'plugins_unknown') }) test('plugins.any.id backward compatibility', async (t) => { await runFixture(t, 'plugins_id_compat') }) test('plugins.any.enabled removed', async (t) => { await runFixture(t, 'plugins_enabled') }) test('plugins.any.package: required', async (t) => { await runFixture(t, 'plugins_package_required') }) test('plugins.any.package: string', async (t) => { await runFixture(t, 'plugins_package_string') }) test('plugins.any.package: should not include a version', async (t) => { await runFixture(t, 'plugins_package_version') }) test('plugins.any.package: should not include a URI scheme', async (t) => { await runFixture(t, 'plugins_package_scheme') }) test('plugins.any.pinned_version: string', async (t) => { await runFixture(t, 'plugins_pinned_version_string') }) test('plugins.any.inputs: object', async (t) => { await runFixture(t, 'plugins_inputs_object') }) test('build: object', async (t) => { await runFixture(t, 'build_object') }) test('build.publish: string', async (t) => { await runFixture(t, 'build_publish_string') }) test('build.publish: parent directory', async (t) => { await runFixture(t, 'build_publish_parent') }) test('build.publish: can be outside of build directory', async (t) => { await runFixture(t, 'build_publish_parent_build') }) test('build.publish: cannot be outside of root repository', async (t) => { await runFixture(t, 'build_publish_parent_root') }) test('build.functions: string', async (t) => { await runFixture(t, 'build_functions_string') }) test('build.functions: parent directory', async (t) => { await runFixture(t, 'build_functions_parent') }) test('build.edge_handlers: string', async (t) => { await runFixture(t, 'build_edge_handlers_string') }) test('build.edge_handlers: parent directory', async (t) => { await runFixture(t, 'build_edge_handlers_parent') }) test('build.base: string', async (t) => { await runFixture(t, 'build_base_string') }) test('build.base: parent directory', async (t) => { await runFixture(t, 'build_base_parent') }) test('build.command: string', async (t) => { await runFixture(t, 'build_command_string') }) test('build.command: array', async (t) => { await runFixture(t, 'build_command_array') }) test('build.command is validated even when not used due to merging', async (t) => { const defaultConfig = { build: { command: false } } await runFixture(t, 'build_command_merge', { flags: { defaultConfig } }) }) test('build.context: property', async (t) => { await runFixture(t, 'build_context_property', { flags: { context: 'development' } }) }) test('build.context: nested property', async (t) => { await runFixture(t, 'build_context_nested_property', { flags: { context: 'development' } }) }) test('build.context: object', async (t) => { await runFixture(t, 'build_context_object') }) test('build.context.CONTEXT: object', async (t) => { await runFixture(t, 'build_context_nested_object') }) test('build.context properties are validated like top-level ones', async (t) => { await runFixture(t, 'build_context_validation') }) test('build.context properties are validated like top-level ones even on different context', async (t) => { await runFixture(t, 'build_context_validation', { flags: { context: 'development' } }) }) test('Warns when using UI plugins together with context-specific plugin configuration', async (t) => { await runFixture(t, 'build_context_plugins_warn', { flags: { defaultConfig: { plugins: [{ package: 'netlify-plugin-test' }] } }, }) }) test('Does not warn when using context-free plugin configuration together with context-specific plugin configuration', async (t) => { await runFixture(t, 'build_context_plugins_nowarn_global') }) test('Does not warn when using no context-free plugin configuration together with context-specific plugin configuration', async (t) => { await runFixture(t, 'build_context_plugins_nowarn_none') }) test('Throws when using UI plugins together with context-specific plugin configuration in a different context', async (t) => { await runFixture(t, 'build_context_plugins_warn', { flags: { context: 'development', defaultConfig: { plugins: [{ package: 'netlify-plugin-test' }] } }, }) }) test('Does not throw when using UI plugins together with context-specific plugin configuration in a different context but with inputs', async (t) => { await runFixture(t, 'build_context_plugins_warn_inputs', { flags: { context: 'development', defaultConfig: { plugins: [{ package: 'netlify-plugin-test' }] } }, }) }) test('functions: object', async (t) => { await runFixture(t, 'function_config_invalid_root') }) test('functions block: object', async (t) => { await runFixture(t, 'function_config_invalid_function_block') }) test('functions.external_node_modules: array of strings', async (t) => { await runFixture(t, 'function_config_invalid_external_modules') }) test('functions.included_files: is array of strings', async (t) => { await runFixture(t, 'function_config_invalid_included_files') }) test('functions.ignored_node_modules: array of strings', async (t) => { await runFixture(t, 'function_config_invalid_ignored_modules') }) test('functions.node_bundler: one of supported bundlers', async (t) => { await runFixture(t, 'function_config_invalid_node_bundler') }) test('functions.directory: defined on the main functions object', async (t) => { await runFixture(t, 'function_config_invalid_nested_directory') }) test('Validates defaultConfig', async (t) => { const defaultConfig = { build: { command: false } } await runFixture(t, 'empty', { flags: { defaultConfig } }) }) test('Validates inlineConfig', async (t) => { const inlineConfig = { build: { command: false } } await runFixture(t, 'empty', { flags: { inlineConfig } }) }) <file_sep>'use strict' const avg = require('math-avg') module.exports = { onPreBuild() { console.log(avg([1, 2])) }, } <file_sep>[build] edge_handlers = "test" <file_sep>'use strict' const { env } = require('process') module.exports = { onPreBuild() { env.TEST_ONE = 'one' env.TEST_TWO = 'two' }, onBuild() { console.log(env.TEST_ONE, env.TEST_TWO, env.LANG) }, onPostBuild() { console.log(typeof env.TEST_ONE, env.TEST_TWO, env.LANG) }, } <file_sep>'use strict' module.exports = { onEnd() { console.log('onEnd one') }, } <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.build.command = 'node --version' }, onBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.functions['*'].external_node_modules = ['test'] }, onPostBuild({ netlifyConfig }) { console.log(netlifyConfig.build.command) console.log(netlifyConfig.functions['*'].external_node_modules) }, } <file_sep>'use strict' const { overrides } = require('@netlify/eslint-config-node') module.exports = { extends: ['plugin:fp/recommended', '@netlify/eslint-config-node'], rules: { strict: 2, // Fails with npm 7 monorepos due to the following bug: // https://github.com/benmosher/eslint-plugin-import/issues/1986 'import/no-extraneous-dependencies': 0, 'import/no-unresolved': 0, 'node/no-missing-require': 0, 'node/no-missing-import': 0, // eslint-plugin-ava needs to know where test files are located 'ava/no-ignored-test-files': [2, { files: ['tests/**/*.js', '!tests/{helpers,fixtures}/**/*.{js,json}'] }], 'ava/no-import-test-files': [2, { files: ['tests/**/*.js', '!tests/{helpers,fixtures}/**/*.{js,json}'] }], // Avoid state mutation except for some known state variables 'fp/no-mutating-methods': [ 2, { allowedObjects: [ 'error', 'errorA', 'req', 'request', 'res', 'response', 'state', 'runState', 'logs', 'logsArray', 'currentEnv', 't', ], }, ], 'fp/no-mutation': [ 2, { commonjs: true, exceptions: [ { object: 'error' }, { object: 'errorA' }, { object: 'res' }, { object: 'state' }, { object: 'runState' }, { object: 'logs' }, { object: 'logsArray' }, { object: 'currentEnv' }, { object: 'process', property: 'exitCode' }, ], }, ], }, overrides: [ ...overrides, { files: ['**/fixtures/**/*.js'], rules: { 'import/no-unresolved': 0, }, }, { files: ['**/fixtures/handlers_*/**/*.js', '**/fixtures/*es_module*/**/*.js'], parserOptions: { sourceType: 'module', }, rules: { 'node/no-unsupported-features/es-syntax': 0, }, }, // @todo As it stands, this rule is problematic with methods that get+send // many parameters, such as `runCommand` in `src/commands/run_command.js`. // We should discuss whether we want to keep this rule or discontinue it. { files: ['packages/build/**/*.js'], rules: { 'max-lines-per-function': 'off', }, }, ], } <file_sep>'use strict' module.exports = { onPreBuild({ utils }) { console.log(Object.keys(utils).sort().join(' ')) }, } <file_sep>[[plugins]] package = "./plugin" [[edge_handlers]] path = "/one" handler = "one" <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.build.command = false }, } <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { netlifyConfig.headers.push({ values: {} }) }, onBuild({ netlifyConfig: { headers } }) { console.log(headers) }, } <file_sep>'use strict' const { version: currentVersion, execPath } = require('process') const { satisfies, clean: cleanVersion } = require('semver') const { engines: { node: nodeVersionSupportedRange }, } = require('../../package.json') const { addErrorInfo } = require('../error/info') // Local plugins and `package.json`-installed plugins use user's preferred Node.js version if higher than our minimum // supported version (Node v10). Else default to the system Node version. // Local and programmatic builds use `@netlify/build` Node.js version, which is // usually the system's Node.js version. const addPluginsNodeVersion = function ({ pluginsOptions, nodePath, userNodeVersion }) { const currentNodeVersion = cleanVersion(currentVersion) return pluginsOptions.map((pluginOptions) => addPluginNodeVersion({ pluginOptions, currentNodeVersion, userNodeVersion, nodePath }), ) } const addPluginNodeVersion = function ({ pluginOptions, pluginOptions: { loadedFrom }, currentNodeVersion, userNodeVersion, nodePath, }) { if (loadedFrom === 'local' || loadedFrom === 'package.json') { return nonUIPluginNodeVersion({ pluginOptions, currentNodeVersion, userNodeVersion, nodePath }) } return { ...pluginOptions, nodePath: execPath, nodeVersion: currentNodeVersion } } const nonUIPluginNodeVersion = function ({ pluginOptions, currentNodeVersion, userNodeVersion, nodePath }) { // If the user Node version does not satisfy our supported engine range use our own system Node version if (!satisfies(userNodeVersion, nodeVersionSupportedRange)) { return { ...pluginOptions, nodePath: execPath, nodeVersion: currentNodeVersion } } return { ...pluginOptions, nodePath, nodeVersion: userNodeVersion } } // Ensure Node.js version is compatible with plugin's `engines.node` const checkNodeVersion = function ({ nodeVersion, packageName, pluginPackageJson: { engines: { node: pluginNodeVersionRange } = {} } = {}, }) { if (pluginNodeVersionRange && !satisfies(nodeVersion, pluginNodeVersionRange)) { throwUserError( `The Node.js version is ${nodeVersion} but the plugin "${packageName}" requires ${pluginNodeVersionRange}`, ) } } const throwUserError = function (message) { const error = new Error(message) addErrorInfo(error, { type: 'resolveConfig' }) throw error } module.exports = { addPluginsNodeVersion, checkNodeVersion } <file_sep>[build] edge_handlers = "/src" [context.production] edge_handlers = "/srcTest" <file_sep>'use strict' module.exports = { onPreBuild({ constants: { FUNCTIONS_SRC } }) { console.log(FUNCTIONS_SRC) }, } <file_sep>'use strict' const { relative } = require('path') const { cwd } = require('process') const test = require('ava') const { runFixture, FIXTURES_DIR } = require('../helpers/main') test('--cwd with no config', async (t) => { await runFixture(t, '', { flags: { cwd: `${FIXTURES_DIR}/empty`, defaultConfig: { build: { publish: '/' } } } }) }) test('--cwd with a relative path config', async (t) => { await runFixture(t, '', { flags: { cwd: relative(cwd(), FIXTURES_DIR), config: 'relative_cwd/netlify.toml' }, }) }) test('build.base current directory', async (t) => { await runFixture(t, 'build_base_cwd') }) test('build.base override', async (t) => { await runFixture(t, 'build_base_override', { flags: { cwd: `${FIXTURES_DIR}/build_base_override/subdir` } }) }) test('--repository-root', async (t) => { await runFixture(t, '', { flags: { repositoryRoot: `${FIXTURES_DIR}/empty` } }) }) test('--repository-root with cwd', async (t) => { await runFixture(t, '', { flags: { repositoryRoot: 'empty' }, cwd: FIXTURES_DIR, useBinary: true }) }) test('No .git', async (t) => { await runFixture(t, 'empty', { copyRoot: { cwd: true, git: false } }) }) test('--cwd non-existing', async (t) => { await runFixture(t, '', { flags: { cwd: '/invalid', repositoryRoot: `${FIXTURES_DIR}/empty` } }) }) test('--cwd points to a non-directory file', async (t) => { await runFixture(t, '', { flags: { cwd: `${FIXTURES_DIR}/empty/netlify.toml`, repositoryRoot: `${FIXTURES_DIR}/empty` }, }) }) test('--repositoryRoot non-existing', async (t) => { await runFixture(t, '', { flags: { repositoryRoot: '/invalid' } }) }) test('--repositoryRoot points to a non-directory file', async (t) => { await runFixture(t, '', { flags: { repositoryRoot: `${FIXTURES_DIR}/empty/netlify.toml` } }) }) test('should detect base directory using package.json in sub dir', async (t) => { await runFixture(t, 'build_base_package_json', { flags: { cwd: `${FIXTURES_DIR}/build_base_package_json/subdir` } }) }) <file_sep>'use strict' const mod1 = require('test') const mod2 = require('test_2') module.exports = [mod1('netlify'), mod2('netlify')] <file_sep>'use strict' const { env } = require('process') module.exports = { onPreBuild({ netlifyConfig: { build: { environment }, }, }) { // eslint-disable-next-line no-param-reassign environment.TEST_ONE = 'one_environment' env.TEST_ONE = 'one_env' // eslint-disable-next-line no-param-reassign environment.TEST_TWO = 'two' env.LANGUAGE = '' }, onBuild() { console.log(env.TEST_ONE, env.TEST_TWO, env.LANGUAGE) }, } <file_sep>'use strict' const { env } = require('process') console.log(env.TEST_ONE, env.TEST_TWO, env.LANG, env.LANGUAGE) <file_sep># Integration tests ## Steps Each integration test has the following steps: 1. Select a fixture directory from `./tests/**/fixtures/` 2. Run the `@netlify/build` main function on that fixture directory 3. Snapshot the output Everything below also applies to `@netlify/config` which follows the same pattern but using its own main function. ## Snapshot testing Snapshot testing is a recent alternative to assertion testing. We use [Ava snapshots](https://github.com/avajs/ava/blob/main/docs/04-snapshot-testing.md). The idea is to: - save a command's output the first time the test is run - compare the commmand's output with the previous snapshot the next time the test is run The test passes if the `@netlify/build` output for a specific fixture directory did not change. If it did change, the diff will be printed on the console. You should check the diff and figure out if the output change was introduced by: - a bug. In that case the bug should be fixed. - an intentional change in the command's logic/output. In that case you should run `ava -u` to update the test snapshots. All tests snapshots will be updated, so make sure you do not update other test snapshots accidentally. When a PR changes test snaphots, the diff shows how the `@netlify/build` output has changed for specific tests. This allows PR reviewers to quickly see how that PR is affecting the output shown to the user. ## Goal Snapshot testing has some downsides: - It is a different approach from assertion testing and can have a steep learning curve. - Any changes to the command output require updating test snapshots. In some cases, this can be lots of snapshots. - Testing internal details can get tricky if it does not directly impact the command output. - The command output might be non-deterministic and require [normalization](#output-normalization). On the other hand, it has the following upsides: - It operates at a high/integration level, giving strong guarantees that what the user will see (the command output) and experience in production matches what was tested. - It is harder to miss a bug due to issues in the test logic itself, since the test logic is limited to the test fixtures directory. - It only tests user-facing behavior not implementation details, requiring fewer code updates when the source code changes. - When the tests do need to be updated, they can be done with a single command (`ava -u`) instead of manually updating each test assertion. - The fixture directories can be used for debugging/running any features of the project (see the [debug mode](#debug-mode)) - Tests can be understood without knowing the implementation details - Code reviewers can see the user-facing changes introduced by a PR without knowing the implementation details, by simply looking at the test snapshots. ## Syntax Every test follows this template: <!-- eslint-disable-next-line ava/no-ignored-test-files --> ```js const test = require('ava') const { runFixture } = require('../../helpers/main') test('test title', async (t) => { await runFixture(t, 'fixture_name') }) ``` This calls under the hood: ```js const netlifyBuild = require('@netlify/build') const runTest = async function () { const output = await netlifyBuild({ repositoryRoot: './fixtures/fixture_name' }) return output } ``` Then snapshots the output. ## Options An additional object can be passed to `runFixture()` with the following options: - `flags` `{object}`: any flags/options passed to the main command - `env` `{object}`: environment variables passed to child processes. To set environment variables in the parent process too, spawn a new process with the `useBinary: true` option. - `useBinary` `{boolean}`: use the CLI entry point instead of the Node.js main function - `repositoryRoot` `{string}`: fixture directory. Defaults to `./fixtures/fixture_name`. - `copyRoot` `{object}`: when defined, copy the fixture directory to a temporary directory This is useful when no parent directory should have a `.git` or `package.json`. - `copyRoot.git` `{boolean}`: whether the copied directory should have a `.git`. Default: `true` - `copyRoot.branch` `{string}`: create a git branch after copy Most tests do not need to specify any of the options above. ## Running tests To run all tests: ``` npx ava ``` To run the tests for a specific file: ``` npx ava /path/to/tests.js ``` To run a single test, use the command above combined with [`test.only()`](https://github.com/avajs/ava/blob/main/docs/01-writing-tests.md#running-specific-tests). Add the `-u` flag to update snapshots. ## Debug mode A debug mode is available when: - debugging why a specific test is failing - writing new tests When run in debug mode: - the command output is printed - new tests do not create test snapshots - other tests are not compared with their existing test snapshots To activate it, set the `PRINT=1` environment variable: ``` PRINT=1 npx ava /path/to/tests.js ``` Using [`test.only()`](https://github.com/avajs/ava/blob/main/docs/01-writing-tests.md#running-specific-tests) to target a specific test is recommended. ## Output normalization Sometimes the `@netlify/build` output contains non-deterministic information such as: - timestamps and time durations - package versions - machine-specific information such as file paths (including in stack traces) - OS-specific information (e.g. file paths use backslashes on Windows) - output different on older Node.js versions Those would make the test snapshot non-reproducible. To fix this, the output is normalized by `./helpers/normalize.js`. This basically performs a series of regular expressions replacements. If you want to remove the normalization during debugging, use the `normalize` option: ```js test('test title', async (t) => { await runFixture(t, 'fixture_name', { normalize: false }) }) ``` `normalize` is `false` when `PRINT=1` is used, `true` otherwise. <file_sep>'use strict' const { copyFile } = require('fs') const { promisify } = require('util') const pCopyFile = promisify(copyFile) const fixtureRedirectsPath = `${__dirname}/_redirects_file` const redirectsPath = `${__dirname}/_redirects` module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.redirects = [...netlifyConfig.redirects, { from: '/one', to: '/two' }] }, async onBuild() { await pCopyFile(fixtureRedirectsPath, redirectsPath) }, onSuccess({ netlifyConfig }) { console.log(netlifyConfig.redirects) }, } <file_sep># Snapshot report for `packages/build/tests/error/tests.js` The actual snapshot is saved in `tests.js.snap`. Generated by [AVA](https://avajs.dev). ## build.failBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_build␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_build␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## build.failBuild() error option > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_build_error_option␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_build_error_option␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_build_error_option/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build_error_option␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ innerTest␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build_error_option␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## build.failBuild() inside a callback > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_build_callback␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_build_callback␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_build_callback/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build_callback␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build_callback␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## build.failBuild() is not available within post-deploy events > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_build_post_deploy␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_build_post_deploy␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_build_post_deploy/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build_post_deploy␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onEnd command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Plugin error: since "onEnd" happens after deploy, the build has already succeeded and cannot fail anymore. This plugin should either:␊ - use utils.build.failPlugin() instead of utils.build.failBuild() to clarify that the plugin failed, but not the build.␊ - use "onPostBuild" instead of "onEnd" if the plugin failure should make the build fail too. Please note that "onPostBuild" (unlike "onEnd") happens before deploy.␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onEnd" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_build_post_deploy␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.failPlugin() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_plugin␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin_two@1.0.0 from netlify.toml␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ onPreBuild␊ ␊ (./plugin_two onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./plugin_two onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.failPlugin() inside a callback > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_plugin_callback␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_plugin_callback␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_plugin_callback/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_plugin_callback␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_plugin_callback␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.failPlugin() error option > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/fail_plugin_error_option␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/fail_plugin_error_option␊ ␊ > Config file␊ packages/build/tests/error/fixtures/fail_plugin_error_option/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_plugin_error_option␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin_two@1.0.0 from netlify.toml␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ onPreBuild␊ ␊ (./plugin_two onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ innerTest␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/fail_plugin_error_option␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./plugin_two onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.cancelBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/cancel␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ` ## build.cancelBuild() inside a callback > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/cancel_callback␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel_callback␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel_callback/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_callback␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ` ## build.cancelBuild() error option > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/cancel_error_option␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel_error_option␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel_error_option/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_error_option␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ innerTest␊ ` ## build.cancelBuild() API call > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ deployId: test␊ repositoryRoot: packages/build/tests/error/fixtures/cancel␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: test␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding authorization connection content-length host user-agent', method: 'POST', url: '/api/v1/deploys/test/cancel', }, ] ## build.cancelBuild() API call no DEPLOY_ID > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/cancel␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: test␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ` ## build.cancelBuild() API call no token > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ deployId: test␊ repositoryRoot: packages/build/tests/error/fixtures/cancel␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: test␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ` ## build.cancelBuild() API call failure > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ deployId: test␊ repositoryRoot: packages/build/tests/error/fixtures/cancel␊ testOpts:␊ env: false␊ host: ...␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ API error on "cancelSiteDeploy" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ request to https://.../api/v1.0.0/deploys/test/cancel failed, reason: getaddrinfo ENOTFOUND ...␊ ␊ Error location␊ While calling the Netlify API endpoint 'cancelSiteDeploy' with:␊ {␊ "deploy_id": "test"␊ }␊ ␊ Error properties␊ {␊ type: 'system',␊ errno: 'ENOTFOUND',␊ code: 'ENOTFOUND',␊ name: 'FetchError',␊ url: 'https://.../api/v1.0.0/deploys/test/cancel',␊ data: {␊ method: 'POST',␊ headers: {␊ 'User-agent': 'netlify/js-client',␊ accept: 'application/json',␊ Authorization: 'Bearer test'␊ }␊ }␊ }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## build.cancelBuild() is not available within post-deploy events > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/cancel_post_deploy␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel_post_deploy␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel_post_deploy/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_post_deploy␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onEnd command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Plugin error: since "onEnd" happens after deploy, the build has already succeeded and cannot fail anymore. This plugin should either:␊ - use utils.build.failPlugin() instead of utils.build.cancelBuild() to clarify that the plugin failed, but not the build.␊ - use "onPostBuild" instead of "onEnd" if the plugin failure should make the build fail too. Please note that "onPostBuild" (unlike "onEnd") happens before deploy.␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onEnd" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_post_deploy␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## exception > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/exception␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/exception␊ ␊ > Config file␊ packages/build/tests/error/fixtures/exception/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## exception with static properties > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/exception_props␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/exception_props␊ ␊ > Config file␊ packages/build/tests/error/fixtures/exception_props/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_props␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Error properties␊ { test: true, type: 'test' }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_props␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## exception with circular references > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/exception_circular␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/exception_circular␊ ␊ > Config file␊ packages/build/tests/error/fixtures/exception_circular/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_circular␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Error properties␊ { test: true, prop: null, objectProp: { self: '[Circular]' } }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_circular␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## exception that are strings > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/exception_string␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/exception_string␊ ␊ > Config file␊ packages/build/tests/error/fixtures/exception_string/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_string␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_string␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## exception that are arrays > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/exception_array␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/exception_array␊ ␊ > Config file␊ packages/build/tests/error/fixtures/exception_array/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_array␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Error properties␊ { errors: [ {} ] }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/exception_array␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Do not log secret values on build errors > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/log_secret␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/log_secret␊ ␊ > Config file␊ packages/build/tests/error/fixtures/log_secret/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ environment:␊ - SECRET␊ publish: packages/build/tests/error/fixtures/log_secret␊ publishOrigin: default␊ plugins:␊ - inputs:␊ notSecret: true␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ environment:␊ - SECRET␊ publish: packages/build/tests/error/fixtures/log_secret␊ publishOrigin: default␊ plugins:␊ - inputs:␊ notSecret: true␊ origin: config␊ package: ./plugin.js␊ ␊ node: bad option: --invalid` ## Report build.command failure > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/command␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "buildCommand",␊ "errorMessage": "Command failed with exit code 9: node --invalid",␊ "context": "node --invalid",␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "buildCommand": "node --invalid",␊ "buildCommandOrigin": "config",␊ "configPath": "packages/build/tests/error/fixtures/command/netlify.toml"␊ },␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid"␊ }␊ }␊ ␊ node: bad option: --invalid` ## Report configuration user error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/config␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ When resolving config file packages/build/tests/error/fixtures/config/netlify.toml:␊ Configuration property build must be a plain object.␊ ␊ Invalid syntax␊ ␊ build = false␊ ␊ Valid syntax␊ ␊ [build]␊ command = "npm run build"␊ ␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "resolveConfig",␊ "errorMessage": "When resolving config file packages/build/tests/error/fixtures/config/netlify.toml:/nConfiguration property build must be a plain object./n/nInvalid syntax/n/n build = false/n/nValid syntax/n/n [build]/n command = /"npm run build/"",␊ "context": "Configuration error",␊ "groupingHash": "Configuration error/nWhen resolving config file /external/path property build must be a plain object./n/nInvalid syntax/n/n build = false/n/nValid syntax/n/n [build]/n command = /"npm run build/"",␊ "severity": "info",␊ "unhandled": false,␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "Configuration error/nWhen resolving config file /external/path property build must be a plain object./n/nInvalid syntax/n/n build = false/n/nValid syntax/n/n [build]/n command = /"npm run build/""␊ }␊ }` ## Report plugin input error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_input␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_input␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_input/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_input␊ publishOrigin: default␊ plugins:␊ - inputs:␊ test: true␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" invalid input "test" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Plugin "./plugin.js" does not accept any inputs but you specified: "test"␊ Check your plugin configuration to be sure that:␊ - the input name is spelled correctly␊ - the input is included in the plugin's available configuration options␊ - the plugin's input requirements have not changed␊ ␊ Plugin inputs␊ test: true␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin.js" from netlify.toml␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_input␊ publishOrigin: default␊ plugins:␊ - inputs:␊ test: true␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "pluginInput",␊ "errorMessage": "Plugin /"./plugin.js/" does not accept any inputs but you specified: /"test/"/external/path your plugin configuration to be sure that:/n - the input name is spelled correctly/n - the input is included in the plugin's available configuration options/n - the plugin's input requirements have not changed/n/nPlugin inputs/ntest: true",␊ "context": "Plugin /"./plugin.js/" invalid input /"test/"",␊ "groupingHash": "Plugin /"./plugin.js/" invalid input /"test/"/external/path /"/external/path" does not accept any inputs but you specified: /external/path your plugin configuration to be sure that:/n - the input name is spelled correctly/n - the input is included in the plugin's available configuration options/n - the plugin's input requirements have not changed/n",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "load",␊ "packageName": "./plugin.js",␊ "input": "test",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" invalid input /"test/"/external/path /"/external/path" does not accept any inputs but you specified: /external/path your plugin configuration to be sure that:/n - the input name is spelled correctly/n - the input is included in the plugin's available configuration options/n - the plugin's input requirements have not changed/n"␊ }␊ }` ## Report plugin validation error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_validation␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_validation␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_validation/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_validation␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Invalid event 'invalid'.␊ Please use a valid event name. One of:␊ - onPreBuild␊ - onBuild␊ - onPostBuild␊ - onSuccess␊ - onError␊ - onEnd␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_validation␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "pluginValidation",␊ "errorMessage": "Invalid event 'invalid'./nPlease use a valid event name. One of:/n - onPreBuild/n - onBuild/n - onPostBuild/n - onSuccess/n - onError/n - onEnd",␊ "context": "Plugin /"./plugin.js/" internal error",␊ "groupingHash": "Plugin /"./plugin.js/" internal error/nInvalid event 'invalid'./nPlease use a valid event name. One of:/n - onPreBuild/n - onBuild/n - onPostBuild/n - onSuccess/n - onError/n - onEnd",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "load",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" internal error/nInvalid event 'invalid'./nPlease use a valid event name. One of:/n - onPreBuild/n - onBuild/n - onPostBuild/n - onSuccess/n - onError/n - onEnd"␊ }␊ }` ## Report plugin internal error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_internal␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_internal␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_internal/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_internal␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_internal␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "pluginInternal",␊ "errorMessage": "test",␊ "context": "Plugin /"./plugin.js/" internal error",␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest"␊ }␊ }` ## Report utils.build.failBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/monitor_fail_build␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/monitor_fail_build␊ ␊ > Config file␊ packages/build/tests/error/fixtures/monitor_fail_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/monitor_fail_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/monitor_fail_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "failBuild",␊ "errorMessage": "test",␊ "context": "Plugin /"./plugin.js/" failed",␊ "groupingHash": "Plugin /"./plugin.js/" failed/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" failed/ntest"␊ }␊ }` ## Report utils.build.failPlugin() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/monitor_fail_plugin␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/monitor_fail_plugin␊ ␊ > Config file␊ packages/build/tests/error/fixtures/monitor_fail_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/monitor_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/monitor_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "failPlugin",␊ "errorMessage": "test",␊ "context": "Plugin /"./plugin.js/" failed",␊ "groupingHash": "Plugin /"./plugin.js/" failed/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" failed/ntest"␊ }␊ }␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Report utils.build.cancelBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/cancel_build␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel_build␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "cancelBuild",␊ "errorMessage": "test",␊ "context": "Build canceled by ./plugin.js",␊ "groupingHash": "Build canceled by ./plugin.js/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Build canceled by ./plugin.js/ntest"␊ }␊ }` ## Report IPC error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/ipc␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/ipc␊ ␊ > Config file␊ packages/build/tests/error/fixtures/ipc/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/ipc␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Plugin exited with exit code 0 and signal null.␊ The plugin might have exited due to a bug terminating the process, such as an infinite loop.␊ The plugin might also have explicitly terminated the process, for example with process.exit().␊ Plugin methods should instead:␊ - on success: return␊ - on failure: call utils.build.failPlugin() or utils.build.failBuild()␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/ipc␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "ipc",␊ "errorMessage": "Plugin exited with exit code 0 and signal null./nThe plugin might have exited due to a bug terminating the process, such as an infinite loop./nThe plugin might also have explicitly terminated the process, for example with process.exit()./nPlugin methods should instead:/n - on success: return/n - on failure: call utils.build.failPlugin() or utils.build.failBuild()",␊ "context": "Plugin /"./plugin.js/" internal error",␊ "groupingHash": "Plugin /"./plugin.js/" internal error/nPlugin exited with exit code 0 and signal null./nThe plugin might have exited due to a bug terminating the process, such as an infinite loop./nThe plugin might also have explicitly terminated the process, for example with process.exit()./nPlugin methods should instead:/n - on success: return/n - on failure: call utils.build.failPlugin() or utils.build.failBuild()",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" internal error/nPlugin exited with exit code 0 and signal null./nThe plugin might have exited due to a bug terminating the process, such as an infinite loop./nThe plugin might also have explicitly terminated the process, for example with process.exit()./nPlugin methods should instead:/n - on success: return/n - on failure: call utils.build.failPlugin() or utils.build.failBuild()"␊ }␊ }` ## Report API error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ deployId: test␊ repositoryRoot: packages/build/tests/error/fixtures/cancel_build␊ testOpts:␊ env: false␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/cancel_build␊ ␊ > Config file␊ packages/build/tests/error/fixtures/cancel_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ API error on "cancelSiteDeploy" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Unauthorized␊ ␊ Error location␊ While calling the Netlify API endpoint 'cancelSiteDeploy' with:␊ {␊ "deploy_id": "test"␊ }␊ ␊ Error properties␊ { name: 'TextHTTPError', status: 401, data: '' }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/cancel_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "api",␊ "errorMessage": "Unauthorized",␊ "context": "API error on /"cancelSiteDeploy/"",␊ "groupingHash": "API error on /"cancelSiteDeploy/"/external/path",␊ "severity": "error",␊ "unhandled": true,␊ "location": {␊ "endpoint": "cancelSiteDeploy",␊ "parameters": {␊ "deploy_id": "test"␊ }␊ },␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "API error on /"cancelSiteDeploy/"/external/path"␊ }␊ }` ## Report dependencies error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/dependencies␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/dependencies␊ ␊ > Config file␊ packages/build/tests/error/fixtures/dependencies/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/dependencies␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/error/fixtures/dependencies/functions␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from functions directory:␊ - test.js␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Dependencies installation error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ A Netlify Function failed to require one of its dependencies.␊ Please make sure it is present in the site's top-level "package.json".␊ ␊ In file "packages/build/tests/error/fixtures/dependencies/functions/test.js"␊ Cannot find module 'does-not-exist'␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/dependencies␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/error/fixtures/dependencies/functions␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "dependencies",␊ "errorMessage": "A Netlify Function failed to require one of its dependencies./nPlease make sure it is present in the site's top-level /"package.json/"./n/nIn file /"packages/build/tests/error/fixtures/dependencies/functions/test.js"/external/path find module 'does-not-exist'/external/path stack:/n- /node_module/path /node_module/path /node_module/path packages/build/src/plugins_core/functions/index.js/n- packages/build/src/commands/get.js/n- packages/build/src/core/main.js/n- packages/build/tests/helpers/main.js/n- packages/build/tests/error/tests.js/n- /node_module/path",␊ "context": "Dependencies installation error",␊ "groupingHash": "Dependencies installation error/n",␊ "severity": "info",␊ "unhandled": false,␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "Dependencies installation error/n"␊ }␊ }` ## Report buildbot mode as releaseStage > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ mode: buildbot␊ repositoryRoot: packages/build/tests/error/fixtures/command␊ testOpts:␊ errorMonitor: 'true'␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "buildCommand",␊ "errorMessage": "Command failed with exit code 9: node --invalid",␊ "context": "node --invalid",␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "buildCommand": "node --invalid",␊ "buildCommandOrigin": "config",␊ "configPath": "packages/build/tests/error/fixtures/command/netlify.toml"␊ },␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid"␊ }␊ }␊ ␊ node: bad option: --invalid` ## Report CLI mode as releaseStage > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ mode: cli␊ repositoryRoot: packages/build/tests/error/fixtures/command␊ testOpts:␊ errorMonitor: 'true'␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "buildCommand",␊ "errorMessage": "Command failed with exit code 9: node --invalid",␊ "context": "node --invalid",␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "buildCommand": "node --invalid",␊ "buildCommandOrigin": "config",␊ "configPath": "packages/build/tests/error/fixtures/command/netlify.toml"␊ },␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid"␊ }␊ }␊ ␊ node: bad option: --invalid` ## Report programmatic mode as releaseStage > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ mode: require␊ repositoryRoot: packages/build/tests/error/fixtures/command␊ testOpts:␊ errorMonitor: 'true'␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "buildCommand",␊ "errorMessage": "Command failed with exit code 9: node --invalid",␊ "context": "node --invalid",␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "buildCommand": "node --invalid",␊ "buildCommandOrigin": "config",␊ "configPath": "packages/build/tests/error/fixtures/command/netlify.toml"␊ },␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid"␊ }␊ }␊ ␊ node: bad option: --invalid` ## Report BUILD_ID > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/command␊ testOpts:␊ errorMonitor: 'true'␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "buildCommand",␊ "errorMessage": "Command failed with exit code 9: node --invalid",␊ "context": "node --invalid",␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "buildCommand": "node --invalid",␊ "buildCommandOrigin": "config",␊ "configPath": "packages/build/tests/error/fixtures/command/netlify.toml"␊ },␊ "pluginPackageJson": false,␊ "BUILD_ID": "test",␊ "other": {␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid"␊ }␊ }␊ ␊ node: bad option: --invalid` ## Report plugin homepage > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_homepage␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_homepage␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_homepage/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_homepage␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/test/test.git␊ Report issues: https://github.com/test/test/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_homepage␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "pluginInternal",␊ "errorMessage": "test",␊ "context": "Plugin /"./plugin.js/" internal error",␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/test/test.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest"␊ }␊ }` ## Report plugin homepage without a repository > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_homepage_no_repo␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_homepage_no_repo␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_homepage_no_repo/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_homepage_no_repo␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Report issues: https://test.com␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_homepage_no_repo␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "pluginInternal",␊ "errorMessage": "test",␊ "context": "Plugin /"./plugin.js/" internal error",␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "config"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "https://test.com",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest"␊ }␊ }` ## Report plugin origin > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_origin␊ testOpts:␊ errorMonitor: true␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_origin␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_origin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_origin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from Netlify app␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from Netlify app␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_origin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: ./plugin.js␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "pluginInternal",␊ "errorMessage": "test",␊ "context": "Plugin /"./plugin.js/" internal error",␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "event": "onPreBuild",␊ "packageName": "./plugin.js",␊ "loadedFrom": "local",␊ "origin": "ui"␊ },␊ "packageName": "./plugin.js",␊ "pluginPackageJson": true,␊ "homepage": "git+https://github.com/netlify/build.git",␊ "other": {␊ "groupingHash": "Plugin /"./plugin.js/" internal error/ntest"␊ }␊ }` ## Report build logs URLs > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/command␊ testOpts:␊ errorMonitor: 'true'␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command␊ publishOrigin: default␊ ␊ Error monitoring payload:␊ {␊ "errorClass": "buildCommand",␊ "errorMessage": "Command failed with exit code 9: node --invalid",␊ "context": "node --invalid",␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid",␊ "severity": "info",␊ "unhandled": false,␊ "location": {␊ "buildLogs": "https://app.netlify.com/sites/testSiteName/deploys/testDeployId",␊ "buildCommand": "node --invalid",␊ "buildCommandOrigin": "config",␊ "configPath": "packages/build/tests/error/fixtures/command/netlify.toml"␊ },␊ "pluginPackageJson": false,␊ "other": {␊ "groupingHash": "node --invalid/nCommand failed with exit code 0: node --invalid"␊ }␊ }␊ ␊ node: bad option: --invalid` ## Top-level errors > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/top␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/top␊ ␊ > Config file␊ packages/build/tests/error/fixtures/top/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/top␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Could not import plugin:␊ test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/top␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Top function errors local > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/function␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/function␊ ␊ > Config file␊ packages/build/tests/error/fixtures/function/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/function␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Could not load plugin:␊ test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/function␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Node module all fields > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/full␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/full␊ ␊ > Config file␊ packages/build/tests/error/fixtures/full/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/full␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - netlify-plugin-test@1.0.0 from netlify.toml and package.json␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-test ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "netlify-plugin-test" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: netlify-plugin-test␊ Version: 1.0.0␊ Repository: git+https://github.com/test/test.git␊ npm link: https://www.npmjs.com/package/netlify-plugin-test␊ Report issues: https://test.com/test␊ ␊ Error location␊ In "onPreBuild" event in "netlify-plugin-test" from netlify.toml and package.json␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/full␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test` ## Node module partial fields > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/partial␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/partial␊ ␊ > Config file␊ packages/build/tests/error/fixtures/partial/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/partial␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - netlify-plugin-test from netlify.toml and package.json␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-test ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "netlify-plugin-test" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: netlify-plugin-test␊ ␊ Error location␊ In "onPreBuild" event in "netlify-plugin-test" from netlify.toml and package.json␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/partial␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test` ## No repository root > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## Process warnings > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/warning␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/warning␊ ␊ > Config file␊ packages/build/tests/error/fixtures/warning/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/warning␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ onPreBuild␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)␊ ␊ ‼ warning (Warning) test␊ STACK TRACE␊ STACK TRACE` ## Uncaught exception > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/uncaught␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/uncaught␊ ␊ > Config file␊ packages/build/tests/error/fixtures/uncaught/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/uncaught␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ UncaughtException: an exception was thrown but not caught: Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/uncaught␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Unhandled promises > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/unhandled_promise␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/unhandled_promise␊ ␊ > Config file␊ packages/build/tests/error/fixtures/unhandled_promise/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/unhandled_promise␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ onPreBuild␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ UnhandledRejection: a promise was rejected but not handled: Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/unhandled_promise␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Exits in plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_exit␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_exit␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_exit/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_exit␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Plugin exited with exit code 1 and signal null.␊ The plugin might have exited due to a bug terminating the process, such as an infinite loop.␊ The plugin might also have explicitly terminated the process, for example with process.exit().␊ Plugin methods should instead:␊ - on success: return␊ - on failure: call utils.build.failPlugin() or utils.build.failBuild()␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_exit␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Plugin errors can have a toJSON() method > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_error_to_json␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_error_to_json␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_error_to_json/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_error_to_json␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: message␊ test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_error_to_json␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Print stack trace of plugin errors > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_stack␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_stack␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_stack/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_stack␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_stack␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Print stack trace of plugin errors during load > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/plugin_load␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/plugin_load␊ ␊ > Config file␊ packages/build/tests/error/fixtures/plugin_load/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_load␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Could not import plugin:␊ test␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/plugin_load␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Print stack trace of build.command errors > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/command_stack␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command_stack␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command_stack/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command_stack␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command_stack␊ publishOrigin: default␊ ␊ node: bad option: --invalid` ## Print stack trace of build.command errors with stack traces > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/command_full_stack␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/command_full_stack␊ ␊ > Config file␊ packages/build/tests/error/fixtures/command_full_stack/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command_full_stack␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node command.js␊ Error: test␊ STACK TRACE␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 2: node command.js␊ ␊ Error location␊ In build.command from netlify.toml:␊ node command.js␊ ␊ Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/error/fixtures/command_full_stack␊ publishOrigin: default` ## Print stack trace of Build command UI settings > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/error/fixtures/none␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/none␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: ui␊ publish: packages/build/tests/error/fixtures/none␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Build command from Netlify app ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In Build command from Netlify app:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: ui␊ publish: packages/build/tests/error/fixtures/none␊ publishOrigin: default␊ ␊ node: bad option: --invalid` ## Print stack trace of validation errors > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ config: /external/path␊ debug: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ When resolving config file /external/path␊ Configuration file does not exist␊ ` ## Redact API token on errors > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ deployId: test␊ mode: buildbot␊ repositoryRoot: packages/build/tests/error/fixtures/api_token_redact␊ testOpts:␊ host: ...␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/error/fixtures/api_token_redact␊ ␊ > Config file␊ packages/build/tests/error/fixtures/api_token_redact/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/api_token_redact␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin.js onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ API error on "createPluginRun" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ request to https://.../api/v1.0.0/deploys/test/plugin_runs failed, reason: getaddrinfo ENOTFOUND ...␊ ␊ Error location␊ While calling the Netlify API endpoint 'createPluginRun' with:␊ {␊ "deploy_id": "test",␊ "body": {␊ "package": "./plugin.js",␊ "version": "1.0.0",␊ "state": "success",␊ "reporting_event": "onPreBuild"␊ }␊ }␊ ␊ Error properties␊ {␊ type: 'system',␊ errno: 'ENOTFOUND',␊ code: 'ENOTFOUND',␊ name: 'FetchError',␊ url: 'https://.../api/v1.0.0/deploys/test/plugin_runs',␊ data: {␊ method: 'POST',␊ headers: {␊ 'Content-Type': 'application/json',␊ 'User-agent': 'netlify/js-client',␊ accept: 'application/json',␊ Authorization: 'Bearer HEX'␊ },␊ body: '{"package":"./plugin.js","version":"1.0.0","state":"success","reporting_event":"onPreBuild"}'␊ }␊ }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/error/fixtures/api_token_redact␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` <file_sep>'use strict' const { unlink, writeFile } = require('fs') const { relative } = require('path') const { cwd } = require('process') const { promisify } = require('util') const test = require('ava') const { tmpName } = require('tmp-promise') const resolveConfig = require('../..') const { runFixture, FIXTURES_DIR } = require('../helpers/main') const pWriteFile = promisify(writeFile) const pUnlink = promisify(unlink) test('Empty configuration', async (t) => { await runFixture(t, 'empty') }) test('No --config but none found', async (t) => { await runFixture(t, 'none', { copyRoot: {} }) }) test('--config with an absolute path', async (t) => { await runFixture(t, '', { flags: { config: `${FIXTURES_DIR}/empty/netlify.toml` } }) }) test('--config with a relative path', async (t) => { await runFixture(t, '', { flags: { config: `${relative(cwd(), FIXTURES_DIR)}/empty/netlify.toml` } }) }) test('--config with an invalid relative path', async (t) => { await runFixture(t, '', { flags: { config: '/invalid' } }) }) test('--defaultConfig CLI flag', async (t) => { const defaultConfig = JSON.stringify({ build: { publish: 'publish' } }) await runFixture(t, 'default_merge', { flags: { defaultConfig }, useBinary: true }) }) test('--defaultConfig merge', async (t) => { const defaultConfig = { build: { publish: 'publish' } } await runFixture(t, 'default_merge', { flags: { defaultConfig } }) }) test('--defaultConfig priority', async (t) => { const defaultConfig = { build: { command: 'echo commandDefault' } } await runFixture(t, 'default_priority', { flags: { defaultConfig } }) }) test('--defaultConfig merges UI plugins with config plugins', async (t) => { const defaultConfig = { plugins: [{ package: 'one', inputs: { test: false, testThree: true } }] } await runFixture(t, 'plugins_merge', { flags: { defaultConfig } }) }) test('--defaultConfig can specify pinned versions', async (t) => { await runFixture(t, 'empty', { flags: { defaultConfig: { plugins: [{ package: 'one', pinned_version: '1' }] } } }) }) test('--defaultConfig ignores pinned versions that are empty strings', async (t) => { await runFixture(t, 'empty', { flags: { defaultConfig: { plugins: [{ package: 'one', pinned_version: '' }] } } }) }) test('--inlineConfig CLI flag', async (t) => { const inlineConfig = JSON.stringify({ build: { publish: 'publish' } }) await runFixture(t, 'default_merge', { flags: { inlineConfig }, useBinary: true }) }) test('--inlineConfig is merged', async (t) => { const inlineConfig = { build: { publish: 'publish' } } await runFixture(t, 'default_merge', { flags: { inlineConfig } }) }) test('--inlineConfig is merged with priority', async (t) => { const inlineConfig = { build: { command: 'echo commandInline' } } await runFixture(t, 'default_priority', { flags: { inlineConfig } }) }) test('--inlineConfig falsy values are ignored', async (t) => { const inlineConfig = { build: { command: undefined, publish: undefined } } await runFixture(t, 'default_priority', { flags: { inlineConfig } }) }) test('--inlineConfig can override the "base"', async (t) => { const defaultConfig = { build: { base: 'defaultBase' } } const inlineConfig = { build: { base: 'base' } } await runFixture(t, 'merge_base', { flags: { defaultConfig, inlineConfig } }) }) test('--inlineConfig cannot use contexts', async (t) => { const inlineConfig = { context: { testContext: { build: { command: 'echo commandPriority' } } } } await runFixture(t, 'default_priority', { flags: { context: 'testContext', inlineConfig } }) }) test('--inlineConfig cannot be overridden by contexts', async (t) => { const defaultConfig = { context: { testContext: { build: { command: 'echo commandDefault' } } } } const inlineConfig = { build: { command: 'echo commandPriority' } } await runFixture(t, 'default_priority', { flags: { context: 'testContext', defaultConfig, inlineConfig } }) }) test('--configMutations can override properties', async (t) => { await runFixture(t, 'default_priority', { flags: { configMutations: [{ keys: ['build', 'command'], value: 'testMutation', event: 'onPreBuild' }] }, }) }) test('--configMutations cannot be overridden by contexts', async (t) => { const defaultConfig = { context: { testContext: { build: { command: 'echo commandDefault' } } } } await runFixture(t, 'default_priority', { flags: { defaultConfig, configMutations: [{ keys: ['build', 'command'], value: 'testMutation', event: 'onPreBuild' }], }, }) }) test('--configMutations events are validated', async (t) => { await runFixture(t, 'default_priority', { flags: { configMutations: [{ keys: ['build', 'command'], value: 'testMutation', event: 'onBuild' }] }, }) }) test('--configMutations cannot be applied on readonly properties', async (t) => { await runFixture(t, 'empty', { flags: { configMutations: [{ keys: ['build', 'base'], value: 'testMutation', event: 'onPreBuild' }] }, }) }) test('--configMutations can mutate functions top-level properties', async (t) => { await runFixture(t, 'empty', { flags: { configMutations: [{ keys: ['functions', 'directory'], value: 'testMutation', event: 'onPreBuild' }] }, }) }) test('--cachedConfig CLI flags', async (t) => { const { returnValue } = await runFixture(t, 'cached_config', { snapshot: false }) await runFixture(t, 'cached_config', { flags: { cachedConfig: returnValue }, useBinary: true }) }) test('--cachedConfigPath CLI flag', async (t) => { const cachedConfigPath = await tmpName() try { await runFixture(t, 'cached_config', { flags: { output: cachedConfigPath }, snapshot: false, useBinary: true }) await runFixture(t, 'cached_config', { flags: { cachedConfigPath, context: 'test' }, useBinary: true }) } finally { await pUnlink(cachedConfigPath) } }) test('--cachedConfig', async (t) => { const { returnValue } = await runFixture(t, 'cached_config', { snapshot: false }) const cachedConfig = JSON.parse(returnValue) await runFixture(t, 'cached_config', { flags: { cachedConfig } }) }) test('--cachedConfigPath', async (t) => { const cachedConfigPath = await tmpName() try { const { returnValue } = await runFixture(t, 'cached_config', { snapshot: false }) await pWriteFile(cachedConfigPath, returnValue) await runFixture(t, 'cached_config', { flags: { cachedConfigPath, context: 'test' } }) } finally { await pUnlink(cachedConfigPath) } }) test('--cachedConfig with a token', async (t) => { const { returnValue } = await runFixture(t, 'cached_config', { snapshot: false }) const cachedConfig = JSON.parse(returnValue) await runFixture(t, 'cached_config', { flags: { cachedConfig, token: 'test' } }) }) test('--cachedConfig with a siteId', async (t) => { const { returnValue } = await runFixture(t, 'cached_config', { snapshot: false, flags: { siteId: 'test' } }) const cachedConfig = JSON.parse(returnValue) await runFixture(t, 'cached_config', { flags: { cachedConfig, siteId: 'test' } }) }) test('Programmatic', async (t) => { const { config } = await resolveConfig({ repositoryRoot: `${FIXTURES_DIR}/empty` }) t.not(config.build.environment, undefined) }) test('Programmatic no options', async (t) => { const { config } = await resolveConfig() t.not(config.build.environment, undefined) }) test('featureFlags can be used programmatically', async (t) => { await runFixture(t, 'empty', { flags: { featureFlags: { test: true, testTwo: false } } }) }) test('featureFlags can be used in the CLI', async (t) => { await runFixture(t, 'empty', { flags: { featureFlags: { test: true, testTwo: false } }, useBinary: true }) }) test('featureFlags can be not used', async (t) => { await runFixture(t, 'empty', { flags: { featureFlags: undefined, debug: true } }) }) <file_sep>'use strict' module.exports = { onPreBuild() {}, } <file_sep>'use strict' const { readFile } = require('fs') const { promisify } = require('util') const pathExists = require('path-exists') const { throwUserError } = require('./error') const { warnTomlBackslashes } = require('./log/messages') const { parseToml } = require('./utils/toml') const pReadFile = promisify(readFile) // Load the configuration file and parse it (TOML) const parseConfig = async function (configPath, logs, featureFlags) { if (configPath === undefined) { return {} } if (!(await pathExists(configPath))) { throwUserError('Configuration file does not exist') } return await readConfigPath(configPath, logs, featureFlags) } // Same but `configPath` is required and `configPath` might point to a // non-existing file. const parseOptionalConfig = async function (configPath, logs, featureFlags) { if (!(await pathExists(configPath))) { return {} } return await readConfigPath(configPath, logs, featureFlags) } const readConfigPath = async function (configPath, logs, featureFlags) { const configString = await readConfig(configPath) validateTomlBlackslashes(logs, configString, featureFlags) try { return parseToml(configString) } catch (error) { throwUserError('Could not parse configuration file', error) } } // Reach the configuration file's raw content const readConfig = async function (configPath) { try { return await pReadFile(configPath, 'utf8') } catch (error) { throwUserError('Could not read configuration file', error) } } const validateTomlBlackslashes = function (logs, configString, featureFlags) { if (!featureFlags.netlify_config_toml_backslash) { return } const result = INVALID_TOML_BLACKSLASH.exec(configString) if (result === null) { return } const [invalidSequence] = result warnTomlBackslashes(logs, invalidSequence) } // The TOML specification forbids unrecognized backslash sequences. However, // `toml-node` does not respect the specification and do not fail on those. // Therefore, we print a warning message. const INVALID_TOML_BLACKSLASH = /(?<!\\)\\[^"\\btnfruU]/u module.exports = { parseConfig, parseOptionalConfig } <file_sep>'use strict' module.exports = { onPreBuild({ utils: { build: { failBuild }, }, }) { const error = new Error('test') error.toJSON = () => ({}) failBuild('message', { error }) }, } <file_sep>'use strict' const { mkdir } = require('fs') const { dirname } = require('path') const { promisify } = require('util') const pMkdir = promisify(mkdir) const DEFAULT_FUNCTIONS_SRC = 'netlify/functions' module.exports = { async onPreBuild({ constants: { FUNCTIONS_SRC } }) { console.log(FUNCTIONS_SRC.endsWith('test')) await pMkdir(dirname(DEFAULT_FUNCTIONS_SRC)) await pMkdir(DEFAULT_FUNCTIONS_SRC) }, onBuild({ constants: { FUNCTIONS_SRC } }) { console.log(FUNCTIONS_SRC.endsWith('test')) }, } <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { Object.defineProperty(netlifyConfig.build, 'ignore', { value: '', enumerable: true }) }, } <file_sep>[Build] Base = "base" Command = "gulp build" Functions = "functions" Edge_handlers = "edge-handlers" Ignore = "doIgnore" Publish = "publish" [Build.Environment] TEST = "test" [Build.Processing.css] bundle = true <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.build.services = { identity: 'two' } }, onBuild({ netlifyConfig: { build: { services }, }, }) { console.log(services) }, } <file_sep>[build] ignore = "test \[this\]" <file_sep>'use strict' module.exports = function testFunc() {} <file_sep>'use strict' const test = require('ava') const { runFixture } = require('../helpers/main') test('build.command empty', async (t) => { await runFixture(t, 'command_empty') }) test('Some properties can be capitalized', async (t) => { await runFixture(t, 'props_case') }) test('Some properties can be capitalized even when merged with defaultConfig', async (t) => { const defaultConfig = { Build: { Base: 'base', Command: 'gulp build default', Functions: 'functions', Edge_handlers: 'edgeHandlers', Ignore: 'doIgnore', Publish: 'publish', Environment: { TEST: 'test' }, Processing: { css: { bundle: false } }, }, } await runFixture(t, 'props_case_default_config', { flags: { defaultConfig } }) }) test('Does not add build.commandOrigin config if there are none', async (t) => { await runFixture(t, 'empty') }) test('Does not add build.commandOrigin config if command is empty', async (t) => { await runFixture(t, 'command_empty') }) test('Add build.commandOrigin config if it came from netlify.toml', async (t) => { await runFixture(t, 'command_origin_config') }) test('Add build.commandOrigin config if it came from contexts', async (t) => { await runFixture(t, 'command_origin_context') }) test('Add build.commandOrigin ui if it came from defaultConfig', async (t) => { const defaultConfig = { build: { command: 'test' } } await runFixture(t, 'empty', { flags: { defaultConfig } }) }) test('Assign default functions if functions.directory is not defined and default directory exists', async (t) => { await runFixture(t, 'default_functions_not_defined') }) test('Assign default functions if functions.directory is not defined and the legacy default directory exists', async (t) => { await runFixture(t, 'legacy_default_functions_not_defined') }) test('Does not assign default functions if default functions directory does not exist', async (t) => { await runFixture(t, 'default_functions_not_defined_directory_not_found') }) test('Does not assign default functions if functions.directory is defined', async (t) => { await runFixture(t, 'default_functions_defined') }) test('Does not assign default functions if build.functions is defined', async (t) => { await runFixture(t, 'default_functions_defined_legacy') }) test('Gives priority to functions.star over functions when defined first', async (t) => { await runFixture(t, 'default_functions_star_priority_first') }) test('Gives priority to functions.star over functions when defined last', async (t) => { await runFixture(t, 'default_functions_star_priority_last') }) test('Assign default edge-handlers if build.edge_handlers is not defined', async (t) => { await runFixture(t, 'default_handlers_not_defined') }) test('Does not assign default edge-handlers if build.edge_handlers is defined', async (t) => { await runFixture(t, 'default_handlers_defined') }) test('Normalizes function configurations defined at the top level', async (t) => { await runFixture(t, 'function_config_top_level') }) test('Normalizes function configurations defined at different levels', async (t) => { await runFixture(t, 'function_config_all_levels') }) test('Handles function configuration objects for functions with the same name as one of the configuration properties', async (t) => { await runFixture(t, 'function_config_ambiguous') }) test('Collects paths from `included_files` defined at different levels', async (t) => { await runFixture(t, 'function_config_included_files') }) test('Merges plugins in netlify.toml and defaultConfig', async (t) => { const defaultConfig = { plugins: [ { package: 'netlify-plugin-test', inputs: { boolean: true, unset: true, array: ['a', 'b'], object: { prop: true, unset: true }, }, }, ], } await runFixture(t, 'merge_netlify_toml_default', { flags: { defaultConfig } }) }) test('Merges context-specific plugins', async (t) => { await runFixture(t, 'merge_netlify_toml_context') }) test('Context-specific plugins config is last in merged array', async (t) => { await runFixture(t, 'merge_netlify_toml_context_last') }) <file_sep># Snapshot report for `packages/build/tests/plugins/tests.js` The actual snapshot is saved in `tests.js.snap`. Generated by [AVA](https://avajs.dev). ## Pass netlifyConfig to plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_valid␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_valid␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_valid/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_valid␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig properties are readonly (set) by default > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_readonly_set␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_readonly_set␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_readonly_set/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_readonly_set␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.ignore" value changed to ''.␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: "netlifyConfig.build.ignore" is read-only.␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_readonly_set␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## netlifyConfig properties are readonly (delete) by default > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_readonly_delete␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_readonly_delete␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_readonly_delete/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_readonly_delete␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Setting "netlifyConfig.build.command" to undefined is not allowed.␊ Please set this property to a specific value instead.␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_readonly_delete␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## netlifyConfig properties are readonly (defineProperty) by default > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_readonly_define␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_readonly_define␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_readonly_define/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_readonly_define␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.ignore" value changed to ''.␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: "netlifyConfig.build.ignore" is read-only.␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_readonly_define␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Some netlifyConfig properties can be mutated > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_general␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_general␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_general/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_general␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./one␊ - inputs: {}␊ origin: config␊ package: ./two␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./one@1.0.0 from netlify.toml␊ - ./two@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./one ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_general␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_general/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./one␊ - inputs: {}␊ origin: config␊ package: ./two␊ ␊ (./one onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./one ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_general/test_functions␊ ␊ (./one onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./two ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_general/test_functions␊ ␊ (./two onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig properties cannot be deleted > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_delete␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_delete␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_delete/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_delete␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Setting "netlifyConfig.build.command" to undefined is not allowed.␊ Please set this property to a specific value instead.␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_delete␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## netlifyConfig properties cannot be assigned to undefined > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_set_undefined␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_set_undefined␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_set_undefined/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_set_undefined␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Setting "netlifyConfig.build.command" to undefined is not allowed.␊ Please set this property to a specific value instead.␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_set_undefined␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## netlifyConfig properties cannot be assigned to null > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_set_null␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_set_null␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_set_null/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_set_null␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Setting "netlifyConfig.build.command" to null is not allowed.␊ Please set this property to a specific value instead.␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_set_null␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## netlifyConfig properties cannot be assigned to undefined with defineProperty > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_define_undefined␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_define_undefined␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_define_undefined/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_define_undefined␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Setting "netlifyConfig.build.command" to undefined is not allowed.␊ Please set this property to a specific value instead.␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_define_undefined␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## netlifyConfig properties mutations is persisted > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_persist␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_persist␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_persist/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_persist␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_mutate_persist␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.*.external_node_modules" value changed to [ 'test' ].␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_mutate_persist␊ publishOrigin: default␊ functions:␊ '*':␊ external_node_modules:␊ - test␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ node --version␊ [ 'test' ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig array properties can be mutated per index > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_array_index␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_array_index␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_array_index/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_array_index␊ publishOrigin: default␊ functions:␊ '*':␊ included_files:␊ - one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.*.included_files" value changed to [ 'one', 'two' ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_array_index␊ publishOrigin: default␊ functions:␊ '*':␊ included_files:␊ - one␊ - two␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig array properties can be pushed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_array_push␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_array_push␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_array_push/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_array_push␊ publishOrigin: default␊ functions:␊ '*':␊ included_files:␊ - one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.*.included_files" value changed to [ 'one', 'two' ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_array_push␊ publishOrigin: default␊ functions:␊ '*':␊ included_files:␊ - one␊ - two␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functionsDirectory mutations are used during functions bundling > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_bundling␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_bundling␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_bundling/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_bundling␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_bundling␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_bundling/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functionsDirectory deletion skips functions bundling > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip/functions␊ Netlify configuration property "functions.directory" value changed to ''.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_skip␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functionsDirectory mutations are used by utils.functions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_utils␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_utils␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_utils/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_utils␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_utils␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_utils/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from test_functions directory:␊ - test.js␊ ␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functionsDirectory mutations are used by constants.FUNCTIONS_SRC > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_constants␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_constants␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_constants/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_constants␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_constants␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_constants/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test_functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functionsDirectory mutations are taken into account by default constants.FUNCTIONS_SRC > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify/functions␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test_functions␊ Netlify configuration property "functions.directory" value changed to ''.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_default/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in netlify/functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify/functions␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functions.star.directory mutations work > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.*.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star/test_functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functions.star.directory has priority over functions.directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority/one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.*.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_star_priority/test_functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functions.directory mutations work > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested/test_functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functions.directory has priority over functions.star.directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority/one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.directory" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_nested_priority/test_functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.functions mutations work > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.functions" value changed to 'test_functions'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build/test_functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ packages/build/tests/plugins/fixtures/config_mutate_functions_directory_build/test_functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test_functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functions mutations are used during functions bundling > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_bundling␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_bundling/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling␊ publishOrigin: default␊ functions:␊ test:␊ node_bundler: esbuild␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.test.node_bundler" value changed to 'zisi'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling␊ publishOrigin: default␊ functions:␊ test:␊ node_bundler: zisi␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from netlify/functions directory:␊ - test.js␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Dependencies installation error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ A Netlify Function failed to require one of its dependencies.␊ Please make sure it is present in the site's top-level "package.json".␊ ␊ In file "packages/build/tests/plugins/fixtures/config_mutate_functions_bundling/netlify/functions/test.js"␊ Cannot find module 'does_not_exist'␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling␊ publishOrigin: default␊ functions:␊ test:␊ node_bundler: zisi␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_bundling/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## netlifyConfig.functions mutations on any property can be used > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_any␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_any␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_any/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_any␊ publishOrigin: default␊ functions:␊ test:␊ node_bundler: esbuild␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_any/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.test.external_node_modules" value changed to [].␊ Netlify configuration property "functions.test.ignored_node_modules" value changed to [].␊ Netlify configuration property "functions.test.included_files" value changed to [].␊ Netlify configuration property "functions.*.node_bundler" value changed to 'zisi'.␊ Netlify configuration property "functions.*.external_node_modules" value changed to [].␊ Netlify configuration property "functions.*.ignored_node_modules" value changed to [].␊ Netlify configuration property "functions.*.included_files" value changed to [].␊ Netlify configuration property "functions.node_bundler" value changed to 'zisi'.␊ Netlify configuration property "functions.external_node_modules" value changed to [ 'test' ].␊ Netlify configuration property "functions.ignored_node_modules" value changed to [ 'test' ].␊ Netlify configuration property "functions.included_files" value changed to [ 'test' ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_any␊ publishOrigin: default␊ functions:␊ '*':␊ external_node_modules:␊ - test␊ ignored_node_modules:␊ - test␊ included_files:␊ - test␊ node_bundler: zisi␊ test:␊ external_node_modules: []␊ ignored_node_modules: []␊ included_files: []␊ node_bundler: esbuild␊ functionsDirectory: packages/build/tests/plugins/fixtures/config_mutate_functions_any/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in netlify/functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.functions mutations can add new functions configs > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_functions_new␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_functions_new␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_functions_new/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_new␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "functions.test" value changed to { included_files: [] }.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_functions_new␊ publishOrigin: default␊ functions:␊ test:␊ included_files: []␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig properties are deeply readonly by default > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_readonly_deep␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_readonly_deep␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_readonly_deep/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_readonly_deep␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "plugins" value changed to [␊ { package: './plugin', origin: 'config', inputs: { example: true } }␊ ].␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: "netlifyConfig.plugins" is read-only.␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_readonly_deep␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## netlifyConfig is updated when headers file is created by a plugin > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_headers_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_headers_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_headers_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [ { for: '/external/path', values: { test: 'one' } } ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when headers file is created by a plugin and publish was changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_headers_plugin_dynamic␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_headers_plugin_dynamic␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_headers_plugin_dynamic/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin_dynamic␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.publish" value changed to 'test'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin_dynamic/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ test␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin_dynamic/test␊ publishOrigin: inline␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [ { for: '/external/path', values: { test: 'one' } } ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when headers file is created by a build command > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_headers_command␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_headers_command␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_headers_command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node command.js␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [ { for: '/external/path', values: { test: 'one' } } ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when headers file is created by a build command and publish was changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_headers_command_dynamic␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_headers_command_dynamic␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_headers_command_dynamic/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command_dynamic␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ Netlify configuration property "build.publish" value changed to 'test'.␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command_dynamic/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node command.js␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command_dynamic/test␊ publishOrigin: inline␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [ { for: '/external/path', values: { test: 'one' } } ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when redirects file is created by a plugin > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_redirects_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_redirects_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_redirects_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when redirects file is created by a plugin and publish was changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_redirects_plugin_dynamic␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_redirects_plugin_dynamic␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_redirects_plugin_dynamic/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_plugin_dynamic␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.publish" value changed to 'test'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_plugin_dynamic/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ test␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_plugin_dynamic/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when redirects file is created by a build command > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_redirects_command␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_redirects_command␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_redirects_command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_command␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node command.js␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_command␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig is updated when redirects file is created by a build command and publish was changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_redirects_command_dynamic␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_redirects_command_dynamic␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_redirects_command_dynamic/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_command_dynamic␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ Netlify configuration property "build.publish" value changed to 'test'.␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_command_dynamic/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node command.js␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_redirects_command_dynamic/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.processing can be assigned all at once > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_processing_all␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_processing_all␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_processing_all/netlify.toml␊ ␊ > Resolved config␊ build:␊ processing:␊ css:␊ bundle: false␊ minify: false␊ html:␊ pretty_urls: false␊ images:␊ compress: false␊ js:␊ bundle: false␊ minify: false␊ skip_processing: false␊ publish: packages/build/tests/plugins/fixtures/config_mutate_processing_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.processing.css.bundle" value changed to true.␊ Netlify configuration property "build.processing.css.minify" value changed to true.␊ Netlify configuration property "build.processing.html.pretty_urls" value changed to true.␊ Netlify configuration property "build.processing.images.compress" value changed to true.␊ Netlify configuration property "build.processing.js.bundle" value changed to true.␊ Netlify configuration property "build.processing.js.minify" value changed to true.␊ Netlify configuration property "build.processing.skip_processing" value changed to true.␊ ␊ > Updated config␊ build:␊ processing:␊ css:␊ bundle: true␊ minify: true␊ html:␊ pretty_urls: true␊ images:␊ compress: true␊ js:␊ bundle: true␊ minify: true␊ skip_processing: true␊ publish: packages/build/tests/plugins/fixtures/config_mutate_processing_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ {␊ css: { bundle: true, minify: true },␊ html: { pretty_urls: true },␊ images: { compress: true },␊ js: { bundle: true, minify: true },␊ skip_processing: true␊ }␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.processing can be assigned individually > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_processing_prop␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_processing_prop␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_processing_prop/netlify.toml␊ ␊ > Resolved config␊ build:␊ processing:␊ css:␊ bundle: false␊ minify: false␊ html:␊ pretty_urls: false␊ images:␊ compress: false␊ js:␊ bundle: false␊ minify: false␊ skip_processing: false␊ publish: packages/build/tests/plugins/fixtures/config_mutate_processing_prop␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.processing.css.bundle" value changed to true.␊ Netlify configuration property "build.processing.css.minify" value changed to true.␊ Netlify configuration property "build.processing.html.pretty_urls" value changed to true.␊ Netlify configuration property "build.processing.images.compress" value changed to true.␊ Netlify configuration property "build.processing.js.bundle" value changed to true.␊ Netlify configuration property "build.processing.js.minify" value changed to true.␊ Netlify configuration property "build.processing.skip_processing" value changed to true.␊ ␊ > Updated config␊ build:␊ processing:␊ css:␊ bundle: true␊ minify: true␊ html:␊ pretty_urls: true␊ images:␊ compress: true␊ js:␊ bundle: true␊ minify: true␊ skip_processing: true␊ publish: packages/build/tests/plugins/fixtures/config_mutate_processing_prop␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ {␊ css: { bundle: true, minify: true },␊ html: { pretty_urls: true },␊ images: { compress: true },␊ js: { bundle: true, minify: true },␊ skip_processing: true␊ }␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.headers can be assigned all at once > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_headers_all␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_headers_all␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_headers_all/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_all␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ headersOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "headers" value changed to [␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_all␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ - for: /external/path␊ values:␊ test: two␊ headersOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.headers can be modified before headers file has been added > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_headers_before␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_headers_before␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_headers_before/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_before␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ headersOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "headers" value changed to [␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_before␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: one␊ - for: /external/path␊ values:␊ test: two␊ headersOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_before␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ - for: /external/path␊ values:␊ test: two␊ headersOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ { for: '/external/path', values: { test: 'three' } },␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.headers can be modified after headers file has been added > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_headers_after␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_headers_after␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_headers_after/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_after␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ headersOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "headers" value changed to [␊ { for: '/external/path', values: { test: 'three' } },␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_headers_after␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ - for: /external/path␊ values:␊ test: two␊ headersOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ { for: '/external/path', values: { test: 'three' } },␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig deletes headers file if headers were changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_save_headers/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_headers␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_headers␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_save_headers/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_headers␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ headersOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "headers" value changed to [␊ { for: '/external/path', values: { test: 'three' } },␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_headers␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ - for: /external/path␊ values:␊ test: two␊ headersOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ { for: '/external/path', values: { test: 'three' } },␊ { for: '/external/path', values: { test: 'one' } },␊ { for: '/external/path', values: { test: 'two' } }␊ ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [[plugins]]␊ package = "./plugin"␊ ␊ [[headers]]␊ for = "/external/path"␊ ␊ [headers.values]␊ test = "three"␊ ␊ [[headers]]␊ for = "/external/path"␊ ␊ [headers.values]␊ test = "one"␊ ␊ [[headers]]␊ for = "/external/path"␊ ␊ [headers.values]␊ test = "two"␊ ␊ [context]␊ ␊ [context.production]␊ ␊ [[context.production.headers]]␊ for = "/external/path"␊ ␊ [context.production.headers.values]␊ test = "three"␊ ␊ [[context.production.headers]]␊ for = "/external/path"␊ ␊ [context.production.headers.values]␊ test = "one"␊ ␊ [[context.production.headers]]␊ for = "/external/path"␊ ␊ [context.production.headers.values]␊ test = "two"␊ ␊ [context.main]␊ ␊ [[context.main.headers]]␊ for = "/external/path"␊ ␊ [context.main.headers.values]␊ test = "three"␊ ␊ [[context.main.headers]]␊ for = "/external/path"␊ ␊ [context.main.headers.values]␊ test = "one"␊ ␊ [[context.main.headers]]␊ for = "/external/path"␊ ␊ [context.main.headers.values]␊ test = "two"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig deletes headers file if any configuration property was changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_delete_headers/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_delete_headers␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_delete_headers␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_delete_headers/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_delete_headers␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ headersOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST␊ publish: packages/build/tests/plugins/fixtures/config_delete_headers␊ publishOrigin: default␊ headers:␊ - for: /external/path␊ values:␊ test: three␊ - for: /external/path␊ values:␊ test: one␊ headersOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ ␊ [build.environment]␊ TEST = "test"␊ ␊ [[plugins]]␊ package = "./plugin"␊ ␊ [[headers]]␊ for = "/external/path"␊ ␊ [headers.values]␊ test = "three"␊ ␊ [[headers]]␊ for = "/external/path"␊ ␊ [headers.values]␊ test = "one"␊ ␊ [context]␊ ␊ [context.production]␊ ␊ [context.production.environment]␊ TEST = "test"␊ ␊ [context.production.build]␊ ␊ [context.production.build.environment]␊ TEST = "test"␊ ␊ [context.main]␊ ␊ [context.main.environment]␊ TEST = "test"␊ ␊ [context.main.build]␊ ␊ [context.main.build.environment]␊ TEST = "test"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Erroneous headers created by a build command are handled > Snapshot 1 `␊ Warning: some headers have syntax errors:␊ ␊ Path should come before header "test"␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_create_headers_command_error/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_headers_command_error␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_headers_command_error␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_headers_command_error/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command_error␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node command.js␊ ␊ > Updated config␊ build:␊ command: node command.js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_command_error␊ publishOrigin: default␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ command = "node command.js"␊ ␊ > Uploaded headers␊ test: one␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Erroneous headers created by a plugin are handled > Snapshot 1 `␊ Warning: some headers have syntax errors:␊ ␊ Could not parse header number 1:␊ {"values":{}}␊ Missing "for" field␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_create_headers_plugin_error/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_create_headers_plugin_error␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: 'true'␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_create_headers_plugin_error␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_create_headers_plugin_error/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "headers" value changed to [ { values: {} } ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_create_headers_plugin_error␊ publishOrigin: default␊ headersOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ []␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [[plugins]]␊ package = "./plugin"␊ ␊ [context]␊ ␊ [context.production]␊ ␊ [[context.production.headers]]␊ ␊ [context.production.headers.values]␊ ␊ [context.main]␊ ␊ [[context.main.headers]]␊ ␊ [context.main.headers.values]␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)␊ ␊ ␊ Warning: some headers have syntax errors:␊ ␊ Could not parse header number 1:␊ {"values":{}}␊ Missing "for" field` ## netlifyConfig.redirects can be assigned all at once > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_redirects_all␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_redirects_all␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_redirects_all/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: config␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "redirects" value changed to [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ { from: '/external/path', to: '/external/path' }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: inline␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.redirects can be modified before redirects file has been added > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_redirects_before␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_redirects_before␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_redirects_before/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_before␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: config␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "redirects" value changed to [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ { from: '/external/path', to: '/external/path' }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_before␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: inline␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_before␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: inline␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.redirects can be modified after redirects file has been added > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_redirects_after␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_redirects_after␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_redirects_after/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_after␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: config␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "redirects" value changed to [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ { from: '/external/path', to: '/external/path' }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_redirects_after␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: inline␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig deletes redirects file if redirects were changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_save_redirects/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_redirects␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_redirects␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_save_redirects/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_redirects␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ status: 200␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: config␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "redirects" value changed to [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ status: 200,␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ { from: '/external/path', to: '/external/path' }␊ ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_redirects␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ status: 200␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: inline␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [[plugins]]␊ package = "./plugin"␊ ␊ [[redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ status = 200␊ ␊ [[redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ [[redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ [context]␊ ␊ [context.production]␊ ␊ [[context.production.redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ status = 200␊ ␊ [[context.production.redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ [[context.production.redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ [context.main]␊ ␊ [[context.main.redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ status = 200␊ ␊ [[context.main.redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ [[context.main.redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onSuccess command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ status: 200,␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ },␊ {␊ from: '/external/path',␊ query: {},␊ to: '/external/path',␊ force: false,␊ conditions: {},␊ headers: {}␊ }␊ ]␊ ␊ (./plugin onSuccess completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig deletes redirects file if any configuration property was changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_delete_redirects/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_delete_redirects␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_delete_redirects␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_delete_redirects/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_delete_redirects␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ status: 200␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: config␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST␊ publish: packages/build/tests/plugins/fixtures/config_delete_redirects␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ redirects:␊ - from: /external/path␊ status: 200␊ to: /external/path␊ - from: /external/path␊ to: /external/path␊ redirectsOrigin: config␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ ␊ [build.environment]␊ TEST = "test"␊ ␊ [[plugins]]␊ package = "./plugin"␊ ␊ [[redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ status = 200␊ ␊ [[redirects]]␊ from = "/external/path"␊ to = "/external/path"␊ ␊ [context]␊ ␊ [context.production]␊ ␊ [context.production.environment]␊ TEST = "test"␊ ␊ [context.production.build]␊ ␊ [context.production.build.environment]␊ TEST = "test"␊ ␊ [context.main]␊ ␊ [context.main.environment]␊ TEST = "test"␊ ␊ [context.main.build]␊ ␊ [context.main.build.environment]␊ TEST = "test"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.command can be changed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_build_command_change␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_build_command_change␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_build_command_change/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_build_command_change␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_mutate_build_command_change␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ node --version␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.command can be added > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_build_command_add␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_build_command_add␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_build_command_add/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_build_command_add␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_mutate_build_command_add␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.command can be removed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_build_command_remove␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_build_command_remove␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_build_command_remove/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: test␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_build_command_remove␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to ''.␊ ␊ > Updated config␊ build:␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_build_command_remove␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.environment can be assigned all at once > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_env_all␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_env_all␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_env_all/netlify.toml␊ ␊ > Resolved config␊ build:␊ environment:␊ - TEST_ONE␊ publish: packages/build/tests/plugins/fixtures/config_mutate_env_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST_TWO" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST_ONE␊ - TEST_TWO␊ publish: packages/build/tests/plugins/fixtures/config_mutate_env_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ { TEST_ONE: 'one', TEST_TWO: 'two' }␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.environment can be assigned individually > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_env_prop␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_env_prop␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_env_prop/netlify.toml␊ ␊ > Resolved config␊ build:␊ environment:␊ - TEST_ONE␊ publish: packages/build/tests/plugins/fixtures/config_mutate_env_prop␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST_TWO" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST_ONE␊ - TEST_TWO␊ publish: packages/build/tests/plugins/fixtures/config_mutate_env_prop␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ { TEST_ONE: 'one', TEST_TWO: 'two' }␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.publish mutations are used by constants.PUBLISH_DIR > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_publish_constants␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_publish_constants␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_publish_constants/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_publish_constants␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ .␊ Netlify configuration property "build.publish" value changed to 'test'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_publish_constants/test␊ publishOrigin: inline␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.build.edge_handlers mutations are used by constants.EDGE_HANDLERS_SRC > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_constants␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_constants␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_constants/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_constants␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ Netlify configuration property "build.edge_handlers" value changed to 'test'.␊ ␊ > Updated config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_constants/test␊ publish: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_constants␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.edge_handlers can be assigned all at once > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_all␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_all␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_all/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "edge_handlers" value changed to [ { path: '/external/path', handler: 'two' } ].␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_edge_handlers_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [ { path: '/external/path', handler: 'two' } ]␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.services can be assigned all at once > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_services_all␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_services_all␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_services_all/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_services_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.services.identity" value changed to 'two'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_services_all␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ { identity: 'two' }␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig.services can be assigned individually > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_services_prop␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_services_prop␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_services_prop/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_services_prop␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.services.identity" value changed to 'two'.␊ ␊ > Updated config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_services_prop␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ { identity: 'two' }␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig mutations fail if done in an event that is too late > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_too_late␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_too_late␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_too_late/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_too_late␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: "netlifyConfig.build.command" cannot be modified after "onPreBuild".␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_too_late␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## netlifyConfig mutations fail correctly on symbols > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_symbol␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_symbol␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_symbol/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --version␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_mutate_symbol␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## netlifyConfig mutations fail if the syntax is invalid > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_mutate_invalid_syntax␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_mutate_invalid_syntax␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_mutate_invalid_syntax/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_invalid_syntax␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to false.␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: When resolving config file packages/build/tests/plugins/fixtures/config_mutate_invalid_syntax/netlify.toml:␊ Configuration property build.command must be a string␊ ␊ Invalid syntax␊ ␊ [build]␊ command = false␊ ␊ Valid syntax␊ ␊ [build]␊ command = "npm run build"␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_mutate_invalid_syntax␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## --saveConfig saves the configuration changes as netlify.toml > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_save_changes/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_changes␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_changes␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_save_changes/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_changes␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_save_changes␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ command = "node --version"␊ ␊ [[plugins]]␊ package = "./plugin"␊ ␊ [context]␊ ␊ [context.production]␊ command = "node --version"␊ ␊ [context.production.build]␊ command = "node --version"␊ ␊ [context.main]␊ command = "node --version"␊ ␊ [context.main.build]␊ command = "node --version"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig is required to save the configuration changes as netlify.toml > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_save_none/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_none␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_none␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_save_none/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_none␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_save_none␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig creates netlify.toml if it does not exist > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_empty␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_empty␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_empty␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from Netlify app␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_save_empty␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: ./plugin.js␊ ␊ (./plugin.js onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ command = "node --version"␊ ␊ [context]␊ ␊ [context.production]␊ command = "node --version"␊ ␊ [context.production.build]␊ command = "node --version"␊ ␊ [context.main]␊ command = "node --version"␊ ␊ [context.main.build]␊ command = "node --version"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig gives higher priority to configuration changes than context properties > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ config: packages/build/tests/plugins/fixtures/config_save_context/test_netlify.toml␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_context␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_context␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_save_context/test_netlify.toml␊ ␊ > Resolved config␊ build:␊ command: mainCommand␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/config_save_context␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_save_context␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ command = "node --version"␊ ␊ [[plugins]]␊ package = "./plugin"␊ ␊ [context]␊ ␊ [context.production]␊ command = "node --version"␊ ␊ [context.production.build]␊ command = "node --version"␊ ␊ [context.main]␊ command = "node --version"␊ ␊ [context.main.build]␊ command = "node --version"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## --saveConfig is performed before deploy > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ branch: main␊ buildbotServerSocket: /test/socket␊ context: production␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_save_deploy␊ saveConfig: true␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_save_deploy␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_save_deploy␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from Netlify app␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.command" value changed to 'node --version'.␊ ␊ > Updated config␊ build:␊ command: node --version␊ commandOrigin: inline␊ publish: packages/build/tests/plugins/fixtures/config_save_deploy␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: ./plugin.js␊ ␊ (./plugin.js onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from a plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --version␊ v1.0.0␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ > Uploaded config␊ [build]␊ command = "node --version"␊ ␊ [context]␊ ␊ [context.production]␊ command = "node --version"␊ ␊ [context.production.build]␊ command = "node --version"␊ ␊ [context.main]␊ command = "node --version"␊ ␊ [context.main.build]␊ command = "node --version"␊ ␊ > Uploaded headers␊ No headers␊ ␊ > Uploaded redirects␊ No redirects␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.CONFIG_PATH > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/config_path␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/config_path␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/config_path/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/config_path␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify.toml␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.PUBLISH_DIR default value > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/publish_default␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/publish_default␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/publish_default/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/publish_default␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ . true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.PUBLISH_DIR default value with build.base > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/publish_default_base␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/publish_default_base/base␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/publish_default_base/netlify.toml␊ ␊ > Resolved config␊ build:␊ base: packages/build/tests/plugins/fixtures/publish_default_base/base␊ publish: packages/build/tests/plugins/fixtures/publish_default_base/base␊ publishOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: /external/path␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - /external/path from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from /external/path ␊ ────────────────────────────────────────────────────────────────␊ ␊ . true␊ ␊ (/external/path onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.PUBLISH_DIR absolute path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/publish_absolute␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/publish_absolute␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/publish_absolute/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/publish_absolute/doesNotExist␊ publishOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ doesNotExist␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.PUBLISH_DIR relative path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/publish_relative␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/publish_relative␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/publish_relative/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/publish_relative/publish␊ publishOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ publish␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.PUBLISH_DIR missing path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/publish_missing␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/publish_missing␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/publish_missing/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/publish_missing/publish␊ publishOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ publish false␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC default value > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_src_default␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_src_default␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_src_default/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_src_default␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ undefined␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC uses legacy default functions directory if it exists > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_src_legacy␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_src_legacy␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_src_legacy/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_src_legacy␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_src_legacy/netlify-automatic-functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify-automatic-functions␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in netlify-automatic-functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC ignores the legacy default functions directory if the new default directory exists > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_src_default_and_legacy␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_src_default_and_legacy␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_src_default_and_legacy/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_src_default_and_legacy␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_src_default_and_legacy/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify/functions␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in netlify/functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC relative path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_src_relative␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_src_relative␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_src_relative/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_src_relative␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_src_relative/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ functions␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC dynamic is ignored if FUNCTIONS_SRC is specified > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ functionsDirectory: /tmp-dir/test␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in test directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC dynamic should bundle Functions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in netlify/functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC automatic value > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_src_auto␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_src_auto␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_src_auto/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_src_auto␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ undefined␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC missing path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_src_missing␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_src_missing␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_src_missing/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_src_missing␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_src_missing/missing␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ missing false␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ The Netlify Functions setting targets a non-existing directory: missing␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_SRC created dynamically > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify/functions␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.INTERNAL_FUNCTIONS_SRC default value > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/internal_functions_src_default␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/internal_functions_src_default␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/internal_functions_src_default/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/internal_functions_src_default␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ .netlify/functions-internal␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.FUNCTIONS_DIST > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_dist␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_dist␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_dist/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_dist␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ .netlify/functions/␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.CACHE_DIR local > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/cache␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/cache/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/cache␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ .netlify/cache␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.CACHE_DIR CI > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ cacheDir: /external/path␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/cache␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/cache/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/cache␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ /external/path␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.IS_LOCAL CI > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ mode: buildbot␊ repositoryRoot: packages/build/tests/plugins/fixtures/is_local␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/is_local␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/is_local/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/is_local␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ false␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.SITE_ID > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/site_id␊ siteId: test␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/site_id␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/site_id/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/site_id␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.IS_LOCAL local > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/is_local␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/is_local␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/is_local/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/is_local␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.NETLIFY_BUILD_VERSION > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/netlify_build_version␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/netlify_build_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/netlify_build_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/netlify_build_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ 1.0.0␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.NETLIFY_API_TOKEN > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/netlify_api_token␊ testOpts:␊ env: false␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/netlify_api_token␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/netlify_api_token/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/netlify_api_token␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.NETLIFY_API_HOST > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ apiHost: test.api.netlify.com␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/netlify_api_host␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/netlify_api_host␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/netlify_api_host/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/netlify_api_host␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test.api.netlify.com␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.NETLIFY_API_HOST default value is set to api.netlify.com > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/netlify_api_host␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/netlify_api_host␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/netlify_api_host/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/netlify_api_host␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ api.netlify.com␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Pass packageJson to plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/package_json_valid␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/package_json_valid␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/package_json_valid/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/package_json_valid␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test_plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Pass empty packageJson to plugins if no package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Pass empty packageJson to plugins if package.json invalid > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/package_json_invalid␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/package_json_invalid␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/package_json_invalid/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/package_json_invalid␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Functions: missing source directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/missing␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/missing␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/missing/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/missing␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/missing/missing␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ The Netlify Functions setting targets a non-existing directory: missing␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Functions: must not be a regular file > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/regular_file␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/regular_file␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/regular_file/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/regular_file␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/regular_file/functions/test.js␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ The Netlify Functions setting should target a directory, not a regular file: functions/test.js␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/regular_file␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/regular_file/functions/test.js` ## Functions: can be a symbolic link > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/symlink␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/symlink␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/symlink/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/symlink␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/symlink/functions-link␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from functions-link directory:␊ - test.js␊ ␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Functions: default directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/default␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/default␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/default/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/default␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Functions: simple setup > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/simple␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/simple␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/simple/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/simple␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/simple/functions␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from functions directory:␊ - test.js␊ ␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Functions: no functions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/none␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/none␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/none/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/none␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/none/functions␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Functions were found in functions directory␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Functions: invalid package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_package_json_invalid␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_package_json_invalid␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_package_json_invalid/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_package_json_invalid␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_package_json_invalid/functions␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from functions directory:␊ - test.js␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ packages/build/tests/plugins/fixtures/functions_package_json_invalid/package.json is invalid JSON: packages/build/tests/plugins/fixtures/functions_package_json_invalid/package.json: Unexpected token { in JSON at position 1␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_package_json_invalid␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_package_json_invalid/functions` ## Functions: --functionsDistDir > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ functionsDistDir: /tmp-dir␊ repositoryRoot: packages/build/tests/plugins/fixtures/simple␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/simple␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/simple/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/simple␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/simple/functions␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from functions directory:␊ - test.js␊ ␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.EDGE_HANDLERS_SRC default value > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/edge_handlers_src_default␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/edge_handlers_src_default␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/edge_handlers_src_default/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/edge_handlers_src_default␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ undefined␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.EDGE_HANDLERS_SRC automatic value > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/edge_handlers_src_auto␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/edge_handlers_src_auto␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/edge_handlers_src_auto/netlify.toml␊ ␊ > Resolved config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/edge_handlers_src_auto/netlify/edge-handlers␊ publish: packages/build/tests/plugins/fixtures/edge_handlers_src_auto␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify/edge-handlers␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from @netlify/plugin-edge-handlers ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Edge Handlers were found in netlify/edge-handlers directory␊ ␊ (@netlify/plugin-edge-handlers onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.EDGE_HANDLERS_SRC relative path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/edge_handlers_src_relative␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/edge_handlers_src_relative␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/edge_handlers_src_relative/netlify.toml␊ ␊ > Resolved config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/edge_handlers_src_relative/custom-edge-handlers␊ publish: packages/build/tests/plugins/fixtures/edge_handlers_src_relative␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ custom-edge-handlers␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from @netlify/plugin-edge-handlers ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Edge Handlers were found in custom-edge-handlers directory␊ ␊ (@netlify/plugin-edge-handlers onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.EDGE_HANDLERS_SRC missing path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/edge_handlers_src_missing␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/edge_handlers_src_missing␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/edge_handlers_src_missing/netlify.toml␊ ␊ > Resolved config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/edge_handlers_src_missing/missing␊ publish: packages/build/tests/plugins/fixtures/edge_handlers_src_missing␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ missing false␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from @netlify/plugin-edge-handlers ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "@netlify/plugin-edge-handlers" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Edge Handlers directory does not exist: packages/build/tests/plugins/fixtures/edge_handlers_src_missing/missing␊ ␊ Plugin details␊ Package: @netlify/plugin-edge-handlers␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/netlify-plugin-edge-handlers.git␊ npm link: https://www.npmjs.com/package/@netlify/plugin-edge-handlers␊ Report issues: https://github.com/netlify/netlify-plugin-edge-handlers/issues␊ ␊ Error location␊ In "onBuild" event in "@netlify/plugin-edge-handlers" from core␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/edge_handlers_src_missing/missing␊ publish: packages/build/tests/plugins/fixtures/edge_handlers_src_missing␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## constants.EDGE_HANDLERS_SRC created dynamically > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ netlify/edge-handlers␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## constants.EDGE_HANDLERS_SRC dynamic is ignored if EDGE_HANDLERS_SRC is specified > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ edge_handlers: /tmp-dir/test␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from @netlify/plugin-edge-handlers ␊ ────────────────────────────────────────────────────────────────␊ ␊ No Edge Handlers were found in test directory␊ ␊ (@netlify/plugin-edge-handlers onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Edge handlers: simple setup > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/handlers_simple␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/handlers_simple␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/handlers_simple/netlify/edge-handlers␊ publish: packages/build/tests/plugins/fixtures/handlers_simple␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from @netlify/plugin-edge-handlers ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Edge Handlers from netlify/edge-handlers directory:␊ - test␊ ␊ (@netlify/plugin-edge-handlers onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Edge handlers: can configure directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/handlers_custom_dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/handlers_custom_dir␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/handlers_custom_dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ edge_handlers: packages/build/tests/plugins/fixtures/handlers_custom_dir/custom-edge-handlers␊ publish: packages/build/tests/plugins/fixtures/handlers_custom_dir␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from @netlify/plugin-edge-handlers ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Edge Handlers from custom-edge-handlers directory:␊ - test␊ ␊ (@netlify/plugin-edge-handlers onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Deploy plugin succeeds > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ buildbotServerSocket: /test/socket␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/empty␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/empty␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/empty/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ Site deploy was successfully initiated␊ ␊ (Deploy site completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Deploy plugin response syntax error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ buildbotServerSocket: /test/socket␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/empty␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/empty␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/empty/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Internal error during "Deploy site" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Invalid response from buildbot: SyntaxError: Unexpected token e in JSON at position 1␊ ␊ Error location␊ During Deploy site␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default` ## Deploy plugin response system error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ buildbotServerSocket: /test/socket␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/empty␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/empty␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/empty/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Internal error during "Deploy site" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Deploy did not succeed: test␊ ␊ Error location␊ During Deploy site␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default` ## Deploy plugin response user error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ buildbotServerSocket: /test/socket␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/empty␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/empty␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/empty/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. Deploy site ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Deploy did not succeed: test␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default` ## plugin.onSuccess is triggered on success > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/success_ok␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/success_ok␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/success_ok/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./plugin.js onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onSuccess command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onSuccess␊ ␊ (./plugin.js onSuccess completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onSuccess is not triggered on failure > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/success_not_ok␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/success_not_ok␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/success_not_ok/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_not_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_not_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## plugin.onSuccess is not triggered on failPlugin() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/success_fail_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/success_fail_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/success_fail_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onSuccess is not triggered on cancelBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/success_cancel_build␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/success_cancel_build␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/success_cancel_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_cancel_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ` ## plugin.onSuccess can fail but does not stop builds > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/success_fail␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/success_fail␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/success_fail/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./plugin.js onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onSuccess command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onSuccess␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onSuccess" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/success_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onError is not triggered on success > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_ok␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_ok␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_ok/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./plugin.js onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onError is triggered on failure > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_not_ok␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_not_ok␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_not_ok/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_not_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onError command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onError␊ ␊ (./plugin.js onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_not_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## plugin.onError is not triggered on failPlugin() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_fail_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_fail_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_fail_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onError is triggered on cancelBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_cancel_build␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_cancel_build␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_cancel_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_cancel_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onError command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onError␊ ␊ (./plugin.js onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ` ## plugin.onError can fail > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_fail␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_fail␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_fail/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onError command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onError␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onError" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## plugin.onError gets an error argument > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_argument␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_argument␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_argument/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_argument␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onError command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ TestError␊ test␊ TestError: test␊ STACK TRACE␊ ␊ (./plugin.js onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ TestError: test␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_argument␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## plugin.onError can be used in several plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/error_several␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/error_several␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/error_several/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_several␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ - inputs: {}␊ origin: config␊ package: ./handler_one.js␊ - inputs: {}␊ origin: config␊ package: ./handler_two.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ - ./handler_one.js@1.0.0 from netlify.toml␊ - ./handler_two.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onError command from ./handler_one.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./handler_one.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onError␊ ␊ Plugin details␊ Package: ./handler_one.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onError" event in "./handler_one.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_several␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ - inputs: {}␊ origin: config␊ package: ./handler_one.js␊ - inputs: {}␊ origin: config␊ package: ./handler_two.js␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onError command from ./handler_two.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./handler_two.js onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/error_several␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ - inputs: {}␊ origin: config␊ package: ./handler_one.js␊ - inputs: {}␊ origin: config␊ package: ./handler_two.js` ## plugin.onEnd is triggered on success > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_ok␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_ok␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_ok/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ␊ (./plugin.js onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onEnd command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onEnd␊ ␊ (./plugin.js onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onEnd is triggered on failure > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_not_ok␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_not_ok␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_not_ok/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_not_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onEnd command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onEnd␊ ␊ (./plugin.js onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_not_ok␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## plugin.onEnd is not triggered on failPlugin() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_fail_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_fail_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_fail_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_fail_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onEnd is triggered on cancelBuild() > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_cancel_build␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_cancel_build␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_cancel_build/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_cancel_build␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onEnd command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onEnd␊ ␊ (./plugin.js onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Build canceled by ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onBuild␊ ` ## plugin.onEnd can fail but it does not stop builds > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_fail␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_fail␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_fail/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onEnd command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onEnd␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onEnd" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_fail␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## plugin.onEnd and plugin.onError can be used together > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_error␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_error␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_error/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onError command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onError␊ ␊ (./plugin.js onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onEnd command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onEnd␊ ␊ (./plugin.js onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## plugin.onEnd can be used in several plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/end_several␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/end_several␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/end_several/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_several␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ - inputs: {}␊ origin: config␊ package: ./handler_one.js␊ - inputs: {}␊ origin: config␊ package: ./handler_two.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ - ./handler_one.js@1.0.0 from netlify.toml␊ - ./handler_two.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onEnd command from ./handler_one.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onEnd one␊ ␊ (./handler_one.js onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onEnd command from ./handler_two.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ onEnd two␊ ␊ (./handler_two.js onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin.js" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin.js␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin.js" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/end_several␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ - inputs: {}␊ origin: config␊ package: ./handler_one.js␊ - inputs: {}␊ origin: config␊ package: ./handler_two.js` ## Local plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/local␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/local␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/local/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/local␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Local plugins directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/local_dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/local_dir␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/local_dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/local_dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Local plugins absolute path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/local_absolute␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/local_absolute␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/local_absolute/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/local_absolute␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: /external/path␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - /external/path from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from /external/path ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (/external/path onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Local plugins invalid path > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/local_invalid␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/local_invalid␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/local_invalid/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/local_invalid␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Plugin could not be found using local path: ./plugin␊ Cannot find module './plugin'␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/local_invalid␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Node module plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/module␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/module␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/module/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/module␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - netlify-plugin-test@1.0.0 from netlify.toml and package.json␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-test ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-test onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## UI plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/ui␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/ui␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/ui␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-test␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - netlify-plugin-test@1.0.0 from Netlify app and package.json␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-test ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-test onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Resolution is relative to the build directory > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ config: packages/build/tests/plugins/fixtures/module_base/netlify.toml␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/module_base␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/module_base/base␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/module_base/base/netlify.toml␊ ␊ > Resolved config␊ build:␊ base: packages/build/tests/plugins/fixtures/module_base/base␊ publish: packages/build/tests/plugins/fixtures/module_base/base␊ publishOrigin: config␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - netlify-plugin-test@1.0.0 from netlify.toml and package.json␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-test ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-test onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Non-existing plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/non_existing␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/non_existing␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/non_existing/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/non_existing␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: does-not-exist␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Plugins must be installed either in the Netlify App or in "package.json".␊ Please run "npm install -D does-not-exist" or "yarn add -D does-not-exist".␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/non_existing␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: does-not-exist` ## Do not allow overriding core plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/core_override␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/core_override␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/core_override/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/core_override␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: '@netlify/plugin-edge-handlers'␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Install plugins in .netlify/plugins/ when not cached > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/valid_package␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/valid_package␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/valid_package/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/valid_package␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Use plugins cached in .netlify/plugins/ > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Do not use plugins cached in .netlify/plugins/ if outdated > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache_outdated␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache_outdated␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache_outdated/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache_outdated␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Fetches the list of plugin versions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Only prints the list of plugin versions in verbose mode > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: false␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache/netlify.toml␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Uses fallback when the plugins fetch fails > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ Warning: could not fetch latest plugins list. Plugins versions might not be the latest.␊ Response code 500 (Internal Server Error)␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Uses fallback when the plugins fetch succeeds with an invalid response > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ Warning: could not fetch latest plugins list. Plugins versions might not be the latest.␊ Request succeeded but with an invalid response:␊ {␊ "error": "test"␊ }␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Can execute local binaries when using .netlify/plugins/ > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache_bin␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache_bin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache_bin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache_bin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ 1.0.0␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Can require site dependencies when using .netlify/plugins/ > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache_site_deps␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache_site_deps␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache_site_deps/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache_site_deps␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Works with .netlify being a regular file > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache_regular_file␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache_regular_file␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache_regular_file/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache_regular_file␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Print a warning when using plugins not in plugins.json nor package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/invalid_package␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/invalid_package␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/invalid_package/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/invalid_package␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: power-cartesian-product␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ ` ## Can use local plugins even when some plugins are cached > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_cache_local␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_cache_local␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_cache_local/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_cache_local␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onPostBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin.js onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Prints outdated plugins installed in package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_outdated_package_json␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_outdated_package_json␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_outdated_package_json/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_outdated_package_json␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml and package.json (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please update its version in "package.json"␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Prints incompatible plugins installed in package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_incompatible_package_json␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_incompatible_package_json␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_incompatible_package_json/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_incompatible_package_json␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 1-0-0 from netlify.toml and package.json (latest 0-3-0, expected 0-2-0, compatible 0-2-0)␊ ␊ > Incompatible plugins␊ - netlify-plugin-contextual-env 1-0-0: version 1.0.0 is the most recent version compatible with Node.js <100␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Does not print incompatible plugins installed in package.json if major version is same > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_incompatible_package_json_same_major␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_incompatible_package_json_same_major␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_incompatible_package_json_same_major/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_incompatible_package_json_same_major␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-4-0 from netlify.toml and package.json (latest 0-4-0, expected 0-4-1, compatible 0-4-1)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Does not print incompatible plugins installed in package.json if not using the compatibility field > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_incompatible_package_json␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_incompatible_package_json␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_incompatible_package_json/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_incompatible_package_json␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 1-0-0 from netlify.toml and package.json (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify non-matching compatibility.nodeVersion > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-1-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-1-0 from netlify.toml (latest 0-3-0, expected 0-1-0, compatible 0-1-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-1-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins ignore compatibility entries without conditions unless pinned > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-1-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-1-0 from netlify.toml (latest 0-3-0, expected 0-1-0, compatible 0-1-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-1-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins does not ignore compatibility entries without conditions if pinned > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (pinned 0-2-0, latest 0-3-0, expected 0-2-0, compatible 0-3-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins ignore compatibility conditions if pinned > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (pinned 0-2-0, latest 0-3-0, expected 0-2-0, compatible 0-3-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify matching compatibility.nodeVersion > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (latest 0-3-0, expected 0-2-0, compatible 0-2-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins compatibility defaults to version field > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify compatibility.migrationGuide > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-1-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-1-0 from netlify.toml (latest 0-3-0, expected 0-1-0, compatible 0-1-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-1-0: latest version is 0-3-0␊ Migration guide: http://test.com␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify matching compatibility.siteDependencies > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (latest 0-3-0, expected 0-2-0, compatible 0-2-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify non-matching compatibility.siteDependencies > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify non-existing compatibility.siteDependencies > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify multiple non-matching compatibility conditions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify multiple matching compatibility conditions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (latest 0-3-0, expected 0-2-0, compatible 0-2-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can specify non-matching compatibility.siteDependencies range > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies_range␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies_range␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies_range/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_site_dependencies_range␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (latest 0-3-0, expected 0-2-0, compatible 0-2-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-2-0: latest version is 0-3-0␊ To upgrade this plugin, please remove it from "netlify.toml" and install it from the Netlify plugins directory instead (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugin versions can be feature flagged > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugin versions that are feature flagged are ignored if no matching feature flag > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-2-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-2-0 from netlify.toml (latest 0-2-0, expected 0-2-0, compatible 0-2-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugin pinned versions that are feature flagged are not ignored if pinned but no matching feature flag > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (pinned 0-3-0, latest 0-2-0, expected 0-3-0, compatible 0-2-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Compatibility order take precedence over the `featureFlag` property > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ testOpts:␊ pluginsListUrl: /test/socket␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/plugins_compat_node_version/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/plugins_compat_node_version␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Installing plugins␊ - netlify-plugin-contextual-env 0-3-0␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ Nothing found... keeping default ENVs␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Pin plugin versions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, { body: { pinned_version: '0.3', }, headers: 'accept accept-encoding authorization connection content-length content-type host user-agent', method: 'PUT', url: '/api/v1/sites/test/plugins/netlify-plugin-contextual-env', }, ] ## Report updatePlugin API error without failing the build > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ API error on "updatePlugin" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Bad Request␊ ␊ Error location␊ While calling the Netlify API endpoint 'updatePlugin' with:␊ {␊ "package": "netlify-plugin-contextual-env",␊ "site_id": "test",␊ "body": {␊ "pinned_version": "0.3"␊ }␊ }␊ ␊ Error properties␊ { name: 'JSONHTTPError', status: 400, json: {} }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, { body: { pinned_version: '0.3', }, headers: 'accept accept-encoding authorization connection content-length content-type host user-agent', method: 'PUT', url: '/api/v1/sites/test/plugins/netlify-plugin-contextual-env', }, ] ## Does not report 404 updatePlugin API error > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, { body: { pinned_version: '0.3', }, headers: 'accept accept-encoding authorization connection content-length content-type host user-agent', method: 'PUT', url: '/api/v1/sites/test/plugins/netlify-plugin-contextual-env', }, ] ## Only pin plugin versions in production > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: false␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Do not pin plugin versions without an API token > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Do not pin plugin versions without a siteId > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Do not pin plugin versions if the build failed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_build_failed␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_build_failed␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_build_failed/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/pin_build_failed␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node --invalid␊ ␊ ────────────────────────────────────────────────────────────────␊ "build.command" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Command failed with exit code 9: node --invalid␊ ␊ Error location␊ In build.command from netlify.toml:␊ node --invalid␊ ␊ Resolved config␊ build:␊ command: node --invalid␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/pin_build_failed␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ node: bad option: --invalid` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Do not pin plugin versions if the plugin failed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_plugin_failed␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_plugin_failed␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_plugin_failed␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "netlify-plugin-contextual-env" failed ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: test␊ ␊ Plugin details␊ Package: netlify-plugin-contextual-env␊ Version: 1.0.0␊ Repository: test␊ npm link: https://www.npmjs.com/package/netlify-plugin-contextual-env␊ ␊ Error location␊ In "onPreBuild" event in "netlify-plugin-contextual-env" from Netlify app␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_plugin_failed␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Do not pin plugin versions if the build was installed in package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_module␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_module␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_module/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_module␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-test␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-test@1.0.0 from netlify.toml and package.json␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-test ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-test onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Do not pin plugin versions if already pinned > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (pinned 0, latest 1-0-0, expected 0, compatible 1-0-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-3-0: latest version is 1-0-0␊ To upgrade this plugin, please uninstall and re-install it from the Netlify plugins directory (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Pinning plugin versions takes into account the compatibility field > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_success␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (pinned 0, latest 1-0-0, expected 0-3-0, compatible 100-0-0)␊ ␊ > Outdated plugins␊ - netlify-plugin-contextual-env 0-3-0: latest version is 1-0-0␊ To upgrade this plugin, please uninstall and re-install it from the Netlify plugins directory (https://app.netlify.com/plugins)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Pin netlify.toml-only plugin versions > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (pinned 0.3, latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding authorization connection host user-agent', method: 'GET', url: '/api/v1/sites/test/plugin_runs/latest?packages%5B%5D=netlify-plugin-contextual-env&state=success', }, { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if there are no matching plugin runs > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding authorization connection host user-agent', method: 'GET', url: '/api/v1/sites/test/plugin_runs/latest?packages%5B%5D=netlify-plugin-contextual-env&state=success', }, { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if there are no plugin runs > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding authorization connection host user-agent', method: 'GET', url: '/api/v1/sites/test/plugin_runs/latest?packages%5B%5D=netlify-plugin-contextual-env&state=success', }, { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if there are no matching plugin runs version > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding authorization connection host user-agent', method: 'GET', url: '/api/v1/sites/test/plugin_runs/latest?packages%5B%5D=netlify-plugin-contextual-env&state=success', }, { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Fails the build when pinning netlify.toml-only plugin versions and the API request fails > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ API error on "getLatestPluginRuns" ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Bad Request␊ ␊ Error location␊ While calling the Netlify API endpoint 'getLatestPluginRuns' with:␊ {␊ "site_id": "test",␊ "packages": [␊ "netlify-plugin-contextual-env"␊ ],␊ "state": "success"␊ }␊ ␊ Error properties␊ {␊ name: 'JSONHTTPError',␊ status: 400,␊ json: [ { package: 'netlify-plugin-contextual-env', version: '1.0.0' } ]␊ }␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding authorization connection host user-agent', method: 'GET', url: '/api/v1/sites/test/plugin_runs/latest?packages%5B%5D=netlify-plugin-contextual-env&state=success', }, ] ## Does not pin netlify.toml-only plugin versions if already pinned > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (pinned 0, latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if installed in UI > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_ui␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_ui␊ ␊ > Config file␊ No config file was defined: using default values.␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_ui␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: ui␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from Netlify app (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if installed in package.json > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_module␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_module␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_module/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_module␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 1-0-1 from netlify.toml and package.json (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if there are no API token > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ siteId: test␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Does not pin netlify.toml-only plugin versions if there are no site ID > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/pin_config_success␊ sendStatus: true␊ testOpts:␊ host: /test/socket␊ pluginsListUrl: /test/socket␊ scheme: http␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/pin_config_success␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/pin_config_success/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/pin_config_success␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: netlify-plugin-contextual-env␊ ␊ > Context␊ production␊ ␊ > Available plugins␊ ␊ > Loading plugins␊ - netlify-plugin-contextual-env 0-3-0 from netlify.toml (latest 0-3-0, expected 0-3-0, compatible 0-3-0)␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from netlify-plugin-contextual-env ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (netlify-plugin-contextual-env onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` > Snapshot 2 [ { body: '', headers: 'accept accept-encoding connection host user-agent', method: 'GET', url: '/', }, ] ## Validate --node-path unsupported version does not fail when no plugins are used > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ nodePath: /external/path␊ repositoryRoot: packages/build/tests/plugins/fixtures/empty␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/empty␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/empty/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/empty␊ publishOrigin: default␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Validate --node-path version is supported by the plugin > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ nodePath: /external/path␊ repositoryRoot: packages/build/tests/plugins/fixtures/engines␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/engines␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/engines/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/engines␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ The Node.js version is 1.0.0 but the plugin "./plugin.js" requires >=1.0.0␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/engines␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js` ## Validate --node-path exists > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ nodePath: /external/path␊ repositoryRoot: packages/build/tests/plugins/fixtures/node_version_simple␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/node_version_simple␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/node_version_simple/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/node_version_simple␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ ────────────────────────────────────────────────────────────────␊ Configuration error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Invalid --node-path CLI flag: /external/path␊ ` ## Provided --node-path version is unused in buildbot for local plugin executions if <10.18.0 > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ mode: buildbot␊ nodePath: /external/path␊ repositoryRoot: packages/build/tests/plugins/fixtures/version_greater_than_minimum␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/version_greater_than_minimum␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/version_greater_than_minimum/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/version_greater_than_minimum␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin.js␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin.js@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin.js ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin.js onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugins can execute local binaries > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/local_bin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/local_bin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/local_bin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/local_bin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ test␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Plugin output can interleave stdout and stderr > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/interleave␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/interleave␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/interleave/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/interleave␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ three␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)␊ ␊ two` ## Plugins can have inputs > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/inputs␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/inputs␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/inputs/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/inputs␊ publishOrigin: default␊ plugins:␊ - inputs:␊ test: true␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ true␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## process.env changes are propagated to other plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/env_changes_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ - ./plugin_two@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onPreBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ one two en_US.UTF-8␊ ␊ (./plugin_two onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one two en_US.UTF-8␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ one two en_US.UTF-8␊ ␊ (./plugin_two onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 5. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ undefined twoChanged en_US.UTF-8␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## process.env changes are propagated to onError and onEnd > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_on_error␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_on_error␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_on_error/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/env_changes_on_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onError command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ ␊ (./plugin onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onEnd command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ ␊ (./plugin onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/env_changes_on_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## process.env changes are propagated to build.command > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_command␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_command␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node print_env1.0.0js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/env_changes_command␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node print_env1.0.0js␊ one two en_US.UTF-8 undefined␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.environment changes are propagated to other plugins > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_build_plugin␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_build_plugin␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_build_plugin/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ - ./plugin_two@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST_ONE" value changed.␊ Netlify configuration property "build.environment.TEST_TWO" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST_ONE␊ - TEST_TWO␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onPreBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ one two en_US.UTF-8␊ ␊ (./plugin_two onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one two en_US.UTF-8␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onBuild command from ./plugin_two ␊ ────────────────────────────────────────────────────────────────␊ ␊ one two en_US.UTF-8␊ Netlify configuration property "build.environment.TEST_ONE" value changed.␊ Netlify configuration property "build.environment.TEST_TWO" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST_ONE␊ - TEST_TWO␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_plugin␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ - inputs: {}␊ origin: config␊ package: ./plugin_two␊ ␊ (./plugin_two onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 5. onPostBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ twoChanged en_US.UTF-8␊ ␊ (./plugin onPostBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.environment changes are propagated to onError and onEnd > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_build_on_error␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_build_on_error␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_build_on_error/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_on_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST_ONE" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST_ONE␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_on_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ ␊ ────────────────────────────────────────────────────────────────␊ 3. onError command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ ␊ (./plugin onError completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 4. onEnd command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one␊ ␊ (./plugin onEnd completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: onBuild␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ In "onBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ environment:␊ - TEST_ONE␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_on_error␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## build.environment changes are propagated to build.command > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_build_command␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_build_command␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_build_command/netlify.toml␊ ␊ > Resolved config␊ build:␊ command: node print_env1.0.0js␊ commandOrigin: config␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_command␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST_ONE" value changed.␊ Netlify configuration property "build.environment.TEST_TWO" value changed.␊ Netlify configuration property "build.environment.LANGUAGE" value changed.␊ ␊ > Updated config␊ build:␊ command: node print_env1.0.0js␊ commandOrigin: config␊ environment:␊ - TEST_ONE␊ - TEST_TWO␊ - LANGUAGE␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_command␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. build.command from netlify.toml ␊ ────────────────────────────────────────────────────────────────␊ ␊ $ node print_env1.0.0js␊ one two en_US.UTF-8 ␊ ␊ (build.command completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## build.environment and process.env changes can be mixed > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/env_changes_build_mix␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/env_changes_build_mix␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/env_changes_build_mix/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_mix␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ Netlify configuration property "build.environment.TEST_ONE" value changed.␊ Netlify configuration property "build.environment.TEST_TWO" value changed.␊ ␊ > Updated config␊ build:␊ environment:␊ - TEST_ONE␊ - TEST_TWO␊ publish: packages/build/tests/plugins/fixtures/env_changes_build_mix␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. onBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ one_environment two␊ ␊ (./plugin onBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Expose some utils > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/keys␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/keys␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/keys/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/keys␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ build cache functions git run status␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Utils are defined > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/defined␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/defined␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/defined/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/defined␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ getCacheDir has list remove restore save␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Can run utils > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_add␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_add␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_add/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_add␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_add/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ The Netlify Functions setting targets a non-existing directory: functions␊ ␊ Packaging Functions from .netlify/functions-internal directory:␊ - test/test.js␊ ␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Can run list util > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/functions_list␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/functions_list␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/functions_list/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/functions_list␊ publishOrigin: default␊ functionsDirectory: packages/build/tests/plugins/fixtures/functions_list/netlify/functions␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ [␊ {␊ "name": "internal_1",␊ "mainFile": "packages/build/tests/plugins/fixtures/functions_list/.netlify/functions-internal/internal_1.js",␊ "runtime": "js",␊ "extension": ".js"␊ },␊ {␊ "name": "user_1",␊ "mainFile": "packages/build/tests/plugins/fixtures/functions_list/netlify/functions/user_1.js",␊ "runtime": "js",␊ "extension": ".js"␊ }␊ ]␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ 2. Functions bundling ␊ ────────────────────────────────────────────────────────────────␊ ␊ Packaging Functions from .netlify/functions-internal directory:␊ - internal_1.js␊ ␊ Packaging Functions from netlify/functions directory:␊ - user_1.js␊ ␊ ␊ (Functions bundling completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Git utils fails if no root > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Invalid head commit HEAD␊ Command failed with exit code 128: git rev-parse HEAD␊ fatal: not a git repository (or any of the parent directories): .git␊ ␊ Error location␊ In "onPreBuild" event in "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Git utils does not fail if no root and not used > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: /tmp-dir␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ /tmp-dir␊ ␊ > Config file␊ /tmp-dir/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: /tmp-dir␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ 1. onPreBuild command from ./plugin ␊ ────────────────────────────────────────────────────────────────␊ ␊ build cache functions git run status␊ ␊ (./plugin onPreBuild completed in 1ms)␊ ␊ ────────────────────────────────────────────────────────────────␊ Netlify Build Complete ␊ ────────────────────────────────────────────────────────────────␊ ␊ (Netlify Build completed in 1ms)` ## Validate plugin is an object > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/object␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/object␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/object/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/object␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Plugin must be an object or a function␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/object␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Validate plugin event handler names > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/handler_name␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/handler_name␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/handler_name/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/handler_name␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ Error: Invalid event 'onInvalid'.␊ Please use a valid event name. One of:␊ - onPreBuild␊ - onBuild␊ - onPostBuild␊ - onSuccess␊ - onError␊ - onEnd␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/handler_name␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` ## Validate plugin event handler function > Snapshot 1 `␊ ────────────────────────────────────────────────────────────────␊ Netlify Build ␊ ────────────────────────────────────────────────────────────────␊ ␊ > Version␊ @netlify/build 1.0.0␊ ␊ > Flags␊ debug: true␊ repositoryRoot: packages/build/tests/plugins/fixtures/handler_function␊ testOpts:␊ pluginsListUrl: test␊ silentLingeringProcesses: true␊ ␊ > Current directory␊ packages/build/tests/plugins/fixtures/handler_function␊ ␊ > Config file␊ packages/build/tests/plugins/fixtures/handler_function/netlify.toml␊ ␊ > Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/handler_function␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin␊ ␊ > Context␊ production␊ ␊ > Loading plugins␊ - ./plugin@1.0.0 from netlify.toml␊ ␊ ────────────────────────────────────────────────────────────────␊ Plugin "./plugin" internal error ␊ ────────────────────────────────────────────────────────────────␊ ␊ Error message␊ TypeError: Invalid event handler 'onBuild': must be a function␊ ␊ Plugin details␊ Package: ./plugin␊ Version: 1.0.0␊ Repository: git+https://github.com/netlify/build.git␊ Report issues: https://github.com/netlify/build/issues␊ ␊ Error location␊ While loading "./plugin" from netlify.toml␊ STACK TRACE␊ ␊ Resolved config␊ build:␊ publish: packages/build/tests/plugins/fixtures/handler_function␊ publishOrigin: default␊ plugins:␊ - inputs: {}␊ origin: config␊ package: ./plugin` <file_sep>'use strict' const STRING_LENGTH = 1e3 module.exports = { onPreBuild() { console.log('a'.repeat(STRING_LENGTH)) console.error('b'.repeat(STRING_LENGTH)) }, onBuild() { console.log('c'.repeat(STRING_LENGTH)) console.error('d'.repeat(STRING_LENGTH)) }, } <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.build.environment = { ...netlifyConfig.build.environment, TEST_TWO: 'two' } }, onBuild({ netlifyConfig: { build: { environment }, }, }) { console.log(environment) }, } <file_sep>'use strict' module.exports = { onPreBuild({ constants: { NETLIFY_BUILD_VERSION } }) { console.log(NETLIFY_BUILD_VERSION) }, } <file_sep>'use strict' const { unlink, writeFile } = require('fs') const { join } = require('path') const { kill, platform } = require('process') const { promisify } = require('util') const zipItAndShipIt = require('@netlify/zip-it-and-ship-it') const test = require('ava') const getNode = require('get-node') const moize = require('moize') const pathExists = require('path-exists') const sinon = require('sinon') const { tmpName } = require('tmp-promise') const { runFixture: runFixtureConfig } = require('../../../config/tests/helpers/main') const { version: netlifyBuildVersion } = require('../../package.json') const { removeDir } = require('../helpers/dir') const { runFixture, FIXTURES_DIR } = require('../helpers/main') const { startServer } = require('../helpers/server') const pWriteFile = promisify(writeFile) const pUnlink = promisify(unlink) test.afterEach.always(() => { if (zipItAndShipIt.zipFunctions.restore) { zipItAndShipIt.zipFunctions.restore() } }) test('--help', async (t) => { await runFixture(t, '', { flags: { help: true }, useBinary: true }) }) test('--version', async (t) => { const { returnValue } = await runFixture(t, '', { flags: { version: true }, useBinary: true }) t.is(returnValue, netlifyBuildVersion) }) test('Exit code is 0 on success', async (t) => { const { exitCode } = await runFixture(t, 'empty', { useBinary: true, snapshot: false }) t.is(exitCode, 0) }) test('Exit code is 1 on build cancellation', async (t) => { const { exitCode } = await runFixture(t, 'cancel', { useBinary: true, snapshot: false }) t.is(exitCode, 1) }) test('Exit code is 2 on user error', async (t) => { const { exitCode } = await runFixture(t, '', { flags: { config: '/invalid' }, useBinary: true, snapshot: false }) t.is(exitCode, 2) }) test('Exit code is 3 on plugin error', async (t) => { const { exitCode } = await runFixture(t, 'plugin_error', { useBinary: true, snapshot: false }) t.is(exitCode, 3) }) test('Success is true on success', async (t) => { const { returnValue: { success }, } = await runFixture(t, 'empty', { programmatic: true, snapshot: false }) t.true(success) }) test('Success is false on build cancellation', async (t) => { const { returnValue: { success }, } = await runFixture(t, 'cancel', { programmatic: true, snapshot: false }) t.false(success) }) test('Success is false on failure', async (t) => { const { returnValue: { success }, } = await runFixture(t, 'plugin_error', { programmatic: true, snapshot: false }) t.false(success) }) test('severityCode is 0 on success', async (t) => { const { returnValue: { severityCode }, } = await runFixture(t, 'empty', { programmatic: true, snapshot: false }) t.is(severityCode, 0) }) test('severityCode is 1 on build cancellation', async (t) => { const { returnValue: { severityCode }, } = await runFixture(t, 'cancel', { programmatic: true, snapshot: false }) t.is(severityCode, 1) }) test('severityCode is 2 on user error', async (t) => { const { returnValue: { severityCode }, } = await runFixture(t, '', { flags: { config: '/invalid' }, programmatic: true, snapshot: false }) t.is(severityCode, 2) }) test('severityCode is 3 on plugin error', async (t) => { const { returnValue: { severityCode }, } = await runFixture(t, 'plugin_error', { programmatic: true, snapshot: false }) t.is(severityCode, 3) }) test('returns config mutations', async (t) => { const { returnValue: { configMutations }, } = await runFixture(t, 'plugin_mutations', { programmatic: true, snapshot: false }) t.deepEqual(configMutations, [ { keys: ['redirects'], keysString: 'redirects', value: [{ from: 'api/*', to: '.netlify/functions/:splat', status: 200 }], event: 'onPreBuild', }, ]) }) test('--cwd', async (t) => { await runFixture(t, '', { flags: { cwd: `${FIXTURES_DIR}/publish` } }) }) test('--repository-root', async (t) => { await runFixture(t, '', { flags: { repositoryRoot: `${FIXTURES_DIR}/empty` } }) }) test('--config', async (t) => { await runFixture(t, '', { flags: { config: `${FIXTURES_DIR}/empty/netlify.toml` } }) }) test('--defaultConfig CLI flag', async (t) => { const defaultConfig = JSON.stringify({ build: { command: 'echo commandDefault' } }) await runFixture(t, 'empty', { flags: { defaultConfig }, useBinary: true }) }) test('--defaultConfig', async (t) => { const defaultConfig = { build: { command: 'echo commandDefault' } } await runFixture(t, 'empty', { flags: { defaultConfig } }) }) test('--cachedConfig CLI flag', async (t) => { const { returnValue } = await runFixtureConfig(t, 'cached_config', { snapshot: false }) await runFixture(t, 'cached_config', { flags: { cachedConfig: returnValue }, useBinary: true }) }) test('--cachedConfigPath CLI flag', async (t) => { const cachedConfigPath = await tmpName() try { await runFixtureConfig(t, 'cached_config', { flags: { output: cachedConfigPath }, snapshot: false, useBinary: true, }) await runFixture(t, 'cached_config', { flags: { cachedConfigPath, context: 'test' }, useBinary: true }) } finally { await pUnlink(cachedConfigPath) } }) test('--cachedConfig', async (t) => { const { returnValue } = await runFixtureConfig(t, 'cached_config', { snapshot: false }) const cachedConfig = JSON.parse(returnValue) await runFixture(t, 'cached_config', { flags: { cachedConfig } }) }) test('--cachedConfigPath', async (t) => { const cachedConfigPath = await tmpName() try { const { returnValue } = await runFixtureConfig(t, 'cached_config', { snapshot: false }) await pWriteFile(cachedConfigPath, returnValue) await runFixture(t, 'cached_config', { flags: { cachedConfigPath, context: 'test' } }) } finally { await pUnlink(cachedConfigPath) } }) test('--context', async (t) => { await runFixture(t, 'context', { flags: { context: 'testContext' } }) }) test('--branch', async (t) => { await runFixture(t, 'context', { flags: { branch: 'testContext' } }) }) test('--baseRelDir', async (t) => { await runFixtureConfig(t, 'basereldir', { flags: { baseRelDir: false } }) }) test('User error', async (t) => { await runFixture(t, '', { flags: { config: '/invalid' } }) }) test('No configuration file', async (t) => { await runFixture(t, 'none') }) test('--dry with one event', async (t) => { await runFixture(t, 'single', { flags: { dry: true } }) }) test('--dry with several events', async (t) => { await runFixture(t, 'several', { flags: { dry: true } }) }) test('--dry-run', async (t) => { await runFixture(t, 'single', { flags: { dryRun: true }, useBinary: true }) }) test('--dry with build.command but no netlify.toml', async (t) => { await runFixture(t, 'none', { flags: { dry: true, defaultConfig: { build: { command: 'echo' } } } }) }) const CHILD_NODE_VERSION = '10.17.0' const VERY_OLD_NODE_VERSION = '4.0.0' // Try `get-node` several times because it sometimes fails due to network failures const getNodeBinary = async function (nodeVersion, retries = 1) { try { return await getNode(nodeVersion) } catch (error) { if (retries < MAX_RETRIES) { return getNodeBinary(nodeVersion, retries + 1) } throw error } } const MAX_RETRIES = 10 // Memoize `get-node` // eslint-disable-next-line no-magic-numbers const mGetNode = moize(getNodeBinary, { isPromise: true, maxSize: 1e3 }) test('--node-path is used by build.command', async (t) => { const { path } = await mGetNode(CHILD_NODE_VERSION) await runFixture(t, 'build_command', { flags: { nodePath: path }, env: { TEST_NODE_PATH: path } }) }) test('--node-path is not used by local plugins', async (t) => { const { path } = await mGetNode(CHILD_NODE_VERSION) await runFixture(t, 'local_node_path_unused', { flags: { nodePath: path }, env: { TEST_NODE_PATH: path } }) }) test('--node-path is not used by plugins added to package.json', async (t) => { const { path } = await mGetNode(CHILD_NODE_VERSION) await runFixture(t, 'package_node_path_unused', { flags: { nodePath: path }, env: { TEST_NODE_PATH: path } }) }) test('--node-path is not used by core plugins', async (t) => { const { path } = await mGetNode(VERY_OLD_NODE_VERSION) await runFixture(t, 'core', { flags: { nodePath: path } }) }) test('featureFlags can be used programmatically', async (t) => { await runFixture(t, 'empty', { flags: { featureFlags: { test: true, testTwo: false } } }) }) test('featureFlags can be used in the CLI', async (t) => { await runFixture(t, 'empty', { flags: { featureFlags: { test: true, testTwo: false } }, useBinary: true }) }) test('featureFlags can be not used', async (t) => { await runFixture(t, 'empty', { flags: { featureFlags: undefined } }) }) const CANCEL_PATH = '/api/v1/deploys/test/cancel' const runWithApiMock = async function (t, flags) { const { scheme, host, requests, stopServer } = await startServer({ path: CANCEL_PATH }) try { await runFixture(t, 'cancel', { flags: { apiHost: host, testOpts: { scheme }, ...flags } }) } finally { await stopServer() } return requests } test('--apiHost is used to set Netlify API host', async (t) => { const requests = await runWithApiMock(t, { token: 'test', deployId: 'test' }) t.is(requests.length, 1) t.snapshot(requests) }) test('Print warning when redirects file is missing from publish directory', async (t) => { await runFixture(t, 'missing_redirects_warning') }) test('Does not print warning when redirects file is not missing from publish directory', async (t) => { await runFixture(t, 'missing_redirects_present') }) test('Does not print warning when redirects file is missing from the build directory', async (t) => { await runFixture(t, 'missing_redirects_absent') }) test('Does not print warning when redirects file is missing both from the build directory and the publish directory', async (t) => { await runFixture(t, 'missing_redirects_none') }) test('Print warning for missing redirects file even with a base directory', async (t) => { await runFixture(t, 'missing_redirects_base') }) test('Print warning when headers file is missing from publish directory', async (t) => { await runFixture(t, 'missing_headers_warning') }) test.serial('Successfully builds ES module function with feature flag', async (t) => { const spy = sinon.spy(zipItAndShipIt, 'zipFunctions') await runFixture(t, 'functions_es_modules', { flags: { featureFlags: { buildbot_es_modules_esbuild: true } }, }) const { args: callArgs } = spy.getCall(0) t.true(callArgs[2].featureFlags.defaultEsModulesToEsbuild) }) test.serial(`Doesn't fail build for ES module function if feature flag is off`, async (t) => { const spy = sinon.spy(zipItAndShipIt, 'zipFunctions') await runFixture(t, 'functions_es_modules', { flags: { featureFlags: { buildbot_es_modules_esbuild: false } }, }) const { args: callArgs } = spy.getCall(0) t.false(callArgs[2].featureFlags.defaultEsModulesToEsbuild) }) test.serial('Passes `parseWithEsbuild` feature flag to zip-it-and-ship-it', async (t) => { const spy = sinon.spy(zipItAndShipIt, 'zipFunctions') await runFixture(t, 'core', { snapshot: false }) await runFixture(t, 'core', { flags: { featureFlags: { buildbot_zisi_esbuild_parser: true } }, snapshot: false, }) t.is(spy.callCount, 2) t.false(spy.firstCall.args[2].featureFlags.parseWithEsbuild) t.true(spy.secondCall.args[2].featureFlags.parseWithEsbuild) }) test('Print warning on lingering processes', async (t) => { const { returnValue } = await runFixture(t, 'lingering', { flags: { testOpts: { silentLingeringProcesses: false }, mode: 'buildbot' }, snapshot: false, }) // Cleanup the lingering process const [, pid] = PID_LINE_REGEXP.exec(returnValue) kill(pid) t.true(returnValue.includes('the following processes were still running')) t.true(returnValue.includes(platform === 'win32' ? 'node.exe' : 'forever.js')) }) const PID_LINE_REGEXP = /^PID: (\d+)$/m test('Functions config is passed to zip-it-and-ship-it (1)', async (t) => { await runFixture(t, 'functions_config_1') }) test('Functions config is passed to zip-it-and-ship-it (2)', async (t) => { await runFixture(t, 'functions_config_2') }) test('Functions config is passed to zip-it-and-ship-it (3)', async (t) => { await runFixture(t, 'functions_config_3') }) test('Shows notice about bundling errors and warnings coming from esbuild', async (t) => { await runFixture(t, 'esbuild_errors_1') }) test('Shows notice about modules with dynamic imports and suggests the usage of `functions.external_node_modules`', async (t) => { await runFixture(t, 'esbuild_errors_2') }) test('Bundles functions from the `.netlify/functions-internal` directory', async (t) => { await runFixture(t, 'functions_internal') }) test('Does not require the `.netlify/functions-internal` directory to exist', async (t) => { await runFixture(t, 'functions_internal_missing') }) test('Does not require the `.netlify/functions-internal` or the user functions directory to exist', async (t) => { await runFixture(t, 'functions_internal_user_missing') }) test('Bundles functions from the `.netlify/functions-internal` directory even if the configured user functions directory is missing', async (t) => { await runFixture(t, 'functions_user_missing') }) // eslint-disable-next-line max-statements test.serial('`rustTargetDirectory` is passed to zip-it-and-ship-it only when running in buildbot', async (t) => { const fixtureWithConfig = 'functions_config_1' const fixtureWithoutConfig = 'functions_internal_missing' const runCount = 4 const spy = sinon.spy(zipItAndShipIt, 'zipFunctions') await runFixture(t, fixtureWithConfig, { flags: { mode: 'buildbot' }, snapshot: false }) await runFixture(t, fixtureWithConfig, { snapshot: false }) await runFixture(t, fixtureWithoutConfig, { flags: { mode: 'buildbot' }, snapshot: false }) await runFixture(t, fixtureWithoutConfig, { snapshot: false }) t.is(spy.callCount, runCount) const { args: call1Args } = spy.getCall(0) const { args: call2Args } = spy.getCall(1) const { args: call3Args } = spy.getCall(2) const { args: call4Args } = spy.getCall(3) t.is( call1Args[2].config['*'].rustTargetDirectory, join(FIXTURES_DIR, fixtureWithConfig, '.netlify', 'rust-functions-cache', '[name]'), ) t.is(call2Args[2].config['*'].rustTargetDirectory, undefined) t.is( call3Args[2].config['*'].rustTargetDirectory, join(FIXTURES_DIR, fixtureWithoutConfig, '.netlify', 'rust-functions-cache', '[name]'), ) t.is(call4Args[2].config['*'].rustTargetDirectory, undefined) }) test('Does not generate a `manifest.json` file when the feature flag is not enabled', async (t) => { const fixtureName = 'functions_internal_no_manifest_2' await removeDir(`${FIXTURES_DIR}/${fixtureName}/.netlify/functions`) await runFixture(t, fixtureName, { flags: { mode: 'buildbot' }, snapshot: false }) t.false(await pathExists(`${FIXTURES_DIR}/${fixtureName}/.netlify/functions/manifest.json`)) }) test('Does not generate a `manifest.json` file when running in buildbot', async (t) => { const fixtureName = 'functions_internal_no_manifest_1' await removeDir(`${FIXTURES_DIR}/${fixtureName}/.netlify/functions`) await runFixture(t, fixtureName, { flags: { featureFlags: { functionsBundlingManifest: true }, mode: 'buildbot' }, snapshot: false, }) t.false(await pathExists(`${FIXTURES_DIR}/${fixtureName}/.netlify/functions/manifest.json`)) }) test('Generates a `manifest.json` file when running outside of buildbot', async (t) => { const fixtureName = 'functions_internal_manifest' await removeDir(`${FIXTURES_DIR}/${fixtureName}/.netlify/functions`) await runFixture(t, fixtureName, { flags: { featureFlags: { functionsBundlingManifest: true }, mode: 'cli' } }) const manifestPath = `${FIXTURES_DIR}/${fixtureName}/.netlify/functions/manifest.json` t.true(await pathExists(manifestPath)) // eslint-disable-next-line import/no-dynamic-require, node/global-require const { functions, timestamp, version: manifestVersion } = require(manifestPath) t.is(functions.length, 3) t.is(typeof timestamp, 'number') t.is(manifestVersion, 1) }) <file_sep>'use strict' const test = require('ava') const { runFixture } = require('../helpers/main') test('Base from defaultConfig', async (t) => { const defaultConfig = { build: { base: 'base' } } await runFixture(t, 'default_config', { flags: { defaultConfig } }) }) test('Base from configuration file property', async (t) => { const { returnValue } = await runFixture(t, 'prop_config') const { buildDir, config: { build: { base, edge_handlers: edgeHandlers, publish }, functionsDirectory, }, } = JSON.parse(returnValue) t.is(base, buildDir) t.true(functionsDirectory.startsWith(buildDir)) t.true(edgeHandlers.startsWith(buildDir)) t.true(publish.startsWith(buildDir)) }) test('Base logic is not recursive', async (t) => { await runFixture(t, 'recursive') }) test('BaseRelDir feature flag', async (t) => { const { returnValue } = await runFixture(t, 'prop_config', { flags: { baseRelDir: false } }) const { buildDir, config: { build: { base, edge_handlers: edgeHandlers, publish }, functionsDirectory, }, } = JSON.parse(returnValue) t.is(base, buildDir) t.false(functionsDirectory.startsWith(buildDir)) t.false(edgeHandlers.startsWith(buildDir)) t.false(publish.startsWith(buildDir)) }) test('Base directory does not exist', async (t) => { await runFixture(t, 'base_invalid') }) test('Use "base" as default value for "publish"', async (t) => { await runFixture(t, 'base_without_publish') }) test('Use "base" as "publish" when it is an empty string', async (t) => { await runFixture(t, 'base_without_publish', { flags: { defaultConfig: { build: { publish: '' } } } }) }) test('Use "base" as "publish" when it is /', async (t) => { await runFixture(t, 'base_without_publish', { flags: { defaultConfig: { build: { publish: '/' } } } }) }) <file_sep>'use strict' const module1 = require('@netlify/imaginary-module-one') const module3 = require('@netlify/imaginary-module-three') const module2 = require('@netlify/imaginary-module-two') module.exports = () => [module1, module2, module3] <file_sep>export const onRequest = function () {} <file_sep>'use strict' const { env } = require('process') module.exports = { onPreBuild({ netlifyConfig: { build: { environment }, }, }) { // eslint-disable-next-line no-param-reassign environment.TEST_ONE = 'one' // eslint-disable-next-line no-param-reassign environment.TEST_TWO = 'two' }, onBuild() { console.log(env.TEST_ONE, env.TEST_TWO, env.LANG) }, onPostBuild() { console.log(env.TEST_ONE, env.TEST_TWO, env.LANG) }, } <file_sep># Changelog ### [2.1.6](https://www.github.com/netlify/build/compare/functions-utils-v2.1.5...functions-utils-v2.1.6) (2021-10-06) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.5 ([#3693](https://www.github.com/netlify/build/issues/3693)) ([3f417f4](https://www.github.com/netlify/build/commit/3f417f4088baa7c6090d86440c06a2df8a66b1cd)) ### [2.1.5](https://www.github.com/netlify/build/compare/functions-utils-v2.1.4...functions-utils-v2.1.5) (2021-10-05) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.4 ([#3687](https://www.github.com/netlify/build/issues/3687)) ([a6ab7b9](https://www.github.com/netlify/build/commit/a6ab7b9dbfebd21bcedcb5dbada4d1620cd6192a)) ### [2.1.4](https://www.github.com/netlify/build/compare/functions-utils-v2.1.3...functions-utils-v2.1.4) (2021-09-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.3 ([#3669](https://www.github.com/netlify/build/issues/3669)) ([cb3fa5f](https://www.github.com/netlify/build/commit/cb3fa5fba1b9e3dd1d7c712d343d3c5adb6db599)) ### [2.1.3](https://www.github.com/netlify/build/compare/functions-utils-v2.1.2...functions-utils-v2.1.3) (2021-09-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.2 ([#3665](https://www.github.com/netlify/build/issues/3665)) ([adc1c43](https://www.github.com/netlify/build/commit/adc1c43fcfb381b79655cddca407d2965a21b61a)) ### [2.1.2](https://www.github.com/netlify/build/compare/functions-utils-v2.1.1...functions-utils-v2.1.2) (2021-09-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.1 ([#3663](https://www.github.com/netlify/build/issues/3663)) ([64cf36d](https://www.github.com/netlify/build/commit/64cf36db8dc441e1670c4b73fa4e74c6d526f4cc)) ### [2.1.1](https://www.github.com/netlify/build/compare/functions-utils-v2.1.0...functions-utils-v2.1.1) (2021-09-23) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.23.0 ([#3653](https://www.github.com/netlify/build/issues/3653)) ([8d36249](https://www.github.com/netlify/build/commit/8d362492ffb2e73d0edfb29968dff8f97319b935)) ## [2.1.0](https://www.github.com/netlify/build/compare/functions-utils-v2.0.10...functions-utils-v2.1.0) (2021-09-21) ### Features * use internal functions directory in functions utils ([#3630](https://www.github.com/netlify/build/issues/3630)) ([7a17b00](https://www.github.com/netlify/build/commit/7a17b007852436b5e259c2fffde58f90abb7ab2c)) ### [2.0.10](https://www.github.com/netlify/build/compare/functions-utils-v2.0.9...functions-utils-v2.0.10) (2021-09-21) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.22.0 ([#3634](https://www.github.com/netlify/build/issues/3634)) ([e1175a3](https://www.github.com/netlify/build/commit/e1175a37c5d1af72bf3298a1060cfd1bf2d4cf07)) ### [2.0.9](https://www.github.com/netlify/build/compare/functions-utils-v2.0.8...functions-utils-v2.0.9) (2021-09-20) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.21.1 ([#3633](https://www.github.com/netlify/build/issues/3633)) ([5f70b85](https://www.github.com/netlify/build/commit/5f70b850f470c18d8b015b0e150b598fe8c8a571)) ### [2.0.8](https://www.github.com/netlify/build/compare/functions-utils-v2.0.7...functions-utils-v2.0.8) (2021-09-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.21.0 ([#3614](https://www.github.com/netlify/build/issues/3614)) ([541da43](https://www.github.com/netlify/build/commit/541da43fd57b1d0413a649d0b948c4f4ff7aba3d)) ### [2.0.7](https://www.github.com/netlify/build/compare/functions-utils-v2.0.6...functions-utils-v2.0.7) (2021-08-24) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.20.0 ([#3551](https://www.github.com/netlify/build/issues/3551)) ([fd2d891](https://www.github.com/netlify/build/commit/fd2d89196ad01882c396894d8f968310bb6bc172)) ### [2.0.6](https://www.github.com/netlify/build/compare/functions-utils-v2.0.5...functions-utils-v2.0.6) (2021-08-20) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.19.0 ([#3535](https://www.github.com/netlify/build/issues/3535)) ([eb11110](https://www.github.com/netlify/build/commit/eb11110b9fc6a54f8f063b2db63c47757b2a3c11)) ### [2.0.5](https://www.github.com/netlify/build/compare/functions-utils-v2.0.4...functions-utils-v2.0.5) (2021-08-19) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.18.0 ([#3530](https://www.github.com/netlify/build/issues/3530)) ([7addb52](https://www.github.com/netlify/build/commit/7addb5290e11065282dc91692ed0c4b5f66990d8)) ### [2.0.4](https://www.github.com/netlify/build/compare/functions-utils-v2.0.3...functions-utils-v2.0.4) (2021-08-10) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.17.0 ([#3409](https://www.github.com/netlify/build/issues/3409)) ([6942dcd](https://www.github.com/netlify/build/commit/6942dcd83b7908710e994b39b5ef4323cf88f039)) ### [2.0.3](https://www.github.com/netlify/build/compare/functions-utils-v2.0.2...functions-utils-v2.0.3) (2021-08-02) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.16.0 ([#3375](https://www.github.com/netlify/build/issues/3375)) ([4d1c90d](https://www.github.com/netlify/build/commit/4d1c90d5218c8d60373a50043ac6cfa6bda1aa9e)) ### [2.0.2](https://www.github.com/netlify/build/compare/functions-utils-v2.0.1...functions-utils-v2.0.2) (2021-07-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.15.1 ([#3344](https://www.github.com/netlify/build/issues/3344)) ([9d9d52f](https://www.github.com/netlify/build/commit/9d9d52f8974a8af298dce47b089bb3c2ba3374ac)) ### [2.0.1](https://www.github.com/netlify/build/compare/functions-utils-v2.0.0...functions-utils-v2.0.1) (2021-07-26) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.15.0 ([#3340](https://www.github.com/netlify/build/issues/3340)) ([3bd2099](https://www.github.com/netlify/build/commit/3bd2099526ba17c351af27d91241d37667caae6b)) ## [2.0.0](https://www.github.com/netlify/build/compare/functions-utils-v1.4.7...functions-utils-v2.0.0) (2021-07-23) ### ⚠ BREAKING CHANGES * deprecate Node 8 (#3322) ### Miscellaneous Chores * deprecate Node 8 ([#3322](https://www.github.com/netlify/build/issues/3322)) ([9cc108a](https://www.github.com/netlify/build/commit/9cc108aab825558204ffef6b8034f456d8d11879)) ### [1.4.7](https://www.github.com/netlify/build/compare/functions-utils-v1.4.6...functions-utils-v1.4.7) (2021-07-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.14.0 ([#3293](https://www.github.com/netlify/build/issues/3293)) ([a371a0d](https://www.github.com/netlify/build/commit/a371a0dbdb3a7c8a05674ab9d6255635cd63d727)) ### [1.4.6](https://www.github.com/netlify/build/compare/functions-utils-v1.4.5...functions-utils-v1.4.6) (2021-07-14) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.13.1 ([#3288](https://www.github.com/netlify/build/issues/3288)) ([f5e5b6b](https://www.github.com/netlify/build/commit/f5e5b6ba91a8ad9e95d4dea5c18078a8e334313a)) ### [1.4.5](https://www.github.com/netlify/build/compare/functions-utils-v1.4.4...functions-utils-v1.4.5) (2021-07-12) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.13.0 ([#3280](https://www.github.com/netlify/build/issues/3280)) ([8249fe1](https://www.github.com/netlify/build/commit/8249fe19d1edab64fad2362757d59d33fabe18c2)) ### [1.4.4](https://www.github.com/netlify/build/compare/functions-utils-v1.4.3...functions-utils-v1.4.4) (2021-07-07) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.12.0 ([#3228](https://www.github.com/netlify/build/issues/3228)) ([3c8a3c6](https://www.github.com/netlify/build/commit/3c8a3c6a4a0e3a29f984739613b6f823b1d7f38c)) ### [1.4.3](https://www.github.com/netlify/build/compare/functions-utils-v1.4.2...functions-utils-v1.4.3) (2021-07-05) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.11.0 ([#3202](https://www.github.com/netlify/build/issues/3202)) ([37df6bd](https://www.github.com/netlify/build/commit/37df6bd5ce55e3176f336285e3b17b9982d8f2f2)) ### [1.4.2](https://www.github.com/netlify/build/compare/functions-utils-v1.4.1...functions-utils-v1.4.2) (2021-07-05) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.9.0 ([#3181](https://www.github.com/netlify/build/issues/3181)) ([1d733f6](https://www.github.com/netlify/build/commit/1d733f69f30db1e06722c1e0b7cd167e1e8ddad9)) ### [1.4.1](https://www.github.com/netlify/build/compare/functions-utils-v1.4.0...functions-utils-v1.4.1) (2021-06-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.8.0 ([#3137](https://www.github.com/netlify/build/issues/3137)) ([872db54](https://www.github.com/netlify/build/commit/872db544c2d1b798e8a93024c2c8b7fb87bf3f04)) ## [1.4.0](https://www.github.com/netlify/build/compare/functions-utils-v1.3.47...functions-utils-v1.4.0) (2021-06-28) ### Features * update dependency @netlify/zip-it-and-ship-it to v4.7.0 ([#3123](https://www.github.com/netlify/build/issues/3123)) ([c70b708](https://www.github.com/netlify/build/commit/c70b70881f836693dff6994287f23bcfe3d25bb9)) ### [1.3.47](https://www.github.com/netlify/build/compare/functions-utils-v1.3.46...functions-utils-v1.3.47) (2021-06-24) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v4.6.0 ([#3105](https://www.github.com/netlify/build/issues/3105)) ([b2c53c7](https://www.github.com/netlify/build/commit/b2c53c789faa5c29295bb2f0209020cd0d9af7b6)) ### [1.3.46](https://www.github.com/netlify/build/compare/functions-utils-v1.3.45...functions-utils-v1.3.46) (2021-06-23) ### Bug Fixes * pin zip-it-and-ship-it to version 4.4.2 ([#3095](https://www.github.com/netlify/build/issues/3095)) ([86a00ce](https://www.github.com/netlify/build/commit/86a00ce3d5ee0bb5e9158ce81531459215ac0015)) ### [1.3.45](https://www.github.com/netlify/build/compare/functions-utils-v1.3.44...functions-utils-v1.3.45) (2021-06-22) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.5.1 ([#3088](https://www.github.com/netlify/build/issues/3088)) ([192d1ff](https://www.github.com/netlify/build/commit/192d1ff219ab5e091e6023d4f14933b1e7cc5230)) ### [1.3.44](https://www.github.com/netlify/build/compare/functions-utils-v1.3.43...functions-utils-v1.3.44) (2021-06-22) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.4.2 ([#3070](https://www.github.com/netlify/build/issues/3070)) ([673f684](https://www.github.com/netlify/build/commit/673f68442849774c62969049e3f0bd7e22ed40b0)) ### [1.3.43](https://www.github.com/netlify/build/compare/functions-utils-v1.3.42...functions-utils-v1.3.43) (2021-06-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.4.1 ([#3034](https://www.github.com/netlify/build/issues/3034)) ([034f13a](https://www.github.com/netlify/build/commit/034f13a59a7ba73b3b0c9b46752b67d971e1a8ac)) ### [1.3.42](https://www.github.com/netlify/build/compare/functions-utils-v1.3.41...functions-utils-v1.3.42) (2021-06-15) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v4.4.0 ([#3011](https://www.github.com/netlify/build/issues/3011)) ([f49b8c3](https://www.github.com/netlify/build/commit/f49b8c3024f070187a66b3f713b1cb3a5154ab0f)) ### [1.3.41](https://www.github.com/netlify/build/compare/functions-utils-v1.3.40...functions-utils-v1.3.41) (2021-06-14) ### Bug Fixes * pin zisi version in functions utils ([#3023](https://www.github.com/netlify/build/issues/3023)) ([9c6b09b](https://www.github.com/netlify/build/commit/9c6b09b89d5b3e1552eb848aea016092c6abcf5e)) ### [1.3.40](https://www.github.com/netlify/build/compare/functions-utils-v1.3.39...functions-utils-v1.3.40) (2021-06-09) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.3.0 ([#2959](https://www.github.com/netlify/build/issues/2959)) ([a5f7b64](https://www.github.com/netlify/build/commit/a5f7b64c6d5a43ec330db989c3862679aa91ea0f)) ### [1.3.39](https://www.github.com/netlify/build/compare/functions-utils-v1.3.38...functions-utils-v1.3.39) (2021-06-04) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.7 ([#2910](https://www.github.com/netlify/build/issues/2910)) ([a96240f](https://www.github.com/netlify/build/commit/a96240f54c4842634d0e2756a9891934926e71f7)) ### [1.3.38](https://www.github.com/netlify/build/compare/functions-utils-v1.3.37...functions-utils-v1.3.38) (2021-06-02) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.6 ([#2900](https://www.github.com/netlify/build/issues/2900)) ([6ae857d](https://www.github.com/netlify/build/commit/6ae857d99cdf69ac9f70cc96a891c9c14804b4a2)) ### [1.3.37](https://www.github.com/netlify/build/compare/functions-utils-v1.3.36...functions-utils-v1.3.37) (2021-05-31) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.5 ([#2891](https://www.github.com/netlify/build/issues/2891)) ([5ccd5f5](https://www.github.com/netlify/build/commit/5ccd5f51c553fd5f588065b384a795d90837ac85)) ### [1.3.36](https://www.github.com/netlify/build/compare/functions-utils-v1.3.35...functions-utils-v1.3.36) (2021-05-31) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.2 ([#2886](https://www.github.com/netlify/build/issues/2886)) ([a4a0549](https://www.github.com/netlify/build/commit/a4a05497ba9809bc6420b31514f690badba4bc53)) ### [1.3.35](https://www.github.com/netlify/build/compare/functions-utils-v1.3.34...functions-utils-v1.3.35) (2021-05-28) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.1 ([#2870](https://www.github.com/netlify/build/issues/2870)) ([6e576b2](https://www.github.com/netlify/build/commit/6e576b252fb08a8e70c0f17e178ff54aede1e272)) ### [1.3.34](https://www.github.com/netlify/build/compare/functions-utils-v1.3.33...functions-utils-v1.3.34) (2021-05-27) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.2.0 ([#2861](https://www.github.com/netlify/build/issues/2861)) ([1bd75f8](https://www.github.com/netlify/build/commit/1bd75f89509c4859cb3e31908d3ce54985142d7c)) ### [1.3.33](https://www.github.com/netlify/build/compare/functions-utils-v1.3.32...functions-utils-v1.3.33) (2021-05-26) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.1.0 ([#2853](https://www.github.com/netlify/build/issues/2853)) ([8269428](https://www.github.com/netlify/build/commit/826942805e8b02aa2462fa547890a263d5b4fbd8)) ### [1.3.32](https://www.github.com/netlify/build/compare/functions-utils-v1.3.31...functions-utils-v1.3.32) (2021-05-17) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^4.0.1 ([#2814](https://www.github.com/netlify/build/issues/2814)) ([122446e](https://www.github.com/netlify/build/commit/122446edb82aa597f1882c543664fbf683744904)) ### [1.3.31](https://www.github.com/netlify/build/compare/functions-utils-v1.3.30...functions-utils-v1.3.31) (2021-05-17) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v4 ([#2800](https://www.github.com/netlify/build/issues/2800)) ([5575708](https://www.github.com/netlify/build/commit/5575708ab19384103dd0e8c477e0ae672750c6cf)) ### [1.3.30](https://www.github.com/netlify/build/compare/functions-utils-v1.3.29...functions-utils-v1.3.30) (2021-05-12) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.10.0 ([#2776](https://www.github.com/netlify/build/issues/2776)) ([e8599eb](https://www.github.com/netlify/build/commit/e8599ebaac5828fbd143dc54bd14abeb1aee6732)) ### [1.3.29](https://www.github.com/netlify/build/compare/functions-utils-v1.3.28...functions-utils-v1.3.29) (2021-05-04) ### Bug Fixes * **deps:** update netlify packages ([#2735](https://www.github.com/netlify/build/issues/2735)) ([6060bab](https://www.github.com/netlify/build/commit/6060babcee003881df46f45eda1118b7737cc4e1)) ### [1.3.28](https://www.github.com/netlify/build/compare/functions-utils-v1.3.27...functions-utils-v1.3.28) (2021-04-23) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.7.0 ([#2633](https://www.github.com/netlify/build/issues/2633)) ([4938a1c](https://www.github.com/netlify/build/commit/4938a1ca36a8dffcec5fb2b10a4e08ac451a8ba7)) ### [1.3.27](https://www.github.com/netlify/build/compare/functions-utils-v1.3.26...functions-utils-v1.3.27) (2021-04-21) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.6.0 ([#2626](https://www.github.com/netlify/build/issues/2626)) ([63e0330](https://www.github.com/netlify/build/commit/63e033014a78229daa9b11360abd24944561ec12)) ### [1.3.26](https://www.github.com/netlify/build/compare/functions-utils-v1.3.25...functions-utils-v1.3.26) (2021-04-20) ### Bug Fixes * **deps:** update netlify packages ([#2622](https://www.github.com/netlify/build/issues/2622)) ([4d35de4](https://www.github.com/netlify/build/commit/4d35de4d4d8d49b460080480c6e5b3610e6ef023)) ### [1.3.25](https://www.github.com/netlify/build/compare/functions-utils-v1.3.24...functions-utils-v1.3.25) (2021-04-16) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.4.0 ([#2609](https://www.github.com/netlify/build/issues/2609)) ([83da9dc](https://www.github.com/netlify/build/commit/83da9dc609296f4cd7409c923e14e6772c2e4463)) ### [1.3.24](https://www.github.com/netlify/build/compare/functions-utils-v1.3.23...functions-utils-v1.3.24) (2021-04-14) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.2.1 ([#2592](https://www.github.com/netlify/build/issues/2592)) ([3fae367](https://www.github.com/netlify/build/commit/3fae3679e78734d2dad9e199870419f22cffd9c9)) * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.3.0 ([#2598](https://www.github.com/netlify/build/issues/2598)) ([5eeed10](https://www.github.com/netlify/build/commit/5eeed1075e0b65aa656be065558668b451896ac7)) ### [1.3.23](https://www.github.com/netlify/build/compare/functions-utils-v1.3.22...functions-utils-v1.3.23) (2021-04-07) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.2.0 ([#2552](https://www.github.com/netlify/build/issues/2552)) ([26b379e](https://www.github.com/netlify/build/commit/26b379e10feb5ee26c3fd426df05a21c0eafb4f1)) ### [1.3.22](https://www.github.com/netlify/build/compare/functions-utils-v1.3.21...functions-utils-v1.3.22) (2021-04-06) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^3.1.0 ([#2536](https://www.github.com/netlify/build/issues/2536)) ([fc694be](https://www.github.com/netlify/build/commit/fc694be35a186ef362c3e1e541d0e4c65af7109d)) ### [1.3.21](https://www.github.com/netlify/build/compare/v1.3.20...v1.3.21) (2021-03-18) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v3 ([#2434](https://www.github.com/netlify/build/issues/2434)) ([fa042b9](https://www.github.com/netlify/build/commit/fa042b974eb5aa87c43d74b60573a3bb77e55e56)) ### [1.3.20](https://www.github.com/netlify/build/compare/v1.3.19...v1.3.20) (2021-03-12) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.7.1 ([#2396](https://www.github.com/netlify/build/issues/2396)) ([b4c070f](https://www.github.com/netlify/build/commit/b4c070fa8ac1406b3f489e5ddb038e4ecbe1f68c)) ### [1.3.19](https://www.github.com/netlify/build/compare/v1.3.18...v1.3.19) (2021-03-11) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.7.0 ([#2391](https://www.github.com/netlify/build/issues/2391)) ([0c1c1dc](https://www.github.com/netlify/build/commit/0c1c1dcce06fc511ba2c26bf2fb52b91e202b670)) ### [1.3.18](https://www.github.com/netlify/build/compare/v1.3.17...v1.3.18) (2021-03-10) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.6.0 ([#2384](https://www.github.com/netlify/build/issues/2384)) ([4311b02](https://www.github.com/netlify/build/commit/4311b02530807eee9b83f063923f0d1932c9ec85)) ### [1.3.17](https://www.github.com/netlify/build/compare/v1.3.16...v1.3.17) (2021-03-04) ### Bug Fixes * **deps:** update netlify packages ([#2352](https://www.github.com/netlify/build/issues/2352)) ([c45bdc8](https://www.github.com/netlify/build/commit/c45bdc8e6165751b4294993426ff32e366f0c55a)) ### [1.3.16](https://www.github.com/netlify/build/compare/v1.3.15...v1.3.16) (2021-03-03) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.4.3 ([#2346](https://www.github.com/netlify/build/issues/2346)) ([76607df](https://www.github.com/netlify/build/commit/76607dff6de5594d2ebbabfb824737d2ce92e902)) ### [1.3.15](https://www.github.com/netlify/build/compare/v1.3.14...v1.3.15) (2021-03-03) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.4.2 ([#2341](https://www.github.com/netlify/build/issues/2341)) ([cbba54d](https://www.github.com/netlify/build/commit/cbba54dea815e61fe40e048de664035fd06df36d)) ### [1.3.14](https://www.github.com/netlify/build/compare/v1.3.13...v1.3.14) (2021-02-26) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to ^2.4.0 ([#2312](https://www.github.com/netlify/build/issues/2312)) ([1dbf0a1](https://www.github.com/netlify/build/commit/1dbf0a1463e33fee4a69e90fbf5d128bfdc22081)) ### [1.3.13](https://www.github.com/netlify/build/compare/v1.3.12...v1.3.13) (2021-02-18) ### Bug Fixes * fix `files` in `package.json` with `npm@7` ([#2278](https://www.github.com/netlify/build/issues/2278)) ([e9df064](https://www.github.com/netlify/build/commit/e9df0645f3083a0bb141c8b5b6e474ed4e27dbe9)) ### [1.3.12](https://www.github.com/netlify/build/compare/v1.3.11...v1.3.12) (2021-02-11) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.3.0 ([#2264](https://www.github.com/netlify/build/issues/2264)) ([40d122d](https://www.github.com/netlify/build/commit/40d122d6e722e55f1925f4179999d0d7ad065999)) ### [1.3.11](https://www.github.com/netlify/build/compare/v1.3.10...v1.3.11) (2021-02-08) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.2.0 ([#2258](https://www.github.com/netlify/build/issues/2258)) ([6faf36b](https://www.github.com/netlify/build/commit/6faf36b24d66f88f93dc96d0190a80af459ad5f4)) ### [1.3.10](https://www.github.com/netlify/build/compare/v1.3.9...v1.3.10) (2021-02-03) ### Bug Fixes * **deps:** force a release for [#2244](https://www.github.com/netlify/build/issues/2244) and bump zip-it-and-ship-it ([#2245](https://www.github.com/netlify/build/issues/2245)) ([25787c2](https://www.github.com/netlify/build/commit/25787c2cf134fbbd8029a142512ff314cbab1951)) ### [1.3.9](https://www.github.com/netlify/build/compare/v1.3.8...v1.3.9) (2021-01-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.3 ([#2227](https://www.github.com/netlify/build/issues/2227)) ([301fe88](https://www.github.com/netlify/build/commit/301fe885ed1a896e7b0766fcc85386510ff9f670)) ### [1.3.8](https://www.github.com/netlify/build/compare/v1.3.7...v1.3.8) (2021-01-29) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.2 ([#2222](https://www.github.com/netlify/build/issues/2222)) ([47adf7a](https://www.github.com/netlify/build/commit/47adf7af089f308b9abe7709675bc84b8f179809)) ### [1.3.7](https://www.github.com/netlify/build/compare/v1.3.6...v1.3.7) (2021-01-26) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.1 ([#2215](https://www.github.com/netlify/build/issues/2215)) ([f6e191e](https://www.github.com/netlify/build/commit/f6e191edbb3bf43ac1b9d75b7e0ab62fabd2062f)) ### [1.3.6](https://www.github.com/netlify/build/compare/v1.3.5...v1.3.6) (2021-01-22) ### Bug Fixes * **deps:** update dependency @netlify/zip-it-and-ship-it to v2.1.0 ([#2197](https://www.github.com/netlify/build/issues/2197)) ([8ed28f9](https://www.github.com/netlify/build/commit/8ed28f9ccbe991f98cf8dcf2acde4c19f01c246d)) ### [1.3.5](https://www.github.com/netlify/build/compare/functions-utils-v1.3.4...v1.3.5) (2021-01-15) ### Bug Fixes * **deps:** update netlify packages ([#2173](https://www.github.com/netlify/build/issues/2173)) ([aba86ab](https://www.github.com/netlify/build/commit/aba86abef35c19d619c60dbb84ad6540afef73a7)) <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig, constants: { FUNCTIONS_SRC } }) { console.log(FUNCTIONS_SRC) // eslint-disable-next-line no-param-reassign netlifyConfig.functions.directory = 'test_functions' }, onBuild({ netlifyConfig, constants: { FUNCTIONS_SRC } }) { console.log(FUNCTIONS_SRC) // eslint-disable-next-line no-param-reassign netlifyConfig.functions.directory = '' }, onPostBuild({ constants: { FUNCTIONS_SRC } }) { console.log(FUNCTIONS_SRC) }, } <file_sep>'use strict' module.exports = { onError() { throw new Error('onError') }, } <file_sep>import { foo } from '../helper' export default foo <file_sep>/* eslint-disable max-lines */ 'use strict' require('./utils/polyfills') const { getApiClient } = require('./api/client') const { getSiteInfo } = require('./api/site_info') const { getInitialBase, getBase, addBase } = require('./base') const { getBuildDir } = require('./build_dir') const { getCachedConfig } = require('./cached_config') const { normalizeContextProps, mergeContext } = require('./context') const { parseDefaultConfig } = require('./default') const { getEnv } = require('./env/main') const { EVENTS } = require('./events') const { resolveConfigPaths } = require('./files') const { getHeadersPath, addHeaders } = require('./headers') const { getInlineConfig } = require('./inline_config') const { cleanupConfig } = require('./log/cleanup') const { logResult } = require('./log/main') const { mergeConfigs } = require('./merge') const { normalizeBeforeConfigMerge, normalizeAfterConfigMerge } = require('./merge_normalize') const { updateConfig, restoreConfig } = require('./mutations/update') const { addDefaultOpts, normalizeOpts } = require('./options/main') const { UI_ORIGIN, CONFIG_ORIGIN, INLINE_ORIGIN } = require('./origin') const { parseConfig } = require('./parse') const { getConfigPath } = require('./path') // eslint-disable-next-line import/max-dependencies const { getRedirectsPath, addRedirects } = require('./redirects') // Load the configuration file. // Takes an optional configuration file path as input and return the resolved // `config` together with related properties such as the `configPath`. const resolveConfig = async function (opts) { const { cachedConfig, cachedConfigPath, host, scheme, pathPrefix, testOpts, token, offline, ...optsA } = addDefaultOpts(opts) // `api` is not JSON-serializable, so we cannot cache it inside `cachedConfig` const api = getApiClient({ token, offline, host, scheme, pathPrefix, testOpts }) const parsedCachedConfig = await getCachedConfig({ cachedConfig, cachedConfigPath, token, api }) if (parsedCachedConfig !== undefined) { return parsedCachedConfig } const { config: configOpt, defaultConfig, inlineConfig, configMutations, cwd, context, repositoryRoot, base, branch, siteId, deployId, buildId, baseRelDir, mode, debug, logs, featureFlags, } = await normalizeOpts(optsA) const { siteInfo, accounts, addons } = await getSiteInfo({ api, siteId, mode, testOpts }) const { defaultConfig: defaultConfigA, baseRelDir: baseRelDirA } = parseDefaultConfig({ defaultConfig, base, baseRelDir, siteInfo, logs, debug, }) const inlineConfigA = getInlineConfig({ inlineConfig, configMutations, logs, debug }) const { configPath, config, buildDir, redirectsPath, headersPath } = await loadConfig({ configOpt, cwd, context, repositoryRoot, branch, defaultConfig: defaultConfigA, inlineConfig: inlineConfigA, baseRelDir: baseRelDirA, logs, featureFlags, }) const env = await getEnv({ mode, config, siteInfo, accounts, addons, buildDir, branch, deployId, buildId, context, }) // @todo Remove in the next major version. const configA = addLegacyFunctionsDirectory(config) const result = { siteInfo, accounts, addons, env, configPath, redirectsPath, headersPath, buildDir, repositoryRoot, config: configA, context, branch, token, api, logs, } logResult(result, { logs, debug }) return result } // Adds a `build.functions` property that mirrors `functionsDirectory`, for // backward compatibility. const addLegacyFunctionsDirectory = (config) => { if (!config.functionsDirectory) { return config } return { ...config, build: { ...config.build, functions: config.functionsDirectory, }, } } // Try to load the configuration file in two passes. // The first pass uses the `defaultConfig`'s `build.base` (if defined). // The second pass uses the `build.base` from the first pass (if defined). const loadConfig = async function ({ configOpt, cwd, context, repositoryRoot, branch, defaultConfig, inlineConfig, baseRelDir, logs, featureFlags, }) { const initialBase = getInitialBase({ repositoryRoot, defaultConfig, inlineConfig }) const { configPath, config, buildDir, base, redirectsPath, headersPath } = await getFullConfig({ configOpt, cwd, context, repositoryRoot, branch, defaultConfig, inlineConfig, baseRelDir, configBase: initialBase, logs, featureFlags, }) // No second pass needed if: // - there is no `build.base` (in which case both `base` and `initialBase` // are `undefined`) // - `build.base` is the same as the `Base directory` UI setting (already // used in the first round) // - `baseRelDir` feature flag is not used. This feature flag was introduced // to ensure backward compatibility. if (!baseRelDir || base === initialBase) { return { configPath, config, buildDir, redirectsPath, headersPath } } const { configPath: configPathA, config: configA, buildDir: buildDirA, redirectsPath: redirectsPathA, headersPath: headersPathA, } = await getFullConfig({ cwd, context, repositoryRoot, branch, defaultConfig, inlineConfig, baseRelDir, configBase: base, base, logs, featureFlags, }) return { configPath: configPathA, config: configA, buildDir: buildDirA, redirectsPath: redirectsPathA, headersPath: headersPathA, } } // Load configuration file and normalize it, merge contexts, etc. const getFullConfig = async function ({ configOpt, cwd, context, repositoryRoot, branch, defaultConfig, inlineConfig, baseRelDir, configBase, base, logs, featureFlags, }) { const configPath = await getConfigPath({ configOpt, cwd, repositoryRoot, configBase }) try { const config = await parseConfig(configPath, logs, featureFlags) const configA = mergeAndNormalizeConfig({ config, defaultConfig, inlineConfig, context, branch, logs, }) const { config: configB, buildDir, base: baseA, } = await resolveFiles({ config: configA, repositoryRoot, base, baseRelDir }) const headersPath = getHeadersPath(configB) const configC = await addHeaders(configB, headersPath, logs) const redirectsPath = getRedirectsPath(configC) const configD = await addRedirects(configC, redirectsPath, logs) return { configPath, config: configD, buildDir, base: baseA, redirectsPath, headersPath } } catch (error) { const configName = configPath === undefined ? '' : ` file ${configPath}` error.message = `When resolving config${configName}:\n${error.message}` throw error } } // Merge: // - `--defaultConfig`: UI build settings and UI-installed plugins // - `inlineConfig`: Netlify CLI flags // Then merge context-specific configuration. // Before and after those steps, also performs validation and normalization. // Those need to be done at different stages depending on whether they should // happen before/after the merges mentioned above. const mergeAndNormalizeConfig = function ({ config, defaultConfig, inlineConfig, context, branch, logs }) { const configA = normalizeConfigAndContext(config, CONFIG_ORIGIN) const defaultConfigA = normalizeConfigAndContext(defaultConfig, UI_ORIGIN) const inlineConfigA = normalizeConfigAndContext(inlineConfig, INLINE_ORIGIN) const configB = mergeConfigs([defaultConfigA, configA]) const configC = mergeContext({ config: configB, context, branch, logs }) const configD = mergeConfigs([configC, inlineConfigA]) const configE = normalizeAfterConfigMerge(configD) return configE } const normalizeConfigAndContext = function (config, origin) { const configA = normalizeBeforeConfigMerge(config, origin) const configB = normalizeContextProps({ config: configA, origin }) return configB } // Find base directory, build directory and resolve all paths to absolute paths const resolveFiles = async function ({ config, repositoryRoot, base, baseRelDir }) { const baseA = getBase(base, repositoryRoot, config) const buildDir = await getBuildDir(repositoryRoot, baseA) const configA = await resolveConfigPaths({ config, repositoryRoot, buildDir, baseRelDir }) const configB = addBase(configA, baseA) return { config: configB, buildDir, base: baseA } } module.exports = resolveConfig // TODO: on next major release, export a single object instead of mutating the // top-level function module.exports.cleanupConfig = cleanupConfig module.exports.updateConfig = updateConfig module.exports.restoreConfig = restoreConfig module.exports.EVENTS = EVENTS /* eslint-enable max-lines */ <file_sep>'use strict' const test = require('ava') const { red } = require('chalk') const hasAnsi = require('has-ansi') // const isCI = require('is-ci') const { runFixture } = require('../helpers/main') // Common options for color-related tests const opts = { snapshot: false, normalize: false, useBinary: true } test('Colors in parent process', async (t) => { const { returnValue } = await runFixture(t, 'parent', { ...opts, flags: { dry: true }, env: { FORCE_COLOR: '1' } }) t.true(hasAnsi(returnValue)) }) test('Colors in child process', async (t) => { const { returnValue } = await runFixture(t, 'child', { ...opts, env: { FORCE_COLOR: '1' } }) t.true(returnValue.includes(red('onPreBuild'))) }) test('Netlify CI', async (t) => { const { returnValue } = await runFixture(t, 'parent', { ...opts, flags: { dry: true, mode: 'buildbot' }, env: { FORCE_COLOR: '1' }, }) t.true(hasAnsi(returnValue)) }) test('No TTY', async (t) => { const { returnValue } = await runFixture(t, 'parent', { ...opts, env: { FORCE_COLOR: '0' }, flags: { dry: true } }) t.false(hasAnsi(returnValue)) }) // In GitHub actions, `update-notifier` is never enabled // @todo: uncomment after upgrading to Ava v4. // See https://github.com/netlify/build/issues/3615 // if (!isCI) { // test('Print a warning when using an old version through Netlify CLI', async (t) => { // // We need to unset some environment variables which would otherwise disable `update-notifier` // await runFixture(t, 'error', { // flags: { mode: 'cli', testOpts: { oldCliLogs: true } }, // env: { NODE_ENV: '' }, // useBinary: true, // }) // }) // } test('Logs whether the build commands came from the UI', async (t) => { const defaultConfig = { build: { command: 'node --invalid' } } await runFixture(t, 'empty', { flags: { defaultConfig } }) }) <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig: { headers, build } }) { console.log(headers) // eslint-disable-next-line no-param-reassign build.publish = 'test' }, onBuild({ netlifyConfig: { headers } }) { console.log(headers) }, } <file_sep># Changelog ### [2.0.2](https://www.github.com/netlify/build/compare/git-utils-v2.0.1...git-utils-v2.0.2) (2021-09-17) ### Bug Fixes * `utils.git` crashes when commit messages or authors have uncommon characters ([#3623](https://www.github.com/netlify/build/issues/3623)) ([895a06c](https://www.github.com/netlify/build/commit/895a06cc998f3f75c3fd204f887fad9c0e45e67d)) ### [2.0.1](https://www.github.com/netlify/build/compare/git-utils-v2.0.0...git-utils-v2.0.1) (2021-08-12) ### Bug Fixes * **deps:** bump execa to the latest version (5.x) ([#3440](https://www.github.com/netlify/build/issues/3440)) ([3e8bd01](https://www.github.com/netlify/build/commit/3e8bd019eddca738a664af9590c313dd5fcd20df)) ## [2.0.0](https://www.github.com/netlify/build/compare/git-utils-v1.0.11...git-utils-v2.0.0) (2021-07-23) ### ⚠ BREAKING CHANGES * deprecate Node 8 (#3322) ### Miscellaneous Chores * deprecate Node 8 ([#3322](https://www.github.com/netlify/build/issues/3322)) ([9cc108a](https://www.github.com/netlify/build/commit/9cc108aab825558204ffef6b8034f456d8d11879)) ### [1.0.11](https://www.github.com/netlify/build/compare/git-utils-v1.0.10...git-utils-v1.0.11) (2021-05-03) ### Bug Fixes * **deps:** update dependency map-obj to v4 ([#2721](https://www.github.com/netlify/build/issues/2721)) ([17559dc](https://www.github.com/netlify/build/commit/17559dcc75dd9f9a73f2a604c9f8ef3140a91b42)) ### [1.0.10](https://www.github.com/netlify/build/compare/git-utils-v1.0.9...git-utils-v1.0.10) (2021-04-26) ### Bug Fixes * **deps:** update dependency map-obj to v3.1.0 ([#2656](https://www.github.com/netlify/build/issues/2656)) ([89e497a](https://www.github.com/netlify/build/commit/89e497a37a892f203a601a510e0e24ae037ad146)) ### [1.0.9](https://www.github.com/netlify/build/compare/git-utils-v1.0.8...git-utils-v1.0.9) (2021-04-23) ### Bug Fixes * fix `utils.git` for repositories with `main` branch ([#2638](https://www.github.com/netlify/build/issues/2638)) ([5f80961](https://www.github.com/netlify/build/commit/5f80961e25387deee9b37bba07379adc1fed44c3)) ### [1.0.8](https://www.github.com/netlify/build/compare/v1.0.7...v1.0.8) (2021-02-18) ### Bug Fixes * fix `files` in `package.json` with `npm@7` ([#2278](https://www.github.com/netlify/build/issues/2278)) ([e9df064](https://www.github.com/netlify/build/commit/e9df0645f3083a0bb141c8b5b6e474ed4e27dbe9)) ### [1.0.7](https://www.github.com/netlify/build/compare/git-utils-v1.0.6...v1.0.7) (2021-02-01) ### Bug Fixes * **deps:** update dependency moize to v6 ([#2231](https://www.github.com/netlify/build/issues/2231)) ([e34454c](https://www.github.com/netlify/build/commit/e34454c633bbc541c4074bdaa15361c84f0c8f04)) <file_sep>'use strict' module.exports = { onPreBuild() { console.log('onPreBuild') }, onBuild() { console.log('onBuild') }, } <file_sep>'use strict' const { exit } = require('process') const test = function () { console.log(new Error('test')) exit(2) } test() <file_sep>'use strict' module.exports = { onPreBuild({ constants: { IS_LOCAL } }) { console.log(IS_LOCAL) }, } <file_sep>'use strict' const { emitWarning } = require('process') const { promisify } = require('util') // TODO: replace with `timers/promises` after dropping Node < 15.0.0 const pSetTimeout = promisify(setTimeout) // 1 second const WARNING_TIMEOUT = 1e3 module.exports = { async onPreBuild() { emitWarning('test') console.log('onPreBuild') await pSetTimeout(WARNING_TIMEOUT) }, } <file_sep>'use strict' const { env } = require('process') module.exports = { onPreBuild() { console.log(env.TEST_ONE, env.TEST_TWO, env.LANG) }, onBuild() { console.log(env.TEST_ONE, env.TEST_TWO, env.LANG) delete env.TEST_ONE env.TEST_TWO = 'twoChanged' }, } <file_sep>'use strict' const body = require('does_not_exist') module.exports.handler = function handler() { return { statusCode: 200, body } } <file_sep>'use strict' module.exports = { onPreBuild({ packageJson: { name } }) { console.log(name) }, } <file_sep># Changelog ### [2.0.1](https://www.github.com/netlify/build/compare/run-utils-v2.0.0...run-utils-v2.0.1) (2021-08-12) ### Bug Fixes * **deps:** bump execa to the latest version (5.x) ([#3440](https://www.github.com/netlify/build/issues/3440)) ([3e8bd01](https://www.github.com/netlify/build/commit/3e8bd019eddca738a664af9590c313dd5fcd20df)) ## [2.0.0](https://www.github.com/netlify/build/compare/run-utils-v1.0.7...run-utils-v2.0.0) (2021-07-23) ### ⚠ BREAKING CHANGES * deprecate Node 8 (#3322) ### Miscellaneous Chores * deprecate Node 8 ([#3322](https://www.github.com/netlify/build/issues/3322)) ([9cc108a](https://www.github.com/netlify/build/commit/9cc108aab825558204ffef6b8034f456d8d11879)) ### [1.0.7](https://www.github.com/netlify/build/compare/v1.0.6...v1.0.7) (2021-03-09) ### Bug Fixes * fix `semver` version with Node 8 ([#2362](https://www.github.com/netlify/build/issues/2362)) ([c72ecd8](https://www.github.com/netlify/build/commit/c72ecd8c8525e269180b427489991d9ec3238022)) ### [1.0.6](https://www.github.com/netlify/build/compare/run-utils-v1.0.5...v1.0.6) (2021-02-18) ### Bug Fixes * fix `files` in `package.json` with `npm@7` ([#2278](https://www.github.com/netlify/build/issues/2278)) ([e9df064](https://www.github.com/netlify/build/commit/e9df0645f3083a0bb141c8b5b6e474ed4e27dbe9)) <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig: { plugins } }) { console.log(Array.isArray(plugins)) }, } <file_sep>'use strict' module.exports = { onPreBuild({ constants: { EDGE_HANDLERS_SRC } }) { console.log(EDGE_HANDLERS_SRC) }, } <file_sep>'use strict' const { platform } = require('process') const test = require('ava') const { runFixture, FIXTURES_DIR } = require('../helpers/main') test('Configuration file - netlify.toml', async (t) => { await runFixture(t, 'toml') }) // Windows directory permissions work differently than Unix. if (platform !== 'win32') { test('Configuration file - read permission error', async (t) => { await runFixture(t, '', { flags: { config: `${FIXTURES_DIR}/read_error/netlify.toml` } }) }) } test('Configuration file - parsing error', async (t) => { await runFixture(t, 'parse_error') }) test('Configuration file - ambiguous backslash in TOML', async (t) => { await runFixture(t, 'parse_backslash_ambiguous', { flags: { featureFlags: { netlify_config_toml_backslash: true } } }) }) test('Configuration file - ambiguous backslash in TOML without feature flag', async (t) => { await runFixture(t, 'parse_backslash_ambiguous', { flags: { featureFlags: { netlify_config_toml_backslash: false } }, }) }) test('Configuration file - valid backslash in TOML', async (t) => { const { returnValue } = await runFixture(t, 'parse_backslash_valid', { flags: { featureFlags: { netlify_config_toml_backslash: true } }, }) t.true(returnValue.includes('\\\\[this\\\\]\\ntest \\" \\b \\t \\n \\f \\r \\u0000 \\u0000')) }) test('Redirects - redirects file', async (t) => { await runFixture(t, 'redirects_file') }) test('Redirects - redirects field', async (t) => { await runFixture(t, 'redirects_field') }) test('Redirects - redirects file and redirects field', async (t) => { await runFixture(t, 'redirects_both') }) test('Redirects - redirects file syntax error', async (t) => { await runFixture(t, 'redirects_file_error') }) test('Redirects - redirects field syntax error', async (t) => { await runFixture(t, 'redirects_field_error') }) test('Redirects - no publish field', async (t) => { await runFixture(t, 'redirects_no_publish') }) test('Redirects - add redirectsOrigin', async (t) => { await runFixture(t, 'empty', { flags: { defaultConfig: { redirects: [] } } }) }) test('Redirects - log redirectsOrigin in debug mode', async (t) => { await runFixture(t, 'empty', { flags: { defaultConfig: { redirects: [] }, debug: true } }) }) test('Redirects - does not use redirects file when using inlineConfig with identical redirects', async (t) => { await runFixture(t, 'redirects_file', { flags: { inlineConfig: { redirects: [{ from: '/from', to: '/to' }] } } }) }) test('Headers - file', async (t) => { await runFixture(t, 'headers_file') }) test('Headers - field', async (t) => { await runFixture(t, 'headers_field') }) test('Headers - file and field', async (t) => { await runFixture(t, 'headers_both') }) test('Headers - file syntax error', async (t) => { await runFixture(t, 'headers_file_error') }) test('Headers - field syntax error', async (t) => { await runFixture(t, 'headers_field_error') }) test('Headers - no publish field', async (t) => { await runFixture(t, 'headers_no_publish') }) test('Headers - add headersOrigin', async (t) => { await runFixture(t, 'empty', { flags: { defaultConfig: { headers: [] } } }) }) test('Headers - log headersOrigin in debug mode', async (t) => { await runFixture(t, 'empty', { flags: { defaultConfig: { headers: [] }, debug: true } }) }) test('Headers - does not use headers file when using inlineConfig with identical headers', async (t) => { await runFixture(t, 'headers_file', { flags: { inlineConfig: { headers: [{ for: '/path', values: { test: 'one' } }] } }, }) }) test('Headers - duplicate case in same path', async (t) => { await runFixture(t, 'headers_duplicate_case_same') }) test('Headers - duplicate case in different paths', async (t) => { await runFixture(t, 'headers_duplicate_case_different') }) <file_sep>[build] edge_handlers = "../../edge_handlers_dir" <file_sep>'use strict' const { cwd: getCwd, chdir } = require('process') const test = require('ava') const pathExists = require('path-exists') const cacheUtils = require('..') const { pWriteFile, pReaddir, createTmpDir, removeFiles } = require('./helpers/main') test('Should allow changing the cache directory', async (t) => { const [cacheDir, srcDir] = await Promise.all([createTmpDir(), createTmpDir()]) const currentDir = getCwd() chdir(srcDir) try { const srcFile = `${srcDir}/test` await pWriteFile(srcFile, '') t.true(await cacheUtils.save(srcFile, { cacheDir })) t.is((await pReaddir(cacheDir)).length, 1) await removeFiles(srcFile) t.true(await cacheUtils.restore(srcFile, { cacheDir })) t.true(await pathExists(srcFile)) } finally { chdir(currentDir) await removeFiles([cacheDir, srcDir]) } }) <file_sep>[build] publish = "publish" edge_handlers = true <file_sep>'use strict' module.exports = { onPreBuild() { // eslint-disable-next-line no-throw-literal throw 'test' }, } <file_sep>'use strict' module.exports = { onPreBuild() { // eslint-disable-next-line no-throw-literal throw [new Error('test'), new Error('testTwo')] }, } <file_sep>'use strict' module.exports = { onPreBuild({ constants: { NETLIFY_API_TOKEN = 'none' } }) { console.log(NETLIFY_API_TOKEN) }, } <file_sep>'use strict' const { copyFile } = require('fs') const { promisify } = require('util') const pCopyFile = promisify(copyFile) const fixtureHeadersPath = `${__dirname}/headers_file` const headersPath = `${__dirname}/_headers` module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.headers = [...netlifyConfig.headers, { for: '/path', values: { test: 'two' } }] }, async onBuild() { await pCopyFile(fixtureHeadersPath, headersPath) }, onPostBuild({ netlifyConfig: { headers } }) { console.log(headers) }, } <file_sep>'use strict' module.exports = { onPreBuild({ utils: { git } }) { console.log(git.modifiedFiles) }, } <file_sep>'use strict' const { resolve } = require('path') module.exports = { onPreBuild({ constants: { PUBLISH_DIR } }) { console.log(PUBLISH_DIR, resolve(PUBLISH_DIR).endsWith('base')) }, } <file_sep>'use strict' const { normalize } = require('path') const test = require('ava') const cpy = require('cpy') const del = require('del') const pathExists = require('path-exists') const { spy } = require('sinon') const sortOn = require('sort-on') const { add, list, listAll } = require('..') const { getDist, createDist, removeDist } = require('./helpers/main') const FIXTURES_DIR = `${__dirname}/fixtures` test('Should copy a source file to a dist directory', async (t) => { const dist = await getDist() try { await add(`${FIXTURES_DIR}/file/test.js`, dist) t.true(await pathExists(`${dist}/test.js`)) } finally { await removeDist(dist) } }) test('Should copy a source directory to a dist directory', async (t) => { const dist = await getDist() try { await add(`${FIXTURES_DIR}/directory/test`, dist) t.true(await pathExists(`${dist}/test/index.js`)) } finally { await removeDist(dist) } }) test('Should throw when source is undefined', async (t) => { const dist = await getDist() try { await t.throwsAsync(add(undefined, dist)) } finally { await removeDist(dist) } }) test('Should throw when source is empty array', async (t) => { const dist = await getDist() try { await t.throwsAsync(add([], dist)) } finally { await removeDist(dist) } }) test('Should throw when source points to non-existing file', async (t) => { const dist = await getDist() try { await t.throwsAsync(add(`${FIXTURES_DIR}/file/doesNotExist.js`, dist)) } finally { await removeDist(dist) } }) test('Should throw when dist is undefined', async (t) => { await t.throwsAsync(add(`${FIXTURES_DIR}/file/test.js`)) }) test('Should copy a source file even if dist directory already exists', async (t) => { const dist = await createDist() try { await add(`${FIXTURES_DIR}/file/test.js`, dist) t.true(await pathExists(`${dist}/test.js`)) } finally { await removeDist(dist) } }) test('Should overwrite dist file if it already exists', async (t) => { const dist = await getDist() const fixtureDir = `${FIXTURES_DIR}/file` await cpy(`${fixtureDir}/test.js`, fixtureDir, { rename: 'test.js.backup' }) try { await add(`${fixtureDir}/test.js`, dist) // eslint-disable-next-line import/no-dynamic-require, node/global-require const func1 = require(`${dist}/test.js`) await cpy(`${fixtureDir}/test_2.js`, fixtureDir, { rename: 'test.js' }) await add(`${fixtureDir}/test.js`, dist) delete require.cache[require.resolve(`${dist}/test.js`)] // eslint-disable-next-line import/no-dynamic-require, node/global-require const func2 = require(`${dist}/test.js`) t.is(func1(), 'one') t.is(func2(), 'two') } finally { await cpy(`${fixtureDir}/test.js.backup`, fixtureDir, { rename: 'test.js' }) await del(`${fixtureDir}/test.js.backup`, { force: true }) await removeDist(dist) } }) test('Should allow "fail" option to customize failures', async (t) => { const fail = spy() await add(undefined, undefined, { fail }) t.true(fail.calledOnce) t.is(typeof fail.firstCall.firstArg, 'string') }) const normalizeFiles = function (fixtureDir, { name, mainFile, runtime, extension, srcFile }) { const mainFileA = normalize(`${fixtureDir}/${mainFile}`) const srcFileA = srcFile === undefined ? {} : { srcFile: normalize(`${fixtureDir}/${srcFile}`) } return { name, mainFile: mainFileA, runtime, extension, ...srcFileA } } test('Can list function main files with list()', async (t) => { const fixtureDir = `${FIXTURES_DIR}/list` const functions = await list(fixtureDir) t.deepEqual( sortOn(functions, ['mainFile', 'extension']), [ { name: 'four', mainFile: 'four.js/four.js.js', runtime: 'js', extension: '.js' }, { name: 'one', mainFile: 'one/index.js', runtime: 'js', extension: '.js' }, { name: 'test', mainFile: 'test', runtime: 'go', extension: '' }, { name: 'test', mainFile: 'test.js', runtime: 'js', extension: '.js' }, { name: 'test', mainFile: 'test.zip', runtime: 'js', extension: '.zip' }, { name: 'two', mainFile: 'two/two.js', runtime: 'js', extension: '.js' }, ].map(normalizeFiles.bind(null, fixtureDir)), ) }) test('Can list all function files with listAll()', async (t) => { const fixtureDir = `${FIXTURES_DIR}/list` const functions = await listAll(fixtureDir) t.deepEqual( sortOn(functions, ['mainFile', 'extension']), [ { name: 'four', mainFile: 'four.js/four.js.js', runtime: 'js', extension: '.js', srcFile: 'four.js/four.js.js', }, { name: 'one', mainFile: 'one/index.js', runtime: 'js', extension: '.js', srcFile: 'one/index.js' }, { name: 'test', mainFile: 'test', runtime: 'go', extension: '', srcFile: 'test' }, { name: 'test', mainFile: 'test.js', runtime: 'js', extension: '.js', srcFile: 'test.js' }, { name: 'test', mainFile: 'test.zip', runtime: 'js', extension: '.zip', srcFile: 'test.zip' }, { name: 'two', mainFile: 'two/two.js', runtime: 'js', extension: '.js', srcFile: 'two/three.js' }, { name: 'two', mainFile: 'two/two.js', runtime: 'js', extension: '.js', srcFile: 'two/two.js' }, ].map(normalizeFiles.bind(null, fixtureDir)), ) }) <file_sep>'use strict' const { mkdir } = require('fs') const { dirname } = require('path') const { promisify } = require('util') const pMkdir = promisify(mkdir) const DEFAULT_EDGE_HANDLERS_SRC = 'netlify/edge-handlers' module.exports = { async onPreBuild({ constants: { EDGE_HANDLERS_SRC } }) { console.log(EDGE_HANDLERS_SRC.endsWith('test')) await pMkdir(dirname(DEFAULT_EDGE_HANDLERS_SRC)) await pMkdir(DEFAULT_EDGE_HANDLERS_SRC) }, onBuild({ constants: { EDGE_HANDLERS_SRC } }) { console.log(EDGE_HANDLERS_SRC.endsWith('test')) }, } <file_sep>'use strict' module.exports = { onPreBuild({ constants: { CONFIG_PATH } }) { console.log(CONFIG_PATH) }, } <file_sep># Changelog ### [15.6.4](https://www.github.com/netlify/build/compare/config-v15.6.3...config-v15.6.4) (2021-10-04) ### Bug Fixes * warn when using odd backslash sequences in netlify.toml ([#3677](https://www.github.com/netlify/build/issues/3677)) ([d3029ac](https://www.github.com/netlify/build/commit/d3029ac8de1e270c2fc2717ed24786506cd112cc)) ### [15.6.3](https://www.github.com/netlify/build/compare/config-v15.6.2...config-v15.6.3) (2021-09-21) ### Bug Fixes * **deps:** update dependency netlify to ^8.0.1 ([#3644](https://www.github.com/netlify/build/issues/3644)) ([a69f777](https://www.github.com/netlify/build/commit/a69f77791b0910abe98e4fb5fddc220295920363)) ### [15.6.2](https://www.github.com/netlify/build/compare/config-v15.6.1...config-v15.6.2) (2021-09-09) ### Bug Fixes * repository root directory validation ([#3598](https://www.github.com/netlify/build/issues/3598)) ([57a45fd](https://www.github.com/netlify/build/commit/57a45fd65a9705c95d8b71575bdb5d7b0d7dfed7)) ### [15.6.1](https://www.github.com/netlify/build/compare/config-v15.6.0...config-v15.6.1) (2021-09-08) ### Bug Fixes * monitor whether headers with different cases have the same path ([#3594](https://www.github.com/netlify/build/issues/3594)) ([029ff7d](https://www.github.com/netlify/build/commit/029ff7dd833fcabcb1e28c01443ff6e52267bcd6)) ## [15.6.0](https://www.github.com/netlify/build/compare/config-v15.5.2...config-v15.6.0) (2021-09-07) ### Features * remove `builders` and `buildersDistDir` ([#3581](https://www.github.com/netlify/build/issues/3581)) ([d27906b](https://www.github.com/netlify/build/commit/d27906bc1390dbeb6ebc64279ce7475d418a8514)) ### [15.5.2](https://www.github.com/netlify/build/compare/config-v15.5.1...config-v15.5.2) (2021-09-07) ### Bug Fixes * add warning message when the same header is used with different cases ([#3590](https://www.github.com/netlify/build/issues/3590)) ([bd4b373](https://www.github.com/netlify/build/commit/bd4b373c34e88821d8bf537933bd26e8674e866c)) ### [15.5.1](https://www.github.com/netlify/build/compare/config-v15.5.0...config-v15.5.1) (2021-09-01) ### Bug Fixes * error handling of syntax errors in plugin configuration changes ([#3586](https://www.github.com/netlify/build/issues/3586)) ([56d902d](https://www.github.com/netlify/build/commit/56d902d88353b5b836ca4124b94532fb744470fc)) ## [15.5.0](https://www.github.com/netlify/build/compare/config-v15.4.1...config-v15.5.0) (2021-08-26) ### Features * add `builders.*` and `builders.directory` configuration properties to `@netlify/config` ([#3560](https://www.github.com/netlify/build/issues/3560)) ([4e9b757](https://www.github.com/netlify/build/commit/4e9b757efcdeec5477cd278ec57feb02dbe49248)) ### [15.4.1](https://www.github.com/netlify/build/compare/config-v15.4.0...config-v15.4.1) (2021-08-19) ### Bug Fixes * remove unused error handlers ([#3510](https://www.github.com/netlify/build/issues/3510)) ([2beefcd](https://www.github.com/netlify/build/commit/2beefcd6cfdeab7642fe02266828730637d865d8)) ## [15.4.0](https://www.github.com/netlify/build/compare/config-v15.3.8...config-v15.4.0) (2021-08-18) ### Features * **build-id:** add a `build-id` flag and expose `BUILD_ID` based on said flag ([#3527](https://www.github.com/netlify/build/issues/3527)) ([94a4a03](https://www.github.com/netlify/build/commit/94a4a03f337d3c2195f4b4a1912f778893ebf485)) ### [15.3.8](https://www.github.com/netlify/build/compare/config-v15.3.7...config-v15.3.8) (2021-08-18) ### Bug Fixes * duplicate code ([#3526](https://www.github.com/netlify/build/issues/3526)) ([74e8879](https://www.github.com/netlify/build/commit/74e8879916851be8d22b308008e9d793c15895e8)) ### [15.3.7](https://www.github.com/netlify/build/compare/config-v15.3.6...config-v15.3.7) (2021-08-17) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to ^4.0.1 ([#3521](https://www.github.com/netlify/build/issues/3521)) ([0aee4c3](https://www.github.com/netlify/build/commit/0aee4c3b360756fe194af259538e653031a9fd20)) ### [15.3.6](https://www.github.com/netlify/build/compare/config-v15.3.5...config-v15.3.6) (2021-08-17) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to v4 ([#3518](https://www.github.com/netlify/build/issues/3518)) ([9b6f234](https://www.github.com/netlify/build/commit/9b6f2349c0ebb3fb4c7c2148274d4120edc39a3a)) ### [15.3.5](https://www.github.com/netlify/build/compare/config-v15.3.4...config-v15.3.5) (2021-08-17) ### Bug Fixes * refactor headers and redirects logic ([#3511](https://www.github.com/netlify/build/issues/3511)) ([1f026bf](https://www.github.com/netlify/build/commit/1f026bf368a6624ed512af3a6f1b7f216dcbb3b3)) ### [15.3.4](https://www.github.com/netlify/build/compare/config-v15.3.3...config-v15.3.4) (2021-08-16) ### Bug Fixes * **deps:** update dependency is-plain-obj to v3 ([#3489](https://www.github.com/netlify/build/issues/3489)) ([b353eec](https://www.github.com/netlify/build/commit/b353eece861296ef18de8e19855a6b2e30ac4fba)) * **deps:** update dependency netlify-headers-parser to ^3.0.1 ([#3508](https://www.github.com/netlify/build/issues/3508)) ([10dbcf8](https://www.github.com/netlify/build/commit/10dbcf87362eb6045a6adfca81a0e4dd638ef567)) * **deps:** update dependency netlify-redirect-parser to ^11.0.1 ([#3506](https://www.github.com/netlify/build/issues/3506)) ([c07443c](https://www.github.com/netlify/build/commit/c07443c1168f6b81fa8cf80eb418eb9b89d22350)) * **deps:** update dependency netlify-redirect-parser to ^11.0.2 ([#3509](https://www.github.com/netlify/build/issues/3509)) ([0a412c1](https://www.github.com/netlify/build/commit/0a412c109f9f7ee17596a8d8f546a43c0a54e8c0)) ### [15.3.3](https://www.github.com/netlify/build/compare/config-v15.3.2...config-v15.3.3) (2021-08-16) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to v3 ([#3483](https://www.github.com/netlify/build/issues/3483)) ([4e95d96](https://www.github.com/netlify/build/commit/4e95d96d4466907b5356f46fd4ce278b551e6b91)) ### [15.3.2](https://www.github.com/netlify/build/compare/config-v15.3.1...config-v15.3.2) (2021-08-16) ### Bug Fixes * **deps:** update dependency p-locate to v5 ([#3495](https://www.github.com/netlify/build/issues/3495)) ([ce07fbc](https://www.github.com/netlify/build/commit/ce07fbccc5e93224e7adab5dc039f9534a49f06b)) ### [15.3.1](https://www.github.com/netlify/build/compare/config-v15.3.0...config-v15.3.1) (2021-08-13) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to v11 ([#3481](https://www.github.com/netlify/build/issues/3481)) ([38ecd1d](https://www.github.com/netlify/build/commit/38ecd1d75fa7a9262abe7a989b784ca95ebd0348)) ## [15.3.0](https://www.github.com/netlify/build/compare/config-v15.2.0...config-v15.3.0) (2021-08-13) ### Features * simplify redirects parsing ([#3475](https://www.github.com/netlify/build/issues/3475)) ([21e33a3](https://www.github.com/netlify/build/commit/21e33a3fde17d5c698c73b16778d3e06ec1cafae)) ## [15.2.0](https://www.github.com/netlify/build/compare/config-v15.1.9...config-v15.2.0) (2021-08-13) ### Features * simplify headers parsing ([#3468](https://www.github.com/netlify/build/issues/3468)) ([ff601ff](https://www.github.com/netlify/build/commit/ff601ffbabafb0ebe28695b3135d5a922e06a57d)) ### [15.1.9](https://www.github.com/netlify/build/compare/config-v15.1.8...config-v15.1.9) (2021-08-13) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to ^10.1.0 ([#3473](https://www.github.com/netlify/build/issues/3473)) ([2ac8555](https://www.github.com/netlify/build/commit/2ac85554e455150434a4d5f3ea6b00268deb30c5)) ### [15.1.8](https://www.github.com/netlify/build/compare/config-v15.1.7...config-v15.1.8) (2021-08-13) ### Bug Fixes * **deps:** remove cp-file usage ([#3470](https://www.github.com/netlify/build/issues/3470)) ([5b98fb4](https://www.github.com/netlify/build/commit/5b98fb494478cc0e7676856ce38f980b406306b9)) ### [15.1.7](https://www.github.com/netlify/build/compare/config-v15.1.6...config-v15.1.7) (2021-08-13) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to ^2.1.1 ([#3462](https://www.github.com/netlify/build/issues/3462)) ([4a0f19f](https://www.github.com/netlify/build/commit/4a0f19fcbe8ae0ab1a81ccb24897238675350964)) ### [15.1.6](https://www.github.com/netlify/build/compare/config-v15.1.5...config-v15.1.6) (2021-08-13) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to v10 ([#3460](https://www.github.com/netlify/build/issues/3460)) ([c9a9ecc](https://www.github.com/netlify/build/commit/c9a9ecc960ca73039d1e28d5f1413fb4f530dbb8)) ### [15.1.5](https://www.github.com/netlify/build/compare/config-v15.1.4...config-v15.1.5) (2021-08-13) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to ^2.1.0 ([#3458](https://www.github.com/netlify/build/issues/3458)) ([e7665ec](https://www.github.com/netlify/build/commit/e7665ecb7bc1960ca19ba2717a2b2d608ae83bb6)) ### [15.1.4](https://www.github.com/netlify/build/compare/config-v15.1.3...config-v15.1.4) (2021-08-13) ### Bug Fixes * **deps:** update dependency find-up to v5 ([#3455](https://www.github.com/netlify/build/issues/3455)) ([e540ec2](https://www.github.com/netlify/build/commit/e540ec26863f0cfaba3736bade0ce7b4aecbe36a)) ### [15.1.3](https://www.github.com/netlify/build/compare/config-v15.1.2...config-v15.1.3) (2021-08-12) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to v2 ([#3448](https://www.github.com/netlify/build/issues/3448)) ([3d83dce](https://www.github.com/netlify/build/commit/3d83dce6efa68df5ef090e57958eff6f78c8f065)) ### [15.1.2](https://www.github.com/netlify/build/compare/config-v15.1.1...config-v15.1.2) (2021-08-12) ### Bug Fixes * delete `_redirects`/`_headers` when persisted to `netlify.toml` ([#3446](https://www.github.com/netlify/build/issues/3446)) ([4bdf2cc](https://www.github.com/netlify/build/commit/4bdf2ccb64edae4254a9b7832f46e2cbeeb322eb)) ### [15.1.1](https://www.github.com/netlify/build/compare/config-v15.1.0...config-v15.1.1) (2021-08-12) ### Bug Fixes * **deps:** bump execa to the latest version (5.x) ([#3440](https://www.github.com/netlify/build/issues/3440)) ([3e8bd01](https://www.github.com/netlify/build/commit/3e8bd019eddca738a664af9590c313dd5fcd20df)) ## [15.1.0](https://www.github.com/netlify/build/compare/config-v15.0.5...config-v15.1.0) (2021-08-12) ### Features * remove headers/redirects duplicate filtering ([#3439](https://www.github.com/netlify/build/issues/3439)) ([ebc88c1](https://www.github.com/netlify/build/commit/ebc88c12eea2a8f47ee02415e94d7c4e451fb356)) ### [15.0.5](https://www.github.com/netlify/build/compare/config-v15.0.4...config-v15.0.5) (2021-08-12) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to ^1.1.1 ([#3441](https://www.github.com/netlify/build/issues/3441)) ([04cee44](https://www.github.com/netlify/build/commit/04cee441dc61aa0efff3216d4a66768808a330ed)) ### [15.0.4](https://www.github.com/netlify/build/compare/config-v15.0.3...config-v15.0.4) (2021-08-12) ### Bug Fixes * **deps:** update dependency netlify-headers-parser to ^1.1.0 ([#3435](https://www.github.com/netlify/build/issues/3435)) ([26b4e4e](https://www.github.com/netlify/build/commit/26b4e4e8ba4a90b85596eaeee216ee5d6fbc509b)) * **deps:** update dependency netlify-redirect-parser to v9 ([#3436](https://www.github.com/netlify/build/issues/3436)) ([7efd2dc](https://www.github.com/netlify/build/commit/7efd2dc7b29d837b4452a1510df76b53a3276845)) ### [15.0.3](https://www.github.com/netlify/build/compare/config-v15.0.2...config-v15.0.3) (2021-08-12) ### Bug Fixes * fix how redirects/headers check for duplicates ([#3424](https://www.github.com/netlify/build/issues/3424)) ([c44f35c](https://www.github.com/netlify/build/commit/c44f35c9562ea42a210ab2f83133b76534543f4d)) ### [15.0.2](https://www.github.com/netlify/build/compare/config-v15.0.1...config-v15.0.2) (2021-08-11) ### Bug Fixes * bump `netlify-headers-parser` ([77177fc](https://www.github.com/netlify/build/commit/77177fcbc2668dc829bac8b8325063cc557c7ed1)) ### [15.0.1](https://www.github.com/netlify/build/compare/config-v15.0.0...config-v15.0.1) (2021-08-11) ### Bug Fixes * error handling of headers and redirects ([#3422](https://www.github.com/netlify/build/issues/3422)) ([add5417](https://www.github.com/netlify/build/commit/add54178e5b046d6ec8d7cc44ac626135a25b9e6)) ## [15.0.0](https://www.github.com/netlify/build/compare/config-v14.4.3...config-v15.0.0) (2021-08-11) ### ⚠ BREAKING CHANGES * add `netlifyConfig.headers` (#3407) ### Features * add `netlifyConfig.headers` ([#3407](https://www.github.com/netlify/build/issues/3407)) ([14888c7](https://www.github.com/netlify/build/commit/14888c73278b6c68538ecaa385e5ce01932b7e09)) ### [14.4.3](https://www.github.com/netlify/build/compare/config-v14.4.2...config-v14.4.3) (2021-08-05) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to ^8.2.0 ([#3399](https://www.github.com/netlify/build/issues/3399)) ([70911c9](https://www.github.com/netlify/build/commit/70911c91729d02475684b179febe9b07e23df293)) ### [14.4.2](https://www.github.com/netlify/build/compare/config-v14.4.1...config-v14.4.2) (2021-08-05) ### Bug Fixes * `redirects[*].status` should not be a float in `netlify.toml` ([#3396](https://www.github.com/netlify/build/issues/3396)) ([1c006ea](https://www.github.com/netlify/build/commit/1c006eae3de54e034dbcd87de5e011b6bfa843e6)) ### [14.4.1](https://www.github.com/netlify/build/compare/config-v14.4.0...config-v14.4.1) (2021-08-04) ### Bug Fixes * persist `build.environment` changes to `netlify.toml` ([#3394](https://www.github.com/netlify/build/issues/3394)) ([101f99e](https://www.github.com/netlify/build/commit/101f99e0ee65eafc577241711c01e142d6b80444)) ## [14.4.0](https://www.github.com/netlify/build/compare/config-v14.3.0...config-v14.4.0) (2021-08-04) ### Features * allow modifying `build.environment` ([#3389](https://www.github.com/netlify/build/issues/3389)) ([76d3bc9](https://www.github.com/netlify/build/commit/76d3bc9c77e28cf500ada47289c01d394d6da6db)) ## [14.3.0](https://www.github.com/netlify/build/compare/config-v14.2.0...config-v14.3.0) (2021-08-03) ### Features * improve config simplification ([#3384](https://www.github.com/netlify/build/issues/3384)) ([b9f7d7a](https://www.github.com/netlify/build/commit/b9f7d7ad1baf063bd3919a16b961007cb94da2e2)) ## [14.2.0](https://www.github.com/netlify/build/compare/config-v14.1.1...config-v14.2.0) (2021-08-03) ### Features * **build:** return config mutations ([#3379](https://www.github.com/netlify/build/issues/3379)) ([8eb39b5](https://www.github.com/netlify/build/commit/8eb39b5ee3fae124498f87046a7776ad5574e011)) ### [14.1.1](https://www.github.com/netlify/build/compare/config-v14.1.0...config-v14.1.1) (2021-08-02) ### Bug Fixes * **deps:** update dependency chalk to ^4.1.1 ([#3367](https://www.github.com/netlify/build/issues/3367)) ([dd258ec](https://www.github.com/netlify/build/commit/dd258ecd758824e56b15fc5f6c73a3180ac0af66)) ## [14.1.0](https://www.github.com/netlify/build/compare/config-v14.0.0...config-v14.1.0) (2021-07-28) ### Features * add `NETLIFY_LOCAL` environment variable ([#3351](https://www.github.com/netlify/build/issues/3351)) ([c3c0716](https://www.github.com/netlify/build/commit/c3c07169ba922010d7233de868a52b6ccd6bcd20)) ## [14.0.0](https://www.github.com/netlify/build/compare/config-v13.0.0...config-v14.0.0) (2021-07-26) ### ⚠ BREAKING CHANGES * deprecate Node 8 (#3322) ### Features * **plugins:** remove feature flag responsible plugin node version execution changes ([#3311](https://www.github.com/netlify/build/issues/3311)) ([8c94faf](https://www.github.com/netlify/build/commit/8c94faf8d1e7cbf830b1cbc722949198759f9f8c)) ### Bug Fixes * **deps:** update dependency netlify to v8 ([#3338](https://www.github.com/netlify/build/issues/3338)) ([6912475](https://www.github.com/netlify/build/commit/6912475b307be67dd003df26d0bf28ae21e3d172)) ### Miscellaneous Chores * deprecate Node 8 ([#3322](https://www.github.com/netlify/build/issues/3322)) ([9cc108a](https://www.github.com/netlify/build/commit/9cc108aab825558204ffef6b8034f456d8d11879)) ## [13.0.0](https://www.github.com/netlify/build/compare/config-v12.6.0...config-v13.0.0) (2021-07-16) ### ⚠ BREAKING CHANGES * change edge-handler default directory (#3296) ### Features * change edge-handler default directory ([#3296](https://www.github.com/netlify/build/issues/3296)) ([86b02da](https://www.github.com/netlify/build/commit/86b02dae85bbd879f107606487853ad3cd2fc147)) ## [12.6.0](https://www.github.com/netlify/build/compare/config-v12.5.0...config-v12.6.0) (2021-07-08) ### Features * delete `netlify.toml` after deploy if it was created due to configuration changes ([#3271](https://www.github.com/netlify/build/issues/3271)) ([444087d](https://www.github.com/netlify/build/commit/444087d528a0e8450031eda65cd5877980a5fa70)) ## [12.5.0](https://www.github.com/netlify/build/compare/config-v12.4.0...config-v12.5.0) (2021-07-08) ### Features * simplify the `netlify.toml` being saved on configuration changes ([#3268](https://www.github.com/netlify/build/issues/3268)) ([15987fe](https://www.github.com/netlify/build/commit/15987fe0d869f01110d4d97c8e8395580eb1a9f7)) ## [12.4.0](https://www.github.com/netlify/build/compare/config-v12.3.0...config-v12.4.0) (2021-07-08) ### Features * restore `netlify.toml` and `_redirects` after deploy ([#3265](https://www.github.com/netlify/build/issues/3265)) ([2441d6a](https://www.github.com/netlify/build/commit/2441d6a8b2be81212384816a0686221d4a6a2577)) ## [12.3.0](https://www.github.com/netlify/build/compare/config-v12.2.1...config-v12.3.0) (2021-07-08) ### Features * fix `_redirects` to `netlify.toml` before deploy ([#3259](https://www.github.com/netlify/build/issues/3259)) ([e32d076](https://www.github.com/netlify/build/commit/e32d076ab642b8a0df72c96d8726e161b65b182f)) ### [12.2.1](https://www.github.com/netlify/build/compare/config-v12.2.0...config-v12.2.1) (2021-07-08) ### Bug Fixes * allow `netlifyConfig.redirects` to be modified before `_redirects` is added ([#3242](https://www.github.com/netlify/build/issues/3242)) ([f3330a6](https://www.github.com/netlify/build/commit/f3330a685aeb0320e1ac445bbe7a908e7a83dbda)) * **deps:** update dependency netlify-redirect-parser to ^8.1.0 ([#3246](https://www.github.com/netlify/build/issues/3246)) ([2f0b9b1](https://www.github.com/netlify/build/commit/2f0b9b1d8350caafee48d38cd05dabf7037a6c20)) ## [12.2.0](https://www.github.com/netlify/build/compare/config-v12.1.1...config-v12.2.0) (2021-07-08) ### Features * add default values for `build.processing` and `build.services` ([#3235](https://www.github.com/netlify/build/issues/3235)) ([2ba263b](https://www.github.com/netlify/build/commit/2ba263ba9ebc54c38410245f021deb906b8a8aa2)) ### [12.1.1](https://www.github.com/netlify/build/compare/config-v12.1.0...config-v12.1.1) (2021-07-07) ### Bug Fixes * return `redirects` with `@netlify/config` ([#3231](https://www.github.com/netlify/build/issues/3231)) ([be511fa](https://www.github.com/netlify/build/commit/be511fa06e09a6589f06f2943ee06de1062c88ec)) ## [12.1.0](https://www.github.com/netlify/build/compare/config-v12.0.1...config-v12.1.0) (2021-07-07) ### Features * persist configuration changes to `netlify.toml` ([#3224](https://www.github.com/netlify/build/issues/3224)) ([f924661](https://www.github.com/netlify/build/commit/f924661f94d04af1e90e1023e385e35587ae301c)) ### [12.0.1](https://www.github.com/netlify/build/compare/config-v12.0.0...config-v12.0.1) (2021-07-06) ### Bug Fixes * handle `plugins[*].pinned_version` being an empty string ([#3221](https://www.github.com/netlify/build/issues/3221)) ([46c43b4](https://www.github.com/netlify/build/commit/46c43b4eca36cd7ad866617e2ce721e45a26abd1)) ## [12.0.0](https://www.github.com/netlify/build/compare/config-v11.0.0...config-v12.0.0) (2021-07-06) ### ⚠ BREAKING CHANGES * return `redirectsPath` from `@netlify/config` (#3207) ### Features * return `redirectsPath` from `@netlify/config` ([#3207](https://www.github.com/netlify/build/issues/3207)) ([35dd205](https://www.github.com/netlify/build/commit/35dd205ca35a393dbb3cff50e79ba1cdad8f8755)) ## [11.0.0](https://www.github.com/netlify/build/compare/config-v10.3.0...config-v11.0.0) (2021-07-06) ### ⚠ BREAKING CHANGES * add `configMutations` flag to `@netlify/config` (#3211) ### Features * add `configMutations` flag to `@netlify/config` ([#3211](https://www.github.com/netlify/build/issues/3211)) ([9037f03](https://www.github.com/netlify/build/commit/9037f03b6d288d136007f0c2c964c04aed3f33f7)) ## [10.3.0](https://www.github.com/netlify/build/compare/config-v10.2.0...config-v10.3.0) (2021-07-05) ### Features * move some mutation logic to `@netlify/config` ([#3203](https://www.github.com/netlify/build/issues/3203)) ([9ce4725](https://www.github.com/netlify/build/commit/9ce47250e806379db93528913c298bc57f3d23a6)) ## [10.2.0](https://www.github.com/netlify/build/compare/config-v10.1.0...config-v10.2.0) (2021-07-05) ### Features * fix `context` override for `edge_handlers` ([#3199](https://www.github.com/netlify/build/issues/3199)) ([54f52e1](https://www.github.com/netlify/build/commit/54f52e19481d528b1660743038aaa747cd439384)) ## [10.1.0](https://www.github.com/netlify/build/compare/config-v10.0.0...config-v10.1.0) (2021-07-05) ### Features * improve `functions` configuration logic ([#3175](https://www.github.com/netlify/build/issues/3175)) ([7085d77](https://www.github.com/netlify/build/commit/7085d7720191c399d8fd9d560ce30a76b483e30a)) ## [10.0.0](https://www.github.com/netlify/build/compare/config-v9.8.0...config-v10.0.0) (2021-07-05) ### ⚠ BREAKING CHANGES * merge `priorityConfig` with `inlineConfig` (#3193) ### Features * merge `priorityConfig` with `inlineConfig` ([#3193](https://www.github.com/netlify/build/issues/3193)) ([35989ef](https://www.github.com/netlify/build/commit/35989ef8fe8196c1da2d36c2f73e4ff82efba6c5)) ## [9.8.0](https://www.github.com/netlify/build/compare/config-v9.7.0...config-v9.8.0) (2021-07-05) ### Features * change `origin` of `inlineConfig` and `priorityConfig` ([#3190](https://www.github.com/netlify/build/issues/3190)) ([5ea2439](https://www.github.com/netlify/build/commit/5ea2439ae8f7de11ba15059820466456ee8df196)) ## [9.7.0](https://www.github.com/netlify/build/compare/config-v9.6.0...config-v9.7.0) (2021-07-05) ### Features * change how `priorityConfig` interacts with contexts ([#3187](https://www.github.com/netlify/build/issues/3187)) ([736c269](https://www.github.com/netlify/build/commit/736c26993385173e37110b8e26c2cf389344de3e)) ## [9.6.0](https://www.github.com/netlify/build/compare/config-v9.5.0...config-v9.6.0) (2021-07-05) ### Features * refactor config contexts logic ([#3174](https://www.github.com/netlify/build/issues/3174)) ([2815d8e](https://www.github.com/netlify/build/commit/2815d8ec46558ab87fb5c7f30e34a3f66c13ac0c)) ## [9.5.0](https://www.github.com/netlify/build/compare/config-v9.4.0...config-v9.5.0) (2021-06-30) ### Features * allow plugins to unset configuration properties ([#3158](https://www.github.com/netlify/build/issues/3158)) ([64e1235](https://www.github.com/netlify/build/commit/64e1235079356f5936638cde812a17027e627b9f)) ## [9.4.0](https://www.github.com/netlify/build/compare/config-v9.3.0...config-v9.4.0) (2021-06-30) ### Features * remove redirects parsing feature flag ([#3150](https://www.github.com/netlify/build/issues/3150)) ([1f297c9](https://www.github.com/netlify/build/commit/1f297c9845bc3a1f3ba4725c9f97aadf0d541e45)) ## [9.3.0](https://www.github.com/netlify/build/compare/config-v9.2.0...config-v9.3.0) (2021-06-28) ### Features * log `redirectsOrigin` in debug mode ([#3128](https://www.github.com/netlify/build/issues/3128)) ([d18601c](https://www.github.com/netlify/build/commit/d18601c04e96ea87e29bac4d6eaf0bf8b5753988)) ## [9.2.0](https://www.github.com/netlify/build/compare/config-v9.1.0...config-v9.2.0) (2021-06-28) ### Features * add `config.redirectsOrigin` ([#3115](https://www.github.com/netlify/build/issues/3115)) ([50a783f](https://www.github.com/netlify/build/commit/50a783ff434d24b528c94d761863f1227a47e9de)) ## [9.1.0](https://www.github.com/netlify/build/compare/config-v9.0.0...config-v9.1.0) (2021-06-24) ### Features * add `priorityConfig` to `@netlify/config` ([#3102](https://www.github.com/netlify/build/issues/3102)) ([013ca1d](https://www.github.com/netlify/build/commit/013ca1d2efbde3547373f17f1550fe9cf60b9826)) ## [9.0.0](https://www.github.com/netlify/build/compare/config-v8.0.1...config-v9.0.0) (2021-06-24) ### ⚠ BREAKING CHANGES * do not print `@netlify/config` return value when `output` is defined (#3109) ### Features * do not print `@netlify/config` return value when `output` is defined ([#3109](https://www.github.com/netlify/build/issues/3109)) ([38363fd](https://www.github.com/netlify/build/commit/38363fd173428b57c948c1ea9329265f013c8007)) ### [8.0.1](https://www.github.com/netlify/build/compare/config-v8.0.0...config-v8.0.1) (2021-06-24) ### Bug Fixes * **plugins:** feature flag plugin execution with the system node version ([#3081](https://www.github.com/netlify/build/issues/3081)) ([d1d5b58](https://www.github.com/netlify/build/commit/d1d5b58925fbe156591de0cf7123276fb910332d)) ## [8.0.0](https://www.github.com/netlify/build/compare/config-v7.7.1...config-v8.0.0) (2021-06-22) ### ⚠ BREAKING CHANGES * update dependency netlify-redirect-parser to v8 (#3091) ### Bug Fixes * update dependency netlify-redirect-parser to v8 ([#3091](https://www.github.com/netlify/build/issues/3091)) ([bf21959](https://www.github.com/netlify/build/commit/bf2195937ae7c33f4a74d64fd8c1cdc2e327a58e)) ### [7.7.1](https://www.github.com/netlify/build/compare/config-v7.7.0...config-v7.7.1) (2021-06-22) ### Bug Fixes * set `redirects` to an empty array with `@netlify/config` binary output ([#3083](https://www.github.com/netlify/build/issues/3083)) ([7543c21](https://www.github.com/netlify/build/commit/7543c217b5b89c978b5178b938b633affe00f1db)) ## [7.7.0](https://www.github.com/netlify/build/compare/config-v7.6.0...config-v7.7.0) (2021-06-22) ### Features * do not print `redirects` with the `@netlify/config` CLI ([#3059](https://www.github.com/netlify/build/issues/3059)) ([ccaa12d](https://www.github.com/netlify/build/commit/ccaa12dffc6701c7d8a2eee176a81b92e330b9c7)) ## [7.6.0](https://www.github.com/netlify/build/compare/config-v7.5.0...config-v7.6.0) (2021-06-22) ### Features * add `build.publishOrigin` to `@netlify/config` ([#3078](https://www.github.com/netlify/build/issues/3078)) ([b5badfd](https://www.github.com/netlify/build/commit/b5badfdda2c7bada76d21583f6f57465b12b16cb)) ## [7.5.0](https://www.github.com/netlify/build/compare/config-v7.4.1...config-v7.5.0) (2021-06-17) ### Features * return `accounts` and `addons` from `@netlify/config` ([#3057](https://www.github.com/netlify/build/issues/3057)) ([661f79c](https://www.github.com/netlify/build/commit/661f79cf9ca6eaee03f25a24a6569bc6cc9302a3)) ### [7.4.1](https://www.github.com/netlify/build/compare/config-v7.4.0...config-v7.4.1) (2021-06-17) ### Bug Fixes * remove `netlify_config_default_publish` feature flag ([#3047](https://www.github.com/netlify/build/issues/3047)) ([0e2c137](https://www.github.com/netlify/build/commit/0e2c137fffae8ad3d4d8243ade3e5f46c0e96e21)) ## [7.4.0](https://www.github.com/netlify/build/compare/config-v7.3.0...config-v7.4.0) (2021-06-15) ### Features * add `--cachedConfigPath` CLI flag ([#3037](https://www.github.com/netlify/build/issues/3037)) ([e317a36](https://www.github.com/netlify/build/commit/e317a36b7c7028fcab6bb0fb0d026e0da522b692)) ## [7.3.0](https://www.github.com/netlify/build/compare/config-v7.2.4...config-v7.3.0) (2021-06-15) ### Features * add `--output` CLI flag to `@netlify/config` ([#3028](https://www.github.com/netlify/build/issues/3028)) ([5a07b84](https://www.github.com/netlify/build/commit/5a07b84c501c36b696f017d585d79d149577dbb2)) ### [7.2.4](https://www.github.com/netlify/build/compare/config-v7.2.3...config-v7.2.4) (2021-06-14) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to v7 ([#3026](https://www.github.com/netlify/build/issues/3026)) ([33b4d2a](https://www.github.com/netlify/build/commit/33b4d2a8ada68941d2f3f0171ac05eb37f77af60)) ### [7.2.3](https://www.github.com/netlify/build/compare/config-v7.2.2...config-v7.2.3) (2021-06-14) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to v5.2.1 ([#3021](https://www.github.com/netlify/build/issues/3021)) ([be298a1](https://www.github.com/netlify/build/commit/be298a1315f89f02fb38ba99762ab029cde20a68)) * pin zisi version in functions utils ([#3023](https://www.github.com/netlify/build/issues/3023)) ([9c6b09b](https://www.github.com/netlify/build/commit/9c6b09b89d5b3e1552eb848aea016092c6abcf5e)) ### [7.2.2](https://www.github.com/netlify/build/compare/config-v7.2.1...config-v7.2.2) (2021-06-14) ### Bug Fixes * **deps:** update dependency netlify-redirect-parser to ^5.2.0 ([#3018](https://www.github.com/netlify/build/issues/3018)) ([374b1cc](https://www.github.com/netlify/build/commit/374b1ccaede449a79d366b75bc38dbdb90d2a9ff)) ### [7.2.1](https://www.github.com/netlify/build/compare/config-v7.2.0...config-v7.2.1) (2021-06-14) ### Bug Fixes * revert `redirects` parsing ([#3016](https://www.github.com/netlify/build/issues/3016)) ([39613cf](https://www.github.com/netlify/build/commit/39613cfd04281e51264ef61a75c3bd4880158a11)) ## [7.2.0](https://www.github.com/netlify/build/compare/config-v7.1.2...config-v7.2.0) (2021-06-11) ### Features * add `config.redirects` ([#3003](https://www.github.com/netlify/build/issues/3003)) ([ec3c177](https://www.github.com/netlify/build/commit/ec3c177fcc6a90a99fb7a584d2402b004704bc7e)) ### [7.1.2](https://www.github.com/netlify/build/compare/config-v7.1.1...config-v7.1.2) (2021-06-11) ### Bug Fixes * refactor some logic related to the `base` directory ([#3001](https://www.github.com/netlify/build/issues/3001)) ([2fa3b43](https://www.github.com/netlify/build/commit/2fa3b43ddc13829505776b21631803a5009de4ea)) ### [7.1.1](https://www.github.com/netlify/build/compare/config-v7.1.0...config-v7.1.1) (2021-06-11) ### Bug Fixes * move some lines of code ([#2999](https://www.github.com/netlify/build/issues/2999)) ([857787f](https://www.github.com/netlify/build/commit/857787fec08612f4e53687d4cbba0374fc4022bf)) ## [7.1.0](https://www.github.com/netlify/build/compare/config-v7.0.3...config-v7.1.0) (2021-06-11) ### Features * refactor some logic related to the `base` directory ([#2997](https://www.github.com/netlify/build/issues/2997)) ([683b9bd](https://www.github.com/netlify/build/commit/683b9bd0e3d1f93ac4f293e904657193e2ca253c)) ### [7.0.3](https://www.github.com/netlify/build/compare/config-v7.0.2...config-v7.0.3) (2021-06-10) ### Bug Fixes * merge conflict ([e1fcf01](https://www.github.com/netlify/build/commit/e1fcf017549a084f7b024a6b7cdceb9154c6462e)) ### [7.0.2](https://www.github.com/netlify/build/compare/config-v7.0.1...config-v7.0.2) (2021-06-10) ### Bug Fixes * refactor a warning message ([#2973](https://www.github.com/netlify/build/issues/2973)) ([dee5bd8](https://www.github.com/netlify/build/commit/dee5bd8c68e77aa027894599e6c30a3eaf6f3c2a)) ### [7.0.1](https://www.github.com/netlify/build/compare/config-v7.0.0...config-v7.0.1) (2021-06-10) ### Bug Fixes * feature flags logging in `@netlify/config` ([#2993](https://www.github.com/netlify/build/issues/2993)) ([03e2978](https://www.github.com/netlify/build/commit/03e2978174ce6e357b66d6df054a441facbfd52d)) ## [7.0.0](https://www.github.com/netlify/build/compare/config-v6.10.0...config-v7.0.0) (2021-06-10) ### ⚠ BREAKING CHANGES * improve support for monorepo sites without a `publish` directory (#2988) ### Features * improve support for monorepo sites without a `publish` directory ([#2988](https://www.github.com/netlify/build/issues/2988)) ([1fcad8a](https://www.github.com/netlify/build/commit/1fcad8a81c35060fbc3ec8cb15ade9762579a166)) ## [6.10.0](https://www.github.com/netlify/build/compare/config-v6.9.2...config-v6.10.0) (2021-06-10) ### Features * improve feature flags logic ([#2960](https://www.github.com/netlify/build/issues/2960)) ([6df6360](https://www.github.com/netlify/build/commit/6df63603ee3822229d1504e95f4622d47387ddfb)) ### [6.9.2](https://www.github.com/netlify/build/compare/config-v6.9.1...config-v6.9.2) (2021-06-09) ### Bug Fixes * refactor warning message related to monorepo `publish` default value ([#2970](https://www.github.com/netlify/build/issues/2970)) ([09b50ac](https://www.github.com/netlify/build/commit/09b50acb82c10eccbf96752e76e47907e50c029f)) ### [6.9.1](https://www.github.com/netlify/build/compare/config-v6.9.0...config-v6.9.1) (2021-06-09) ### Bug Fixes * move build directory logic to its own file ([#2969](https://www.github.com/netlify/build/issues/2969)) ([db6eba3](https://www.github.com/netlify/build/commit/db6eba3ad9b72662ee23615b97408d064fcccd21)) ## [6.9.0](https://www.github.com/netlify/build/compare/config-v6.8.0...config-v6.9.0) (2021-06-09) ### Features * simplify code related to `base` directory ([#2951](https://www.github.com/netlify/build/issues/2951)) ([bfffc2e](https://www.github.com/netlify/build/commit/bfffc2e86a82ded738074b1ed32ce2bf0d8d4a91)) ## [6.8.0](https://www.github.com/netlify/build/compare/config-v6.7.3...config-v6.8.0) (2021-06-09) ### Features * refactor configuration file paths resolution ([#2954](https://www.github.com/netlify/build/issues/2954)) ([d059450](https://www.github.com/netlify/build/commit/d0594507501936a2eaba2b59c912d51962f738b8)) ### [6.7.3](https://www.github.com/netlify/build/compare/config-v6.7.2...config-v6.7.3) (2021-06-08) ### Bug Fixes * `@netlify/config` `README` update ([#2946](https://www.github.com/netlify/build/issues/2946)) ([baf5a9a](https://www.github.com/netlify/build/commit/baf5a9aff5eb8a5040930189fc0406e46980a994)) ### [6.7.2](https://www.github.com/netlify/build/compare/config-v6.7.1...config-v6.7.2) (2021-06-04) ### Bug Fixes * **deps:** update dependency netlify to ^7.0.1 ([#2908](https://www.github.com/netlify/build/issues/2908)) ([28f1366](https://www.github.com/netlify/build/commit/28f13666a0dec4625c221619175f554aa7c8b761)) ### [6.7.1](https://www.github.com/netlify/build/compare/config-v6.7.0...config-v6.7.1) (2021-05-27) ### Bug Fixes * **deps:** update dependency netlify to v7 ([#2858](https://www.github.com/netlify/build/issues/2858)) ([866fddb](https://www.github.com/netlify/build/commit/866fddbb0eb9a8272997960197b8418c62a4b06b)) ## [6.7.0](https://www.github.com/netlify/build/compare/config-v6.6.0...config-v6.7.0) (2021-05-24) ### Features * **config:** consider package.json when detecting base directory ([#2838](https://www.github.com/netlify/build/issues/2838)) ([9172222](https://www.github.com/netlify/build/commit/9172222dea8458bf32119788fc89c17264757e5f)) ## [6.6.0](https://www.github.com/netlify/build/compare/config-v6.5.0...config-v6.6.0) (2021-05-21) ### Features * print a warning message when `base` is set but not `publish` ([#2827](https://www.github.com/netlify/build/issues/2827)) ([a9fb807](https://www.github.com/netlify/build/commit/a9fb807be477bcd2419520b92d8a7c7d7ee03088)) ## [6.5.0](https://www.github.com/netlify/build/compare/config-v6.4.4...config-v6.5.0) (2021-05-12) ### Features * **config:** return repository root ([#2785](https://www.github.com/netlify/build/issues/2785)) ([9a05786](https://www.github.com/netlify/build/commit/9a05786266c51031ccaef1f216f21c5821ec92fb)) ### [6.4.4](https://www.github.com/netlify/build/compare/config-v6.4.3...config-v6.4.4) (2021-05-05) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.27 ([#2745](https://www.github.com/netlify/build/issues/2745)) ([c2725e8](https://www.github.com/netlify/build/commit/c2725e835e1b13c233f53201399c767a75e1bab1)) ### [6.4.3](https://www.github.com/netlify/build/compare/config-v6.4.2...config-v6.4.3) (2021-05-04) ### Bug Fixes * **deps:** update netlify packages ([#2735](https://www.github.com/netlify/build/issues/2735)) ([6060bab](https://www.github.com/netlify/build/commit/6060babcee003881df46f45eda1118b7737cc4e1)) ### [6.4.2](https://www.github.com/netlify/build/compare/config-v6.4.1...config-v6.4.2) (2021-05-03) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.25 ([#2733](https://www.github.com/netlify/build/issues/2733)) ([0a06086](https://www.github.com/netlify/build/commit/0a060867d3896adf61daf4ddd875e872a1ae956d)) ### [6.4.1](https://www.github.com/netlify/build/compare/config-v6.4.0...config-v6.4.1) (2021-05-03) ### Bug Fixes * **deps:** update dependency map-obj to v4 ([#2721](https://www.github.com/netlify/build/issues/2721)) ([17559dc](https://www.github.com/netlify/build/commit/17559dcc75dd9f9a73f2a604c9f8ef3140a91b42)) * local builds version pinning ([#2717](https://www.github.com/netlify/build/issues/2717)) ([f3a8c17](https://www.github.com/netlify/build/commit/f3a8c17dbcbc9c4f44ba97acf9e886e1cb03da71)) ## [6.4.0](https://www.github.com/netlify/build/compare/config-v6.3.2...config-v6.4.0) (2021-05-03) ### Features * add support for `functions.included_files` config property ([#2681](https://www.github.com/netlify/build/issues/2681)) ([d75dc74](https://www.github.com/netlify/build/commit/d75dc74d9bbe9b542b17afce37419bed575c8651)) ### [6.3.2](https://www.github.com/netlify/build/compare/config-v6.3.1...config-v6.3.2) (2021-04-29) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.24 ([#2686](https://www.github.com/netlify/build/issues/2686)) ([914b7cb](https://www.github.com/netlify/build/commit/914b7cb11ee0bd9edb95f304c34fecc01e36bdc3)) ### [6.3.1](https://www.github.com/netlify/build/compare/config-v6.3.0...config-v6.3.1) (2021-04-29) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.23 ([#2684](https://www.github.com/netlify/build/issues/2684)) ([cf821f1](https://www.github.com/netlify/build/commit/cf821f102ea219af730c3b6d9989c16a0500e211)) ## [6.3.0](https://www.github.com/netlify/build/compare/config-v6.2.1...config-v6.3.0) (2021-04-27) ### Features * allow buildbot to pin plugin versions in `@netlify/config` ([#2674](https://www.github.com/netlify/build/issues/2674)) ([2e8a086](https://www.github.com/netlify/build/commit/2e8a0866b6bc60dfbeaccc54edc093c82d5aef7a)) ### [6.2.1](https://www.github.com/netlify/build/compare/config-v6.2.0...config-v6.2.1) (2021-04-26) ### Bug Fixes * add some newlines before some warning message ([#2652](https://www.github.com/netlify/build/issues/2652)) ([fc96155](https://www.github.com/netlify/build/commit/fc96155d137fb9a772dda25586007d04a30bf448)) * **deps:** update dependency map-obj to v3.1.0 ([#2656](https://www.github.com/netlify/build/issues/2656)) ([89e497a](https://www.github.com/netlify/build/commit/89e497a37a892f203a601a510e0e24ae037ad146)) * missing colors in `@netlify/config` warnings ([#2651](https://www.github.com/netlify/build/issues/2651)) ([5133c2a](https://www.github.com/netlify/build/commit/5133c2a8c95af70b928b6f7b3e3de702b0570bd8)) ## [6.2.0](https://www.github.com/netlify/build/compare/config-v6.1.0...config-v6.2.0) (2021-04-23) ### Features * improve context-specific configuration validation ([#2648](https://www.github.com/netlify/build/issues/2648)) ([e5059f9](https://www.github.com/netlify/build/commit/e5059f999488e9833c129f4a26d10811e7541878)) ## [6.1.0](https://www.github.com/netlify/build/compare/config-v6.0.3...config-v6.1.0) (2021-04-23) ### Features * validate all contexts in configuration ([#2641](https://www.github.com/netlify/build/issues/2641)) ([447f21e](https://www.github.com/netlify/build/commit/447f21ed87079ef4b12a96e67ca55b4f2ba544b3)) ### [6.0.3](https://www.github.com/netlify/build/compare/config-v6.0.2...config-v6.0.3) (2021-04-23) ### Bug Fixes * support `main` branch in `@netlify/config` ([#2639](https://www.github.com/netlify/build/issues/2639)) ([7728c60](https://www.github.com/netlify/build/commit/7728c60aed1e7c3bf0bb7a95aeef8b6686ca7478)) ### [6.0.2](https://www.github.com/netlify/build/compare/config-v6.0.1...config-v6.0.2) (2021-04-20) ### Bug Fixes * **deps:** update netlify packages ([#2622](https://www.github.com/netlify/build/issues/2622)) ([4d35de4](https://www.github.com/netlify/build/commit/4d35de4d4d8d49b460080480c6e5b3610e6ef023)) ### [6.0.1](https://www.github.com/netlify/build/compare/config-v6.0.0...config-v6.0.1) (2021-04-14) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.18 ([#2602](https://www.github.com/netlify/build/issues/2602)) ([c36356d](https://www.github.com/netlify/build/commit/c36356de80c4a19fb8ee808f074c9c9e827ebc07)) ## [6.0.0](https://www.github.com/netlify/build/compare/config-v5.12.0...config-v6.0.0) (2021-04-14) ### ⚠ BREAKING CHANGES * simplify `inlineConfig`, `defaultConfig` and `cachedConfig` CLI flags (#2595) ### Features * simplify `inlineConfig`, `defaultConfig` and `cachedConfig` CLI flags ([#2595](https://www.github.com/netlify/build/issues/2595)) ([c272632](https://www.github.com/netlify/build/commit/c272632db8825f85c07bb05cd90eacb1c8ea2544)) ## [5.12.0](https://www.github.com/netlify/build/compare/config-v5.11.1...config-v5.12.0) (2021-04-12) ### Features * deep merge context-specific plugin config ([#2572](https://www.github.com/netlify/build/issues/2572)) ([0a29162](https://www.github.com/netlify/build/commit/0a2916234a14ef0f99f093c8c5cdde0727d0f09f)) ### [5.11.1](https://www.github.com/netlify/build/compare/config-v5.11.0...config-v5.11.1) (2021-04-12) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.17 ([#2589](https://www.github.com/netlify/build/issues/2589)) ([925a1c4](https://www.github.com/netlify/build/commit/925a1c4613be2d96142caecda9dd452a0fd4f951)) ## [5.11.0](https://www.github.com/netlify/build/compare/config-v5.10.0...config-v5.11.0) (2021-04-09) ### Features * add a test related to context-specific plugins config ([#2570](https://www.github.com/netlify/build/issues/2570)) ([cb23b93](https://www.github.com/netlify/build/commit/cb23b938c32775ff852ce815bc3622b9c0cfcf5a)) ## [5.10.0](https://www.github.com/netlify/build/compare/config-v5.9.0...config-v5.10.0) (2021-04-09) ### Features * allow context-specific plugins configuration ([#2567](https://www.github.com/netlify/build/issues/2567)) ([dc3b462](https://www.github.com/netlify/build/commit/dc3b46223fe2d965d6a8fb479e41f65bc7c89478)) ## [5.9.0](https://www.github.com/netlify/build/compare/config-v5.8.0...config-v5.9.0) (2021-04-08) ### Features * move validation related to duplicated plugins configuration ([#2566](https://www.github.com/netlify/build/issues/2566)) ([df2e5d5](https://www.github.com/netlify/build/commit/df2e5d563397b90ec79982f264c851e9bd21b2c4)) ## [5.8.0](https://www.github.com/netlify/build/compare/config-v5.7.0...config-v5.8.0) (2021-04-08) ### Features * refactor configuration merge logic ([#2564](https://www.github.com/netlify/build/issues/2564)) ([06ea3fd](https://www.github.com/netlify/build/commit/06ea3fd438c25f8f372b4a111119e116f7d90f6d)) ## [5.7.0](https://www.github.com/netlify/build/compare/config-v5.6.0...config-v5.7.0) (2021-04-08) ### Features * refactor configuration merge logic ([#2561](https://www.github.com/netlify/build/issues/2561)) ([839d400](https://www.github.com/netlify/build/commit/839d4008dd3d515785bdff12174910902d242709)) * refactors how plugins configurations are currently merged ([#2562](https://www.github.com/netlify/build/issues/2562)) ([7276576](https://www.github.com/netlify/build/commit/7276576020d9bf133f1e50666a614c10e980be3b)) ## [5.6.0](https://www.github.com/netlify/build/compare/config-v5.5.1...config-v5.6.0) (2021-04-08) ### Features * improve how context-specific config are merged ([#2555](https://www.github.com/netlify/build/issues/2555)) ([a642a9d](https://www.github.com/netlify/build/commit/a642a9d36f24dc5c93e43304858007c524035b71)) ### [5.5.1](https://www.github.com/netlify/build/compare/config-v5.5.0...config-v5.5.1) (2021-04-07) ### Bug Fixes * context properties should not unset plugins ([#2558](https://www.github.com/netlify/build/issues/2558)) ([32be1bb](https://www.github.com/netlify/build/commit/32be1bb7d052d8e4a0b9bcbf9d5d0dbd428a8535)) ## [5.5.0](https://www.github.com/netlify/build/compare/config-v5.4.0...config-v5.5.0) (2021-04-07) ### Features * validate `context.{context}.*` properties ([#2551](https://www.github.com/netlify/build/issues/2551)) ([4559349](https://www.github.com/netlify/build/commit/45593491b6a053c0d256a169d4ff998187c533e9)) ## [5.4.0](https://www.github.com/netlify/build/compare/config-v5.3.1...config-v5.4.0) (2021-04-07) ### Features * refactor configuration property origins ([#2549](https://www.github.com/netlify/build/issues/2549)) ([b1d7c66](https://www.github.com/netlify/build/commit/b1d7c6623a16a62941ddd2f3d406657c4206b096)) ### [5.3.1](https://www.github.com/netlify/build/compare/config-v5.3.0...config-v5.3.1) (2021-04-07) ### Bug Fixes * improve config normalization logic ([#2547](https://www.github.com/netlify/build/issues/2547)) ([7945e0a](https://www.github.com/netlify/build/commit/7945e0ab496f48da006392646cf0512f6a564348)) ## [5.3.0](https://www.github.com/netlify/build/compare/config-v5.2.0...config-v5.3.0) (2021-04-07) ### Features * refactor how origin is added to context-specific configs ([#2545](https://www.github.com/netlify/build/issues/2545)) ([c3f45b2](https://www.github.com/netlify/build/commit/c3f45b288544200a6408a9af7bdfb955d45ebb81)) ## [5.2.0](https://www.github.com/netlify/build/compare/config-v5.1.1...config-v5.2.0) (2021-04-07) ### Features * refactor plugins[*].origin ([#2540](https://www.github.com/netlify/build/issues/2540)) ([43ad104](https://www.github.com/netlify/build/commit/43ad104928d707b864a6e667270d783ae4e5cbac)) ### [5.1.1](https://www.github.com/netlify/build/compare/config-v5.1.0...config-v5.1.1) (2021-04-06) ### Bug Fixes * validate build.command even when not used due to config merge ([#2541](https://www.github.com/netlify/build/issues/2541)) ([95c8e70](https://www.github.com/netlify/build/commit/95c8e7088c8956b34535548da4b2c7a3014ff37d)) ## [5.1.0](https://www.github.com/netlify/build/compare/config-v5.0.1...config-v5.1.0) (2021-04-01) ### Features * add functions config object to build output ([#2518](https://www.github.com/netlify/build/issues/2518)) ([280834c](https://www.github.com/netlify/build/commit/280834c079995ad3c3b5607f983198fba6b3ac13)) ### [5.0.1](https://www.github.com/netlify/build/compare/config-v5.0.0...config-v5.0.1) (2021-04-01) ### Bug Fixes * reinstate legacy build.functions property ([#2519](https://www.github.com/netlify/build/issues/2519)) ([488bea6](https://www.github.com/netlify/build/commit/488bea6f6a75aaf7bdd33b9c5d781b49f2316168)) ## [5.0.0](https://www.github.com/netlify/build/compare/config-v4.3.0...config-v5.0.0) (2021-03-30) ### ⚠ BREAKING CHANGES * add functions.directory property (#2496) ### Features * add functions.directory property ([#2496](https://www.github.com/netlify/build/issues/2496)) ([d72b1d1](https://www.github.com/netlify/build/commit/d72b1d1fb91de3fa23310ed477a6658c5492aed0)) ## [4.3.0](https://www.github.com/netlify/build/compare/v4.2.0...v4.3.0) (2021-03-23) ### Features * add context support to the functions block ([#2447](https://www.github.com/netlify/build/issues/2447)) ([5813826](https://www.github.com/netlify/build/commit/581382662506b01695fcbedadc0ea4b7d19b7efc)) ## [4.2.0](https://www.github.com/netlify/build/compare/v4.1.3...v4.2.0) (2021-03-18) ### Features * add functions configuration API to @netlify/config ([#2390](https://www.github.com/netlify/build/issues/2390)) ([654d32e](https://www.github.com/netlify/build/commit/654d32eb49bea33816b1adde02f13f0843db9cdd)) * add functions.*.node_bundler config property ([#2430](https://www.github.com/netlify/build/issues/2430)) ([72bed60](https://www.github.com/netlify/build/commit/72bed606e4395a42861bf0f78c43eb81bcdcc326)) ### [4.1.3](https://www.github.com/netlify/build/compare/v4.1.2...v4.1.3) (2021-03-12) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.16 ([#2399](https://www.github.com/netlify/build/issues/2399)) ([528d5b9](https://www.github.com/netlify/build/commit/528d5b99e09d38c414bb4daa7c906a72bdd83302)) ### [4.1.2](https://www.github.com/netlify/build/compare/v4.1.1...v4.1.2) (2021-03-10) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.14 ([#2387](https://www.github.com/netlify/build/issues/2387)) ([d5886f1](https://www.github.com/netlify/build/commit/d5886f1537734af0abf06bd59d083ca16d6b49a5)) ### [4.1.1](https://www.github.com/netlify/build/compare/v4.1.0...v4.1.1) (2021-03-09) ### Bug Fixes * fix `host` option in `@netlify/config` ([#2379](https://www.github.com/netlify/build/issues/2379)) ([64d8386](https://www.github.com/netlify/build/commit/64d8386daf5f1f069ea95fb655a593b05f8f8107)) ## [4.1.0](https://www.github.com/netlify/build/compare/v4.0.4...v4.1.0) (2021-03-08) ### Features * allow passing Netlify API host to Netlify API client ([#2288](https://www.github.com/netlify/build/issues/2288)) ([5529b1d](https://www.github.com/netlify/build/commit/5529b1dc92eccb6a932f80b006e83acfa0034413)) ### [4.0.4](https://www.github.com/netlify/build/compare/v4.0.3...v4.0.4) (2021-03-04) ### Bug Fixes * **deps:** update netlify packages ([#2352](https://www.github.com/netlify/build/issues/2352)) ([c45bdc8](https://www.github.com/netlify/build/commit/c45bdc8e6165751b4294993426ff32e366f0c55a)) ### [4.0.3](https://www.github.com/netlify/build/compare/v4.0.2...v4.0.3) (2021-03-03) ### Bug Fixes * **deps:** update dependency netlify to ^6.1.11 ([#2343](https://www.github.com/netlify/build/issues/2343)) ([bafca4e](https://www.github.com/netlify/build/commit/bafca4e8d2d462c1816695483bc1e381cc199b33)) ### [4.0.2](https://www.github.com/netlify/build/compare/v4.0.1...v4.0.2) (2021-02-18) ### Bug Fixes * fix `files` in `package.json` with `npm@7` ([#2278](https://www.github.com/netlify/build/issues/2278)) ([e9df064](https://www.github.com/netlify/build/commit/e9df0645f3083a0bb141c8b5b6e474ed4e27dbe9)) ### [4.0.1](https://www.github.com/netlify/build/compare/v4.0.0...v4.0.1) (2021-02-09) ### Bug Fixes * **deps:** update dependency netlify to v6.1.7 ([#2261](https://www.github.com/netlify/build/issues/2261)) ([607c848](https://www.github.com/netlify/build/commit/607c84868af5db36e18c9a9160b4d5e811c22e3a)) ## [4.0.0](https://www.github.com/netlify/build/compare/v3.1.2...v4.0.0) (2021-02-04) ### ⚠ BREAKING CHANGES * use netlify/functions as the default functions directory (#2188) ### Features * use netlify/functions as the default functions directory ([#2188](https://www.github.com/netlify/build/issues/2188)) ([84e1e07](https://www.github.com/netlify/build/commit/84e1e075b5efd7ca26ccaf2531511e7737d97f1f)) ### [3.1.2](https://www.github.com/netlify/build/compare/v3.1.1...v3.1.2) (2021-02-02) ### Bug Fixes * add SITE_ID and SITE_NAME env vars to local builds ([#2239](https://www.github.com/netlify/build/issues/2239)) ([113e4d2](https://www.github.com/netlify/build/commit/113e4d2c48e0264e48f391e5a7d219332d012fab)) ### [3.1.1](https://www.github.com/netlify/build/compare/v3.1.0...v3.1.1) (2021-01-29) ### Bug Fixes * **deps:** update dependency netlify to v6.1.5 ([#2225](https://www.github.com/netlify/build/issues/2225)) ([fec5c83](https://www.github.com/netlify/build/commit/fec5c83c12ebf7572aaf8756fdbec6e9fe1e3699)) ## [3.1.0](https://www.github.com/netlify/build/compare/v3.0.5...v3.1.0) (2021-01-27) ### Features * allow override of API URL ([#2190](https://www.github.com/netlify/build/issues/2190)) ([3e1be70](https://www.github.com/netlify/build/commit/3e1be7057ac9f217405b2cbe15f39e1ecd7496e6)) ### [3.0.5](https://www.github.com/netlify/build/compare/v3.0.4...v3.0.5) (2021-01-27) ### Bug Fixes * **deps:** update dependency netlify to v6.1.4 ([#2219](https://www.github.com/netlify/build/issues/2219)) ([3a75574](https://www.github.com/netlify/build/commit/3a7557400d46388aad42250f6d9751f1617f3cd0)) ### [3.0.4](https://www.github.com/netlify/build/compare/v3.0.3...v3.0.4) (2021-01-25) ### Bug Fixes * **deps:** update dependency netlify to v6.1.3 ([#2210](https://www.github.com/netlify/build/issues/2210)) ([b7c2c40](https://www.github.com/netlify/build/commit/b7c2c4049e9037cf855475543b13e33c32ceb4a6)) ### [3.0.3](https://www.github.com/netlify/build/compare/v3.0.2...v3.0.3) (2021-01-25) ### Bug Fixes * **deps:** update dependency netlify to v6.1.1 ([#2200](https://www.github.com/netlify/build/issues/2200)) ([930805e](https://www.github.com/netlify/build/commit/930805ec70cedbb08d58490c038ea9bcd8ecd35f)) ### [3.0.2](https://www.github.com/netlify/build/compare/config-v3.0.1...v3.0.2) (2021-01-22) ### Bug Fixes * **deps:** update dependency netlify to v6.1.0 ([#2194](https://www.github.com/netlify/build/issues/2194)) ([4b39e9c](https://www.github.com/netlify/build/commit/4b39e9c746c3a8cf1753bd66913883f2adff6ed8)) <file_sep>'use strict' module.exports = () => 'two' <file_sep>[build] edge_handlers = "custom-edge-handlers" <file_sep>'use strict' const { exit } = require('process') exit(1) <file_sep>'use strict' const { writeFile } = require('fs') const { promisify } = require('util') const pWriteFile = promisify(writeFile) module.exports = { async onPreBuild({ netlifyConfig: { redirects }, constants: { PUBLISH_DIR } }) { console.log(redirects) await pWriteFile(`${PUBLISH_DIR}/_redirects`, '/from /to') }, onBuild({ netlifyConfig: { redirects } }) { console.log(redirects) }, } <file_sep>'use strict' module.exports = { onPreBuild({ netlifyConfig }) { // eslint-disable-next-line no-param-reassign netlifyConfig.headers = [...netlifyConfig.headers, { for: '/path', values: { test: 'two' } }] }, onBuild({ netlifyConfig: { headers } }) { console.log(headers) }, }
b70b7d54b329c2059ffe4109d33b7e0f5dc4fb62
[ "JavaScript", "TOML", "Markdown" ]
118
JavaScript
bengry/build
05c84e23975c5d3cfa43fb72718a7ff49e141e6f
cbef8e9090c33eba8aa24f1e46e7a8beecd8b33b
refs/heads/master
<repo_name>changkon/VAMIX<file_sep>/src/model/TimeBoundedRangeModel.java package model; import javax.swing.DefaultBoundedRangeModel; /** * * The BoundedRangeModel used as the JSlider model for the time bar. This model extends DefaultBoundedRangeModel and also includes a boolean variable * which indicates when it should be active in triggering events. </br> * * {@link listener.MediaPlayerListener} </br> * {@link panel.PlaybackPanel} */ @SuppressWarnings("serial") public class TimeBoundedRangeModel extends DefaultBoundedRangeModel { private boolean active = true; // Toggle active public void setActive(boolean value) { active = value; } public boolean getActive() { return active; } @Override protected void fireStateChanged() { super.fireStateChanged(); // After every event. Turn active back to true. active = true; } } <file_sep>/src/worker/TextFilterSaveWorker.java package worker; import java.util.ArrayList; import java.util.Iterator; import javax.swing.ProgressMonitor; import operation.MediaTimer; /** * Encodes text edit filter options to video file. Progress is shown on progress monitor. */ public class TextFilterSaveWorker extends DefaultWorker { private String inputFile, outputFile; private ArrayList<Object[]> textList; public TextFilterSaveWorker(String inputFile, String outputFile, ArrayList<Object[]> textList, ProgressMonitor monitor) { super(monitor); this.inputFile = inputFile; this.outputFile = outputFile; this.textList = textList; initialiseVariables(); } @Override protected String getCommand() { //detects the number of seconds to display for and what to display StringBuilder command = new StringBuilder(); command.append("avconv -i \'" + inputFile + "\' -c:a copy -vf drawtext=\"fontfile="); for (Iterator<Object[]> iter = textList.iterator(); iter.hasNext();) { Object[] i = iter.next(); command.append(i[3] + ": fontsize="); command.append(i[4] + ": fontcolor="); command.append(i[5] + ": x="); command.append(i[6] + ": y="); command.append(i[7] + ": text=\'"); command.append(i[2] + "\': draw=\'gt(t," + MediaTimer.getSeconds(i[0].toString()) + ")*lt(t,"); command.append(MediaTimer.getSeconds(i[1].toString()) + ")\'"); if (iter.hasNext()) { command.append(":,drawtext=fontfile="); } } command.append("\" -y \'" + outputFile + "\'"); return command.toString(); } @Override protected String getSuccessMessage() { return "Filtering has completed"; } @Override protected String getCancelMesssage() { return "Filtering was interrupted"; } } <file_sep>/src/panel/MainPanel.java package panel; import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; /** * Super panel which contains the mediaPanel, audioFiltersPanel and videoFilterPanel. {@link frame.VamixFrame} * @author chang * */ @SuppressWarnings("serial") public class MainPanel extends JPanel { private static MainPanel theInstance = null; private JPanel mediaPanel, audioFilterPanel, videoFilterPanel; public static MainPanel getInstance() { if (theInstance == null) { theInstance = new MainPanel(); } return theInstance; } private MainPanel() { setLayout(new MigLayout()); mediaPanel = MediaPanel.getInstance(); audioFilterPanel = AudioFilterPanel.getInstance(); videoFilterPanel = VideoFilterPanel.getInstance(); add(mediaPanel, "push, grow"); add(videoFilterPanel, "span 1 2, width 550px, pushy, growy, wrap"); add(audioFilterPanel, "pushx, growx, height 354px"); } } <file_sep>/src/component/FileType.java package component; /** * Enum for media type. Each type contains valid keywords which are used to identify file type when called by file command. * @author chang * */ public enum FileType { AUDIO(new String[] {"audio", "Audio"}), VIDEO(new String[] {"video", "ISO Media", "Matroska", "AVI"}), TEXT(new String[] {"ASCII text", "UTF-8"}); private String[] type; private FileType(String[] type) { this.type = type; } public String[] getSupportedFormats() { return type; } } <file_sep>/src/component/Playback.java package component; /** * Common media player commands saved as constants. */ public enum Playback { PLAY, PAUSE, STOP, FASTFORWARD, REWIND, MUTE, UNMUTE, MAXVOLUME, OPEN, DOWNLOAD, FULLSCREEN, LEFT, RIGHT; } <file_sep>/src/component/ProgressRenderer.java package component; import java.awt.Component; import javax.swing.JProgressBar; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; /** * Updates the table with correct progress value. <br/> * {@link panel.DownloadPanel} * @author chang * */ @SuppressWarnings("serial") public class ProgressRenderer extends JProgressBar implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int progress = (int)value; setValue(progress); setString(progress + "%"); setStringPainted(true); return this; } } <file_sep>/src/worker/AudioReplaceWorker.java package worker; import javax.swing.ProgressMonitor; /** * Creates a new video and replaces that video's audio with a new audio. * */ public class AudioReplaceWorker extends DefaultWorker { private String videoFileInput; private String audioFileInput; private String videoFileOutput; public AudioReplaceWorker(String videoFileInput, String audioFileInput, String videoFileOutput, ProgressMonitor monitor) { super(monitor); this.videoFileInput = videoFileInput; this.audioFileInput = audioFileInput; this.videoFileOutput = videoFileOutput; initialiseVariables(); } @Override protected String getCommand() { return "avconv -i \'" + videoFileInput + "\' -i \'" + audioFileInput + "\' -map 0:v -map 1:a " + "-c:v copy -c:a copy -y \'" + videoFileOutput + "\'"; } @Override protected String getSuccessMessage() { return "Replacing audio complete"; } @Override protected String getCancelMesssage() { return "Replacing audio cancelled"; } } <file_sep>/README.md VAMIX Prototype =============== README ------ Running VAMIX --------------- Through the terminal: java -jar filename.jar Through Eclipse: Import files to eclipse project and add src, help and res to be source folders. Add miglayout-4.0-swing.jar and vlcj-3.0.1.jar to Build Path. Media Player ------------ Open media files by pressing the Open media file icon which looks like an opened folder or by pressing Media->Open.. button from Menu. Play and pause media files by pressing play/pause icon. Stop media by pressing stop icon. You can resume playing same media file by pressing play. Likewise, a media file which finished playing can be replayed by pressing play. Fast forward or rewind media by pressing fastforward/rewind button. Resume play by pressing play button. Mute and unmute media by pressing the speaker icon to the left of the volume slider. Maximise audio by pressing the speaker icon to the right of the volume slider. Adjust audio manually by dragging volume slider or clicking area in volume slider. Adjust media time by dragging time slider or clicking area in time slider. Double click media player component to enter full screen. The fullscreen button toggles fullscreen. If fullscreen is not supported, a message will appear. During fullscreen, the playback panel appears whenever mouse is moved and disappears after 3 seconds of idle. Exiting fullscreen can be achieved by pressing esc and playing/pausing by pressing space during fullscreen mode. Download -------- Enter url to textfield and press download button to start download. Specify file location and overwrite if necessary. Cancel download by selecting the desired download and press cancel button. Downloading can be resumed if you cancel download and start again by overwriting it. If it's the same download, it will continue from before. Before downloading, it checks if it's a valid link. If it's not a valid link, it tells user. TextFilter ---------- Has a choice between text font, text size, text colour, text position. The duration of the text edit is determined by specifying the start and end times. The start and end button can be pressed to get the current media time. The text to be displayed must be added to the text box. Add the data to the table by pressing Add. Edit the data by selecting the row to edit on the table and press edit. Delete data by selecting the row to delete and press the Delete button. Preview text edit by selecting the row to preview and press the preview button. Save text edit to the video by pressing the Save Video button and specify output name and file type. Save current work by pressing Save Work button and save the current session into a text file. Load previous work by pressing Load Work button and choose an appropriate text file. Fade Filter ----------- Specify start and end time for fade effects. Choose fade type and then press Add to add the fade effect data to the table. Edit fade data by selecting the row to edit and press Edit. Delete fade data by selecting the row to delete and press delete. Preview fade effect by selecting the fade effect to preview on the table and press Preview Fade. Save the fade effects by pressing Save Fade and specify output filename and type. Save work by pressing Save Work to save the current session. Load work by pressing Load Work to load previous fade effect sessions. Subtitle -------- Import subtitles to the table by pressing the import button. Specify the start and end times for the subtitle to appear in the video. Put the desired text into the text box. Add subtitles by pressing Add. Edit subtitles in the table by selecting the row in the table and press Edit. Delete subtitle data by selecting the row in the table and press Delete. Save the subtitle in the table to a srt file by pressing Save Subtitle. Place subtitle to a video file by pressing Add Subtitle to Video button and choose a subtitle file and then specify the output name and file type. Extraction ---------- Extracts AUDIO from MEDIA file. Must be playing a video in media player first. Specify extraction times: Put in times in the following format hh:mm:ss and click Extract button. Extract full audio Click extract entire file which extracts audio from the media file. Replace Audio ------------- Must be playing a video in media player first. Choose an audio file to replace by clicking Choose File button under Replace Audio header. The selected file path will be shown on the JTextField. Replace audio by pressing Replace button and choose output filename. Overlay Audio ------------- Must be playing a video in media player first. Choose an audio file to overlay by clicking Choose File button under Overlay Audio header. The selected file path will be shown on the JTextField. Overlay audio by pressing Overlay button and choose output filename. Add Audio Track --------------- Must be playing a video in media player first. Choose an audio file to add to video file by clicking Choose File button. The selected file path will be shown on the JTextField. Add audio track by clicking Add Track button and choose output filename. Change Volume ------------- Must be playing media player with a media file which has an audio track. Select a multiplier using the JSpinner which increments/decrements the value by 0.1. The selection values are between 0 - 5. eg. half the volume of the original should be set to 0.5 Change volume by clicking Change Volume button and choose output filename. Known Bugs ---------- 1. FullScreen is not perfect. If the media player is paused during the main menu entering fullscreen will play video instead of remaining paused. Mute icons and keeping mute is not implemented at the moment. 2. For some progress monitors such as during Change Volume, the progress bar does not update when the input file is an audio file. This is because of an error during avconv command. However, the output file still seems to work as expected. 3. For previewing fade filters, preview doesn't work properly. If the fade filter effect is not near the start of the video, the video remains black in the preview window. If the user keeps playing the preview window until the end of the video, the window freezes and the user is unabe to close the window unless VAMIX is closed. More Information ---------------- For more information, please see the User Manual <file_sep>/src/operation/FileSelection.java package operation; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import component.FileType; /** * Class which deals with returning and getting strings of file selection (audio/video/text) by JFileChooser. * @author chang * */ public abstract class FileSelection { protected ArrayList<String[]> inputFilterList, outputFilterList; protected FileType fileType; protected String warningMessage; public FileSelection(ArrayList<String[]> inputFilterList, ArrayList<String[]> outputFilterList, FileType fileType, String warningMessage) { this.inputFilterList = inputFilterList; this.outputFilterList = outputFilterList; this.fileType = fileType; this.warningMessage = warningMessage; } /** * Returns the selected file. Returns null if the user cancels selection. * @return file of specific type */ public String getInputFilename() { JFileChooser chooser = new JFileChooser(); // Removes the accept all filter. chooser.setAcceptAllFileFilterUsed(false); // Adds appropriate filters to filechooser. for (String[] element : inputFilterList) { chooser.addChoosableFileFilter(new FileNameExtensionFilter(element[0], element[1])); } int selection = chooser.showOpenDialog(null); if (selection == JFileChooser.APPROVE_OPTION) { File saveFile = chooser.getSelectedFile(); String inputFilename = saveFile.getAbsolutePath(); // Checks that the file is the correct file or else it displays an error message. if (!VamixProcesses.validContentType(fileType, inputFilename)) { JOptionPane.showMessageDialog(null, inputFilename + warningMessage); return null; } return inputFilename; } return null; } /** * Returns the output filename. Asks user if overwrite is desired if same file exists. </br> * Returns null if user cancels selection or does not want to overwrite. * @return filename of output file */ public String getOutputFilename() { JFileChooser chooser = new JFileChooser(); // Removes the accept all filter. chooser.setAcceptAllFileFilterUsed(false); for (String[] element : outputFilterList) { chooser.addChoosableFileFilter(new FileNameExtensionFilter(element[0], element[1])); } int selection = chooser.showSaveDialog(null); if (selection == JFileChooser.APPROVE_OPTION) { File saveFile = chooser.getSelectedFile(); String extensionType = chooser.getFileFilter().getDescription(); String outputFilename = saveFile.getAbsolutePath(); /* * Check the output filename and adds the correct extension type. If the output filename already has the extension added, it * doesn't append extension again. */ for (String[] element : outputFilterList) { if (extensionType.contains(element[0]) && !saveFile.getAbsolutePath().contains(element[1])) { outputFilename = outputFilename + "." + element[1]; break; } } // Checks to see if the filename the user wants to save already exists so it asks if it wants to overwrite or not. if (Files.exists(Paths.get(outputFilename))) { int overwriteSelection = JOptionPane.showConfirmDialog(null, "File already exists, do you want to overwrite?", "Select an option", JOptionPane.YES_NO_OPTION); // Overwrite if yes. if (overwriteSelection == JOptionPane.OK_OPTION) { return outputFilename; } } else { return outputFilename; } } return null; } protected void setInputFilterList(ArrayList<String[]> inputFilterList) { this.inputFilterList = inputFilterList; } protected void setOutputFilterList(ArrayList<String[]> outputFilterList) { this.outputFilterList = outputFilterList; } } <file_sep>/src/operation/LogSession.java package operation; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; public class LogSession { // Arbitrary separator value. Selected as it is an unlikely pattern. private static final String SEPARATORVALUE = ",;;,"; /** * Saves the data given to a text file. Separates each value by the separator value. * @param filename * @param type * @param data */ public static void saveLog(String outputFilename, String type, Vector data) { File file = new File(outputFilename); if (file.exists()) { file.delete(); } try { BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilename)); // Write the type of the saved file. writer.append(type + "\n"); for (Object element : data) { Vector v = (Vector)element; Object[] values = v.toArray(); for (Object i : values) { writer.append(i + SEPARATORVALUE); } writer.append("\n"); } writer.close(); JOptionPane.showMessageDialog(null, "Log has been recorded."); } catch (IOException e) { e.printStackTrace(); } } /** * Reads the text file and returns the values back. If the text file is incorrect log file, return null. * @param filename * @param type * @return */ public static ArrayList<Object[]> getLog(String inputFilename, String type) { try { BufferedReader buffer = new BufferedReader(new FileReader(inputFilename)); String line = buffer.readLine(); if (line.equals(type)) { ArrayList<Object[]> list = new ArrayList<Object[]>(); while ((line = buffer.readLine()) != null) { String[] split = line.split(SEPARATORVALUE); list.add(split); } buffer.close(); return list; } else { buffer.close(); JOptionPane.showMessageDialog(null, "Incorrect log text. Cannot load work"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } <file_sep>/src/operation/TextFileSelection.java package operation; import java.util.ArrayList; import component.FileType; public class TextFileSelection extends FileSelection { @SuppressWarnings("serial") private static ArrayList<String[]> filterList = new ArrayList<String[]>() {{ add(new String[] {"Text/txt", "txt"}); }}; public TextFileSelection() { super(filterList, filterList, FileType.TEXT, " does not refer to a valid txt file."); } } <file_sep>/src/worker/FadeFilterSaveWorker.java package worker; import java.util.ArrayList; import java.util.Iterator; import javax.swing.ProgressMonitor; import operation.MediaTimer; import panel.FadeFilterPanel; /** * Output the fade filter effects to a new video file. * @author chang * */ public class FadeFilterSaveWorker extends DefaultWorker { private String inputFile, outputFile; private ArrayList<Object[]> fadeList; private float mediaFrameRate; public FadeFilterSaveWorker(String inputFile, String outputFile, ArrayList<Object[]> fadeList, float mediaFrameRate, ProgressMonitor monitor) { super(monitor); this.inputFile = inputFile; this.outputFile = outputFile; this.fadeList = fadeList; this.mediaFrameRate = mediaFrameRate; initialiseVariables(); } @Override protected String getCommand() { StringBuilder command = new StringBuilder(); String type = ""; command.append("avconv -i \'" + inputFile + "\' -c:a copy -vf \'fade="); for (Iterator<Object[]> iter = fadeList.iterator(); iter.hasNext();) { Object[] i = iter.next(); // Type is Fade In or Fade Out type = i[2].toString(); FadeFilterPanel fadePanel = FadeFilterPanel.getInstance(); // Append correct fade type. if (type.equals(fadePanel.fadeSelection[0])) { command.append("in:"); } else { command.append("out:"); } int startSeconds = MediaTimer.getSeconds(i[0].toString()); int endSeconds = MediaTimer.getSeconds(i[1].toString()); String formattedDifference = MediaTimer.getFormattedTime(Math.abs(startSeconds - endSeconds) * 1000); // State what frame the fade effect should start and then append the duration of the fade effect. command.append(Math.round(MediaTimer.getCurrentFrame(i[0].toString(), mediaFrameRate)) + ":"); command.append(Math.round((int)MediaTimer.getCurrentFrame(formattedDifference, mediaFrameRate))); // If another fade effect is present, append string. if (iter.hasNext()) { command.append(", fade="); } } command.append("\' -y \'" + outputFile + "\'"); return command.toString(); } @Override protected String getSuccessMessage() { return "Adding fade filters complete"; } @Override protected String getCancelMesssage() { return "Adding fade filter was interrupted"; } } <file_sep>/src/component/MyTextFieldFilter.java package component; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; /** * * Filtering only numbers * @see http://stackoverflow.com/questions/9477354/how-to-allow-introducing-only-digits-in-jtextfield * */ public class MyTextFieldFilter extends DocumentFilter { // Called when insertString method is called on document. eg textField.getDocument().insertString(..); @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { boolean isDigits = true; for(char c : string.toCharArray()) { if (!Character.isDigit(c)) { isDigits = false; break; } } if (isDigits) { super.insertString(fb, offset, string, attr); } } // Invoked whenever text is input into textfield @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { boolean isDigits = true; for(char c : text.toCharArray()) { if (!Character.isDigit(c)) { isDigits = false; break; } } if (isDigits) { super.replace(fb, offset, length, text, attrs); } } }<file_sep>/src/worker/OverlayWorker.java package worker; import javax.swing.ProgressMonitor; /** * Overlays video with existing audio and another video. Outputs a new video. */ public class OverlayWorker extends DefaultWorker { private String videoFileInput, audioFileInput, videoFileOutput; public OverlayWorker(String videoFileInput, String audioFileInput, String videoFileOutput, ProgressMonitor monitor) { super(monitor); this.videoFileInput = videoFileInput; this.audioFileInput = audioFileInput; this.videoFileOutput = videoFileOutput; initialiseVariables(); } @Override protected String getCommand() { return "avconv -i \'" + videoFileInput + "\' -i \"" + audioFileInput + "\" -filter_complex" + " \"[0:a][1:a]amix[out]\" -map \"[out]\" -map 0:v -c:v copy -strict experimental -y \'" + videoFileOutput + "\'"; } @Override protected String getSuccessMessage() { return "Overlaying audio complete"; } @Override protected String getCancelMesssage() { return "Overlaying audio cancelled"; } } <file_sep>/src/panel/AudioFirstPagePanel.java package panel; import java.awt.CardLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.ButtonModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.ProgressMonitor; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.miginfocom.swing.MigLayout; import operation.AudioFileSelection; import operation.FileSelection; import operation.MediaTimer; import operation.VamixProcesses; import operation.VideoFileSelection; import res.MediaIcon; import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer; import worker.AudioReplaceWorker; import worker.ExtractAudioWorker; import worker.OverlayWorker; import component.FileType; import component.Playback; /** * First page of audio panel. Contains extraction, replace and overlay features. * @author changkon * */ @SuppressWarnings("serial") public class AudioFirstPagePanel extends JPanel implements ActionListener { private static AudioFirstPagePanel theInstance = null; private EmbeddedMediaPlayer mediaPlayer = MediaPanel.getInstance().getMediaPlayerComponentPanel().getMediaPlayer(); private TitledBorder title; private JPanel audioExtractionPanel = new JPanel(new MigLayout()); private JPanel audioReplacePanel = new JPanel(new MigLayout()); private JPanel audioOverlayPanel = new JPanel(new MigLayout()); private JTextField startTimeInput = new JTextField(10); private JTextField lengthInput = new JTextField(10); private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); private JButton extractButton = new JButton("Extract"); private JButton extractFullButton = new JButton("Extract entire file"); private JButton selectAudioReplaceFileButton = new JButton("Choose File"); private JTextField selectedAudioReplaceFileTextField = new JTextField(); private JButton audioReplaceButton = new JButton("Replace"); private JButton selectAudioOverlayFileButton = new JButton("Choose File"); private JTextField selectedAudioOverlayFileTextField = new JTextField(); private JButton audioOverlayButton = new JButton("Overlay"); private FileSelection audioFileSelection, videoFileSelection; private JButton rightButton; private JPanel navigationPanel; public static AudioFirstPagePanel getInstance() { if (theInstance == null) { theInstance = new AudioFirstPagePanel(); } return theInstance; } private AudioFirstPagePanel() { setLayout(new MigLayout("fill")); title = BorderFactory.createTitledBorder("Audio First Page"); setBorder(title); setAudioExtractionPanel(); setAudioReplacePanel(); setAudioOverlayPanel(); setNavigationPanel(); audioFileSelection = new AudioFileSelection(); videoFileSelection = new VideoFileSelection(); addListeners(); add(audioExtractionPanel, "wrap 0px, pushx, growx"); add(audioReplacePanel, "wrap 0px, pushx, growx"); add(audioOverlayPanel, "pushx, growx, wrap 0px"); add(navigationPanel, "south"); } // Initialise panel for extraction and its layout private void setAudioExtractionPanel() { JLabel extractionLabel = new JLabel("Extraction"); JLabel timeLabel = new JLabel("Please input times in hh:mm:ss"); JLabel startTimeLabel = new JLabel("Start Time:"); JLabel lengthLabel = new JLabel("Length Time:"); Font font = extractionLabel.getFont().deriveFont(Font.BOLD, 16f); // Default is 12. JLabel orLabel = new JLabel("OR"); extractionLabel.setFont(font); extractButton.setForeground(Color.WHITE); extractButton.setBackground(new Color(59, 89, 182)); // blue extractFullButton.setForeground(Color.WHITE); extractFullButton.setBackground(new Color(59, 89, 182)); // blue audioExtractionPanel.add(extractionLabel, "wrap"); audioExtractionPanel.add(timeLabel, "wrap"); audioExtractionPanel.add(startTimeLabel, "split 4"); audioExtractionPanel.add(startTimeInput); audioExtractionPanel.add(lengthLabel); audioExtractionPanel.add(lengthInput); audioExtractionPanel.add(extractButton); audioExtractionPanel.add(orLabel, "gapleft 30"); audioExtractionPanel.add(extractFullButton, "gapleft 30, wrap"); } // Initialise panel for replace and its layout private void setAudioReplacePanel() { JLabel replaceAudioLabel = new JLabel("Replace Audio"); Font font = replaceAudioLabel.getFont().deriveFont(Font.BOLD, 16f); // Default is 12. replaceAudioLabel.setFont(font); // Custom coloured button selectAudioReplaceFileButton.setForeground(Color.WHITE); selectAudioReplaceFileButton.setBackground(new Color(59, 89, 182)); // blue audioReplaceButton.setBackground(new Color(219, 219, 219)); // light grey audioReplacePanel.add(replaceAudioLabel, "wrap"); audioReplacePanel.add(selectAudioReplaceFileButton); audioReplacePanel.add(selectedAudioReplaceFileTextField, "pushx, growx, wrap"); audioReplacePanel.add(audioReplaceButton); } private void setAudioOverlayPanel() { JLabel audioOverlayLabel = new JLabel("Overlay Audio"); Font font = audioOverlayLabel.getFont().deriveFont(Font.BOLD, 16f); audioOverlayLabel.setFont(font); selectAudioOverlayFileButton.setForeground(Color.WHITE); selectAudioOverlayFileButton.setBackground(new Color(59, 89, 182)); // blue audioOverlayButton.setBackground(new Color(219, 219, 219)); // light grey audioOverlayPanel.add(audioOverlayLabel, "wrap"); audioOverlayPanel.add(selectAudioOverlayFileButton); audioOverlayPanel.add(selectedAudioOverlayFileTextField, "pushx, growx, wrap"); audioOverlayPanel.add(audioOverlayButton); } private void setNavigationPanel() { navigationPanel = new JPanel(new MigLayout()); MediaIcon mediaIcon = new MediaIcon(15, 15); rightButton = new JButton(mediaIcon.getIcon(Playback.RIGHT)); rightButton.setToolTipText("Go to next page"); rightButton.setBorderPainted(false); rightButton.setFocusPainted(false); rightButton.setContentAreaFilled(false); navigationPanel.add(rightButton, "pushx, align right"); } // Initialise listeners private void addListeners() { extractButton.addActionListener(this); extractFullButton.addActionListener(this); selectAudioReplaceFileButton.addActionListener(this); audioReplaceButton.addActionListener(this); selectAudioOverlayFileButton.addActionListener(this); audioOverlayButton.addActionListener(this); rightButton.addActionListener(this); rightButton.getModel().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { ButtonModel model = (ButtonModel) e.getSource(); if (model.isRollover()) { rightButton.setBorderPainted(true); } else { rightButton.setBorderPainted(false); } } }); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == extractButton) { if (validateTime(startTimeInput.getText()) && validateTime(lengthInput.getText()) && VamixProcesses.validateMediaWithAudioTrack(mediaPlayer)) { String outputFilename = audioFileSelection.getOutputFilename(); if (outputFilename != null) { executeExtract(VamixProcesses.getFilename(mediaPlayer.mrl()), outputFilename, startTimeInput.getText(), lengthInput.getText()); } } } else if (e.getSource() == extractFullButton) { if (VamixProcesses.validateMediaWithAudioTrack(mediaPlayer)) { String outputFilename = audioFileSelection.getOutputFilename(); if (outputFilename != null) { String length = MediaTimer.getFormattedTime(mediaPlayer.getLength()); executeExtract(VamixProcesses.getFilename(mediaPlayer.mrl()), outputFilename, "00:00:00", length); } } } else if (e.getSource() == selectAudioReplaceFileButton) { String filename = audioFileSelection.getInputFilename(); if (filename != null) { selectedAudioReplaceFileTextField.setText(filename); } } else if (e.getSource() == audioReplaceButton) { if (VamixProcesses.validateVideoWithAudioTrack(mediaPlayer) && VamixProcesses.validateTextfield(selectedAudioReplaceFileTextField.getText(), FileType.AUDIO)) { File audioFile = new File(selectedAudioReplaceFileTextField.getText()); String audioPath = audioFile.getAbsolutePath(); String videoPath = videoFileSelection.getOutputFilename(); if (videoPath != null) { executeReplace(VamixProcesses.getFilename(mediaPlayer.mrl()), audioPath, videoPath); } } } else if (e.getSource() == selectAudioOverlayFileButton) { String filename = audioFileSelection.getInputFilename(); if (filename != null) { selectedAudioOverlayFileTextField.setText(filename); } } else if (e.getSource() == audioOverlayButton) { if (VamixProcesses.validateVideoWithAudioTrack(mediaPlayer) && VamixProcesses.validateTextfield(selectedAudioOverlayFileTextField.getText(), FileType.AUDIO)) { // This assumes that the audio selected is valid. No checking is done. File audioFile = new File(selectedAudioOverlayFileTextField.getText()); String audioPath = audioFile.getAbsolutePath(); String videoPath = videoFileSelection.getOutputFilename(); if (videoPath != null) { executeOverlay(VamixProcesses.getFilename(mediaPlayer.mrl()), audioPath, videoPath); } } } else if (e.getSource() == rightButton) { AudioFilterPanel audioFilterPanel = AudioFilterPanel.getInstance(); CardLayout card = (CardLayout)audioFilterPanel.getLayout(); card.show(audioFilterPanel, audioFilterPanel.AUDIOSECONDPAGESTRING); } } /** * {@link worker.AudioReplaceWorker} <br /> * Calls AudioReplaceWorker. Opens ProgressMonitor. * * @param videoInput * @param audioInput * @param videoOutput */ private void executeReplace(String videoInput, String audioInput, String videoOutput) { int audioInputLength = VamixProcesses.probeDuration(audioInput); int mediaPlayerLength = (int)(mediaPlayer.getLength() / 1000); ProgressMonitor monitor = new ProgressMonitor(null, "Replacing audio has started", "In progress..", 0, Math.max(audioInputLength, mediaPlayerLength)); AudioReplaceWorker worker = new AudioReplaceWorker(videoInput, audioInput, videoOutput, monitor); worker.execute(); } /** * {@link worker.OverlayWorker} <br /> * Calls OverlayWorker. Opens ProgressMonitor. * * @param videoInput * @param audioInput * @param videoOutput */ private void executeOverlay(String videoInput, String audioInput, String videoOutput) { int audioInputLength = VamixProcesses.probeDuration(audioInput); int videoInputLength = (int)(mediaPlayer.getLength() / 1000); ProgressMonitor monitor = new ProgressMonitor(null, "Overlaying audio has started", "In progress..", 0, Math.max(audioInputLength, videoInputLength)); OverlayWorker worker = new OverlayWorker(videoInput, audioInput, videoOutput, monitor); worker.execute(); } /** * {@link worker.ExtractAudioWorker } * * @param inputFilename * @param outputFilename * @param startTime * @param lengthTime */ private void executeExtract(String inputFilename, String outputFilename, String startTime, String lengthTime) { int lengthOfAudio = MediaTimer.getSeconds(lengthTime); ProgressMonitor monitor = new ProgressMonitor(null, "Extraction has started", "", 0, lengthOfAudio); ExtractAudioWorker worker = new ExtractAudioWorker(inputFilename, outputFilename, startTime, lengthTime, monitor); worker.execute(); } /** * Determines if the user input a valid time in the specified format. hh:mm:ss <br /> * * @param time * @return */ private boolean validateTime(String time) { Date inputTime = null; try { // Checks that you can formulate date from given input. inputTime = timeFormat.parse(time); } catch (ParseException e) { // The time that was input does not match our given time format. JOptionPane.showMessageDialog(null, time + " is in the wrong time format"); return false; } // Time can be rounded so ensure input time is correct. eg 61 seconds automatically becomes 1min 1sec. if (!timeFormat.format(inputTime).equals(time)) { JOptionPane.showMessageDialog(null, "Invalid time"); return false; } // If we reach this statement, time has been validated. return true; } } <file_sep>/src/panel/MediaPlayerComponentPanel.java package panel; import java.awt.BorderLayout; import javax.swing.JPanel; import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent; import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer; /** * Panel containing the mediaPlayer and mediaPlayerComponent. It uses BorderLayout so that it is automatically resized. * @author changkon * */ @SuppressWarnings("serial") public class MediaPlayerComponentPanel extends JPanel { private EmbeddedMediaPlayerComponent mediaPlayerComponent; private EmbeddedMediaPlayer mediaPlayer; public MediaPlayerComponentPanel() { setLayout(new BorderLayout()); mediaPlayerComponent = new EmbeddedMediaPlayerComponent(); mediaPlayer = mediaPlayerComponent.getMediaPlayer(); add(mediaPlayerComponent.getVideoSurface(), BorderLayout.CENTER); } public EmbeddedMediaPlayerComponent getMediaPlayerComponent() { return mediaPlayerComponent; } public EmbeddedMediaPlayer getMediaPlayer() { return mediaPlayer; } } <file_sep>/src/operation/VideoFileSelection.java package operation; import java.util.ArrayList; import component.FileType; public class VideoFileSelection extends FileSelection { @SuppressWarnings("serial") private static ArrayList<String[]> filterList = new ArrayList<String[]>() {{ add(new String[] {"MPEG-4/mp4", "mp4"}); add(new String[] {"Audio Video Interleaved/avi", "avi"}); add(new String[] {"Matroska/mkv", "mkv"}); }}; public VideoFileSelection() { super(filterList, filterList, FileType.VIDEO, " does not refer to a valid video file."); } } <file_sep>/src/operation/SubtitleFileSelection.java package operation; import java.util.ArrayList; import component.FileType; public class SubtitleFileSelection extends FileSelection { @SuppressWarnings("serial") private static ArrayList<String[]> filterList = new ArrayList<String[]>() {{ add(new String[] {"SubRip Text/srt", "srt"}); }}; @SuppressWarnings("serial") private static ArrayList<String[]> outputVideoFilterList = new ArrayList<String[]>() {{ add(new String[] {"Matroska/mkv", "mkv"}); }}; public SubtitleFileSelection() { super(filterList, filterList, FileType.TEXT, " does not refer to a valid srt file."); } @Override public String getOutputFilename() { setOutputFilterList(filterList); return super.getOutputFilename(); } public String getOutputVideoFilename() { setOutputFilterList(outputVideoFilterList); return super.getOutputFilename(); } } <file_sep>/src/res/FilterColor.java package res; import java.awt.Color; /** * Enum of colors used for filterPanel. * */ public enum FilterColor { BLACK(Color.BLACK), RED(Color.RED), BLUE(Color.BLUE), GREEN(Color.GREEN), YELLOW(Color.YELLOW), ORANGE(Color.ORANGE); private Color color; private FilterColor(Color color) { this.color = color; } public Color getColor() { return color; } public static FilterColor toFilterColor(String str){ switch(str) { case "BLACK": return FilterColor.BLACK; case "RED": return FilterColor.RED; case "BLUE": return FilterColor.BLUE; case "GREEN": return FilterColor.GREEN; case "YELLOW": return FilterColor.YELLOW; case "ORANGE": return FilterColor.ORANGE; default: return null; } } } <file_sep>/src/operation/AudioFileSelection.java package operation; import java.util.ArrayList; import component.FileType; public class AudioFileSelection extends FileSelection { @SuppressWarnings("serial") private static ArrayList<String[]> filterList = new ArrayList<String[]>() {{ add(new String[] {"MPEG/mp3", "mp3"}); }}; public AudioFileSelection() { super(filterList, filterList, FileType.AUDIO, " does not refer to a valid audio file."); } } <file_sep>/src/operation/MediaTimer.java package operation; import java.util.concurrent.TimeUnit; /** * Responsible for converting time into formatted version and vice versa. */ public class MediaTimer { /** * Returns formatted time in hh:mm:ss format. Input is in milliseconds * @param time * @return */ public static String getFormattedTime(long time) { int hours = (int)TimeUnit.MILLISECONDS.toHours(time) % 24; int minutes = (int)TimeUnit.MILLISECONDS.toMinutes(time) % 60; int seconds = (int)TimeUnit.MILLISECONDS.toSeconds(time) % 60; return String.format("%02d:%02d:%02d", hours, minutes, seconds); } /** * Returns a formatted string for the time to display correct time in media player. hh:mm:ss or mm:ss * @param time * @return formatted time. hh:mm:ss or mm:ss */ public static String getMediaTime(long time) { int hours = (int)TimeUnit.MILLISECONDS.toHours(time) % 24; int minutes = (int)TimeUnit.MILLISECONDS.toMinutes(time) % 60; int seconds = (int)TimeUnit.MILLISECONDS.toSeconds(time) % 60; if (hours == 0) { return String.format("%02d:%02d", minutes, seconds); } return String.format("%02d:%02d:%02d", hours, minutes, seconds); } /** * Returns the formatted string when given the hours, minutes and seconds. * @param hours * @param minutes * @param seconds * @return formatted string. hh:mm:ss */ public static String getFormattedTime(int hours, int minutes, int seconds) { return String.format("%02d:%02d:%02d", hours, minutes, seconds); } /** * Returns amount of seconds from hh:mm:ss format. * @param formattedTime * @return number of seconds in hh:mm:ss time */ public static int getSeconds(String formattedTime) { int seconds = 0; String[] times = formattedTime.split(":"); seconds = Integer.parseInt(times[2]); // times[2] seconds seconds += Integer.parseInt(times[1]) * 60; // times[1] minutes seconds += Integer.parseInt(times[0]) * 3600; // times[0] hours return seconds; } /** * Receive two formatted times, hh:mm:ss and return the difference in hh:mm:ss * @param formattedTime1 * @param formattedTime2 * @return difference in time formatted in hh:mm:ss */ public static String getDifferenceInTimeFormatted(String formattedTime1, String formattedTime2) { int difference = Math.abs(getSeconds(formattedTime1) - getSeconds(formattedTime2)); return getFormattedTime((long)difference); } /** * Receive two formatted times, hh:mm:ss and return the difference in seconds * @param formattedTime1 * @param formattedTime2 * @return difference in time in seconds */ public static int getDifferenceInTimeSeconds(String formattedTime1, String formattedTime2) { return Math.abs(getSeconds(formattedTime1) - getSeconds(formattedTime2)); } /** * Returns the current frame of the video. * @param videoSeconds * @param frameRate * @return current frame */ public static float getCurrentFrame(String formattedTime, float frameRate) { return getSeconds(formattedTime) * frameRate; } } <file_sep>/src/panel/AudioFilterPanel.java package panel; import java.awt.CardLayout; import javax.swing.JPanel; /** * Contains the audio panels and stores them in a super panel using cardlayout. {@link panel.MainPanel} * @author chang * */ @SuppressWarnings("serial") public class AudioFilterPanel extends JPanel { private static AudioFilterPanel theInstance = null; private JPanel audioFirstPagePanel, audioSecondPagePanel; public final String AUDIOFIRSTPAGESTRING = "First Page"; public final String AUDIOSECONDPAGESTRING = "Second Page"; public static AudioFilterPanel getInstance() { if (theInstance == null) { theInstance = new AudioFilterPanel(); } return theInstance; } private AudioFilterPanel() { setLayout(new CardLayout()); audioFirstPagePanel = AudioFirstPagePanel.getInstance(); audioSecondPagePanel = AudioSecondPagePanel.getInstance(); add(audioFirstPagePanel, AUDIOFIRSTPAGESTRING); add(audioSecondPagePanel, AUDIOSECONDPAGESTRING); } } <file_sep>/src/worker/AudioTrackWorker.java package worker; import javax.swing.ProgressMonitor; /** * Adds another audio track to a video file. * @author chang * */ public class AudioTrackWorker extends DefaultWorker { private String videoFileInput; private String audioFileInput; private String videoFileOutput; public AudioTrackWorker(String videoFileInput, String audioFileInput, String videoFileOutput, ProgressMonitor monitor) { super(monitor); this.videoFileInput = videoFileInput; this.audioFileInput = audioFileInput; this.videoFileOutput = videoFileOutput; initialiseVariables(); } @Override protected String getCommand() { return "avconv -i \'" + videoFileInput + "\' -i \'" + audioFileInput + "\' -map 0 -map 1:a -c:v copy -c:a copy -y \'" + videoFileOutput + "\'"; } @Override protected String getSuccessMessage() { return "Adding audio track complete"; } @Override protected String getCancelMesssage() { return "Adding audio track cancelled"; } } <file_sep>/src/listener/MediaPlayerListener.java package listener; import java.lang.reflect.InvocationTargetException; import javax.swing.SwingUtilities; import model.TimeBoundedRangeModel; import operation.MediaTimer; import panel.PlaybackPanel; import res.MediaIcon; import uk.co.caprica.vlcj.player.MediaPlayer; import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter; import component.Playback; /** * Updates media frame when media frame state has changed. Because this is not in the EDT, it must call on invokeAndWait * to get GUI to be updated thread safe. Updates the GUI components when media is being played, such as button icons and label. * Extends MediaPlayerEventAdapter */ public class MediaPlayerListener extends MediaPlayerEventAdapter { private PlaybackPanel playbackPanel; private MediaIcon mediaIcon; public MediaPlayerListener(PlaybackPanel playbackPanel) { this.playbackPanel = playbackPanel; mediaIcon = playbackPanel.mediaIcon; } // executed synchronously on the AWT event dispatching thread. Call is blocked until all processing AWT events have been // processed. @Override public void mediaParsedChanged(final MediaPlayer mediaPlayer, int newStatus) { super.mediaParsedChanged(mediaPlayer, newStatus); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { playbackPanel.finishTimeLabel.setText(MediaTimer.getMediaTime(mediaPlayer.getLength())); /* * When setting the minimum value, it calls its change listeners. As our timeslider forcibly changes * time, we want to disable setting time to zero in case we need to start from a different time. */ ((TimeBoundedRangeModel)playbackPanel.timeSlider.getModel()).setActive(false); playbackPanel.timeSlider.setMinimum(0); playbackPanel.timeSlider.setMaximum((int)mediaPlayer.getLength()); // only accepts int. playbackPanel.startTimeLabel.setText(MediaTimer.getMediaTime(mediaPlayer.getTime())); playbackPanel.muteButton.setIcon(mediaIcon.getIcon(Playback.UNMUTE)); mediaPlayer.mute(false); } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void paused(MediaPlayer mediaPlayer) { super.paused(mediaPlayer); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { playbackPanel.playButton.setIcon(mediaIcon.getIcon(Playback.PLAY)); } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void playing(MediaPlayer mediaPlayer) { super.playing(mediaPlayer); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { playbackPanel.playButton.setIcon(mediaIcon.getIcon(Playback.PAUSE)); } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void stopped(MediaPlayer mediaPlayer) { super.stopped(mediaPlayer); // Prepares media to be played when play button is pressed. mediaPlayer.prepareMedia(mediaPlayer.mrl()); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { playbackPanel.playButton.setIcon(mediaIcon.getIcon(Playback.PLAY)); playbackPanel.startTimeLabel.setText(PlaybackPanel.initialTimeDisplay); playbackPanel.finishTimeLabel.setText(PlaybackPanel.initialTimeDisplay); playbackPanel.timeSlider.setValue(0); } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void finished(MediaPlayer mediaPlayer) { super.finished(mediaPlayer); // Prepares media to be played when play button is pressed. mediaPlayer.prepareMedia(mediaPlayer.mrl()); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { playbackPanel.playButton.setIcon(mediaIcon.getIcon(Playback.PLAY)); playbackPanel.startTimeLabel.setText(PlaybackPanel.initialTimeDisplay); playbackPanel.finishTimeLabel.setText(PlaybackPanel.initialTimeDisplay); playbackPanel.timeSlider.setValue(0); } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void timeChanged(MediaPlayer mediaPlayer, final long newTime) { super.timeChanged(mediaPlayer, newTime); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { playbackPanel.startTimeLabel.setText(MediaTimer.getMediaTime(newTime)); // Turn "off" the change listener. So that when it calls statechanged, it does set time because the boolean is set to false. ((TimeBoundedRangeModel)playbackPanel.timeSlider.getModel()).setActive(false); playbackPanel.timeSlider.setValue((int)newTime); // only accepts int. } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } } <file_sep>/src/frame/FullScreenMediaPlayerFrame.java package frame; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.Timer; import operation.MediaTimer; import operation.VamixProcesses; import panel.MediaPanel; import panel.MediaPlayerComponentPanel; import panel.PlaybackPanel; import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent; import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer; import component.MediaCountFSM; /** * Opens media in <b>fullscreen</b>. It loads the previous playback settings. It has enter fullscreen and exit fullscreen methods. </br> * Also look at the following classes. </br> * {@link panel.MediaPlayerComponentPanel} </br> * {@link panel.PlaybackPanel} </br> * {@link component.MediaCountFSM} * @author changkon * */ @SuppressWarnings("serial") public class FullScreenMediaPlayerFrame extends JFrame implements ActionListener, ComponentListener { private JFrame vamixFrame; private PlaybackPanel playbackPanel; private JLayeredPane layeredPane; private EmbeddedMediaPlayer mediaPanelMediaPlayer, mediaPlayer; private EmbeddedMediaPlayerComponent mediaPlayerComponent; private Timer t; private MediaCountFSM currentState = MediaCountFSM.ZERO; // initial state. private GraphicsDevice g; public FullScreenMediaPlayerFrame(JFrame vamixFrame) { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.vamixFrame = vamixFrame; // Update counter every second. t = new Timer(1000, this); // Get the media player from mediaPanel mediaPanelMediaPlayer = MediaPanel.getInstance().getMediaPlayerComponentPanel().getMediaPlayer(); MediaPlayerComponentPanel canvasPanel = new MediaPlayerComponentPanel(); mediaPlayerComponent = canvasPanel.getMediaPlayerComponent(); mediaPlayer = canvasPanel.getMediaPlayer(); playbackPanel = new PlaybackPanel(mediaPlayer); // We don't want the feature to open media files in fullscreen mode. playbackPanel.openButton.setVisible(false); // Initially make it invisible playbackPanel.setVisible(false); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); g = ge.getDefaultScreenDevice(); // Set sizes of panel through absolute values. Determined by screen size of monitor. Dimension screenSize = new Dimension(g.getDisplayMode().getWidth(), g.getDisplayMode().getHeight()); Dimension playbackSize = MediaPanel.getInstance().getPlaybackPanel().getSize(); // Set the bounds for the components in fullscreen. canvasPanel.setBounds(0, 0, screenSize.width, screenSize.height); playbackPanel.setBounds(0, g.getDisplayMode().getHeight() - playbackSize.height, g.getDisplayMode().getWidth(), playbackSize.height); // smaller the position number, the higher the component within its depth. The higher number is at the front. // use jlayeredpane to get layering effect. layeredPane = new JLayeredPane(); layeredPane.add(canvasPanel, new Integer(0)); layeredPane.add(playbackPanel, new Integer(1)); add(layeredPane); addListeners(); // Add key binding. 0 means no modfier // Got help from http://stackoverflow.com/questions/15422488/java-keybindings canvasPanel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "EXIT"); canvasPanel.getActionMap().put("EXIT", new FullScreenAction("EXIT")); canvasPanel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "PLAY/PAUSE"); canvasPanel.getActionMap().put("PLAY/PAUSE", new FullScreenAction("PLAY/PAUSE")); } /** * Enter fullscreen and play from correct time. */ public void setFullScreen() { if (g.isFullScreenSupported()) { if (!mediaPanelMediaPlayer.isPlayable()) { JOptionPane.showMessageDialog(null, "Media file must be playing first before entering fullscreen."); return; } if (mediaPanelMediaPlayer.isPlaying()) { mediaPanelMediaPlayer.pause(); } // hide the vamixFrame. vamixFrame.setVisible(false); // Remove border. setUndecorated(true); String mediaPath = VamixProcesses.getFilename(mediaPanelMediaPlayer.mrl()); // set fullscreen g.setFullScreenWindow(this); // Play the media with the correct time. mediaPlayer.playMedia(mediaPath, ":start-time=" + (mediaPanelMediaPlayer.getTime() / 1000)); playbackPanel.volumeSlider.setValue(mediaPanelMediaPlayer.getVolume()); } else { JOptionPane.showMessageDialog(null, "Fullscreen is not supported"); } } /** * Exit fullscreen and play correct time in MediaPanel mediaPlayer. */ public void exitFullScreen() { vamixFrame.setVisible(true); // Sets the correct time for the mediaPanel media player when exiting full screen and volume. PlaybackPanel mediaPanelPlayback = MediaPanel.getInstance().getPlaybackPanel(); mediaPanelPlayback.startTimeLabel.setText(MediaTimer.getMediaTime(mediaPlayer.getTime())); mediaPanelPlayback.timeSlider.setValue((int)mediaPlayer.getTime()); mediaPanelPlayback.volumeSlider.setValue(mediaPlayer.getVolume()); if (mediaPlayer.isPlaying()) { mediaPanelMediaPlayer.play(); } mediaPlayer.release(); dispose(); } private void addListeners() { mediaPlayerComponent.getVideoSurface().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { exitFullScreen(); } } }); mediaPlayerComponent.getVideoSurface().addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { t.stop(); t.start(); currentState = currentState.reset(); playbackPanel.setVisible(true); } }); mediaPlayerComponent.getVideoSurface().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { exitFullScreen(); } } }); playbackPanel.addComponentListener(this); } @Override public void actionPerformed(ActionEvent e) { /* * Called everytime the counter is running. Obtain the next state and if it reaches accepting state, hide the * playback panel. */ currentState = currentState.next(); if (currentState == MediaCountFSM.THREE) { playbackPanel.setVisible(false); } } @Override public void componentHidden(ComponentEvent e) { t.stop(); } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentResized(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } /** * Class responsible for executing exitFullScreen method and toggling pause. * @author changkon * */ private class FullScreenAction extends AbstractAction { private String cmd; public FullScreenAction(String cmd) { this.cmd = cmd; } @Override public void actionPerformed(ActionEvent e) { if (cmd.equals("EXIT")) { exitFullScreen(); } else if (cmd.equals("PLAY/PAUSE")) { mediaPlayer.pause(); } } } }
7d6541ff3548e654ab2ec82d23d8ad78b647e3a3
[ "Markdown", "Java" ]
25
Java
changkon/VAMIX
d3627d7f0e2c4cd7122da81c0cd06bda9a3bfa87
f89e7cba0a3a4fdb475fec7ea80249e36467171e
refs/heads/master
<repo_name>Tajdik/My-MODX-template-starter<file_sep>/gulpfile.js // gulpfile.js var gulp = require('gulp'); var watch = require('gulp-watch'); var scss = require('gulp-sass'); var minify = require('gulp-minify-css'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var ftp = require('gulp-ftp'); // --- Tasks // --- Compile SCSS to CSS, minify and export to public folder gulp.task('scss', function () { return gulp.src('development/scss/app.scss') .pipe(scss().on('error', function (err) {console.log(err); })) .pipe(concat('styles.css')) .pipe(minify()) .pipe(rename('styles.min.css')) .pipe(gulp.dest('public')); }); // --- Compile JS and export to public folder gulp.task('js', function () { return gulp.src('development/js/*.js') .pipe(uglify()) .pipe(concat('scripts.js')) .pipe(gulp.dest('public')); }); // --- Public folder upload to FTP gulp.task('ftp', function () { return gulp.src('public/*') .pipe(ftp({ host: 'XXX', user: 'xxx', pass: 'xxx', remotePath:'/templates/' })); }); // --- Watch gulp.task('watch', function () { watch('development/scss/*.scss', function () { gulp.start('scss'); }); watch('development/js/*.js', function () { gulp.start('js'); }); watch('public/*.*', function () { gulp.start('ftp'); }); }); // --- Default Gulp task gulp.task('default', ['scss', 'js', 'ftp' ,'watch']);<file_sep>/readme.md # My MODx template starter kit When I build new website using MODx, I'm starting with this Starter Template. It's based bit on [html5boilerplate.com](http://html5boilerplate.com/) and customited with MODx tags. This is not just template for MODx, but simple tool or workflow im using to build new web. Im using [SASS](http://sass-lang.com/) and [GULP](http://gulpjs.com/) to simplify my work. I'm not yet writing my own JS, so Gulp is configured just tu concat and minify js files. ## Quick description of my workflow I'm not building sites localy, coz I dont want handle problems with hosting (and want to have something to show to clients). So I created Gulp tasks to build CSS and JS files from development SASS and JS files, minify them and upload them to MODx template folder on live site. ## What will You need to start? 1. [Node.js](http://nodejs.org/) installed 2. [MODx](http://www.modx.com/) instaled and running online 3. FTP account details (if you can create new FTP accout heading straith to assets/template folder of your MODx site - great) 4. [GULP](http://gulpjs.com/) installed globaly `$ npm install gulp -g` Init package.json to install all dependencies. Go to Starter folder and just type: `$ npm install` ## Let's get started Clone this starter theme, or just copy entire starter folder and place it whenever you want. You can see few files and folders. Index.html contain content of your new template. Public folder is empty. Node_modules contain dependencies and finaly development folder contain scss and js folders. I'm working just in scss folder. Or sometimes in js folder, when im adding js files for image carousel, lightbox etc. In scss folder is app.scss file. Here I just specify scss files to import (like own styles, normalize, foundation, lightbox etc). Create and import scss files you want. Or add styles to _starters.scss. Gulp will do the hard work and upload files to FTP for you. ### Gulp is configured to: 1. From app.scss (in development/scss folder) create and minify css file named styles.min.css 2. From development/js folder take all content, concatenate, minify and create sripts.js file 3. Watch app.scss and development/js folder for changes 4. Upload all files from public folder to FTP ## Now some setup In MODx resources create new template. Give it some name, and copy content of `index.html` to your new template. In assets folder create new `templates` folder. Configure gulpfile.js to your FTP account login details and set-up remote folder. If You created new FTP accout and set remote folder to `assets` folder, set `remotePath` to `/templates/`. If You set remote folder to `assets/templates`, set just `/`. **Example:** ```javascript gulp.task('ftp', function () { return gulp.src('public/*') .pipe(ftp({ host: 'ftp.mydomain.com', user: 'newUserJustForGulp', pass: '<PASSWORD>', remotePath:'/templates/' })); }); ``` Dont forget to **add your new MODx template to your old resources**, or you will not see difference. Thats all. Now you can build your site with SASS :-). ## The MIT License (MIT) http://mit-license.org/ 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.
e610348547369f6784db7824e33ea1d86ce4a97e
[ "JavaScript", "Markdown" ]
2
JavaScript
Tajdik/My-MODX-template-starter
757c8c6933d3511e5f9be6a13d138431945ff3c7
00d0d583a46f952007c2c3d2f178428736332324
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnObjectEffect : HumanEffect { public GameObject objectPrefab; public Vector2 offsetFromTarget = Vector2.zero; private GameObject spawnedObject = null; public override void OnStartEffect(Human human) { if (!spawnedObject) spawnedObject = Instantiate(objectPrefab, (Vector2)human.transform.position + offsetFromTarget, Quaternion.identity); } public override void OnEndEffect(Human human) { if (spawnedObject) Destroy(spawnedObject); spawnedObject = null; } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using ClipperLib; using UnityEngine; using UnityEngine.Rendering; [RequireComponent(typeof(PolygonCollider2D))] public class Cuttable : MonoBehaviour { [HideInInspector] public PolygonCollider2D polygonCollider; private Camera cullCamera; private Mesh cullMesh; private static float lastClippingZ = 0; private void Start() { polygonCollider = GetComponent<PolygonCollider2D>(); InitializeMask(); SetVertices(polygonCollider.GetPath(0)); } public void SetVertices(Vector2[] points) { polygonCollider.SetPath(0, points); cullMesh.Clear(); cullMesh.vertices = points.Select(vertex => new Vector3(vertex.x, vertex.y, 0)).ToArray(); cullMesh.triangles = new Triangulator(points).Triangulate(); } private void InitializeMask() { lastClippingZ += 0.1f; cullMesh = new Mesh(); var sr = GetComponent<SpriteRenderer>(); if (!sr) return; var sprite = sr.sprite; var width = sprite.texture.width; var height = sprite.texture.height; if (sr.drawMode == SpriteDrawMode.Tiled) { width = (int) (width * sr.size.x); height = (int) (height * sr.size.y); } var rt = new RenderTexture(width, height, 16, RenderTextureFormat.ARGB32); rt.Create(); var newcamera = new GameObject("Culling Camera"); newcamera.transform.parent = transform; newcamera.transform.localPosition = new Vector3(0, 0, lastClippingZ); cullCamera = newcamera.AddComponent<Camera>(); cullCamera.nearClipPlane = 0.01f; cullCamera.farClipPlane = 0.09f; cullCamera.orthographic = true; cullCamera.orthographicSize = sprite.bounds.size.y / 2; cullCamera.targetTexture = rt; cullCamera.backgroundColor = Color.black; cullCamera.cullingMask = 1 << LayerMask.NameToLayer("Clipping"); var clippingmask = new GameObject("Clipping Mask") {layer = LayerMask.NameToLayer("Clipping")}; clippingmask.transform.parent = transform; clippingmask.transform.localPosition = new Vector3(0, 0, lastClippingZ + 0.05f); clippingmask.layer = LayerMask.NameToLayer("Clipping"); clippingmask.AddComponent<MeshRenderer>(); clippingmask.AddComponent<MeshFilter>().mesh = cullMesh; sr.material.SetTexture("_Mask", rt); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Human Sprites", menuName = "Human/Sprites", order = 1)] public class HumanSpriteSelection : ScriptableObject { [SerializeField] private HumanSpriteSet[] sprites; public Sprite GetSprite(int index, bool crouching = false) { HumanSpriteSet set = GetSpriteSet(index); return (crouching ? set.crouching : set.main); } public HumanSpriteSet GetSpriteSet(int index) { return sprites[index]; } public int GetSpriteCount() { return sprites.Length; } } [System.Serializable] public class HumanSpriteSet { public Sprite main; public Sprite crouching; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class WinScreen : MonoBehaviour { [Header("Managers")] public ScoreManager scoreManager; [Header("References")] public Image realWinnerImg; public Text realWinnerTxt; public Text awards; public Image[] scoreWinnersImg; public Text[] scoreWinnersTxt; public Button retry; [Header("Settings")] public Vector2 offscreenDisplacement; public float enterTime = 1; [Header("Format")] public string realWinnerString = "Winner - Player {0}"; public string scoreString = "Player {0} - {1}"; public string awardString = "{0} - Player {1}"; private Vector2 startPos; private bool shouldShow = false; #region SubClass private class PlayerScore { public int controller; public Human player; public int score; } #endregion void Start() { PlayerManager.instance.onPlayerWin.AddListener(OnWin); startPos = transform.position; transform.position = startPos + offscreenDisplacement; } void Update() { if (shouldShow) { transform.position = Vector2.Lerp(transform.position, startPos, Time.unscaledDeltaTime * (1 / enterTime)); if (Vector2.Distance(transform.position, startPos) < 10) EventSystem.current.SetSelectedGameObject(retry.gameObject); } } public void OnWin(int winner) { if (shouldShow) return; Human[] players = PlayerManager.instance.humans; if (winner > 0) { realWinnerImg.sprite = players[winner - 1].GetSprite(); realWinnerTxt.text = string.Format(realWinnerString, winner); } PlayerScore[] playerScores = new PlayerScore[players.Length]; float[] scores = scoreManager.GetScores(); for (int i = 0; i < players.Length; i++) { playerScores[i] = new PlayerScore { controller = i + 1, score = (int)(scores[i] * 10), player = players[i] }; } playerScores = SortPlayerScores(ref playerScores); for (int i = playerScores.Length - 1; i >= 0; i--) { scoreWinnersImg[i].sprite = playerScores[i].player.GetSprite(); scoreWinnersTxt[i].text = string.Format(scoreString, playerScores[i].controller, playerScores[i].score); } Time.timeScale = 0.5f; shouldShow = true; scoreManager.GameActive = false; } private PlayerScore[] SortPlayerScores(ref PlayerScore[] scores) { for (int p = 0; p < scores.Length - 1; p++) { for (int i = scores.Length - 1; i > 0; i--) { if (scores[i].score > scores[i - 1].score) { (scores[i], scores[i - 1]) = (scores[i - 1], scores[i]); } } } return scores; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IWormController { Vector2 GetMoveDirection(); bool GetBoosting(); bool GetEating(); } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectiveBanner : MonoBehaviour { public float duration = 5f; public AnimationCurve shakeOverTime; public AnimationCurve rotationOverTime; public AnimationCurve gravityOverTime; private Vector3 mainPosition; private float time = 0; void Start() { Destroy(gameObject, duration); mainPosition = transform.position; } void Update() { time += Time.deltaTime; transform.rotation = Quaternion.Euler(0, 0, rotationOverTime.Evaluate(time)); mainPosition = (Vector2) mainPosition + Physics2D.gravity * Vector2.up * gravityOverTime.Evaluate(time); transform.position = (Vector2)mainPosition + (Random.insideUnitCircle * shakeOverTime.Evaluate(time)); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeteorManager : MonoBehaviour { [HideInInspector] public List<GameObject> meteors; [Header("Prefabs")] [SerializeField] private Meteor meteorPrefab; [Header("Settings")] [SerializeField] private AnimationCurve meteorRate; [SerializeField] private float maxMeteorTime; [SerializeField] private BoxCollider2D spawnArea; private float timePassed = 0f; void Update() { timePassed += Time.deltaTime; //print("---"); //print(meteorRate.Evaluate(timePassed / maxMeteorTime)); //print(Time.deltaTime); //print(Time.deltaTime * meteorRate.Evaluate(timePassed / maxMeteorTime)); if (Random.Range(0f, 1f) < Time.deltaTime * meteorRate.Evaluate(timePassed / maxMeteorTime)) { var meteor = Instantiate(meteorPrefab); var colliderPos = (Vector2) spawnArea.transform.position + spawnArea.offset; meteor.transform.position = new Vector3( Random.Range(colliderPos.x - spawnArea.size.x / 2, colliderPos.x + spawnArea.size.x / 2), Random.Range(colliderPos.y - spawnArea.size.y / 2, colliderPos.y + spawnArea.size.y / 2), 0 ); meteor.meteorVelocity = new Vector2(Random.Range(-1.5f, 1.5f), Random.Range(-5.5f, -6.5f)); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Worm : MonoBehaviour { [Header("Controller")] public int controllerNum = 0; private IWormController control; [Header("Settings")] [SerializeField] private int numSegments = 4; [SerializeField] private float segmentLength = 1.5f; [SerializeField] private float moveSpeed = 1f; [SerializeField] private float gravity = 1f; [Header("Prefabs")] [SerializeField] private GameObject head; private Cutter wormEater; [SerializeField] private GameObject segment; private List<GameObject> segments = new List<GameObject>(); [SerializeField] private GameObject tail; private List<Vector3> trail = new List<Vector3>(); void Start() { // temp control = new PlayerWormController(controllerNum); wormEater = head.GetComponent<Cutter>(); segments.Add(segment); for(var i = 1; i < numSegments; i++) { segments.Add(Instantiate(segment, segment.transform.parent)); } trail = new List<Vector3> {head.transform.position}; } void Update() { var moveDir = control.GetMoveDirection(); head.transform.position += new Vector3(moveDir.x, moveDir.y, 0) * Time.deltaTime * moveSpeed; if ((head.transform.position - trail[trail.Count - 1]).magnitude > 0.1) { trail.Add(head.transform.position); var totalLength = 0f; var lastPos = trail[trail.Count - 1]; for (var i = trail.Count - 2; i <= 0; i++) { if (totalLength > segmentLength * (numSegments + 2)) { trail.RemoveAt(i); } else { var pos = trail[i]; totalLength += (lastPos - pos).magnitude; } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BotHumanController : IHumanController { protected int controllerNum = 0; protected Human human; private bool needMove = false; private float moveMagnitude = 0; private bool needJump = false; private enum BotControllerState { IDLE, WANDER, RUN } private BotControllerState state = BotControllerState.IDLE; private float needMovemnentUpdate = 3f; private float targetMoveMagnitude = 0; private BotSettings settings; public BotHumanController(int controllerNum, Human human, BotSettings settings) { this.controllerNum = controllerNum; this.human = human; this.settings = settings; } public bool GetJumpButton() { return needJump; } public float GetMoveMagnitude() { return moveMagnitude; } public bool ShouldMove() { return needMove; } public void Update() { switch (state) { case BotControllerState.IDLE: targetMoveMagnitude = 0; if (GetDistanceFromMeteor() < settings.minimumIdleDistance || Random.Range(0, 100f) <= settings.idleEndChance) { state = BotControllerState.WANDER; } break; case BotControllerState.WANDER: needMovemnentUpdate -= Time.deltaTime; if (needMovemnentUpdate <= 0) { targetMoveMagnitude = Random.Range(0, 2) == 0 ? -1 : 1; needMovemnentUpdate += settings.wanderUpdateDelay; } if (GetDistanceFromMeteor() > settings.minimumIdleDistance && Random.Range(0, 100f) <= settings.wanderEndChance) { state = BotControllerState.IDLE; } if (GetDistanceFromMeteor() < settings.runDistance) { state = BotControllerState.RUN; } if (moveMagnitude > settings.wanderJumpMinimumSpeed) { if (!needJump) needJump = Random.Range(0, 100) == 0; else { needJump = Random.Range(0, 100) <= settings.wanderContinueJumpChance; } } break; case BotControllerState.RUN: targetMoveMagnitude = 1 - Mathf.Clamp01(GetDistanceFromMeteor()); targetMoveMagnitude = Mathf.Sign(GetDirectionToMeteor().x); needJump = Mathf.Abs(GetDirectionToMeteor().y) > settings.runDistanceToJump && Random.Range(0, 100f) <= settings.runJumpChance; if (GetDistanceFromMeteor() > settings.runDistance) { state = BotControllerState.WANDER; } break; } moveMagnitude = Mathf.Lerp(moveMagnitude, targetMoveMagnitude, Time.deltaTime * 2); needMove = moveMagnitude != 0; } private float GetDistanceFromMeteor() { Vector2 closest = Vector2.zero; float closestDistance = float.MaxValue; foreach (Vector2 pos in PlayerManager.instance.GetMeteorPositions()) { float newDist = Vector2.Distance(pos, human.transform.position); if (newDist < closestDistance) { closest = pos; } } return closestDistance; } private Vector2 GetDirectionToMeteor() { Vector2 closest = Vector2.zero; float closestDistance = float.MaxValue; foreach (Vector2 pos in PlayerManager.instance.GetMeteorPositions()) { float newDist = Vector2.Distance(pos, human.transform.position); if (newDist < closestDistance) { closest = pos; } } return (Vector2)human.transform.position - closest; } public bool GetCrouchButton() { return Random.Range(0, 100) < settings.crouchChance; } public bool GetDashButton() { return false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BubbleShieldEffect : HumanEffect { public GameObject displayPrefab; public int shieldCount = 1; private GameObject displayObject = null; public override void OnStartEffect(Human human) { human.SetInvulnerable(true); if (!displayObject) displayObject = Instantiate(displayPrefab, human.transform); } public override void OnEndEffect(Human human) { human.SetInvulnerable(false); if (displayObject) Destroy(displayObject); displayObject = null; } public override void OnDamageTaken(Human human, float damage) { shieldCount--; } public override bool CanContinue() { return shieldCount > 0; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.PlayerLoop; using UnityEngine.XR.WSA; public class ParticleSplatter : MonoBehaviour { [SerializeField] private ParticleSystem particles; public void Splatter(Vector3 position, float weight) { var splatter = Instantiate(particles); splatter.transform.position = position; splatter.emission.SetBursts(new ParticleSystem.Burst[] { new ParticleSystem.Burst(0.0f, (short) (30 * weight), (short) (40 * weight)) }); /*var emission = splatter.emission; emission.rateOverTimeMultiplier *= weight; var bursts = new ParticleSystem.Burst[emission.burstCount]; emission.GetBursts(bursts); foreach (var burst in bursts) { var curve = burst.count; curve.curveMultiplier *= weight; } splatter.emission.SetBursts(bursts);*/ } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CharacterSelection : Selectable { public int controllerNumber; public Image preview; public HumanSpriteSelection sprites; public Image background; public Text readyText; private int index; private Vector2 prevInput; private bool lateStartRan = false; void Update() { if (!lateStartRan) { LateStart(); lateStartRan = true; } CheckInput(); } private void LateStart() { index = 0; if (!JoystickExists(controllerNumber)) { Randomize(); } UpdateChange(); readyText.enabled = false; } #region Interface public void Next() { index++; index %= sprites.GetSpriteCount(); UpdateChange(); } public void Prev() { index--; if (index < 0) index += sprites.GetSpriteCount(); UpdateChange(); } public void Randomize() { index = Random.Range(0, sprites.GetSpriteCount()); UpdateChange(); } #endregion private void CheckInput() { Vector2 input = new Vector2(Input.GetAxis($"Joystick{controllerNumber}X"), 0); if (IsInputRight(input)) Next(); if (IsInputLeft(input)) Prev(); prevInput = input; } private bool IsInputLeft(Vector2 input) { return (input.x < -0.5f) && !(prevInput.x < -0.5f); } private bool IsInputRight(Vector2 input) { return (input.x > 0.5f) && !(prevInput.x > 0.5f); } private void UpdateChange() { preview.sprite = sprites.GetSprite(index); PlayerPrefs.SetInt($"PLAYER{controllerNumber}_SPRITE_INDEX", index); } private bool JoystickExists(int joystick) { joystick -= 1; string[] joysticks = Input.GetJoystickNames(); return joystick < joysticks.Length && !string.IsNullOrEmpty(joysticks[joystick]); } public void OnReady(int controller) { if (controller == controllerNumber) OnReady(); } private void OnReady() { background.color = new Color(background.color.r - 0.1f, background.color.g - 0.1f, background.color.b - 0.1f); readyText.enabled = true; } public void OnUnReady(int controller) { if (controller == controllerNumber) OnUnReady(); } private void OnUnReady() { background.color = new Color(background.color.r + 0.1f, background.color.g + 0.1f, background.color.b + 0.1f); readyText.enabled = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class CameraZoom : MonoBehaviour { [Header("Settings")] [SerializeField] private float minZoom = 1f; [SerializeField] private float maxZoom = 1f; [SerializeField] private float smoothFactor = 1f; [SerializeField] private bool differentMargins = false; [ConditionalHide("differentMargins", true, true)] [SerializeField] private float screenMargin = 0f; [ConditionalHide("differentMargins", true, false)] [SerializeField] private Margins screenMargins; void Update() { if (!IsAllOnScreen()) { ZoomOut(); } else if (IsAllOnScreen(2f)) { ZoomIn(); } } public bool IsAllOnScreen(float marginMultiplier = 1) { bool ret = true; foreach (Vector2 position in PlayerManager.instance.GetPlayerPositions()) { Vector2 screenPos = Camera.main.WorldToViewportPoint(position); if (screenPos.x < ((differentMargins ? screenMargins.left : screenMargin) * marginMultiplier)) ret = false; if (screenPos.x > 1 - ((differentMargins ? screenMargins.right : screenMargin) * marginMultiplier)) ret = false; if (screenPos.y < ((differentMargins ? screenMargins.down : screenMargin) * marginMultiplier)) ret = false; if (screenPos.y > 1 - ((differentMargins ? screenMargins.up : screenMargin) * marginMultiplier)) ret = false; } return ret; } public bool ZoomOut() { bool ret = false; float newZoom = Mathf.MoveTowards(Camera.main.orthographicSize, maxZoom, Time.deltaTime * smoothFactor); if (newZoom > maxZoom) { newZoom = maxZoom; ret = true; } Camera.main.orthographicSize = newZoom; return ret; } public bool ZoomIn() { bool ret = false; float newZoom = Mathf.MoveTowards(Camera.main.orthographicSize, minZoom, Time.deltaTime * smoothFactor); if (newZoom < minZoom) { newZoom = minZoom; ret = true; } Camera.main.orthographicSize = newZoom; return ret; } private void OnDrawGizmos() { Camera cam = GetComponent<Camera>(); Vector2 outPointTL = cam.ViewportToWorldPoint(new Vector2(differentMargins ? screenMargins.left : screenMargin, 1 - (differentMargins ? screenMargins.up : screenMargin))); Vector2 outPointBR = cam.ViewportToWorldPoint(new Vector2(1 - (differentMargins ? screenMargins.right : screenMargin), differentMargins ? screenMargins.down : screenMargin)); Vector2 inPointTL = cam.ViewportToWorldPoint(new Vector2(2 * (differentMargins ? screenMargins.left : screenMargin), 1 - (2 * (differentMargins ? screenMargins.up : screenMargin)))); Vector2 inPointBR = cam.ViewportToWorldPoint(new Vector2(1 - (2 * (differentMargins ? screenMargins.right : screenMargin)), 2 * (differentMargins ? screenMargins.down : screenMargin))); Gizmos.DrawLine(outPointTL, new Vector2(outPointTL.x, outPointBR.y)); Gizmos.DrawLine(new Vector2(outPointTL.x, outPointBR.y), outPointBR); Gizmos.DrawLine(outPointTL, new Vector2(outPointBR.x, outPointTL.y)); Gizmos.DrawLine(new Vector2(outPointBR.x, outPointTL.y), outPointBR); Gizmos.DrawLine(inPointTL, new Vector2(inPointTL.x, inPointBR.y)); Gizmos.DrawLine(new Vector2(inPointTL.x, inPointBR.y), inPointBR); Gizmos.DrawLine(inPointTL, new Vector2(inPointBR.x, inPointTL.y)); Gizmos.DrawLine(new Vector2(inPointBR.x, inPointTL.y), inPointBR); } } [System.Serializable] public class Margins { public float up = 0f; public float down = 0f; public float left = 0f; public float right = 0f; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class HumanEffectManager : MonoBehaviour { public Human target; private Dictionary<string, HumanEffectInstance> effects; public void Awake() { effects = new Dictionary<string, HumanEffectInstance>(); target.onHurt.AddListener(OnDamageTaken); } public void AddEffect(HumanEffectInstance instance) { string effectID = instance.GetEffect().id; if (effects.ContainsKey(effectID)) { effects[effectID].AddDuration(instance.GetDuration()); } else { effects.Add(effectID, instance); instance.OnStartEffect(target); } } public void AddEffect(HumanEffect effect, float duration) { AddEffect(new HumanEffectInstance(effect, duration)); } public void RemoveEffect(string id) { effects[id].OnEndEffect(target); effects.Remove(id); } public void OnDamageTaken(float damage) { foreach(HumanEffectInstance effect in effects.Values) { effect.OnDamageTaken(target, damage); } } private void Update() { List<string> toRemove = new List<string>(); foreach(HumanEffectInstance effect in effects.Values) { effect.Update(); if (effect.IsExpired) { toRemove.Add(effect.GetEffect().id); } } foreach (string id in toRemove) { RemoveEffect(id); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHumanController : IHumanController { protected int controllerNum = 0; protected Human human; private Vector2 movement = Vector2.zero; private bool jumpButton = false; private bool dashButton = false; public PlayerHumanController(int controllerNum, Human human) { this.controllerNum = controllerNum; this.human = human; } public bool GetCrouchButton() { return movement.y > 0; } public bool GetDashButton() { return dashButton; } public bool GetJumpButton() { return jumpButton; } public float GetMoveMagnitude() { return movement.x; } public bool ShouldMove() { return movement.x != 0; } public void Update() { movement = new Vector2(Input.GetAxis($"Joystick{controllerNum}X"), Input.GetAxis($"Joystick{controllerNum}Y")); jumpButton = Input.GetAxis($"Joystick{controllerNum}button0") != 0; dashButton = Input.GetAxis($"Joystick{controllerNum}button1") != 0; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IDamageable { void Damage(Vector2 damageSource, float damageMultiplier = 1); void Damage(float rawDamage); } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShowInside : MonoBehaviour { public float transitionTime = 0.1f; public float transparency = 0.25f; private bool showInside = false; private Color startColour; private Color endColour; private SpriteRenderer sr; private float timer = 0; [SerializeField] private bool arePlayersInside = false; void Start() { sr = GetComponent<SpriteRenderer>(); startColour = sr.color; endColour = new Color(sr.color.r, sr.color.g, sr.color.b, 1 - transparency); } void Update() { timer += Time.deltaTime * (1 / transitionTime) * (showInside ? 1 : -1); timer = Mathf.Clamp01(timer); if (arePlayersInside && !showInside) Show(); if (!arePlayersInside && showInside) Hide(); sr.color = Color.Lerp(startColour, endColour, timer); } public void Show() { showInside = true; } public void Hide() { showInside = false; } private void OnTriggerStay2D(Collider2D collision) { if (collision.GetComponent<Human>()) { arePlayersInside = true; } } private void OnTriggerExit2D(Collider2D collision) { arePlayersInside = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class PlayerManager : MonoBehaviour { public static PlayerManager instance = null; public bool allowPlayerControl = true; public BotSettings botSettings; public Human[] humans; public PlayerWinEvent onPlayerWin = new PlayerWinEvent(); private string[] previousJoysticks = null; private MeteorManager meteorManager; private Cinemachine.CinemachineTargetGroup targetGroup; private void Awake() { if (instance == null) { instance = this; Physics2D.IgnoreLayerCollision(8, 8); Physics2D.IgnoreLayerCollision(8, 9); meteorManager = FindObjectOfType<MeteorManager>(); targetGroup = FindObjectOfType<Cinemachine.CinemachineTargetGroup>(); foreach (Human human in humans) { human.onDeath.AddListener(new UnityAction(() => { targetGroup.RemoveMember(human.transform); })); targetGroup.AddMember(human.transform, 1, 2); } } } private void Update() { string[] joysticks = Input.GetJoystickNames(); if (previousJoysticks == null) { previousJoysticks = new string[joysticks.Length]; for (int i = 0; i < humans.Length; i++) humans[i].ChangeController(new BotHumanController(i + 1, humans[i], botSettings)); } for (int i = 0; i < humans.Length; i++) { int controller = i + 1; if (allowPlayerControl) { if (!JoystickExists(previousJoysticks, i) && JoystickExists(joysticks, i)) { humans[i].ChangeController(new PlayerHumanController(controller, humans[i])); } if (JoystickExists(previousJoysticks, i) && !JoystickExists(joysticks, i)) { humans[i].ChangeController(new BotHumanController(controller, humans[i], botSettings)); } } } if (GetNumberOfHumans() <= 1) { int[] remaining = GetRemainingPlayers(); onPlayerWin.Invoke(remaining.Length > 0 ? remaining[0] : -1); } previousJoysticks = joysticks; } private bool JoystickExists(string[] joystickNames, int joystick) { return joystick < joystickNames.Length && !string.IsNullOrEmpty(joystickNames[joystick]); } public int GetNumberOfHumans() { int ret = 0; foreach (Human human in humans) { if (human.IsAlive()) ret++; } return ret; } public int[] GetRemainingPlayers() { List<int> ret = new List<int>(); for (int i = 0; i < humans.Length; i++) { if (humans[i].IsAlive()) ret.Add(i + 1); } return ret.ToArray(); } public Vector2[] GetMeteorPositions() { List<GameObject> meteors = meteorManager.meteors; Vector2[] positions = new Vector2[meteors.Count]; for (int i = 0; i < meteors.Count; i++) { positions[i] = meteors[i].transform.position; } return positions; } public Vector2[] GetPlayerPositions() { List<Vector2> ret = new List<Vector2>(); for (int i = 0; i < humans.Length; i++) { ret.Add(humans[i].transform.position); } return ret.ToArray(); } public void SetPlayerToBot(int controller) { humans[controller - 1].ChangeController(new BotHumanController(controller, humans[controller - 1], botSettings)); } } [System.Serializable] public class PlayerWinEvent : UnityEvent<int> {} <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerUp : MonoBehaviour { public HumanEffect effect; public float duration; private void OnCollisionEnter2D(Collision2D collision) { HumanEffectManager humanEffects = collision.collider.GetComponent<HumanEffectManager>(); if (humanEffects) { humanEffects.AddEffect(effect, duration); Destroy(gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using Cinemachine; using UnityEngine; using UnityEngineInternal; [RequireComponent(typeof(Cutter), typeof(Rigidbody2D))] public class Meteor : MonoBehaviour { [Header("Prefabs")] [SerializeField] private Explosion explosionPrefab; [Header("Sounds")] [SerializeField] private AudioClip[] fallingSounds; [SerializeField] private AudioClip[] explosionSounds; [Header("Explosion Damage")] [SerializeField] private AnimationCurve damageCurve; [SerializeField] private float maxDamageDistance; [Header("Explosion Size")] [SerializeField] private AnimationCurve explosionRadiusCurve; [SerializeField] private float lowExplosionHeight; [SerializeField] private float highExplosionHeight; [HideInInspector] public Vector2 meteorVelocity = new Vector2(-1, -3); private Cutter cutter; private Rigidbody2D rb; private AudioSource asc; private CinemachineCollisionImpulseSource collisionImpulse; private void Start() { cutter = GetComponent<Cutter>(); rb = GetComponent<Rigidbody2D>(); asc = GetComponent<AudioSource>(); collisionImpulse = GetComponent<CinemachineCollisionImpulseSource>(); asc.PlayOneShot(fallingSounds[Random.Range(0, fallingSounds.Length)]); } private void OnCollisionEnter2D(Collision2D other) { Touchdown(); } private void OnTriggerEnter2D(Collider2D other) { Touchdown(); } private void Touchdown() { var hitObjects = Physics2D.OverlapCircleAll(transform.position, maxDamageDistance); foreach (var hit in hitObjects) { var damageables = hit.GetComponents<IDamageable>(); if (damageables.Length > 0) { var distance = (transform.position - hit.transform.position).magnitude; foreach (var damageable in damageables) { damageable.Damage(damageCurve.Evaluate(distance)); } } var particleSplatter = hit.GetComponent<ParticleSplatter>(); if (particleSplatter != null) { print(1f / hitObjects.Length); particleSplatter.Splatter(transform.position, 1f / hitObjects.Length); } } var height = transform.position.y; var explosionRadius = explosionRadiusCurve.Evaluate((height - lowExplosionHeight) / (highExplosionHeight - lowExplosionHeight)); cutter.CutRadius = explosionRadius; cutter.Cut(); var explosion = Instantiate(explosionPrefab); explosion.transform.position = transform.position; explosion.Explode(explosionRadius); AudioSource.PlayClipAtPoint(explosionSounds[Random.Range(0, explosionSounds.Length)], explosion.transform.position); Destroy(gameObject); } private void Update() { rb.MovePosition(rb.position + (meteorVelocity * Time.deltaTime)); var angle = Mathf.Atan2(meteorVelocity.y, meteorVelocity.x) * Mathf.Rad2Deg + 90f; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); var height = transform.position.y; collisionImpulse.m_ImpulseDefinition.m_AmplitudeGain = explosionRadiusCurve.Evaluate((height - lowExplosionHeight) / (highExplosionHeight - lowExplosionHeight)); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainMenuGameplay : MonoBehaviour { public GameObject levelPrefab; public FadeUI fade; public PlayerManager playerManager; public GameObject levelObj; public GameObject[] players; private bool isResetting = false; public void Reset() { if (isResetting) return; isResetting = true; fade.shouldShow = true; Invoke("ResetMid", 1); } private void ResetMid() { // Replace players foreach (Human h in playerManager.humans) { if (h) Destroy(h.gameObject); } playerManager.humans = new Human[players.Length]; for (int i = 0; i < players.Length; i++) { playerManager.humans[i] = Instantiate(players[i], new Vector2((2 * i) - 8, 3), Quaternion.identity).GetComponent<Human>(); playerManager.SetPlayerToBot(i + 1); } // Replace level if (levelObj) Destroy(levelObj); levelObj = Instantiate(levelPrefab); Invoke("ResetFinal", 1); } private void ResetFinal() { isResetting = false; fade.shouldShow = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class HumanEffect : MonoBehaviour { public string id = "NULL"; public virtual void OnStartEffect(Human human) {/*MT*/} public virtual void OnEndEffect(Human human) {/*MT*/} public virtual void OnDamageTaken(Human human, float damage) {/*MT*/} public virtual bool CanContinue() { return true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class HumanEffectInstance { private HumanEffect effect; private float duration = 0; public bool IsExpired { get { return duration <= 0; } } public HumanEffectInstance(HumanEffect effect, float duration) { this.effect = effect; this.duration = duration; } public void Update() { duration -= Time.deltaTime; if (!effect.CanContinue()) duration = -1; } public void OnStartEffect(Human human) { effect.OnStartEffect(human); } public void OnEndEffect(Human human) { effect.OnEndEffect(human); } public void OnDamageTaken(Human human, float damage) { effect.OnDamageTaken(human, damage); } public void AddDuration(float duration) { this.duration += duration; } public float GetDuration() { return duration; } public HumanEffect GetEffect() { return effect; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(SpriteRenderer))] [RequireComponent(typeof(TrailRenderer))] public class Human : MonoBehaviour, IDamageable { #region Inspector [Header("Controller")] public int controllerNum = 0; [Header("Settings")] [SerializeField] private int maxJumpCount = 2; [SerializeField] private float jumpHeight = 3; [SerializeField] private float fallModifier = 1f; [SerializeField] private float speed = 1f; [SerializeField] private float dashSpeed = 1f; [SerializeField] private float dashCooldown = 0.5f; [SerializeField] private float deathYLevel = -5.5f; [Header("References")] public PlayerIndicator indicator; public StunIndicator stunIndicator; public GameObject deathEffect; [Header("Sprites")] public HumanSpriteSelection spritesReference; [Header("Events")] public OnHurtEvent onHurt = new OnHurtEvent(); public OnDeathEvent onDeath = new OnDeathEvent(); #endregion #region Private Variables // Control Object. This object controls what is inputted and when private IHumanController control; // Is a player controlling? private bool controllerConnected = false; // Was the jump input pressed last frame? private bool jumpWasPressed = false; // Can you normal jump? private bool canJump = false; // Can you wall jump? private bool canWallJump = false; // How many times have you jumped since last on ground? private int jumpCount = 0; // Invulnuability Flag private bool invulnerable = false; // Was dash button pressed last frame? private bool dashWasPressed = false; // Is crouch button pressed? private bool isCrouching = false; // Alive Flag private bool alive = true; // Remaining Stun Time private float stunTime = 0; // Enum for wall collision private enum WallSide { NONE, LEFT, RIGHT } // Which side are we touching a wall private WallSide attachedToWall = WallSide.NONE; // References private Rigidbody2D rb; private SpriteRenderer sr; private TrailRenderer tr; // Cooldown for dash private float dashTimer = 0; // Sprite Set For Player private HumanSpriteSet sprite; #endregion #region Unity Events void Start() { // Get References rb = GetComponent<Rigidbody2D>(); sr = GetComponent<SpriteRenderer>(); tr = GetComponent<TrailRenderer>(); // Set the Sprite int offset = PlayerPrefs.GetInt($"PLAYER{controllerNum}_SPRITE_INDEX", 1); sprite = spritesReference.GetSpriteSet(offset); sr.sprite = sprite.main; // Disable Trail tr.emitting = false; } void Update() { // Abort if no control object is found if (control == null) return; // Disable Wall Jump canWallJump = false; // Check if able to wall jump canWallJump = (attachedToWall == WallSide.LEFT) || (attachedToWall == WallSide.RIGHT); // Check if moving down if (rb.velocity.y < 0) { // Increase falling speed by multiplier of gravity rb.velocity += Vector2.up * Physics2D.gravity.y * (fallModifier - 1) * Time.deltaTime; } // If moving in the X if (Mathf.Abs(rb.velocity.x) > 0) { // Decrease velocity by 30% rb.velocity = new Vector2(rb.velocity.x * 0.7f, rb.velocity.y); } // Check if not stunned if (stunTime <= 0f) { // Update based on control object GetControlInput(); } else { // Decrease stun time stunTime -= Time.deltaTime; // Reset dash cooldown dashTimer = 0; } // Reset wall detection attachedToWall = WallSide.NONE; // Update sprite display UpdateDisplay(); // If too low, die if (transform.position.y < deathYLevel) Kill(); // CHEATS if (Input.GetKeyDown($"{controllerNum}")) { if (IsAlive()) Kill(); else { alive = true; gameObject.SetActive(true); } } // END CHEATS } private void OnCollisionStay2D(Collision2D collision) { if (collision.collider.gameObject.layer == 12) return; // Get Points of Contact ContactPoint2D[] contactPoints = new ContactPoint2D[collision.contactCount]; collision.GetContacts(contactPoints); // Iterate over contact points foreach (ContactPoint2D cp in contactPoints) { // Convert contact point to local space Vector2 point = transform.InverseTransformPoint(cp.point); // If point is low enough if (point.y <= -0.10f) { // Reset jump count jumpCount = 0; // Enable Jumping canJump = true; } else { // If this isn't a jump-through platform if (!collision.collider.GetComponent<PlatformEffector2D>()) { // Check direction and set wall detection if (point.x < -0.07f) { attachedToWall = WallSide.LEFT; } if (point.x > 0.07f) { attachedToWall = WallSide.RIGHT; } } } } } private void OnCollisionExit2D(Collision2D collision) { // Reset Wall Detection attachedToWall = WallSide.NONE; // Increment Jump Count jumpCount++; // Disable Wall Jump canWallJump = false; } #endregion #region Interface public bool ChangeController(IHumanController controller) { // Set controller control = controller; // Check if player controlled controllerConnected = control is PlayerHumanController; // Update indicator display indicator?.UpdateValues(controllerNum, controllerConnected); // return player controlled flag return controllerConnected; } public void Move(float magnitude) { // Store last movement in x float previousX = rb.velocity.x; // Get new movement Vector2 newVelocity = new Vector2(magnitude * speed, rb.velocity.y); // If moving in new direction if (Mathf.Sign(newVelocity.x) != Mathf.Sign(previousX)) { // Smooth turnaround newVelocity = new Vector2(previousX + (newVelocity.x * 0.01f), newVelocity.y); } else { // Continue at the higher speed newVelocity = new Vector2(Mathf.Max(Mathf.Abs(previousX), Mathf.Abs(newVelocity.x)) * Mathf.Sign(newVelocity.x), newVelocity.y); } // Set new movement rb.velocity = newVelocity; } public void Jump(float magnitude = 1, float angle = 0) { // Check for valid value if (jumpHeight <= 0) return; // Get a target hight based on magnitude float targetHeight = jumpHeight * magnitude; // Get velocity based on target height float velocity = Mathf.Sqrt(-2.0f * Physics2D.gravity.y * targetHeight); // Create Vector Vector2 jumpVector = Vector2.up * (float.IsNaN(velocity) ? 0 : velocity); // If angle is specified if (angle != 0) { // Rotate vector float rad = angle * Mathf.Deg2Rad; float cos = Mathf.Cos(rad); float sin = Mathf.Sin(rad); jumpVector = new Vector2((jumpVector.x * cos) - (jumpVector.y * sin), (jumpVector.y * cos) - (jumpVector.x * sin)); } // Apply velocity rb.velocity = new Vector2(rb.velocity.x + jumpVector.x, jumpVector.y); // Increment Jump Count jumpCount++; // If jump count reaches max disable jump if (jumpCount >= maxJumpCount) canJump = false; // Reset Wall Detection attachedToWall = WallSide.NONE; // Disable Wall Jump canWallJump = false; } public void Dash() { // If cooldown is not completed, stop if (dashTimer > 0) return; // Add Velocity based on movement rb.velocity += Vector2.right * control.GetMoveMagnitude() * dashSpeed; // Enable Trail tr.emitting = true; // Set Cooldown dashTimer = dashCooldown; } public void Kill() { // If already dead, stop if (!alive) return; // Run Death Event onDeath.Invoke(); // Set Alive Flag alive = false; // Create Partcles, Schedule Destruction Destroy(Instantiate(deathEffect, transform.position, Quaternion.identity), 5); //Destroy(gameObject); gameObject.SetActive(false); //// Stun for 2 Seconds //Stun(2, 0); //// Move into the air //transform.position += (Vector3) Vector2.up * 5f; // //// Set to ghost colour; //GetComponent<SpriteRenderer>().color = new Color(0.5f, 0.75f, 1f, 0.5f); } public void Stun(float time, float random = 0.1f) { stunTime += (isCrouching ? 0.25f : 1) * time * Random.Range(1 - random, 1 + random); } public void Damage(Vector2 damageSource, float damageMultiplier = 1) { float distance = Vector2.Distance(transform.position, damageSource); float damage = 1 - Mathf.Pow(distance / damageMultiplier, 2); Damage(damage); } public bool DropThrough() { bool ret = false; if (DropThrough(Vector2.zero)) ret = true; return ret; } public bool DropThrough(Vector2 offset) { RaycastHit2D hit = Physics2D.Raycast((Vector2) transform.position + offset + new Vector2(0, -0.17f), Vector2.down, 0.5f); Debug.DrawLine((Vector2) transform.position + offset + new Vector2(0, -0.1f), (Vector2) transform.position + offset + new Vector2(0, -0.17f) + (Vector2.down * 0.5f), Color.white); if (hit && hit.collider) Debug.Log(hit.collider.name); if (hit && hit.collider && hit.collider.GetComponent<PlatformEffector2D>()) { canJump = false; StartCoroutine(FullDropThrough(hit.collider)); return true; } return false; } public void Damage(float rawDamage) { if (!alive || invulnerable) rawDamage = 0; onHurt.Invoke(rawDamage); if (rawDamage > 0.75f) Kill(); else Stun(rawDamage * 2f); } #endregion #region Helper Methods private void UpdateDisplay() { stunIndicator.shouldShow = stunTime > 0f; if (dashTimer <= dashCooldown - 0.2f) tr.emitting = false; sr.flipX = rb.velocity.x < 0; } private void GetControlInput() { control.Update(); UpdateMovement(); UpdateCrouching(); UpdateJumping(); UpdateDashing(); } private void UpdateMovement() { if (control.ShouldMove()) Move(control.GetMoveMagnitude()); } private void UpdateCrouching() { bool wasCrouching = isCrouching; isCrouching = !control.ShouldMove() && control.GetCrouchButton(); if (!wasCrouching && isCrouching) sr.sprite = sprite.crouching; if (wasCrouching && !isCrouching) sr.sprite = sprite.main; } private void UpdateJumping() { bool isJumpDown = IsJumpDown(); if (isCrouching && control.GetJumpButton() && DropThrough()) { } else if (control.GetJumpButton()) { if (isJumpDown) { if (canWallJump) { Jump(3, attachedToWall == WallSide.LEFT ? -45 : 45); } else if (canJump) { Jump(); } } } else if (rb.velocity.y > 0) { rb.velocity += Vector2.up * Physics2D.gravity.y * 3 * Time.deltaTime; } } private void UpdateDashing() { bool dashButton = control.GetDashButton(); if (!dashWasPressed && dashButton) Dash(); dashWasPressed = dashButton; dashTimer -= Time.deltaTime; } private bool IsJumpDown() { bool wasDownFlg = jumpWasPressed; jumpWasPressed = control.GetJumpButton(); return !wasDownFlg && jumpWasPressed; } public IEnumerator FullDropThrough(Collider2D col) { Physics2D.IgnoreCollision(GetComponent<Collider2D>(), col, true); yield return new WaitForSeconds(0.2f); Physics2D.IgnoreCollision(GetComponent<Collider2D>(), col, false); } #endregion #region Getters/Setters public bool IsAlive() { return alive; } public int GetJumpCount() { return maxJumpCount; } public void SetJumpCount(int maxJumpCount) { this.maxJumpCount = maxJumpCount; } public float GetDashSpeed() { return dashSpeed; } public void SetDashSpeed(float dashSpeed) { this.dashSpeed = dashSpeed; } public void SetInvulnerable(bool invulnerable) { this.invulnerable = invulnerable; } public Sprite GetSprite() { return sprite.main; } #endregion } #region Events [System.Serializable] public class OnHurtEvent : UnityEvent<float> {} [System.Serializable] public class OnDeathEvent : UnityEvent { } #endregion <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; public class SceneManager : MonoBehaviour { private static readonly Dictionary<Scenes, int> scenes = new Dictionary<Scenes, int>() { { Scenes.MAIN_MENU, -1 }, { Scenes.LOBBY, 0 }, { Scenes.GAME, 1 }, { Scenes.WIN_SCREEN, -1 }, { Scenes.LOADING_MENU, -1 } }; public static void LoadSceneStatic(int scene) { Time.timeScale = 1; UnityEngine.SceneManagement.SceneManager.LoadScene(scene); } public static void LoadSceneStatic(Scenes scene) { LoadSceneStatic(scenes[scene]); } public void LoadScene(Scenes scene) { LoadSceneStatic(scene); } public void LoadScene(int scene) { LoadSceneStatic(scene); } } [System.Serializable] public enum Scenes { MAIN_MENU, LOBBY, GAME, WIN_SCREEN, LOADING_MENU } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Bot Settings", menuName = "Bots/Bot Settings", order = 1)] public class BotSettings : ScriptableObject { [Header("Idle")] [Tooltip("The minimum distance the bot must be from the worm to idle")] public float minimumIdleDistance = 5f; [Tooltip("The chance to wander every frame that bot is idling")] public float idleEndChance = 30f; [Header("Wander")] [Tooltip("The amount of seconds until bots change wandering paths")] public float wanderUpdateDelay = 3f; [Tooltip("The chance to stop wandering and switch to either idle or run")] public float wanderEndChance = 30f; [Tooltip("The minimum speed needed to jump while wandering")] public float wanderJumpMinimumSpeed = 0.7f; [Tooltip("The chance to continue holding a jump")] public float wanderContinueJumpChance = 90f; [Header("Running")] [Tooltip("The maximum distance from the worm to run")] public float runDistance = 1f; [Tooltip("The distance from the worm verticly to force a jump while running")] public float runDistanceToJump = 0.25f; [Tooltip("The the chance to allow the bot to hold the jump")] public float runJumpChance = 60f; [Header("Movement")] [Tooltip("The minimum movement needed to move")] public float movementDeadzone = 0f; [Tooltip("The chance a bot will crouch")] public float crouchChance = 40f; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeteorItemSpawner : MonoBehaviour { public GameObject[] possibleItems; public float spawnChance; private bool willSpawn; void Start() { willSpawn = Random.RandomRange(0, 1f) < spawnChance; } private void OnDestroy() { if (willSpawn) { var powerUp = Instantiate(possibleItems[Random.Range(0, possibleItems.Length)]); powerUp.transform.position = transform.position; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.UIElements; [RequireComponent(typeof(AudioSource))] public class Explosion : MonoBehaviour { public void Explode(float radius) { transform.localScale = new Vector3(radius * 4, radius * 4, 1); GetComponent<Animator>().SetTrigger("Explode"); } public void Destroy() { Destroy(gameObject); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; public class ScoreManager : MonoBehaviour { public float groundY; private float[] scores; private int[] scoreOrder; public TextMeshProUGUI[] scoreIndicators; public bool GameActive = true; void Start() { scores = new float[PlayerManager.instance.humans.Length]; scoreOrder = new int[PlayerManager.instance.humans.Length]; for (var i = 0; i < scoreIndicators.Length; i++) { if (i < scores.Length) { scoreIndicators[i].text = $"P{i + 1}: {scores[i]}"; } else { scoreIndicators[i].gameObject.SetActive(false); } } } void Update() { if (!GameActive) { return; } var multipliers = new float[PlayerManager.instance.humans.Length]; for(var i = 0; i < scores.Length; i++) { var human = PlayerManager.instance.humans[i]; if (human.IsAlive()) { multipliers[i] = Mathf.Max(1, human.transform.position.y - groundY); scores[i] += Time.deltaTime * multipliers[i]; } } var sorted = scores.Select((x, i) => new KeyValuePair<int, float>(i, x)) .OrderBy(x => x.Value).Reverse(); scoreOrder = sorted.Select(x => x.Key).ToArray(); for (var place = 0; place < scoreOrder.Length; place++) { var score_i = scoreOrder[place]; if (score_i < scoreIndicators.Length) { var fontSizes = new float[] {14, 13, 12, 11}; scoreIndicators[score_i].fontSize = place < fontSizes.Length ? fontSizes[place] : fontSizes[fontSizes.Length - 1]; scoreIndicators[score_i].gameObject.transform.SetAsLastSibling(); } } for (var i = 0; i < scoreIndicators.Length; i++) { if (i < scores.Length) { var multiplier = multipliers[i].ToString("F1"); var score = scores[i].ToString("F0"); scoreIndicators[i].text = $"P{i + 1} x{multiplier}\n{score}"; } } } public float[] GetScores() { return scores; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class ReadyCheck : MonoBehaviour { [SerializeField] private int buttonIndex = 0; [SerializeField] private int playerNumber = 8; [Header("Events")] public OnNewReady onNewReady = new OnNewReady(); public OnNewReady onNewUnReady = new OnNewReady(); public OnReady onReady = new OnReady(); private bool[] ready; private bool[] connected; private bool needReady = true; void Start() { ready = new bool[playerNumber]; connected = new bool[playerNumber]; } void Update() { if (!needReady) return; string[] joysticks = Input.GetJoystickNames(); bool[] newConnected = new bool[playerNumber]; for (int i = 0; i < playerNumber; i++) { newConnected[i] = JoystickExists(joysticks, i); } for (int i = 0; i < playerNumber; i++) { if (ready[i] && (newConnected[i] && !connected[i])) { ready[i] = false; onNewUnReady.Invoke(i + 1); } if (!ready[i] && (Input.GetKeyDown($"joystick {i + 1} button {buttonIndex}") || !newConnected[i])) { onNewReady.Invoke(i + 1); Debug.Log($"READY PLAYER {i + 1}"); ready[i] = true; } } connected = newConnected; bool isAllReady = true; foreach (bool r in ready) if (!r) isAllReady = false; if (isAllReady) { onReady.Invoke(); needReady = false; } } private bool JoystickExists(string[] joystickNames, int joystick) { return joystick < joystickNames.Length && !string.IsNullOrEmpty(joystickNames[joystick]); } } #region [System.Serializable] public class OnNewReady : UnityEvent<int> { } [System.Serializable] public class OnReady : UnityEvent { } #endregion <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using ClipperLib; using Path = System.Collections.Generic.List<ClipperLib.IntPoint>; using Paths = System.Collections.Generic.List<System.Collections.Generic.List<ClipperLib.IntPoint>>; using Random = System.Random; public class Cutter : MonoBehaviour { public float CutResolution = 1000f; public float CutRadius = 0.5f; public void Cut() { var colliders = Physics2D.OverlapCircleAll(new Vector2(transform.position.x, transform.position.y), CutRadius); foreach (var hitCollider in colliders) { if (hitCollider.gameObject == gameObject) continue; var cuttable = hitCollider.GetComponent<Cuttable>(); if(cuttable == null) continue; var relativePos = transform.position - hitCollider.transform.position; var polygonCollider = cuttable.polygonCollider; var subjects = new Paths { polygonCollider.points.Select(point => { Vector2 rotatedPoint = polygonCollider.transform.TransformDirection(point); return new IntPoint(rotatedPoint.x * CutResolution, rotatedPoint.y * CutResolution); }).ToList() }; var clip = new Paths {new Path(20)}; for (var i = 0; i < 20; i++) { var theta = i * 2 * Mathf.PI / 20f; clip[0].Add(new IntPoint((relativePos.x + (Math.Cos(theta) * CutRadius)) * CutResolution, (relativePos.y + (Math.Sin(theta) * CutRadius)) * CutResolution)); } var solution = new Paths(); var c = new Clipper(); c.AddPaths(subjects, PolyType.ptSubject, true); c.AddPaths(clip, PolyType.ptClip, true); c.Execute(ClipType.ctDifference, solution, PolyFillType.pftEvenOdd, PolyFillType.pftEvenOdd); if (solution.Count > 0) { for (var i = 0; i < solution.Count; i++) { if (i > 0) { var clone = Instantiate(cuttable, polygonCollider.transform.parent); foreach (Transform child in clone.transform) { Destroy(child.gameObject); } } cuttable.SetVertices(solution[i].Select( point => (Vector2) polygonCollider.transform.InverseTransformDirection(new Vector2(point.X / CutResolution, point.Y / CutResolution)) ).ToArray()); } } else { Destroy(polygonCollider.gameObject); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IHumanController { bool ShouldMove(); float GetMoveMagnitude(); bool GetJumpButton(); bool GetCrouchButton(); bool GetDashButton(); void Update(); } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(RectTransform))] public class PulsingTitle : MonoBehaviour { public AnimationCurve scale; public float timeScale = 1; private RectTransform rectTransform; void Start() { rectTransform = GetComponent<RectTransform>(); } void Update() { float time = (Time.time * timeScale) % 1; rectTransform.localScale = new Vector2(scale.Evaluate(time), scale.Evaluate(time)); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FasterDashEffect : HumanEffect { public float dashSpeed = 60; private float prevDashSpeed = 40; public override void OnStartEffect(Human human) { prevDashSpeed = human.GetDashSpeed(); human.SetDashSpeed(dashSpeed); } public override void OnEndEffect(Human human) { human.SetDashSpeed(prevDashSpeed); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class NavigationByNumber : MonoBehaviour { public bool upPathRequiresNumbers = false; [ConditionalHide("upPathRequiresNumbers", true, false)] public PathByNumber pathsOnUp; [ConditionalHide("upPathRequiresNumbers", true, true)] public Selectable pathOnUp; public bool leftPathRequiresNumbers = false; [ConditionalHide("leftPathRequiresNumbers", true, false)] public PathByNumber pathsOnLeft; [ConditionalHide("leftPathRequiresNumbers", true, true)] public Selectable pathOnLeft; public bool rightPathRequiresNumbers = false; [ConditionalHide("rightPathRequiresNumbers", true, false)] public PathByNumber pathsOnRight; [ConditionalHide("rightPathRequiresNumbers", true, true)] public Selectable pathOnRight; public bool downPathRequiresNumbers = false; [ConditionalHide("downPathRequiresNumbers", true, false)] public PathByNumber pathsOnDown; [ConditionalHide("downPathRequiresNumbers", true, true)] public Selectable pathOnDown; public Selectable SelectOnUp(int controller) { return upPathRequiresNumbers ? pathsOnUp[controller] : pathOnUp; } public Selectable SelectOnDown(int controller) { return downPathRequiresNumbers ? pathsOnDown[controller] : pathOnDown; } public Selectable SelectOnLeft(int controller) { return leftPathRequiresNumbers ? pathsOnLeft[controller] : pathOnLeft; } public Selectable SelectOnRight(int controller) { return rightPathRequiresNumbers ? pathsOnRight[controller] : pathOnRight; } } [System.Serializable] public class PathByNumber { // I AM AWARE ARRAYS EXIST -- This is for formatting in the inspector [SerializeField] private Selectable joystick1; [SerializeField] private Selectable joystick2; [SerializeField] private Selectable joystick3; [SerializeField] private Selectable joystick4; [SerializeField] private Selectable joystick5; [SerializeField] private Selectable joystick6; [SerializeField] private Selectable joystick7; [SerializeField] private Selectable joystick8; public Selectable this[int index] { get { switch(index) { case 1: return joystick1; case 2: return joystick2; case 3: return joystick3; case 4: return joystick4; case 5: return joystick5; case 6: return joystick6; case 7: return joystick7; case 8: return joystick8; default: return null; } } set { switch (index) { case 1: joystick1 = value; break; case 2: joystick2 = value; break; case 3: joystick3 = value; break; case 4: joystick4 = value; break; case 5: joystick5 = value; break; case 6: joystick6 = value; break; case 7: joystick7 = value; break; case 8: joystick8 = value; break; } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; // Credit To: http://www.brechtos.com/hiding-or-disabling-inspector-properties-using-propertydrawers-within-unity-5/ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] public class ConditionalHideAttribute : PropertyAttribute { //The name of the bool field that will be in control public string ConditionalSourceField = ""; //TRUE = Hide in inspector / FALSE = Disable in inspector public bool HideInInspector = false; //TRUE = Invert Conditional public bool InvertConditional = false; public ConditionalHideAttribute(string conditionalSourceField) { this.ConditionalSourceField = conditionalSourceField; this.HideInInspector = false; this.InvertConditional = false; } public ConditionalHideAttribute(string conditionalSourceField, bool hideInInspector) { this.ConditionalSourceField = conditionalSourceField; this.HideInInspector = hideInInspector; this.InvertConditional = false; } public ConditionalHideAttribute(string conditionalSourceField, bool hideInInspector, bool invertConditional) { this.ConditionalSourceField = conditionalSourceField; this.HideInInspector = hideInInspector; this.InvertConditional = invertConditional; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class StunIndicator : MonoBehaviour { public SpriteMask mask; public SpriteRenderer forground; public SpriteRenderer background; public float speed = 1f; public bool shouldShow = false; void Update() { if (shouldShow != mask.enabled) { mask.enabled = shouldShow; } forground.transform.localPosition += (Vector3) Vector2.right * Time.deltaTime * speed; if (forground.transform.localPosition.x > 0.25f) forground.transform.localPosition = Vector2.zero; background.transform.localPosition += (Vector3) Vector2.left * Time.deltaTime * speed; if (background.transform.localPosition.x < -0.25f) background.transform.localPosition = Vector2.zero; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(MaskableGraphic))] public class FadeUI : MonoBehaviour { public float timeScale = 1; public bool shouldShow = false; private MaskableGraphic graphic; private Color showColour = Color.white; private Color hideColour = new Color(1, 1, 1, 0); private float currTime; void Start() { graphic = GetComponent<MaskableGraphic>(); graphic.color = shouldShow ? showColour : hideColour; currTime = shouldShow ? 1 : 0; } void Update() { currTime += Time.deltaTime * timeScale * (shouldShow ? 1 : -1); currTime = Mathf.Clamp01(currTime); graphic.color = Color.Lerp(hideColour, showColour, currTime); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class ControllerNavigation : MonoBehaviour { public Selectable[] startSelection; private Selectable[] selected; private Vector2[] prevInput; private bool[] prevPressed; void Start() { selected = new Selectable[startSelection.Length]; for (int i = 0; i < startSelection.Length; i++) Select(startSelection[i], i); prevInput = new Vector2[startSelection.Length]; for (int i = 0; i < prevInput.Length; i++) prevInput[i] = Vector2.zero; prevPressed = new bool[startSelection.Length]; for (int i = 0; i < prevPressed.Length; i++) prevPressed[i] = false; } void Update() { Navigate(); CheckPress(); } public void Select(Selectable selectable, int controller) { Selectable last = selected[controller]; selected[controller] = selectable; UpdateDisplay(last, selectable); } private void CheckPress() { for(int i = 0; i < selected.Length; i++) { bool pressed = Input.GetAxis($"Joystick{i + 1}button0") > 0; if (pressed && !prevPressed[i]) { Press(i); } prevPressed[i] = pressed; } } public void Press(int controller) { Selectable s = selected[controller]; if (s is Button) { ((Button) s).onClick.Invoke(); } } public Selectable NavigateUp(Selectable start, int controller) { Selectable s = start.navigation.selectOnUp; NavigationByNumber nav = start.GetComponent<NavigationByNumber>(); if (nav) s = nav.SelectOnUp(controller); if (!s) return start; if (s.interactable) return s; Selectable newS = NavigateUp(s, controller); return newS == s ? start : newS; } public Selectable NavigateDown(Selectable start, int controller) { Selectable s = start.navigation.selectOnDown; NavigationByNumber nav = start.GetComponent<NavigationByNumber>(); if (nav) s = nav.SelectOnDown(controller); if (!s) return start; if (s.interactable) return s; Selectable newS = NavigateDown(s, controller); return newS == s ? start : newS; } public Selectable NavigateLeft(Selectable start, int controller) { Selectable s = start.navigation.selectOnLeft; NavigationByNumber nav = start.GetComponent<NavigationByNumber>(); if (nav) s = nav.SelectOnLeft(controller); if (!s) return start; if (s.interactable) return s; Selectable newS = NavigateLeft(s, controller); return newS == s ? start : newS; } public Selectable NavigateRight(Selectable start, int controller) { Selectable s = start.navigation.selectOnRight; NavigationByNumber nav = start.GetComponent<NavigationByNumber>(); if (nav) s = nav.SelectOnRight(controller); if (!s) return start; if (s.interactable) return s; Selectable newS = NavigateRight(s, controller); return newS == s ? start : newS; } private void Navigate() { for (int i = 0; i < selected.Length; i++) { Vector2 input = new Vector2(Input.GetAxis($"Joystick{i + 1}X"), Input.GetAxis($"Joystick{i + 1}Y")); if (IsInputDown(input, i)) Select(NavigateDown(selected[i], i + 1), i); if (IsInputUp(input, i)) Select(NavigateUp(selected[i], i + 1), i); if (IsInputRight(input, i)) Select(NavigateRight(selected[i], i + 1), i); if (IsInputLeft(input, i)) Select(NavigateLeft(selected[i], i + 1), i); prevInput[i] = input; } } private void UpdateDisplay(Selectable last, Selectable next) { if (last) last.OnDeselect(new BaseEventData(EventSystem.current)); if (next) next.OnSelect(new BaseEventData(EventSystem.current)); } private bool IsInputUp(Vector2 input, int controller) { return (input.y < -0.5f) && !(prevInput[controller].y < -0.5f); } private bool IsInputDown(Vector2 input, int controller) { return (input.y > 0.5f) && !(prevInput[controller].y > 0.5f); } private bool IsInputLeft(Vector2 input, int controller) { return (input.x < -0.5f) && !(prevInput[controller].x < -0.5f); } private bool IsInputRight(Vector2 input, int controller) { return (input.x > 0.5f) && !(prevInput[controller].x > 0.5f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class KillTrigger : MonoBehaviour { private void OnTriggerEnter2D(Collider2D collision) { Human human = collision.GetComponent<Human>(); if (human) human.Kill(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MultiJumpEffect : HumanEffect { public int jumpCount = 4; private int prevJumpCount = 2; public override void OnStartEffect(Human human) { prevJumpCount = human.GetJumpCount(); human.SetJumpCount(jumpCount); } public override void OnEndEffect(Human human) { human.SetJumpCount(prevJumpCount); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerIndicator : MonoBehaviour { [Header("References")] public SpriteRenderer indicator; public SpriteRenderer arrow; [Header("Animation Settings")] public float animTime = 0.25f; public Vector3 offset = Vector2.up; public float changeAcceleration = 2.5f; [Header("Indicator Settings")] public Sprite[] playerNumberSprites; public Color[] playerNumberColours; private float animTimer = 0; private bool moveDirection = true; private int controllerNumber = -1; private bool isConnected = false; private SpriteRenderer tmpChangeSprite = null; private float timeScale = 1f; private enum IndicatorAnimationState { BOBBING, CHANGING, NONE } private IndicatorAnimationState state = IndicatorAnimationState.BOBBING; void Update() { if (controllerNumber <= 0) return; UpdateAnimation(); } public void UpdateValues(int controllerNumber, bool isConnected) { if (this.controllerNumber != controllerNumber || this.isConnected != isConnected) { this.controllerNumber = controllerNumber; this.isConnected = isConnected; ChangeState(IndicatorAnimationState.CHANGING); } } private void UpdateAnimation() { switch (state) { case IndicatorAnimationState.BOBBING: animTimer -= Time.deltaTime; if (animTimer <= 0) { animTimer += animTime; indicator.transform.localPosition = (moveDirection ? offset : -offset); moveDirection = !moveDirection; } break; case IndicatorAnimationState.CHANGING: animTimer += Time.deltaTime * timeScale; float percentage = animTimer / animTime; indicator.transform.localPosition = Vector2.Lerp(Vector2.up, Vector2.zero, percentage); if (percentage >= 1f) { indicator.transform.localPosition = Vector2.zero; if (tmpChangeSprite) { Destroy(tmpChangeSprite.gameObject); tmpChangeSprite = null; } arrow.color = playerNumberColours[controllerNumber]; ChangeState(IndicatorAnimationState.BOBBING); animTimer = 0; moveDirection = true; } timeScale += changeAcceleration; break; } } private void ChangeState(IndicatorAnimationState state) { if (this.state == IndicatorAnimationState.CHANGING) { if (tmpChangeSprite) { Destroy(tmpChangeSprite.gameObject); tmpChangeSprite = null; } } this.state = state; if (this.state == IndicatorAnimationState.CHANGING) { timeScale = 1f; GameObject go = Instantiate(indicator.gameObject, indicator.transform.position, Quaternion.identity, transform); tmpChangeSprite = go.GetComponent<SpriteRenderer>(); indicator.sprite = playerNumberSprites[isConnected ? controllerNumber : 0]; indicator.color = playerNumberColours[controllerNumber]; indicator.transform.localPosition = Vector2.up; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CloudMovement : MonoBehaviour { public bool randomizeStart = true; public bool randomizeSpeed = false; [ConditionalHide("randomizeSpeed", true, true)] public float speed = 1f; [ConditionalHide("randomizeSpeed", true, false)] public float minSpeed = 1f; [ConditionalHide("randomizeSpeed", true, false)] public float maxSpeed = 1f; private Vector2 startPos; private Vector2 endPos; private float timer = 0f; void Start() { startPos = transform.position; endPos = new Vector2(-transform.position.x, transform.position.y); speed = Random.Range(minSpeed, maxSpeed); if (randomizeStart) timer = Random.Range(0f, 1f); } void Update() { timer += Time.deltaTime * speed; transform.position = Vector2.Lerp(startPos, endPos, timer); if (timer > 1) { timer = 0; if (randomizeSpeed) { speed = Random.Range(minSpeed, maxSpeed); } } } private void OnDrawGizmos() { Gizmos.DrawLine(transform.position, new Vector3(-transform.position.x, transform.position.y, transform.position.z)); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectLaunchingScript : MonoBehaviour, IDamageable { [Header("Settings")] public float explosionForce = 8; public float damageThreshold = 0.75f; public int hitsToDestroy = int.MaxValue; [Header("Particles")] public bool particleEffectOnHit = false; [ConditionalHide("particleEffectOnHit", true, false)] public PropParticlesContainer particles; [Header("Sprite")] public bool damageSprite = false; [ConditionalHide("damageSprite", true, false)] public DestroyablePropSprite sprites; Rigidbody2D rb; SpriteRenderer sr; private int hits = 0; private void Start() { rb = GetComponent<Rigidbody2D>(); sr = GetComponent<SpriteRenderer>(); } public void Damage(Vector2 damageSource, float damageMultiplier = 1) { float distance = Vector2.Distance(transform.position, damageSource); float damage = 1 - Mathf.Pow(distance / damageMultiplier, 2); Damage(damage); } public void Damage(float rawDamage) { if (rawDamage > damageThreshold) { rb.velocity = Vector2.up * explosionForce; if (particleEffectOnHit) particles.PlayParticles(transform); if (damageSprite) { sr.sprite = sprites.GetNextSprite(); } hits++; if (hits > hitsToDestroy) { Destroy(gameObject); } } } } [System.Serializable] public class PropParticlesContainer { public bool oneTimeOnly = true; public PropParticles[] particles; private bool consumed = false; public void PlayParticles(Transform transform) { if (!consumed) { foreach (PropParticles p in particles) { p.PlayParticles(transform); } if (oneTimeOnly) consumed = true; } } } [System.Serializable] public class PropParticles { public GameObject particles; public Vector2 offset; public bool shouldParent = false; public void PlayParticles(Transform transform) { Vector2 newPosition = transform.localPosition + (transform.InverseTransformVector(offset)); GameObject particlesObj = null; if (shouldParent) { particlesObj = GameObject.Instantiate(particles, newPosition, Quaternion.identity, transform); } else { particlesObj = GameObject.Instantiate(particles, newPosition, Quaternion.identity); } particlesObj.transform.localScale = Vector3.one * 0.3f; } } [System.Serializable] public class DestroyablePropSprite { [Range(0, 1)] public float chanceOfBreaking = 1; public Sprite[] sprites; private int currSprite = 0; public Sprite GetNextSprite() { if (Random.Range(0f, 1f) < chanceOfBreaking) { currSprite = Mathf.Min(sprites.Length - 1, currSprite + 1); } return sprites[currSprite]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.XR; public class PlayerWormController : IWormController { private int controllerNum; public PlayerWormController(int controllerNum) { this.controllerNum = controllerNum; } public Vector2 GetMoveDirection() { var vertical = Input.GetAxis($"Joystick{controllerNum}Y"); var horizontal = Input.GetAxis($"Joystick{controllerNum}X"); var direction = new Vector2(vertical, horizontal); if (direction.sqrMagnitude > 1) { direction.Normalize(); } return direction; } public bool GetBoosting() { return false; } public bool GetEating() { return true; } }
470a95336c21268954d25108059138813d5c1318
[ "C#" ]
45
C#
PixelRavenGames/PR_Tremors_2D
5e17949331b8a914dca3171b964432e9c266f1d3
2067ad5c5faf0b07d730d45a1253f4357accddd4
refs/heads/master
<repo_name>rleteixeira/kafka<file_sep>/CouchbaseDemo/src/main/resources/application.properties spring.couchbase.bootstrap-hosts=localhost spring.couchbase.env.timeouts.connect=10000 spring.couchbase.env.timeouts.socket-connect=10000 spring.data.couchbase.auto-index=true spring.couchbase.bucket.name=SAMPLE spring.couchbase.bucket.password=<PASSWORD> <file_sep>/CouchbaseDemo/Dockerfile FROM openjdk:8-jre-slim COPY ./build/libs/CouchbaseDemo-0.0.1-SNAPSHOT.jar /Sample/CouchDemo/ WORKDIR /Sample/CouchDemo/ EXPOSE 8080 CMD ["java","-Dspring.couchbase.bootstrap-hosts=couchbase","-Dspring.couchbase.bucket.password=<PASSWORD>","-jar","CouchbaseDemo-0.0.1-SNAPSHOT.jar"] <file_sep>/CouchbaseDemo/README.md ####Creating couchbase image#### 1.build the image using docker file avaialeble in /Users/arunbonam/Documents/couch-docker 2.run docker compose file for couchbase db to start 3.docker-compose run -d --service-ports --name couchbase couchbase [bring both spring boot and couchbase to same network [custom bridge network]] 4.verify localhost:8091 5.create SAMPLE bucket with username as bucket name and password as <PASSWORD> ###SPRING APP#### 1.build the image from docker file available in /Downloads/CouchbaseDemo 2.in docker file makes sure application.properties are overridden with -Dprops 3.run docker compose file for spring-boot to start in the same network 4.verify by posting json to localhost:8080/employee/add . <file_sep>/src/main/java/com/getest/KafkaConsumer/Kafkalocal/EmployeeRepository.java package com.getest.KafkaConsumer.Kafkalocal; import com.getest.KafkaConsumer.Kafkalocal.domain.WorkUnit; import org.springframework.data.couchbase.repository.CouchbaseRepository; import org.springframework.stereotype.Repository; @Repository interface CouchRepository extends CouchbaseRepository <WorkUnit,Integer>{ } <file_sep>/Dockerfile FROM java:8 COPY ./build/libs/*.jar /SAMPLE/KafkaConsumer/app.jar WORKDIR /SAMPLE/KafkaConsumer/ ENTRYPOINT ["java","-jar","app.jar"]
ce0aa6e669ea2d3c0e6ccc29668e4fc3f9aa6a2b
[ "Markdown", "Java", "Dockerfile", "INI" ]
5
INI
rleteixeira/kafka
7398a75d68e8670fc3c3640b63da1ed3284f7637
38fb6b97e24239d19a552f991ebbb0dcdabb7e22
refs/heads/master
<file_sep>// // ViewMenu.swift // MenuOnWindow // // Created by <NAME> on 28/04/17. // Copyright © 2017 Piyush. All rights reserved. // import UIKit class ViewMenu: UIView { @IBOutlet weak var tblMenu: UITableView! var cellobj : SimpleCell = SimpleCell() let arrMenuItem = ["Home", "FirstView", "SecondView", "ThirdView", "FourthView", "FifthView"] let appdel = UIApplication.shared.delegate as! Appdelegate @IBOutlet weak var viewTbl: UIView! public func registerMethod() { // For registering classes tblMenu.register(UINib(nibName: "SimpleCell", bundle: nil), forCellReuseIdentifier: "SimpleCell") } } extension ViewMenu: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didselect",indexPath.row) let menuObj : MenuOnWindow = MenuOnWindow() let storyboard = UIStoryboard(name: "Main", bundle: nil) switch indexPath.row { case 0: let viewContr = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController menuObj.push_POP_to_ViewController(destinationVC: viewContr, isAnimated: true) case 1: let ftviewobj = storyboard.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController menuObj.push_POP_to_ViewController(destinationVC: ftviewobj, isAnimated: true) case 2: let sdviewobj = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController menuObj.push_POP_to_ViewController(destinationVC: sdviewobj, isAnimated: true) case 3: let tdviewobj = storyboard.instantiateViewController(withIdentifier: "ThirdViewController") as! ThirdViewController menuObj.push_POP_to_ViewController(destinationVC: tdviewobj, isAnimated: true) case 4: let fourthviewobj = storyboard.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController menuObj.push_POP_to_ViewController(destinationVC: fourthviewobj, isAnimated: true) case 5: let fifthviewobj = storyboard.instantiateViewController(withIdentifier: "FifthViewController") as! FifthViewController menuObj.push_POP_to_ViewController(destinationVC: fifthviewobj, isAnimated: true) default: print("Default") } } } extension ViewMenu: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrMenuItem.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { cellobj = tblMenu.dequeueReusableCell(withIdentifier: "SimpleCell") as! SimpleCell! cellobj.lblName.text = arrMenuItem[indexPath.row] as String return cellobj } } <file_sep># MenuOnWindow MenuOnWindow ![alt tag](https://github.com/IosPower/MenuOnWindow/blob/master/MenuOnWindow.gif) <file_sep>// // MenuOnWindow.swift // MenuOnWindow // // Created by <NAME> on 01/05/17. // Copyright © 2017 Piyush. All rights reserved. // import UIKit var viewWidthHeight: CGFloat = 150 // XibView WidthHeight var screenWidth: CGFloat = UIScreen.main.bounds.size.width var screenHeight: CGFloat = UIScreen.main.bounds.size.height class MenuOnWindow: NSObject { var windowApp: UIWindow? static var btnMenu = UIButton() static var xibView : ViewMenu? static var navController = UINavigationController() //MARK:- Btn Load On Window func loadNewView(window: UIWindow, navigation: UINavigationController) { windowApp = window MenuOnWindow.navController = navigation MenuOnWindow.btnMenu = UIButton(type: .custom) MenuOnWindow.btnMenu.setTitle("Menu", for: .normal) MenuOnWindow.btnMenu.titleLabel?.textAlignment = .center MenuOnWindow.btnMenu.titleLabel!.font = UIFont.systemFont(ofSize: 15) MenuOnWindow.btnMenu.setTitleColor(UIColor.white, for: .normal) MenuOnWindow.btnMenu.backgroundColor = UIColor.black MenuOnWindow.btnMenu.frame = CGRect(x: 10, y: 20, width: 45, height: 45) MenuOnWindow.btnMenu.layer.cornerRadius = MenuOnWindow.btnMenu.frame.size.width/2 MenuOnWindow.btnMenu.layer.masksToBounds = true MenuOnWindow.btnMenu.addTarget(self, action: #selector(btnMenuAction(sender:)), for: .touchUpInside) let panner = UIPanGestureRecognizer(target: self, action: #selector(self.panDidFire(panner:))) MenuOnWindow.btnMenu.addGestureRecognizer(panner) window.addSubview(MenuOnWindow.btnMenu) window.makeKeyAndVisible() } //MARK:- Pan GestureRecognizer func panDidFire(panner: UIPanGestureRecognizer) { let offset = panner.translation(in: windowApp) panner.setTranslation(CGPoint.zero, in: windowApp) var center = MenuOnWindow.btnMenu.center center.x += offset.x center.y += offset.y MenuOnWindow.btnMenu.center = center if panner.state == .ended || panner.state == .cancelled { UIView.animate(withDuration: 0.3) { if MenuOnWindow.btnMenu.frame.origin.x < 0 { MenuOnWindow.btnMenu.frame = CGRect(x: 10, y: MenuOnWindow.btnMenu.frame.origin.y, width: MenuOnWindow.btnMenu.frame.size.width, height: MenuOnWindow.btnMenu.frame.size.height) } else if (MenuOnWindow.btnMenu.frame.origin.x + MenuOnWindow.btnMenu.frame.size.width) > screenWidth { MenuOnWindow.btnMenu.frame = CGRect(x:screenWidth - MenuOnWindow.btnMenu.frame.size.width - 10, y: MenuOnWindow.btnMenu.frame.origin.y, width: MenuOnWindow.btnMenu.frame.size.width, height: MenuOnWindow.btnMenu.frame.size.height) } if MenuOnWindow.btnMenu.frame.origin.y < 0 { MenuOnWindow.btnMenu.frame = CGRect(x: MenuOnWindow.btnMenu.frame.origin.x, y: 20, width: MenuOnWindow.btnMenu.frame.size.width, height: MenuOnWindow.btnMenu.frame.size.height) } else if (MenuOnWindow.btnMenu.frame.origin.y + MenuOnWindow.btnMenu.frame.size.height) > screenHeight { MenuOnWindow.btnMenu.frame = CGRect(x:MenuOnWindow.btnMenu.frame.origin.x, y: screenHeight - MenuOnWindow.btnMenu.frame.size.height - 10, width: MenuOnWindow.btnMenu.frame.size.width, height: MenuOnWindow.btnMenu.frame.size.height) } } } else if panner.state == .began { touchViewRemove() } } //MARK:- Button Action func btnMenuAction(sender: UIButton) { touchViewAddOrRemove() } //MARK:- TouchView Method func touchViewRemove() { if MenuOnWindow.xibView != nil { MenuOnWindow.xibView?.removeFromSuperview() MenuOnWindow.xibView = nil MenuOnWindow.btnMenu.setTitle("Open", for:.normal) } } func touchViewAddOrRemove() { if MenuOnWindow.xibView != nil { MenuOnWindow.xibView?.removeFromSuperview() MenuOnWindow.xibView = nil MenuOnWindow.btnMenu.setTitle("Open", for:.normal) } else { MenuOnWindow.btnMenu.setTitle("Close", for:.normal) MenuOnWindow.xibView = Bundle.main.loadNibNamed("ViewMenu", owner: self, options: nil)?[0] as? ViewMenu MenuOnWindow.xibView?.dropShadow() MenuOnWindow.xibView?.viewTbl.layer.cornerRadius = 5.0 MenuOnWindow.xibView?.viewTbl.layer.masksToBounds = true MenuOnWindow.xibView?.registerMethod() let btnCenter = MenuOnWindow.btnMenu.center MenuOnWindow.xibView?.layer.cornerRadius = 5.0 if btnCenter.x > (screenWidth/2) { if btnCenter.y > (screenHeight/2) { MenuOnWindow.xibView?.frame = CGRect(x: MenuOnWindow.btnMenu.frame.origin.x - viewWidthHeight, y: MenuOnWindow.btnMenu.frame.origin.y - viewWidthHeight , width: viewWidthHeight, height: viewWidthHeight) } else { MenuOnWindow.xibView?.frame = CGRect(x: MenuOnWindow.btnMenu.frame.origin.x - viewWidthHeight, y: MenuOnWindow.btnMenu.frame.origin.y + MenuOnWindow.btnMenu.frame.height, width: viewWidthHeight, height: viewWidthHeight) } } else { if btnCenter.y > (screenHeight/2) { MenuOnWindow.xibView?.frame = CGRect(x: MenuOnWindow.btnMenu.frame.origin.x + MenuOnWindow.btnMenu.frame.width, y: MenuOnWindow.btnMenu.frame.origin.y - viewWidthHeight, width: viewWidthHeight, height: viewWidthHeight) } else { MenuOnWindow.xibView?.frame = CGRect(x: MenuOnWindow.btnMenu.frame.origin.x + MenuOnWindow.btnMenu.frame.width, y: MenuOnWindow.btnMenu.frame.origin.y + MenuOnWindow.btnMenu.frame.height, width: viewWidthHeight, height: viewWidthHeight) } } MenuOnWindow.xibView?.backgroundColor = UIColor.green windowApp?.addSubview(MenuOnWindow.xibView!) windowApp?.bringSubview(toFront: MenuOnWindow.btnMenu) } } //MARK:- Push_Pop ViewController func push_POP_to_ViewController(destinationVC:UIViewController,isAnimated:Bool) { var VCFound:Bool = false let viewControllers:NSArray = MenuOnWindow.navController.viewControllers as NSArray var indexofVC:NSInteger = 0 for vc in viewControllers { if (vc as AnyObject).nibName == (destinationVC.nibName){ VCFound = true break }else{ indexofVC += 1 } } if VCFound == true { MenuOnWindow.navController.popToViewController(viewControllers.object(at: indexofVC) as! UIViewController, animated: isAnimated) }else{ MenuOnWindow.navController.pushViewController(destinationVC , animated: isAnimated) } touchViewRemove() } } //MARK:- DropShadow View extension UIView { func dropShadow() { self.layer.masksToBounds = true self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.7 self.layer.shadowOffset = CGSize(width: -2, height: 2) self.layer.shadowRadius = 5.0 self.clipsToBounds = false self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath self.layer.shouldRasterize = true } }
17959707be516459ef624a9e1e3cbd460e9d4436
[ "Swift", "Markdown" ]
3
Swift
carabina/MenuOnWindow
234ca29fefd2ab8b47443f608cb06c27174a6407
6bef298461ceef683211bca215b0bfc351f56077
refs/heads/main
<repo_name>newtoncy/LR1<file_sep>/README.md # LR1 当前的目标是搞出一种描述性语言。 让公司的前端可以很方便的将写好的代有模板渲染语法的html注册到后端。 这没啥意义,主要是为了好玩<file_sep>/url_mount/grammar.py # -*- coding: utf-8 -*- # @File : grammar.py # @Date : 2020-11-07 # @Author : 王超逸 # @Brief : from collections import namedtuple, defaultdict, deque import copy from itertools import product from typing import Set, FrozenSet, Iterable def calc_once(function): def warp(*args, **kwargs): if not hasattr(function, "_result"): function._result = function(*args, **kwargs) return function._result return warp __Production = namedtuple("Production", ["left", "right", "pos", "follow"]) LR1TableRow = namedtuple("LR1TableRow", ["shift_map", "goto_map", "reduce_map"]) # 空串 EPSILON = 0xff0001 END = "__$__" class Production(__Production): def __str__(self): right = list(self.right) if self.pos != -1: right.insert(self.pos, "#") if self.follow: return "%s -> %s , %s" % (self.left, " ".join(right), self.follow) return "%s -> %s" % (self.left, " ".join(right)) def __repr__(self): return str(self) def start(self, follow="$"): return Production(self.left, self.right, 0, follow) @property def next_v(self): """ :type self: Production :return 如果没有到末尾,则返回语法符号。如果到了末尾,返回None。如果位置无效,抛出assertError """ assert 0 <= self.pos <= len(self.right) if self.pos == len(self.right): return None return self.right[self.pos] @property def shift(self): """ :type self: Production :param self: :return: """ assert self.pos < len(self.right) return Production(self.left, self.right, self.pos + 1, self.follow) Statue = FrozenSet[Production] class GrammarError(Exception): def __init__(self, name, description) -> None: super().__init__("语法定义错误:%s,%s" % (name, description), name, description) class Grammar(object): def __init__(self, filename="url_mount/grammar_def", start_v="文件"): self.start_v = start_v self._start_status = None self.productions = self.load_grammar_def(filename) self.production_dict = defaultdict(list) for production in self.productions: self.production_dict[production.left].append(production) self.production_dict = dict(self.production_dict) self._closure_map = {} @property def start_status(self) -> Statue: if self._start_status is None: assert len(self.production_dict[self.start_v]) == 1, "开始符号的候选式只能且必须有一个" start_p = self.production_dict[self.start_v][0] self._start_status = self.closure({start_p.start()}) return self._start_status @property @calc_once def lr1Table(self): queue = deque() queue.append(self.start_status) lr1_table = {} while queue: status: Statue = queue.popleft() pnextv_p = defaultdict(set) # {self.next_v(p) for p in status} for p in status: pnextv_p[p.next_v].add(p) reduce = {} if None in pnextv_p: for p in pnextv_p[None]: if p.follow in reduce: raise GrammarError("规约规约冲突", [str(p) for p in status]) reduce[p.follow] = p pnextv_p.pop(None) goto = {} shift = {} for v in pnextv_p.keys(): next_status = self.closure({p.shift for p in pnextv_p[v]}) # 非终结符 if v in self.production_dict: goto[v] = next_status # 终结符 else: shift[v] = next_status if set(reduce.keys()) & set(shift.keys()): raise GrammarError("移入规约冲突", [str(p) for p in status]) queue.append(next_status) lr1_table[status] = LR1TableRow(shift, goto, reduce) return lr1_table def get_first_set(self, v_list): """ 由一个文法符号数组得到其first_set :type v_list: Iterable """ first_set = set() for x in v_list: # 终结符 if x not in self.production_dict: first_set.add(x) return first_set if EPSILON not in self.first_set[x]: first_set |= self.first_set[x] return first_set first_set |= self.first_set[x] - {EPSILON} first_set.add(EPSILON) return first_set @property @calc_once def first_set(self): first_set = defaultdict(set) vn_set = set(self.production_dict.keys()) while True: first_set_copy = copy.deepcopy(first_set) # 对每个vn for vn in vn_set: # 对vn的每个产生式 for vn_p in self.production_dict[vn]: all_have_epsilon = True # 对每个产生式的每个语法符号 for vn_p_x in vn_p.right: # 如果是终结符 if vn_p_x not in vn_set: first_set[vn].add(vn_p_x) all_have_epsilon = False break # 如果没有空串 if EPSILON not in first_set[vn_p_x]: first_set[vn] |= first_set[vn_p_x] all_have_epsilon = False break first_set[vn] |= first_set[vn_p_x] - {EPSILON} # 如果每一项都含有空串 if all_have_epsilon: first_set[vn].add(EPSILON) if first_set_copy == first_set: break return first_set def closure(self, I): """ :type I: set """ J = copy.copy(I) J_copy = None while J != J_copy: J_copy = copy.copy(J) for p in J_copy: next_v = p.next_v if next_v in self.production_dict: follows = self.get_first_set(list(p.right[p.pos + 1:]) + list(p.follow)) for pp, follow in product(self.production_dict[next_v], follows): J.add(pp.start(follow)) J = frozenset(J) # 这是为了让相同的闭包始终只有一个在内存里 # 如果直接返回J的话,内存中可能会有很多个J的拷贝 if J not in self._closure_map: self._closure_map[J] = J return self._closure_map[J] @staticmethod def load_grammar_def(filename): productions = [] with open(filename, "rt", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue t = line.split("->") left = t[0].strip() t = t[1].split("|") for right in t: productions.append(Production(left, tuple([i.strip() for i in right.split(" ") if i]), -1, "")) return productions lr1_table = Grammar().lr1Table lr1_table = Grammar().lr1Table print() <file_sep>/url_mount/adapter.py # -*- coding: utf-8 -*- # @File : adapter.py # @Date : 2020-11-07 # @Author : 王超逸 # @Brief : 不同后台框架的适配器 class Adapter(object): def __init__(self, app_context): """ :param app_context: app的上下文,根据需要传入 """ self.app_context = app_context def route(self, url, file_path, flags=None, data=None, sub_route=None): """ 生成并注册好一个视图. :param sub_route: 视图所属的子路由 :param url: url :param data: 传给模板文件的数据 :param file_path:模板文件位置 :param flags: render是否进行模板渲染 :return: None """ raise NotImplementedError() def mount(self, base_file_path, base_url, flags=None, sub_route=None): """ 生成并注册好一个视图,将静态文件夹挂载到url。 :param sub_route: 视图所属的子路由 :param base_file_path: :param base_url: :param flags: :return: None """ raise NotImplementedError() def get_sub_route(self, base_url): """ :return:返回一个sub route对象 """ raise NotImplementedError() def register_all(self): """ 在结束时会调用这个方法 如果注册的对象是nginx之类的。可能需要在这里更新配置文件 :return: """ raise NotImplementedError() <file_sep>/test/test_lexical.py import unittest from url_mount.lexical_analysis import get_token_sequence class MyTestCase(unittest.TestCase): def test_something(self): code = """ # 路由语法 route "a/b" to "path/to/you.html" (render) route "a/b2" to "path/to/you.html" (raw) # 引用子路由 route "url/" to sub route "m1.route" route "url/" to sub route route1 # 静态文件挂载语法 mount "url/" to "path/to/static/dir" (auto_html) # 路由到python函数 from module1.module2 import functionA route "url/" to functionA # 子路由内联定义 @route1 route "c/d" to "path/to/you.html" (render) route "c/d2" to "path/to/you.html" (raw) """ result = str(get_token_sequence(code)) with open(r"test\test_lexical_expect.txt", "rt")as f: self.assertEqual(result, f.read()) if __name__ == '__main__': unittest.main() <file_sep>/url_mount/lexical_analysis.py # -*- coding: utf-8 -*- # @File : lexical_analysis.py # @Date : 2020-11-07 # @Author : 王超逸 # @Brief : 词法分析 import re from collections import namedtuple token_re = [ ("@", r"@"), ("mount", "mount"), ("route", "route"), ("to", "to"), ("sub_route", "sub route"), ("from", "from"), ("import", "import"), ("str", r"[\",'].*?[\",']"), ("(", r"\("), (")", r"\)"), (".", "."), ("id", r"([a-zA-Z_]|[^\x00-\xff])([\w]|[^\x00-\xff])*") ] class LexicalErrors(Exception): def __init__(self, word, line): super().__init__("词法错误,第%d行,%s..." % (line, word)) Token = namedtuple("Token", ("name", "org", "pos_line")) def get_token_sequence(code_org): """ :type code_org: str """ lines = code_org.split('\n') token_sequence = [] for i, line in enumerate(lines): line = line.strip() if line.startswith("#"): continue remain = line while remain: # 长度优先,同等长度,从上到下有先 matched = None token_name = None max_matched = 0 for name, regular in token_re: t = re.match(regular, remain) if not t: continue t = t.group(0) if len(t) > max_matched: matched = t token_name = name max_matched = len(t) if not matched: raise LexicalErrors(remain, i) token_sequence.append(Token(token_name, matched, i)) remain = remain[len(matched):] remain = remain.strip() return token_sequence
f3ca1eeda187689b57676ff0d847b53e27c72a35
[ "Markdown", "Python" ]
5
Markdown
newtoncy/LR1
51df97c4d00d4255bcc55d8f49cf097bb837a20d
f91c0c6dc9c0c11da7866629e696af91e80e368c
refs/heads/master
<file_sep>Build a Thermometer web-application incorporating an API in Javascript. Testing in Jasmine DB in Postgres Phase 2 - React UI <file_sep>'use strict'; describe('Thermostat', function() { } )
f6f457118c180ca936ac358edc03dc79c9e4739d
[ "Markdown", "JavaScript" ]
2
Markdown
kurianvijay/thermometer_js
9894a3e3eae8567445c7da5e79b853a308a99a9c
043c97db72b05432ef9bf3a0a97dc2f05811cfe6
refs/heads/master
<repo_name>dczysz/web-practice<file_sep>/vue/Components/app.js Vue.component('card', { props: [ 'title', 'content' ], data() { return { likes: 0 } }, template: ` <div class="card"> <div class="card-body"> <h3 class="card-title">{{ title }}</h3> <div class="card-text"> {{ content }} </div> <div class="text-center text-muted display-4">{{ likes }}</div> <button @click="likeArticle" class="btn btn-info btn-sm">Like</button> <button @click="deleteArticle" class="btn btn-danger btn-sm">Delete Me</button> </div> </div> `, methods: { deleteArticle() { this.$emit('delete-article', this.title); }, likeArticle() { this.likes++; } } }); new Vue({ el: '#app', data: { articles: [ { title: 'First Article Title', content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' }, { title: 'Second Article Title', content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' }, { title: 'Third Article Title', content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' } ] }, methods: { removeArticle(e) { this.articles = this.articles.filter( article => article.title !== e ); } } });
bb0727a30353a3c71867545fdbee550650083660
[ "JavaScript" ]
1
JavaScript
dczysz/web-practice
f3238bb4170a6d6b5cec02b14885c63dc4bec75c
878d1d8afd8f21bbdea324b50b7c424d909ec422
refs/heads/master
<repo_name>l1Dan/Objective-C<file_sep>/BaiSi/Podfile platform :ios, 9.0 target "BaiSi" do pod 'AFNetworking', '~> 3.0.4' pod 'SDWebImage', '~> 3.7.5' pod 'SVProgressHUD', '~> 2.0-beta8' pod 'MJExtension', '~> 3.0.10' pod 'MJRefresh', '~> 3.1.0' pod 'DACircularProgress', '~> 2.3.1' pod 'pop', '~> 1.0.9' end <file_sep>/BaiSi/README.md ### 高仿百思不得姐,非官方。仅供个人参考学习,不得商用。
b2ea95177a459409a88975236785e6ffac87ec4a
[ "Markdown", "Ruby" ]
2
Ruby
l1Dan/Objective-C
5bea77f5b54e5302f533c1bfd39a36fbe6446466
94a47cdcbb45738a1fcdc36804c41a7fb7c26f51
refs/heads/master
<file_sep>## Implement a Caesar cipher, both encoding and decoding. ## The key is an integer from 1 to 25. This cipher rotates the letters ## of the alphabet (A to Z). The encoding replaces each letter with the ## 1st to 25th next letter in the alphabet (wrapping Z to A). ## So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". ## This simple "monoalphabetic substitution cipher" provides almost ## no security, because an attacker who has the encoded message can ## either use frequency analysis to guess the key, or just try all 25 keys. def codify(str, key, cmd): encList = [None] * 26 encodedStr = "" for i in range(26): if cmd == "en": encList[i] = (i + key) % 26 else: encList[i] = (i - key) % 26 for i in range(len(str)): num = ord(str[i]) if num > 96 and num < 123: num -= 97 encodedNum = encList[num] + 97 encodedStr += chr(encodedNum) else: encodedStr += str[i] return encodedStr def main(): cmd = "de" while True: choice = raw_input("Do you want to encode, or decode a string? (e/d): ") if choice == 'e': cmd = "en" key = 0 while True: key = raw_input("Enter a key for the Caesar Cipher(1-25): ") if int(key) >0 and int(key) <26: break else: print "Sorry! Please enter a valid key from 1 - 25" str = raw_input("Enter the phrase you want coded: ") newStr = codify(str, int(key), cmd) print "The " + cmd + "coded phrase is: " + newStr + "\n" choice2 = raw_input("Would you like to code something else: (y/n) ") if choice2 == "n": print "Goodbye!" break if __name__ == '__main__': main() <file_sep>def reverse(s): l = len(s) - 1 reverseStr = "" for i in xrange(l,-1,-1): reverseStr += s[i] return reverseStr def main(): s = raw_input("Enter a string to reverse: ") print "The reversed string is: " + reverse(s) if __name__ == '__main__': main() <file_sep>def total_cost(price, tax): return int(price) + (int(price) * float(tax)/100) def main(): price = raw_input('Enter the price of an item: $') tax = raw_input('Enter the tax rate(%): ') print "The total cost is %.2f." % total_cost(price,tax) if __name__ == '__main__': main()<file_sep>def fibonacci(n): a = 0 b = 1 print a, print b, for i in xrange(n-2): c = a + b print c, a = b b = c def main(): n = raw_input("Enter how many Fibonacci numbers you want: ") fibonacci(int(n)) if __name__ == '__main__': main() <file_sep>def toBinary (dec): binNum = "" while (dec > 0): digit = dec % 2 binNum = str(digit) + binNum dec /= 2 return binNum def toDec (bin): decNum = 0 for i in xrange(len(str(bin))): digit = bin % 10 decNum += digit * (2 ** i) bin /= 10 return decNum<file_sep>def add_numbers(number1,number2): # Adding two numbers # User might also enter float numbers sum = float(number1) + float(number2) # Display the sum # will print value in float print("The sum of {0} and {1} is {2}" .format(number1, number2, sum)) def multiply_numbers(number1,number2): multiply = float(number1) + float(number2) # Display the sum # will print value in float print("The sum of {0} and {1} is {2}" .format(number1, number2, multiply)) def main(): number1 = input("First number: ") number2 = input("\nSecond number: ") add_numbers(number1,number2) multiply_numbers(number1,number2)
c423d53b29956e8b6cea0cf9b8d1c0fa1c2140bb
[ "Python" ]
6
Python
HishamAlshaaer/projects-1
ada9c9e312aad2c236bbde9126055cc433325d47
80085b919397cf5ed35ffba72d183598934a4738
refs/heads/main
<repo_name>RUbak602/Engine_stress_test<file_sep>/Engine_stress_test/Engine_stress_test/Engines.h #pragma once #include <vector> namespace engines { //Добавление двигателя struct InternalCombustionEngine { //Момент инерции двигателя I (кг∙м2) double I = 10; //Температура перегрева double overheatTemperature = 110; //Коэффициент зависимости скорости нагрева от крутящего момента double Hm = 0.01; //Коэффициент зависимости скорости нагрева от скорости вращения коленвала double Hv = 0.0001; //Коэффициент зависимости скорости охлаждения от температуры двигателя и окружающей среды double C = 0.1; //Значения для крутящего момента M std::vector<double> startM = { 20, 75, 100, 105, 75, 0 }; //Значения для скорости вращения коленвала std::vector<double> startV = { 0, 75, 150, 200, 250, 300 }; double M; double V; //Функция для нахождения скорости охлаждения двигателя double Vc(double ambientTemperature, double engineTemperature); //Функция для нахождения скорости нагревания двигателя double Vh(); }; }<file_sep>/README.md # Engine_stress_test Reserch of engine overheating time depending on the ambient temperature <file_sep>/Engine_stress_test/Engine_stress_test/TestStand.h #pragma once #include "Engines.h" #include <iostream> #define ABSOLUTE_ERROR 10e-2 #define MAX_TIME 1800 namespace standArrea { template <typename T> class TestStand { int numberOfMandV; double engineTemperature; double ambientTemperature; T* engine; public: //Функция возвращает время перегрева двигателя int StartEngine(); //Конструктор класса TestStand TestStand(T& engine, const double ambientTemperature); }; template<typename T> TestStand<T>::TestStand(T& engine, const double ambientTemperature) { this->engine = &engine; this->engine->M = engine.startM[0]; this->engine->V = engine.startV[0]; engineTemperature = ambientTemperature; this->ambientTemperature = ambientTemperature; } template<typename T> int TestStand<T>::StartEngine() { // Текущее усколрение вала //std::cout << "Current M - " << engine->M << std::endl; //std::cout << "Current I - " << engine->I << std::endl; double acceleration = engine->M / engine->I; //std::cout << "Current acceleration - " << acceleration << std::endl; // Погрешность температуры для определения времени double eps = engine->overheatTemperature - engineTemperature; // Текущее время рабоы двигателя int time = 0; //Промежуток времени через который змеряется температура в секундах int deltaTime = 1; //Начальная скорость на текущем промежутке double V_0 = 0; //Текущая граница для интерполяции крутящего момента и подсчета ускорения вращения вала int currentNumberInStartV = 1; //Флаг на достижение максимального предоставленного крутящего момента bool VIsMax = false; while (eps > ABSOLUTE_ERROR && time < MAX_TIME) { time+= deltaTime; engine->V = V_0 + acceleration * deltaTime; V_0 = engine->V; //Проверка перехода к другому значению ускорения (достижение определенной скорости вращения) if (engine->V > engine->startV[currentNumberInStartV] && VIsMax == false) { acceleration = engine->startM[currentNumberInStartV]/ engine->I; currentNumberInStartV++; if (currentNumberInStartV == engine->startM.size()-1) { VIsMax = true; } } //Интерполяция для значения M (крутящий момент) engine->M = engine->startM[currentNumberInStartV - 1] + ((engine->startM[currentNumberInStartV] - engine->startM[currentNumberInStartV - 1]) / (engine->startV[currentNumberInStartV] - engine->startV[currentNumberInStartV - 1])) * (engine->V - engine->startV[currentNumberInStartV - 1]); //Рассчет температуры engineTemperature = engineTemperature + (engine->Vc(ambientTemperature, engineTemperature) + engine->Vh()) * deltaTime; //Обновление условия цикла eps = engine->overheatTemperature - engineTemperature; } return time; } }<file_sep>/Engine_stress_test/Engine_stress_test/Engine_stress_test.cpp // Engine_stress_test.cpp // #include "TestStand.h" #include <iostream> using namespace std; int main() { double ambientTemperature; cout << "Please, enter ambient temperature in degrees Celsius" << endl; cin >> ambientTemperature; engines::InternalCombustionEngine engine; standArrea::TestStand<engines::InternalCombustionEngine> stand(engine, ambientTemperature); double time = stand.StartEngine(); if (time == MAX_TIME) cout << endl << "At this ambient temperature, the engine does not overheat." << endl; else cout << endl << "Time of engine overheating: " << time << " sec" << endl; } <file_sep>/Engine_stress_test/Engine_stress_test/Engines.cpp #include "Engines.h" namespace engines { double InternalCombustionEngine::Vc(double ambientTemperature, double engineTemperature) { return C * (ambientTemperature - engineTemperature); } double InternalCombustionEngine::Vh() { return M * Hm + V * V * Hv; } }
3c8c69afcd9d82350e5589ebaa6619fab2ac6b59
[ "Markdown", "C++" ]
5
C++
RUbak602/Engine_stress_test
f8ea35f7e7e0415580b249d3f2f1d66eebeceb2a
f58177c0b04660f36a465597a72ebc488e24f449
refs/heads/master
<file_sep>import Foundation class OptionsModel { var gameName: String = "Game" var scoreSelectionEnabled: Bool = true init(gameName: String, scoreSelectionEnabled: Bool) { self.gameName = gameName self.scoreSelectionEnabled = scoreSelectionEnabled } } <file_sep>import Foundation struct GameNames { static let rook = "Rook" static let tenThousand = "10,000" static let phase10 = "Phase 10" static let hearts = "Hearts" } <file_sep>import UIKit class GameButton: UIButton { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.cornerRadius = 5 backgroundColor = UIColor(colorLiteralRed: 0, green: 116/255, blue: 145/255, alpha: 1) setTitleColor(UIColor(colorLiteralRed: 255, green: 255, blue: 255, alpha: 1), for: .normal) } } <file_sep>import Foundation import XCTest @testable import ScoreKeeper class HomeModelTests: XCTestCase { } <file_sep>import UIKit class OptionsViewController: UIViewController { var optionsModel: OptionsModel? @IBOutlet weak var optionsTitle: UILabel! { didSet { optionsTitle.text = ""} } override func viewDidLoad() { super.viewDidLoad() optionsTitle.text = "\(optionsModel?.gameName ?? "Game") Options" } } <file_sep>import Foundation @testable import ScoreKeeper class HomeModelMock: HomeModelProtocol { func setOptionsBy(gameName: String, for optionsViewController: OptionsViewController) { <#code#> } } <file_sep>import UIKit class MainViewController: UIViewController { var homeModel: HomeModel? override func viewDidLoad() { super.viewDidLoad() homeModel = HomeModel() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let pressedButton = sender as? UIButton, let gameName = pressedButton.currentTitle, let optionsViewController = segue.destination as? OptionsViewController, let homeModel = homeModel else { return } homeModel.setOptionsBy(gameName: gameName, for: optionsViewController) } @IBAction func gameButtonPressed(_ sender: UIButton) { performSegue(withIdentifier: "options", sender: sender) } } <file_sep>import Foundation protocol HomeModelProtocol { func setOptionsBy(gameName: String, for optionsViewController: OptionsViewController) } class HomeModel: HomeModelProtocol { func setOptionsBy(gameName: String, for optionsViewController: OptionsViewController) { optionsViewController.optionsModel = OptionsModel(gameName: gameName, scoreSelectionEnabled: gameName != GameNames.phase10) } }
498f57ee26a213a77e310ab0faf382cc715d31cd
[ "Swift" ]
8
Swift
bdlindsay/ScoreKeeper
95d57f3f4676096f020978f419685a815ed019d7
e03684001df0aa178d07199ebcd062d0a419a773
refs/heads/master
<repo_name>cis197/inclass-server-demo<file_sep>/index.js const express = require('express') const app = express() const path = require('path') const cors = require('cors') var bodyParser = require('body-parser') app.use(bodyParser.json()) let messages = [] app.use(cors()) app.get('/', (req,res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')) }) app.post('/newmessage', (req,res,next) => { const {message} = req.body; messages.push(message) res.sendStatus(200) }) app.get('/messages', (req,res,next) => { res.json(messages) }) app.get('/clear', (req,res,next) => { messages = [] res.sendStatus(200) }) const PORT = 3000 app.listen(PORT, () => { console.log('listening!') })
ea1a937e08dad33ac3b6b2d9d3b492d5a9d230a8
[ "JavaScript" ]
1
JavaScript
cis197/inclass-server-demo
2b1a4f8b29f0768a9498bee0f95ed5c238f48940
45f42aad27e30e0cc0090278d542ea1c70c23b24
refs/heads/master
<file_sep><?php include_once "includes/header.php"; ?> <section id="intro" class=" hidden-xs home-video text-light"> <div class="home-video-wrapper"> <div class="homevideo-container"> <div id="P1" class="bg-player" style="display:block; margin: auto; background: rgba(0,0,0,0.5)" data-property="{videoURL:'https://www.youtube.com/watch?v=kVXlGt_Q4uE&feature=youtu.be',containment:'.homevideo-container', quality: 'hd720', showControls: false, autoPlay:true, mute:true, startAt:0, opacity:1}"> </div> </div> <div class="overlay"> <div class="text-center video-caption"> <div class="wow bounceInDown" data-wow-offset="0" data-wow-delay="0.8s"> <h1 style="margin: 0 0 30px;font-family: 'Patua One', cursive; font-size: 30px; font-weight: 40; color: #fff;" class="big-heading font-light"> <span id="js-rotating">Pretende Construir ?</span> <br>projetamos a sua casa do seu jeito ! </h1> </div> </div> </div> </div> </section> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h1 class="tag-home"> O contínuo crescimento da empresa é uma consequência direta de sua <strong>dedicação e filosofia de trabalho</strong>, realizando constantemente reformas de casas, salões comerciais, sobrados e outros tipos de construções.</h1> <hr /> </div> </div> </div> <!-- MENU SECTION END--> <div id="slideshow-sec"> <div id="carousel-div" class="carousel slide" data-ride="carousel" > <div class="carousel-inner"> <div class="item active"> <img src="assets/img/2.jpg" alt="" /> <div class="carousel-caption"> <h1 class="wow slideInLeft" data-wow-duration="2s" > Projetos</h1> <h2 class="wow slideInRight" data-wow-duration="2s" >Desenvolvimento 3D</h2> </div> </div> <div class="item"> <img src="assets/img/g1.jpg" alt="" /> <div class="carousel-caption"> <h1 class="wow slideInLeft" data-wow-duration="2s" >Regularização</h1> <h2 class="wow slideInRight" data-wow-duration="2s" >AVCB/CLCB</h2> g </div> </div> <div class="item"> <img src="assets/img/3.jpg" alt="" /> <div class="carousel-caption"> <h1 class="wow slideInLeft" data-wow-duration="2s" >Reformas</h1> <h2 class="wow slideInRight" data-wow-duration="2s" >Pinturas</h2> </div> </div> </div> <!--INDICATORS--> <ol class="carousel-indicators"> <li data-target="#carousel-div" data-slide-to="0" class="active"></li> <li data-target="#carousel-div" data-slide-to="1"></li> <li data-target="#carousel-div" data-slide-to="2"></li> </ol> <!--PREVIUS-NEXT BUTTONS--> <a class="left carousel-control" href="#carousel-div" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-div" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> <!-- BELOW SLIDESHOW SECTION END--> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h1 class="tag-home"> A Engenharia Gilles oferece diversos serviços, sempre visando minimizar custos das obras, e anulando os conflitos de execução evitando disperdicios de material e tempo.</h1> <hr /> </div> </div> </div> <!-- TAG HOME SECTION END--> <!-- SLIDESHOW SECTION END--> <div class="below-slideshow"> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="txt-block"> <i class="fa fa-building fa-4x"></i> <h4>Projetos</h4> <p > Plano geral da Construção, reunindo plantas, cortes, elevações, detalhamento de instalações hidráulicas e elétricas, previsão de paisagismo e acabamentos. </p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="txt-block"> <i class="fa fa-city fa-4x"></i> <h4>Pinturas</h4> <p > Um projeto de pintura é um projeto complementar que acontece no acabamento da obra, cujo foco é o finalização e detalhamento do projeto (paredes, ferragens, madeiras). </p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="txt-block"> <i class="fab fa-codepen fa-4x"></i> <h4>Maquetes Eletrônica 3D</h4> <p > Uma representação visual em 3 dimensões de um projeto de arquitetura por meio de softwares que dão uma noção visual muito próxima da realidade, com volume e profundidade. </p> </div> </div> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="txt-block"> <i class="fa fa-fire-extinguisher fa-4x"></i> <h4>Projeto Preventivo</h4> <p > O projeto contém soluções adequadas para cada ocupação dos espaços do prédio, assim conferindo uma distribuição e dimensionamento de modo a proteger em caso de incêndios. </p> </div> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="txt-block"> <i class="fa fa-clipboard fa-4x"></i> <h4>Regularização AVCB/CLCB</h4> <p > Documento emitido pelo Corpo de Bombeiros da Policia Militar do Estado de São Paulo (CBPMESP) certificando vistoria a edificação de condições em segurança contra incêndio. </p> </div> </div> </div> </div> </div> <!-- BELOW SLIDESHOW SECTION END--> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h1 class="tag-home">Contamos com uma equipe de <strong>pintura profissional</strong> com o que há de novo no mercado, alinhada com o cliente para tornar o projeto completamente personalizado e único do início ao acabamento.</h1> <hr /> </div> </div> </div> <!-- TAG HOME SECTION END--> <div class="container"> <div class="row Design"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="just-txt-div"> <h2>Design e econômia</h2> <br /> <p> Projetos com <strong>qualidade de forma econômica</strong>. <br> Monte seu próprio projeto, ajudaremos a montar sua casa<br> e planejar toda a gestão. </p> <p> Agende seu atendimento<br><br> <strong>email: </strong><EMAIL><br> <strong>whatsApp:</strong>(16) 99240-9076 </p> <p> <strong>Engenharia Gilles</strong> tem o melhor preço para sua obra, entrega rápida, atendendo em toda região do estado de Sao Paulo. </p> </div> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"><br> <div class="form"> <h2>Entre em contato</h2><br> <form action="processa.php" method="post" > <div class="form-group"> <input type="text" name="assunto" class="form-control" placeholder="Digite um assunto"> </div><br> <div class="form-group"> <input type="text" name="nome" class="form-control" placeholder="Digite seu nome"> </div><br> <div class="form-group"> <input type="text" name="email" class="form-control" placeholder="Digite seu email"> </div><br> <div class="form-group"> <input type="text" name="telefone" class="form-control" placeholder="Digite seu telefone"> </div> <input type="submit" value="Enviar" class="btn btn-success"> </form> </div> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3 text-center "> <div class="heading-section"> <h2>Parcerias</h2> </div> </div> </div> <div class="row"> <div class="col-md-12 col-xs-12 text-center"> <img class="img-responsive" src="assets/img/img-1.jpg" alt="Parcerias"> </div> </div> </div> <!-- Rodapé /// Footer /// --> <?php include_once "includes/footer.php"; ?> <!-- <EMAIL> senha: 1981entrar --><file_sep><?php include_once ('includes/header.php'); ?> <link href="assets/css/style_servico.css" rel="stylesheet" /> <section> <div class="container container-services"> <div class=" row"> <div class="margin_top"> <div class="col-lg-4 "> <h1 class="align_center">Projetos</h1> <div class="div-img"> <img src="assets/img/projeto1.png" class="img-responsive" alt="projetos"> </div> </div> <div class="col-lg-7"> <div class="img-font"> <p class="special">A Engenharia Gilles tem projeto para ideal para você, com ferramentas o processo do qual a ideia/sonho do cliente pode ser concretizada. Seguindo um conjunto de passos normativos voltados para o planejamento formal de uma edificação, regulamentado por normas técnicas e por um código de obras, o projeto civil é essencial para que a obra siga o que foi planejado. Definindo o Projeto com a materialização da idéia, do espaço imaginado, é a representação da concepção projetual.<br><br> Calculando cada material no processo pelo qual a obra foi concebida para ter o máximo de aproveitamento dos recursos e ecônomia na representação final da construção. Venha fazer um projeto conosco, ou conhecer nossos projetos já prontos.</p> </div> </div> </div> </div> <hr> <div class="row"> <div class="margin_top"> <div class="col-lg-7"> <h1 class="align_center">Pinturas</h1> <div class="img-font"> <p>Para oferecer um atendimento ainda mais especializado a engenharia Gilles oferece aos seus clientes o serviço de pintura em todo tipo de projeto. Assim, os clientes tem a oportunidade de tirar todas as suas dúvidas a respeito de qual cor escolher para decorar cada um dos cantos de sua casa, escritório ou qualquer outro tipo de imóvel.</p> <p>A Engenharia Gilles também oferece este atendimento para reformas e restauração para topo tipo de imóvel.</p> </div> </div> <div class="col-lg-4 "> <div class="div-img"> <img src="assets/img/f8.jpg" class="img-responsive" alt="pinturas"> </div> </div> </div> </div> <hr> <div class="row"> <div class="margin_top"> <div class="col-lg-4 "> <h1 class="align_center">Maquetes</h1> <div class="div-img"> <img src="assets/img/maquete1.jpg" class="img-responsive" alt="maquetes"> </div> </div> <div class="col-lg-7"> <div class="img-font"> <p class="special">Construir o modelo 3D da obra simplifica os processo de andamento gerando da imagem uma animação final / filme da maquete.<br><br>Para que você otenha requinte e a sofisticação inerentes na sua vida refletidos em sua residência de alto padrão, com o conforto de não ter de se preocupar com o acompanhamento da obra, mantendo seu bom gosto e estilo. </p> </div> </div> </div> </div> <hr> <div class="row"> <div class="margin_top"> <div class="col-lg-7"> <h1 class="align_center">Projeto Preventivo</h1> <div class="img-font"> <p>O Projeto de Prevenção e Combate ao Incêndio é um desenho técnico elaborado por um engenheiro especializado na área de combate a incêndio, que calcula todo o sistema de segurança do imóvel, bem como os instrumentos a serem utilizados para sua proteção em casos de incêndio, sendo sua elaboração elemento essencial à obtenção do AVCB, CLCB ou Licença do Corpo de Bombeiros em São Paulo. </p> <p>Projeto respeitando as Normas de Segurança Contra Incêndio, para obras novas e adequação para edificações existentes.</p> </div> </div> <div class="col-lg-4 "> <div class="div-img"> <img src="assets/img/preventivo1.jpg" class="img-responsive" alt="projeto preventivo"> </div> </div> </div> </div> <hr> <div class="row"> <div class="margin_top"> <div class="col-lg-4 "> <h1 class="align_center">Regularizações</h1> <div class="div-img"> <img src="assets/img/regularizacao1.png" class="img-responsive" alt="Regularização"> </div> </div> <div class="col-lg-7"> <div class="img-font"> <p class="special">O Auto de Vistoria do Corpo de Bombeiros (AVCB) ou o Certificado de Licença do Corpo de Bombeiros CLCB, é um laudo utilizado para comprovar a consolidação e segurança dos edifícios em casos de incêndio, adquirido após certificação de projeto e vistoria realizada pelo Corpo de Bombeiros do Estado de São Paulo. <br><br> Qual é o objetivo do AVCB, CLCB - SP? <br><br> Adquirir o Laudo Auto de Vistoria do Corpo de Bombeiros (AVCB) ou o Certificado de Licença do Corpo de Bombeiros CLCB, é imprescindível à regularização de qualquer tipo de empresa com sede física, sendo o meio pelo qual o Corpo de Bombeiros atesta aos órgãos públicos estatais e municipais a segurança do imóvel, e permite assim, a circulação regular de pessoas e bens dentro das edificações.</p> </div> </div> </div> </div> <hr> </div> </section> <?php include_once ('includes/footer.php'); ?><file_sep> // Menu Mobile////////////////////////////////////////////////////////////////////// // Abrir menu mobile document.getElementById("hamburguer-icon").onclick = function(){ document.getElementById("sliding-header-menu-outer").style.right = "0"; }; // Fechando Menu Mobile document.getElementById("sliding-header-menu-close-button").onclick = function(){ document.getElementById("sliding-header-menu-outer").style.right = "-320px"; }; /* Efeito deslizante .sliding-header-menu_outer{ right:-320px width:320px; overflow:hidden; position: fixed; transition: right 300ms ease-out; } */ ////////////////////////////////////////////////////////// Missão , Visão , Valores ///////////////////////////// // About us Tab var aboutUs = { "Missão": "Fazer com que cada cliente seja reconhecido como autoridade em seu segmento de atuação. Agregar valor ao negócio, potencializar o crescimento das operações e promover e estreitar o relacionamento do cliente com o seu público alvo, por meio da geração de conteúdo de relevância.", "Visão": "Ser reconhecida pelos clientes e pelo mercado como uma empresa parceira, inovadora e criativa, que oferece sempre os melhores produtos e soluções em Comunicação Empresarial Integrada.", "Valores": "<ul><li>Comprometimento</li><li>Inovação</li><li>Ética profissional</li><li>Superação dos resultados</li><li>Melhoria contínua</li></ul>" }; // variaveis de cores var unselected_color = "#646872"; var selected_color = "#2A2D34"; var about_tags = document.getElementsByClassName("single-tab"); // varre cada variavel para colocar os atributos for(var a = 0; a < about_tags.length; a++){ about_tags[a].onclick = function (){ // fazendo um loop para percorrer os elementos e tirar as cores de todos os eles for (var b = 0; b < about_tags.length; b++){ about_tags[b].style['background-color'] = unselected_color; about_tags[b].style['font-weight'] = "normal"; } // dando o efeito no objeto onde está clicando this.style['background-color'] = selected_color; this.style['font-weight'] = "bold"; // Pegando os textos para a caixa box aboutUs // var selecionado = this.innerHTML; document.getElementById("box-text").innerHTML = aboutUs[selecionado]; }; } // Finalizendo o box aboutUs // ///////////////////// Inicio Slider de serviços //////////////////////////////// var our_services = [ { 'title': 'Webdesign', 'text': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent finibus tincidunt sem non sodales. Nunc et quam in magna vehicula sollicitudin. Aliquam erat volutpat. Maecenas dolor mi, aliquet ac quam aliquet, condimentum dictum nisi.' }, { 'title': 'Branding', 'text': 'Praesent finibus tincidunt sem non sodales. Nunc et quam in magna vehicula sollicitudin. Aliquam erat volutpat. Maecenas dolor mi, aliquet ac quam aliquet, condimentum dictum nisi.' }, { 'title': 'Marketing Digital', 'text': 'Nunc et quam in magna vehicula sollicitudin. Aliquam erat volutpat. Maecenas dolor mi, aliquet ac quam aliquet, condimentum dictum nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent finibus.' } ]; // id = service_previous (seta de voltar) // id = service_next ( seta de prosseguir) // id = service-title ( titulo ) // id = service-text ( texto ) var servico_atual = 0; // seta de voltar document.getElementById("service-previous").onclick = function(){ if(servico_atual == 0) { var servico_anterior = our_services.length - 1; } else { var servico_anterior = servico_atual - 1; } document.getElementById("service-title").innerHTML = our_services[servico_anterior].title; document.getElementById("service-text").innerHTML = our_services[servico_anterior].text; servico_atual = servico_anterior; }; ////////////////////////// fim seta voltar ///////////////////////////// // seta proximo document.getElementById("service-next").onclick = function(){ if(servico_atual == our_services.length - 1) { var servico_seguinte = 0; } else { var servico_seguinte = servico_atual + 1; } document.getElementById("service-title").innerHTML = our_services[servico_seguinte].title; document.getElementById("service-text").innerHTML = our_services[servico_seguinte].text; servico_atual = servico_seguinte; }; // Data Footer ( colocando data automático ) var ano_atual = new Date; ano_atual = ano_atual.getFullYear(); //console.log(ano_atual) document.getElementById("current_year").innerHTML = ano_atual; // Finalizar Data Footer // id = map // API Key Google : <KEY> <file_sep><?php include_once ('includes/header.php'); ?> <link href="assets/css/style_contato.css" rel="stylesheet" /> <style> .bgimg-1 { background-image: url(assets/img/contato1.jpg); min-height: 400px; background-repeat: no-repeat; width: 100%; } .bgimg-2 { background-image: url(assets/img/contato2.png); min-height: 400px; width: 100%; background-repeat: no-repeat; } .caption { position: absolute; left: 0; top: 50%; width: 100%; text-align: center; color: #000; } </style> <div class="container"> <div class="bgimg-1 hidden-xs col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="caption"> <span class="border">Converse conosco</span> </div> </div> <hr> <div class="row row1"> <div class="col-sm-6"> <h1 class="tag-contact">Nossos Contatos</h1> <ul class="contact-info"> <li><i class="fas fa-phone"></i> (16) 3343 - 4921</li> <li><i class="fas fa-mobile-alt"></i> (16) 99240 - 9076</li> <li><i class="far fa-envelope"></i> <EMAIL></li> </ul> </div> <div class="col-sm-6"> <h1 class="tag-contact"> Aqui você contrata os serviços necessários para construir o projeto dos seus sonhos. Ah, e se preferir alterar uma planta ou fazer um projeto novo, nós fazemos!! <br> Solicite um orçamento com o nosso engenheiro. </h1> </div> </div> <hr> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><br> <div class="form"> <h2 style="text-align: center;">Entre em contato</h2><br> <form action="processa.php" method="post"> <div class="form-group"> <input type="text" name="mensagem" class="form-control" placeholder="Digite um assunto"> </div><br> <div class="form-group"> <input type="text" name="nome" class="form-control" placeholder="Digite seu nome"> </div><br> <div class="form-group"> <input type="text" name="email" class="form-control" placeholder="Digite seu email"> </div><br> <div class="form-group"> <input type="text" name="telefone" class="form-control" placeholder="Digite seu telefone"> </div> <input type="submit" value="Enviar" class="btn btn-success"> </form> </div> </div> <div class="bgimg-2 hidden-xs col-lg-12 col-md-12 col-sm-12 col-xs-12"> </div> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h1 class="tag-home">Somos um escritório de engenharia online, voltado <strong>exclusivamente para a venda de projetos e construções.</strong> Nossos projetos são elaborados por engenheiros projetistas qualificados, satisfazendo os mais diversos perfis de clientes com um modelo de negócio versátil e inovador.</h1> <hr /> </div> </div> </div> <?php include_once ('includes/footer.php'); ?> <file_sep><?php include_once('includes/header.php'); ?> <link href="assets/css/style_sobre.css" rel="stylesheet" /> <style> .bgimg-1 { background-image: url(assets/img/const2.jpg); min-height: 400px; background-repeat: no-repeat; } .bgimg-2 { background-image: url(assets/img/const3.jpg); min-height: 400px; width: 100%; background-repeat: no-repeat; } .caption { position: absolute; left: 0; top: 50%; width: 100%; text-align: center; color: #000; } h4 { font-size: 1.5em; color: green; } @media only screen and (min-width:0px) and (max-width:480px) { h2 { font-size: 1.2em; font-weight: 600; } } </style> <hr/> <div class="container"> <div class="bgimg-1 col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="caption"> <span class="border">Como surgiu a empresa</span> </div> </div> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <h1 class="tag-about"> Como já faz sucesso em países com Estados Unidos e Canadá, surgiu a necessidade de viabilizarmos plantas de casas e projetos feitos por profissionais competentes e de bom gosto a preços muitos mais acessíveis que um escritório de engenharia convencional. Tendo, assim como objetivo a satisfação plena de nossos clientes, através da excelência no atendimento e acompanhamento técnico necessário. Com isso, apresentamos um escritório virtual que contém uma grande variedade de projetos de plantas já prontos, mas com a escolha de modificá-los ou criar um modelo sob-medida, além de projetos complementares e de reformas interiores/exteriores. Para saber mais entre em contato conosco, para conhecer mais projetos finalizados e também em andamento. </h1> <hr/> </div> </div> <div class="col-lg-12 col-md-12 col-sm-6 col-xs-6 hidden-xs img-tablet"> <div class="bgimg-2"></div> </div> <div class="container"> <!-- Trigger the modal with a button --> <button type="button" class=" text-center btn btn-info btn-lg button-mobile button-tablet button-modal" data-toggle="modal" data-target="#myModal">Entre em contato</button> <!-- Modal --> <div class="modal fade" id="myModal" style="padding-right: 20em;" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title text-center">Preencha os campos abaixo</h4> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="margin-left: 5em;"><br> <div class="form"> <h2>Entre em contato</h2><br> <form action="processa.php" method="post"> <div class="form-group"> <input type="text" name="mensagem" class="form-control" placeholder="Digite um assunto"> </div><br> <div class="form-group"> <input type="text" name="nome" class="form-control" placeholder="Digite seu nome"> </div><br> <div class="form-group"> <input type="text" name="email" class="form-control" placeholder="Digite seu email"> </div><br> <div class="form-group"> <input type="text" name="telefone" class="form-control" placeholder="Digite seu telefone"> </div> <input type="submit" value="Enviar" class="btn btn-success"> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button> </div> </div> </div> </div> </div> </div> <?php include_once ('includes/footer.php'); ?>
e75e2c5728b443f15079d88c11f15f8d6d057ab7
[ "JavaScript", "PHP" ]
5
PHP
FernandoRodriguesDaSilva/gilles
0d9b3c9e362665bb19b6c163c52611db4becf84e
0650a57b5d52f6e416d7b7decf20ef8521ce1f68
refs/heads/master
<file_sep><?php class TaskOneController extends BaseController { private function getPosts() { $posts = [ [ 'title' => 'Article 1', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 2', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 3', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 4', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 5', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 6', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 7', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 8', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 9', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], [ 'title' => 'Article 10', 'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ], ]; return $posts; } public function showRoot() { return Redirect::action('TaskOneController@showHome'); } public function showHome() { $urls = [ 'Articles' => URL::route('atricles'), 'About' => URL::route('about'), 'Contact-us' => URL::route('contact-us') ]; return View::make('home', ['urls' => $urls]); } public function showAtricles() { return View::make('atricles', ['posts' => $this->getPosts()]); } public function showPost($post) { forEach($this->getPosts() as $key => $item) { if($post == $key) { return View::make('post', ['post' => $item]); } } return Redirect::action('TaskOneController@showNotFound'); } public function showNotFound() { return View::make('notFound'); } public function showAbout() { return View::make('about'); } public function showContactUs($error = null) { return View::make('contact-us', ['error' => $error]); } public function showThankYou() { $name = Input::old('name'); return View::make('thank-you', ['name' => $name]); } public function submitForm() { if(Input::has('name') && Input::has('text')) { return Redirect::action('TaskOneController@showThankYou')->withInput(); } else { return $this->showContactUs(true); } } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', array('as' => 'root', 'uses' => 'TaskOneController@showRoot')); Route::get('/home', 'TaskOneController@showHome'); Route::get('/atricles', array('as' => 'atricles', 'uses' => 'TaskOneController@showAtricles')); Route::get('/atricles/{post}', array('as' => 'post', 'uses' => 'TaskOneController@showPost')); Route::get('/notFound', array('as' => 'notFound', 'uses' => 'TaskOneController@showNotFound')); Route::get('/about', array('as' => 'about', 'uses' => 'TaskOneController@showAbout')); Route::get('/contact-us', array('as' => 'contact-us', 'uses' => 'TaskOneController@showContactUs')); Route::get('/thank-you', array('as' => 'thank-you ', 'uses' => 'TaskOneController@showThankYou')); Route::post('/submit-form', array('as' => 'submit-form ', 'uses' => 'TaskOneController@submitForm'));
e9d92d75c26fd4f29e97a65c1bd8b8b9d7180156
[ "PHP" ]
2
PHP
SeeNelse/laravel_gfl
4f3bbc77052a48c3bb763361d9b097bd8a4c2811
ee645128ba33a04d02ab476873b94e29f249e325
refs/heads/master
<file_sep> https://www.freecodecamp.org/news/https-medium-freecodecamp-org-best-free-open-data-sources-anyone-can-use-a65b514b0f2d/ https://data.worldbank.org/ http://datatopics.worldbank.org/consumption/country/Afghanistan https://www.google.com/publicdata/directory https://www.data.gov/ https://www.kaggle.com/datasets https://towardsdatascience.com/top-10-great-sites-with-free-data-sets-581ac8f6334 (!!) https://crime-data-explorer.fr.cloud.gov/downloads-and-docs by <NAME> What is Open Data? In simple terms, Open Data means the kind of data which is open for anyone and everyone for access, modification, reuse, and sharing. Open Data derives its base from various “open movements” such as open source, open hardware, open government, open science etc. Governments, independent organizations, and agencies have come forward to open the floodgates of data to create more and more open data for free and easy access. Why Is Open Data Important? Open data is important because the world has grown increasingly data-driven. But if there are restrictions on the access and use of data, the idea of data-driven business and governance will not be materialized. Therefore, open data has its own unique place. It can allow a fuller understanding of the global problems and universal issues. It can give a big boost to businesses. It can be a great impetus for machine learning. It can help fight global problems such as disease or crime or famine. Open data can empower citizens and hence can strengthen democracy. It can streamline the processes and systems that the society and governments have built. It can help transform the way we understand and engage with the world. So here’s my list of 15 awesome Open Data sources: 1. World Bank Open Data As a repository of the world’s most comprehensive data regarding what’s happening in different countries across the world, World Bank Open Data is a vital source of Open Data. It also provides access to other datasets as well which are mentioned in the data catalog. World Bank Open Data is massive because it has got 3000 datasets and 14000 indicators encompassing microdata, time series statistics, and geospatial data. Accessing and discovering the data you want is also quite easy. All you need to do is to specify the indicator names, countries or topics and it will open up the treasure-house of Open Data for you. It also allows you to download data in different formats such as CSV, Excel, and XML. If you are a journalist or academic, you will be enthralled by the array of tools available to you. You can get access to analysis and visualization tools that can bolster your research. It can felicitate a deeper and better understanding of global problems. You can get access to the API which can help you create the data visualizations you need, live combinations with other data sources and many more such features. Therefore, it’s no surprise that World Bank Open Data tops any list of Open Data sources! 2. WHO (World Health Organization) — Open data repository WHO’s Open Data repository is how WHO keeps track of health-specific statistics of its 194 Member States. The repository keeps the data systematically organized. It can be accessed as per different needs. For instance, whether it is mortality or burden of diseases, one can access data classified under 100 or more categories such as the Millennium Development Goals (child nutrition, child health, maternal and reproductive health, immunization, HIV/AIDS, tuberculosis, malaria, neglected diseases, water and sanitation), non communicable diseases and risk factors, epidemic-prone diseases, health systems, environmental health, violence and injuries, equity etc. For your specific needs, you can go through the datasets according to themes, category, indicator, and country. The good thing is that it is possible to download whatever data you need in Excel Format. You can also monitor and analyze data by making use of its data portal. The API to the World Health Organization’s data and statistics content is also available. 3. Google Public Data Explorer Launched in 2010, Google Public Data Explorer can help you explore vast amounts of public-interest datasets. You can visualize and communicate the data for your respective uses. It makes the data from different agencies and sources available. For instance, you can access data from World Bank, U. S. Bureau of Labor Statistics and U.S. Bureau, OECD, IMF, and others. Different stakeholders access this data for a variety of purposes. Whether you are a student or a journalist, whether you are a policy maker or an academic, you can leverage this tool in order to create visualizations of public data. You can deploy various ways of representing the data such as line graphs, bar graphs, maps and bubble charts with the help of Data Explorer. The best part is that you would find these visualizations quite dynamic. It means that you will see them change over time. You can change topics, focus on different entries and modify the scale. It is easily shareable too. As soon as you get the chart ready, you can embed it on your website or blog or simply share a link with your friends. 4. Registry of Open Data on AWS (RODA) This is a repository containing public datasets. It is data which is available from AWS resources. As far as RODA is concerned, you can discover and share the data which is publicly available. In RODA, you can use keywords and tags for common types of data such as genomic, satellite imagery and transportation in order to search whatever data that you are looking for. All of this is possible on a simple web interface. For every dataset, you will discover detail page, usage examples, license information and tutorials or applications that use this data. By making use of a broad range of compute and data analytics products, you can analyze the open data and build whatever services you want. While the data you access is available through AWS resources, you need to bear in mind that it is not provided by AWS. This data belongs to different agencies, government organizations, researchers, businesses and individuals. 5. European Union Open Data Portal You can access whatever open data EU institutions, agencies and other organizations publish on a single platform namely European Union Open Data Portal. The EU Open Data Portal is home to vital open data pertaining to EU policy domains. These policy domains include economy, employment, science, environment, and education. Around 70 EU institutions, organizations or departments such as Eurostat, the European Environment Agency, the Joint Research Centre and other European Commission Directorates General and EU Agencies have made their datasets public and allowed access. These datasets have crossed the number of 11700 till date. The portal enables easy access. You can easily search, explore, link, download and reuse the data through a catalog of common metadata. You can do so for your specific purposes. It could be commercial or non-commercial purposes. You can search the metadata catalog through an interactive search engine (Data tab) and SPARQL queries (Linked data tab). By making use of this catalog, you can gain access to the data stored on the different websites of the EU institutions, agencies and organizations. 6. FiveThirtyEight It is a great site for data-driven journalism and story-telling. It provides its various sources of data for a variety of sectors such as politics, sports, science, economics etc. You can download the data as well. When you access the data, you will come across a brief explanation regarding each dataset with respect to its source. You will also get to know what it stands for and how to use it. In order to render this data user-friendly, it provides datasets in as simple, non-proprietary formats such as CSV files as possible. Needless to say, these formats can be easily accessed and processed by humans as well as machines. With the help of these datasets, you can create stories and visualizations as per your own requirements and preference. 7. U.S. Census Bureau U.S. Census Bureau is the biggest statistical agency of the federal government. It stores and provides reliable facts and data regarding people, places, and economy of America. The Census Bureau considers its noble mission to extend its services as the most reliable provider of quality data. Whether it is a federal, state, local or tribal government, all of them make use of census data for a variety of purposes. These governments use this data to determine the location of new housing and public facilities. They also make use of it at the time of examining the demographic characteristics of communities, states, and the USA. This data is also made use of in planning of transportation systems and roadways. When it comes to deciding quotas and creating police and fire precincts, this data comes in handy. When governments create localized areas of elections, schools, utilities etc, they make use of this data. It is a practice to compile population information once a decade and this data are quite useful in accomplishing the same. There are various tools such as American Fact Finder, Census Data Explorer and Quick Facts which are useful in case you want to search, customize and visualize data. For instance, Quick Facts alone contains statistics for all the states, counties, cities and even towns with a population of 5000 or more. Likewise, American Fact Finder can help you discover popular facts such as population, income etc. It provides information that is frequently requested. The good thing is that you can search, interact with the data, get to know about popular statistics and see the related charts through Census Data Explorer. Moreover, you can also use visual tool to customize data on an interactive maps experience. 8. Data.gov Data.gov is the treasure-house of US government’s open data. It was only recently that the decision was made to make all government data available for free. When it was launched, there were only 47. There are now 180,000 datasets. Why Data.gov is a great resource is because you can find data, tools, and resources that you can deploy for a variety of purposes. You can conduct your research, develop your web and mobile applications and even design data visualizations. All you need to do is enter keywords in the search box and browse through types, tags, formats, groups, organization types, organizations, and categories. This will facilitate easy access to data or datasets that you need. Data.gov follows the Project Open Data Schema — a set of requisite fields (Title, Description, Tags, Last Update, Publisher, Contact Name, etc.) for every data set displayed on Data.gov. 9. DBpedia As you know, Wikipedia is a great source of information. DBpedia aims at getting structured content from the valuable information that Wikipedia created. With DBpedia, you can semantically search and explore relationships and properties of Wikipedia resource. This includes links to other related datasets as well. There are around 4.58 million entities in the DBpedia dataset. 4.22 million are classified in ontology, including 1,445,000 persons, 735,000 places, 123,000 music albums, 87,000 films, 19,000 video games, 241,000 organizations, 251,000 species and 6,000 diseases. There are labels and abstracts for these entities in around 125 languages. There are 25.2 million links to images. There are 29.8 million links to external web pages. All you need to do in order to use DBpedia is write SPARQL queries against endpoint or by downloading their dumps. DBpedia has benefitted several enterprises, such as Apple (via Siri), Google (via Freebase and Google Knowledge Graph), and IBM (via Watson), and particularly their respective prestigious projects associated with artificial intelligence. 10. freeCodeCamp Open Data It is an open source community. Why it matters is because it enables you to code, build pro bono projects after nonprofits and grab a job as a developer. In order to make this happen, the freeCodeCamp.org community makes available enormous amounts of data every month. They have turned it into open data. You will find a variety of things in this repository. You can find datasets, analysis of the same and even demos of projects based on the freeCodeCamp data. You can also find links to external projects involving the freeCodeCamp data. It can help you with a diversity of projects and tasks that you may have in mind. Whether it is web analytics, social media analytics, social network analysis, education analysis, data visualization, data-driven web development or bots, the data offered by this community can extremely useful and effective. 11. Yelp Open Datasets The Yelp dataset is basically a subset of nothing but our own businesses, reviews and user data for use in personal, educational and academic pursuits. There are 5,996,996 reviews, 188,593 businesses, 280,991 pictures and 10 metropolitan areas included in Yelp Open Datasets. You can use them for different purposes. Since they are available as JSON files, you can use them in order to teach students about databases. You can use them to learn NLP or for sample production data while you understand how to design mobile apps. In this dataset, you will find each file composed of a single object type, one JSON-object per-line. 12. UNICEF Dataset Since UNICEF concerns itself with a wide variety of critical issues, it has compiled relevant data on education, child labor, child disability, child mortality, maternal mortality, water and sanitation, low birth-weight, antenatal care, pneumonia, malaria, iodine deficiency disorder, female genital mutilation/cutting, and adolescents. UNICEF’s open datasets published on the IATI Registry: http://www.iatiregistry.org/publisher/unicef has been extracted directly from UNICEF’s operating system (VISION) and other data systems, and it reflects inputs made by individual UNICEF offices. The good thing is that there is a regular update when it comes to these datasets. Every month, the data is updated in order to make it more comprehensive, reliable and accurate. You can freely and easily access this data. In order to do so, you can download this data in CSV format. You can also preview sample data prior to downloading it. While anybody can explore and visualize UNICEF’s datasets, there are three principal publishers: UNICEF’s AID TRANSPARENCY PORTAL : You can far more easily access the datasets if you use this portal. It also includes details for each country that UNICEF works in. Publisher d-portal : It is, at the moment, in BETA. With this, portal, you can explore IATI data. You can search the information related to development activities, budgets etc. You can explore this information country-wise. Publisher’s data platform : On this platform, you can easily access statistics, charts, and metrics on data accessed via the IATI Registry. If you click on the headers, you can also sort many of the tables that you see on the platform. You will also find many of the datasets in the platforms in machine-readable JSON format. 13. Kaggle Kaggle is great because it promotes the use of different dataset publication formats. However, the better part is that it strongly recommends that the dataset publishers share their data in an accessible, non-proprietary format. The platform supports open and accessible data formats. It is important not just for access but also for whatever you want to do with this data. Therefore, Kaggle Dataset clearly defines the file formats which are recommended while sharing data. The unique thing about Kaggle datasets is that it is not just a data repository. Each dataset stands for a community that enables you to discuss data, find out public codes and techniques, and conceptualize your own projects in Kernels. CSV, JSON, SQLite, Archive, Big Query etc. are files types that Kaggle supports. You can find a variety of resources in order to start working on your open data project. The best part is that Kaggle allows you to publish and share datasets privately or publicly. 14. LODUM It is the Open Data initiative of the University of Münster. Under this initiative, it is made possible for anyone to access any public information about the university in machine-readable formats. You can easily access and reuse it as per your needs. Open data about scientific artifacts and encoded as linked data is made available under this project. With the help of Linked Data, it is possible to share and use data, ontologies and various metadata standards. It is, in fact, envisaged that it will be the accepted standard for providing metadata, and the data itself on the Web. The LODUM team has co-initiated LinkedUniversities.org and LinkedScience.org. You can use SPARQL editor or SPARQL package of R to analyze data. SPARQL Package enables to connect to a SPARQL endpoint over HTTP, pose a SELECT query or an update query (LOAD, INSERT, DELETE). 15. UCI Machine Learning Repository It serves as a comprehensive repository of databases, domain theories, and data generators that are used by the machine learning community for the empirical analysis of machine learning algorithms. In this repository, there are, at present, 463 datasets as a service to the machine learning community. The Center for Machine Learning and Intelligent Systems at the University of California, Irvine hosts and maintains it. <NAME> had originally created it as a graduate student at UC Irvine. Since then, students, educators, and researchers all over the world make use of it as a reliable source of machine learning datasets. How it works is that each dataset has its distinct webpage which enlists all the known details including any relevant publications that investigate it. You can download these datasets as ASCII files, often the useful CSV format. The details of datasets are summarized by aspects like attribute types, number of instances, number of attributes and year published that can be sorted and searched. Open Data Portals and Search Engines: While there are plenty of datasets published by numerous agencies every year, very few datasets become recognized and established. The reason why very few such datasets sustain as useful resource is that it is a challenge to develop, manage and provide the data in a way that people and organizations find it useful and easy to use. However, please find below a list of other few important open data portals and platforms that permit users to access open data quite easily, study the impact and glean valuable insights. Google dataset search Dataverse Open Data Kit Ckan Open Data Monitor Plenar.io Open Data Impact Map <file_sep>-- Shangde: -- Query 1: group the loan by district and calculate the total amount of loan on each date in each district SELECT SUM(LOAN.amount), LOAN.start_date FROM dmelisso.LOAN LOAN JOIN dmelisso.account ACCOUNT on ACCOUNT.account_id = LOAN.account_id JOIN dmelisso.DISTRICT_detail on DISTRICT_detail.district_id = ACCOUNT.district_id GROUP BY LOAN.start_date, DISTRICT_detail.district_id ORDER BY LOAN.start_date; -- Query 2: group the card by district and calculate the amount of card issued on each date in each district SELECT COUNT(CARD.card_id) AS number_of_cards FROM dmelisso.CARD JOIN dmelisso.DISPOSITION on DISPOSITION.disp_id = CARD.disp_id JOIN dmelisso.ACCOUNT on ACCOUNT.account_id = DISPOSITION.account_id JOIN dmelisso.DISTRICT_detail on DISTRICT_detail.district_id = ACCOUNT.district_id GROUP BY CARD.issued, DISTRICT_detail.district_id; <file_sep>import React, {Component} from 'react' import axios from 'axios'; import {Line} from 'react-chartjs-2'; export class LinechartQuery5Part5 extends Component { constructor(props) { super(props); this.state = {Data: {}}; } componentDidMount() { axios.get("api/getTransactionTrendByBalanceOfAccountHolder") .then(res => { console.log(res); const records = res.data; /* * { "trans_num": 802, "account_balance_rank": 2, "month_interval": "7-1993" } * */ let dates = []; let transNumHighBalanceAccount = []; let transNumMediumBalanceAccount = []; let transNumLowBalanceAccount = []; records.forEach(record => { dates.push(record.month_interval); if (record.account_balance_rank === 1) { transNumHighBalanceAccount.push(record.trans_num); transNumMediumBalanceAccount.push(null); transNumLowBalanceAccount.push(null); } else { if (record.account_balance_rank === 2){ transNumHighBalanceAccount.push(null); transNumMediumBalanceAccount.push(record.trans_num); transNumLowBalanceAccount.push(null); }else{ transNumHighBalanceAccount.push(null); transNumMediumBalanceAccount.push(null); transNumLowBalanceAccount.push(record.trans_num); } } }); this.setState({ Data: { labels: dates, datasets: [ { label: 'High balance account holding client transaction trend', data: transNumHighBalanceAccount, fill: false, lineTension: 0.3, backgroundColor: "rgba(225,0,0,0.4)", borderColor: "red", // The main line color borderCapStyle: 'square', borderDash: [], // try [5, 15] for instance borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "black", pointBackgroundColor: "white", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "brown", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Medium balance account holding client transaction trend', data: transNumMediumBalanceAccount, fill: false, lineTension: 0.3, backgroundColor: "rgba(167,105,0,0.4)", borderColor: "rgb(167, 105, 0)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Low balance account holding client transaction trend', data: transNumLowBalanceAccount, fill: false, lineTension: 0.3, backgroundColor: "rgba(105,167,0,0.4)", borderColor: "green", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, } ] } }); }) } render() { return ( <div> <Line data={this.state.Data} options={{maintainAspectRatio: true}}/> </div> ) } } export default LinechartQuery5Part5 <file_sep>import React, {Component} from 'react' import axios from 'axios'; import {Line} from 'react-chartjs-2'; export class LinechartQuery5Part3 extends Component { constructor(props) { super(props); this.state = {Data: {}}; } componentDidMount() { axios.get("api/getCardUsageTrendByType") .then(res => { console.log(res); const records = res.data; /* { card_type: "classic" ​​​ month_interval: "1-1993" ​​​ trans_num: 11 ​​​}, {​​​ card_type: "gold" ​​​ month_interval: "1-1993" ​​​ trans_num: 7 }, {​​​ card_type: "junior" ​​​ month_interval: "1-1993" ​​​ trans_num: 2 ​​ } * */ let dates = []; let transNumClassic = []; let transNumGold = []; let transNumJunior = []; records.forEach(record => { dates.push(record.month_interval); if (record.card_type === 'classic') { transNumClassic.push(record.trans_num); transNumGold.push(null); transNumJunior.push(null); } else { if (record.card_type === 'gold') { transNumClassic.push(null); transNumGold.push(record.trans_num); transNumJunior.push(null); } else { transNumClassic.push(null); transNumGold.push(null); transNumJunior.push(record.trans_num); } } }); this.setState({ Data: { labels: dates, datasets: [ { label: 'Classic type card holder transaction trend', data: transNumClassic, fill: false, lineTension: 0.3, backgroundColor: "rgba(225,0,0,0.4)", borderColor: "red", // The main line color borderCapStyle: 'square', borderDash: [], // try [5, 15] for instance borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "black", pointBackgroundColor: "white", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "brown", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Gold type card holder transaction trend', data: transNumGold, fill: false, lineTension: 0.3, backgroundColor: "rgba(167,105,0,0.4)", borderColor: "rgb(167, 105, 0)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Junior type card holder transaction trend', data: transNumJunior, fill: false, lineTension: 0.3, backgroundColor: "rgba(105,167,0,0.4)", borderColor: "green", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, } ] } }); }) } render() { return ( <div> <Line data={this.state.Data} options={{maintainAspectRatio: true}}/> </div> ) } } export default LinechartQuery5Part3 <file_sep>import React, {Component} from 'react' import axios from 'axios'; import {Line} from 'react-chartjs-2'; export class LinechartQuery5Part1 extends Component { constructor(props) { super(props); this.state = {Data: {}}; } componentDidMount() { axios.get("api/getTransTrendUrbanNonUrban") .then(res => { console.log(res); const records = res.data; /* * { "trans_num": 36, "urban_rank": 1, "month_interval": "1-1993" } * */ let dates = []; let transNumUrban = []; let transNumNonUrban = []; //let xAxisCounter = 0; records.forEach(record => { //xAxisCounter++; dates.push(record.month_interval); if (record.urban_rank === 1) { transNumUrban.push(record.trans_num); transNumNonUrban.push(null); } else { transNumUrban.push(null); transNumNonUrban.push(record.trans_num); } }); this.setState({ Data: { labels: dates, datasets: [ { label: 'Urban area resident client transaction trend', data: transNumUrban, fill: false, lineTension: 0.3, backgroundColor: "rgba(225,0,0,0.4)", borderColor: "red", // The main line color borderCapStyle: 'square', borderDash: [], // try [5, 15] for instance borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "black", pointBackgroundColor: "white", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "brown", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Non-Urban area resident client transaction trend', data: transNumNonUrban, fill: false, lineTension: 0.3, backgroundColor: "rgba(167,105,0,0.4)", borderColor: "rgb(167, 105, 0)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, } ] } }); }) } render() { return ( <div> <Line data={this.state.Data} options={{maintainAspectRatio: true}}/> </div> ) } } export default LinechartQuery5Part1 <file_sep> cx-Oracle pandas pymysql sqlalchemy flask flask-deprecate python-dotenv <file_sep># This file stores helpers for parsing database rows from pprint import pprint import time import json import decimal import datetime import utils conn = utils.get_connection_oracle() def fetch_data_as_json(sql, num_rows=None, debug=False): if num_rows is None: data = conn.execute(sql).fetchmany() else: data = conn.execute(sql).fetchmany(num_rows) if debug: pprint(data) return json.dumps([dict(r) for r in data], default=alchemyencoder) def fetch_data(sql, description, num_rows=None, debug=False): """ :arg sql - the query to execute :arg description - the human-friendly summary of the query """ start_time = time.time() if num_rows is None: data = conn.execute(sql).fetchall() else: data = conn.execute(sql).fetchmany(num_rows) if debug: pprint(data) elapsed = time.time() - start_time return json.dumps( { 'sql': sql, 'description': description, 'elapsed': elapsed, 'rowCount': len(data), 'rows': [dict(r) for r in data], }, default=alchemyencoder ) def alchemyencoder(obj): """JSON encoder function for SQLAlchemy special classes.""" if isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, decimal.Decimal): return float(obj) <file_sep># Professor feedback 1. I do not understand your use of the term "in time". Do you mean "over time"? This query seems to be a trend query. But I do not see the logical connection between "remaining account balances" and "getting a loan". Dimitrios, please explain. 2. I have the impression that this query has a similar structure like Query 1. Therefore, it does not qualify. 3. This is an interesting query but no trend query. You deal with absolute values here presented in a bar chart. 4. This is similar to the previous query. 5. A heat map is interesting but not a trend query in our sense. 6. I am not sure whether the answer to this query leads to a line graph since I do not see a continuous evolution. It is more a bar chart with a bar for each selected time unit. But it is a trend query. 7. This is not a trend query. 8. A histogram here shows the amount of loans for each kind of loan. But all numbers are absolute and do not show a trend in the sense of our project. You could talk about an "absolute trend" here that actually represents a ranking. 9. A pie chart does not represent a trend in the sense of our project but rather a ranking. 10. A heat map is interesting but not a trend query in our sense. # Initial queries 1. Plot the remaining account balance of the clients in time. We will project 2 lines on this graph color-coded for males and females. We will use filters to look for specific ages in this line graph. This can provide useful information to the user, since they can observe the trend of the clients’ remaining amounts, in case they ask the bank for a loan. 2. Plot the transaction amount in time. We will project 2 lines on this graph color-coded for credit transactions and withdrawals. It is important for a banker to know if their client is spending more and more money over time, or if they are trying to cut back. We can also filter the information in this line graph. 3. Plot the number of each type of card issued per year over all the available years in the data set. In this bar chart we can place filters on the years we are interested in. The importance of this graph lies within the fact that some cards are premium, and the bank might be lending more money to some clients by giving them a higher credit limit. 4. Plot the number of people of each loan status over the available years in the data set. In this bar chart we can place filters on the amount of the loan that was taken and the time period the user wants to look at. This query is useful since the user can see how many loans are active/inactive and which ones have been paid/not paid. 5. Heatmap of the inhabitants on the various districts. This could be beneficial to the bank in order to decide where its next physical store should be. 6. Plot the creation of entrepreneur accounts over time using time filters. This is a line graph that can be used by the bank to identify if in a specific amount of time it has attracted more entrepreneurs. 7. Create a bar chart of the various statement frequencies. This is useful in order for the bank to find out when its clients prefer to receive their statements. 8. Create a histogram of the amounts for each type of loan status and color-code the number of loans in each amount. We will create filters in order for the user to see only the amounts they are interested in. 9. Create a pie chart with the transaction characterization for the Transaction table, such as insurance payment, statement payment, interest credited, sanction interest if negative balance, household payment, pension and loan payment. With this graph the bank will know which payments are most common and which ones are more rare in order to adjust its fees accordingly. 10. Heatmap of the transactions. This can be very useful if the bank is considering targeting certain parts of the country with mail offers. # Discussed queries 1. Dimitrios ```sql SELECT SUM(balance) FROM TRANSACTION Client -> Disposit -> Transaction group by month gender ``` 2. not good 3. Andrei - Display two lines for credit cards ```sql SELECT TO_CHAR(issued, 'YYYY-MM'), count(*) from dmelisso.card group by TO_CHAR(issued, 'YYYY-MM') order by 1; cards -> disposition -> client -> birth - cumulative - stack overflow https://data.stackexchange.com/stackoverflow/query/81416/cumulative-sum-with-group-by - diff in number of cards added: https://stackoverflow.com/questions/15762585/mysql-query-to-get-trend-of-temperature ``` 4. Andrei - Loan -> Disposition -> Client.birth_number ```sql SELECT L.STATUS , TO_CHAR(START_DATE, 'YYYY-MM') AS theMonth , COUNT(*) FROM dmelisso.LOAN L JOIN dmelisso.DISPOSITION D ON D.account_id = L.account_id JOIN dmelisso.CLIENT c ON c.client_id = d.client_id WHERE TO_DATE('1999-01-01', 'YYYY-MM-DD') - BIRTH_NUMBER > 40 -- this needs to be fixed GROUP BY L.STATUS , TO_CHAR(START_DATE, 'YYYY-MM') ORDER BY L.STATUS, TO_CHAR(START_DATE, 'YYYY-MM') ; ``` 5. not good 6. Forget about it since we don't have enterpreneurs in time 7. Srija # of accounts groupped by create_month and age group 8. Mukul - count of transactions - sum trans_amount - group by month and district - filter by district_detail 9. Shangde - one query <file_sep>""" This script stores the helper functions @see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html https://oracle-base.com/articles/8i/constraint-checking-updates https://stackoverflow.com/questions/42727990/speed-up-to-sql-when-writing-pandas-dataframe-to-oracle-database-using-sqlalch https://stackoverflow.com/questions/31997859/bulk-insert-a-pandas-dataframe-using-sqlalchemy """ #from pandas.io.sql import SQLTable # #def _execute_insert(self, conn, keys, data_iter): # print("Using monkey-patched _execute_insert") # data = [dict(zip(keys, row)) for row in data_iter] # conn.execute(self.table.insert().values(data)) # #SQLTable._execute_insert = _execute_insert import pandas as pd import csv import numpy as np from sqlalchemy import create_engine from sqlalchemy import types as sqlt from pprint import pprint from config.settings import DB_USER, DB_PASS, DB_HOST, DB_SID import logging # logging.basicConfig(level=logging.INFO) logging.basicConfig(filename='berka.log', level=logging.INFO, format='%(asctime)s %(message)s') log = logging.getLogger(__name__) # NROWS = 200 NROWS = None # None = All rows CHUNK_SIZE = 20 TABLE_REGION = 'region' TABLE_DISTRICT = 'district' TABLE_ACCOUNT = 'account' TABLE_ORDER = 'order' TABLE_TRANSACTION = 'transaction' # TODO TABLE_CLIENT = 'client' TABLE_DISPOSITION = 'disposition' TABLE_CARD = 'card' TABLE_LOAN = 'loan' # change to 1 to process LOAD_CONFIG = { TABLE_REGION: 0, TABLE_DISTRICT: 1, TABLE_ACCOUNT: 0, TABLE_ORDER: 0, TABLE_TRANSACTION: 1, TABLE_CLIENT: 0, TABLE_DISPOSITION: 0, TABLE_CARD: 0, TABLE_LOAN: 0, } def get_connection_mysql(): # not used DB_USER = 'root' DB_PASS = '<PASSWORD>' DB_HOST = 'app.sharpspring.localhost.com' DB_NAME = 'berka' dsn = "mysql+pymysql://{}:{}@{}/{}".format(DB_USER, DB_PASS, DB_HOST, DB_NAME) engine = create_engine(dsn, pool_recycle=3600) return engine def get_connection_oracle(): # https://docs.sqlalchemy.org/en/13/dialects/oracle.html dsn = "oracle+cx_oracle://{}:{}@{}/{}".format(DB_USER, DB_PASS, DB_HOST, DB_SID) print(f'Connecting to {DB_USER}@{DB_HOST}/{DB_SID}') try: # https://github.com/pandas-dev/pandas/issues/8953 conn = create_engine(dsn, max_identifier_length=128, pool_size=10, max_overflow=5, pool_recycle=3600, encoding="UTF-8") return conn except Exception as exc: log.error('Failed to create db connection due: {}'.format(exc)) return None # TODO: add lat/long if we find it def load_region(conn, filename): df = pd.read_csv(filename, sep=',', low_memory=False, nrows=NROWS) columns = { "ID": "region_id", "Region": "region_name", "Capital": "region_capital", "Area": "region_area", "Population": "region_population", "GDP": "region_gdp", "Website": "region_website", } df.rename(columns=columns, inplace=True) df.sort_values(by=['region_id'], inplace=True) log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) log.info(f"columns: {df.columns}") # df.to_sql('region', con=conn, if_exists='append', index=False, chunksize=CHUNK_SIZE) df.to_csv('back_region.csv', index=False, quoting=csv.QUOTE_NONNUMERIC) log.info(f'Finished data import for: {filename}') data = conn.execute("SELECT * FROM region WHERE ROWNUM <= 20").fetchall() pprint(data) # multiple districts form one region def load_district(conn, filename): df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) # A1;A2;A3;A4;A5;A6;A7;A8;A9;A10;A11;A12;A13;A14;A15;A16 # North Bohemia - > Usti nad Labem (7) # east Bohemia -> Pardubice (10) # west Bohemia -> Karlovy Vary (6) # south Moravia -> 13 # north Moravia -> Moravia-Silesia (12) """ a1: This is the district code. The Czech Republic is divided into districts. An integer has been assigned to each of these districts. a2: This is the district name. We can associate the district number with the district code and the region. a3: The region in which clients are located. a4: The number of inhabitants. a5: Number of municipalities with less than 499 inhabitants. a6: Number of municipalities with number of inhabitants 500 - 1999. a7: Number of municipalities with number of inhabitants 2000 - 9999. a8: Number of municipalities with more than 10000 inhabitants. a9: Number of cities. a10: Ratio of urban inhabitants. a11: Average salary. a14: Number of entrepreneurs per 1000 inhabitants. a12: Unemployment rate of 1995. a13: Unemployment rate of 1996. a15: Number of crimes committed in 1995. a16: Number of crimes committed in 1996. """ columns = { "A1": "district_id", "A2": "district_name", "A3": "region_id", "A9": "cities", "A10": "ratio_urban", "A11": "salary_average", "A14": "ratio_entrepreneurs", "A4": "inhabitants", "A5": "municipalities_500", "A6": "municipalities_2k", "A7": "municipalities_10k", "A8": "municipalities_10k_above", 'A12': 'unempl_1995', 'A13': 'unempl_1996', 'A15': 'crimes_1995', 'A16': 'crimes_1996', } df.rename(columns=columns, inplace=True) df.sort_values(by=['district_id'], inplace=True) log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) log.info(f"columns: {df.columns}") df_distr = df[['district_id', 'region_id', 'district_name']] df_distr_detail = df[ ['district_id', 'cities', 'salary_average', 'ratio_urban', 'ratio_entrepreneurs']] df_distr_population = df[ ['district_id', 'inhabitants', 'municipalities_500', 'municipalities_2k', 'municipalities_10k', 'municipalities_10k_above']] # df_distr.to_sql('district', con=conn, if_exists='append', index=False) df_distr.to_csv('back_district.csv', index=False, quoting=csv.QUOTE_NONNUMERIC) # df_distr_detail.to_sql('district_detail', con=conn, if_exists='append', index=False) # df_distr_population.to_sql('district_population', con=conn, if_exists='append', index=False) # split district history for years 1995 and 1996 df_h1 = df[['district_id', 'unempl_1995', 'crimes_1995']].copy() df_h2 = df[['district_id', 'unempl_1996', 'crimes_1996']].copy() df_h1['year'] = 1995 df_h2['year'] = 1996 # fix column names h1_cols = {'unempl_1995': 'ratio_unemployment', 'crimes_1995': 'crimes'} h2_cols = {'unempl_1996': 'ratio_unemployment', 'crimes_1996': 'crimes'} df_h1.rename(columns=h1_cols, inplace=True) df_h2.rename(columns=h2_cols, inplace=True) # write both sets to the same table log.info('writing district_history 1995...') df_h1.to_sql('district_history', con=conn, if_exists='append', index=False) log.info('writing district_history 1996...') df_h2.to_sql('district_history', con=conn, if_exists='append', index=False) log.info(f'Finished data import for: {filename}') data = conn.execute("SELECT * FROM district WHERE ROWNUM <= 20").fetchall() pprint(data) def load_account(conn, filename): df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) df['date'] = pd.to_datetime(df['date'], format="%y%m%d") df.rename(columns={"date": "created_date"}, inplace=True) df.sort_values(by=['account_id'], inplace=True) log.info("columns: {}".format(df.columns)) """ Replace `frequency` strings with abbreviations - POPLATEK MESICNE changed to MONTHLY ISSUANCE (MO) - POPLATEK TYDNE changed to WEEKLY ISSUANCE (WE) - POPLATEK PO OBRATU change to ISSUANCE AFTER TRANSACTION (AT) """ df['frequency'].replace({'POPLATEK MESICNE': 'MO'}, inplace=True) df['frequency'].replace({'POPLATEK TYDNE': 'WE'}, inplace=True) df['frequency'].replace({'POPLATEK PO OBRATU': 'AT'}, inplace=True) log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) """ CREATE TABLE account ( account_id number NOT NULL, district_id number NOT NULL, frequency char(2) NOT NULL, created_date date NOT NULL, PRIMARY KEY (account_id), FOREIGN KEY(district_id) REFERENCES district (district_id) INITIALLY DEFERRED DEFERRABLE ) ; CREATE INDEX created_date ON account(created_date); """ dtype = { 'account_id': sqlt.Integer, 'district_id': sqlt.Integer, 'frequency': sqlt.NCHAR(2), 'created_date': sqlt.Date, } df.to_sql('account', con=conn, if_exists='append', index=False, dtype=dtype) # df.to_sql('account', con=conn, if_exists='append', index=False) log.info('Finished data import for: {}'.format(filename)) data = conn.execute("SELECT * FROM account WHERE ROWNUM <= 10").fetchall() pprint(data) def load_order(conn, filename): # this function writes to the `account_order` table # "order_id";"account_id";"bank_to";"account_to";"amount";"k_symbol" """ CREATE TABLE account_order ( order_id number NOT NULL, account_id number NOT NULL, bank_to char(2) NOT NULL, account_to number NOT NULL, amount decimal(10,2) NOT NULL, category char(3) NOT NULL, PRIMARY KEY (order_id), FOREIGN KEY(account_id) REFERENCES account (account_id), FOREIGN KEY(account_to) REFERENCES account (account_id) ); """ df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) cols = {'k_symbol': 'category'} df.rename(columns=cols, inplace=True) log.info("account_order columns: {}".format(df.columns)) # Apply english appreviations # 'POJISTNE' - INS => stands for Insurance Payment # 'SIPO' - HSE => stands for Household Payment # 'LEASING' - LSE => stands for Leasing Payment # 'UVER' - LOA => stands for Loan Payment # ' ' - UNK => stands for Unknown df['category'].replace({'POJISTNE': 'INS'}, inplace=True) df['category'].replace({'SIPO': 'HSE'}, inplace=True) df['category'].replace({'LEASING': 'LSN'}, inplace=True) df['category'].replace({'UVER': 'LOA'}, inplace=True) df['category'].replace({' ': 'UNK'}, inplace=True) pprint(df) log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) # dtype : dict of column name to SQL type, default None dtype = { 'order_id': sqlt.Integer, 'account_id': sqlt.Integer, 'bank_to': sqlt.NCHAR(2), 'account_to': sqlt.Integer, 'amount': sqlt.Numeric, 'category': sqlt.NCHAR(2), } df.to_sql('account_order', con=conn, if_exists='append', index=False, dtype=dtype) log.info('Finished data import for: {}'.format(filename)) def load_transaction(conn, filename): """ "trans_id";"account_id";"date";"type";"operation";"amount";"balance";"k_symbol";"bank";"account" CREATE TABLE transaction ( trans_id number NOT NULL, account_id number NOT NULL, created_date date NOT NULL, trans_type char(2) NOT NULL, -- CR+=credit, DB=-debit operation char(3) NOT NULL, amount decimal(10,2) NOT NULL, balance decimal(10,2) NOT NULL, category char(3) NOT NULL, bank_to char(2), account_to number, PRIMARY KEY (trans_id), FOREIGN KEY(account_id) REFERENCES account (account_id) ); """ # df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) df = pd.read_csv(filename, sep=';', low_memory=False) print("== df size: {}".format(len(df))) cols = { 'date': 'created_date', 'type': 'trans_type', 'k_symbol': 'category', 'bank': 'bank_to', 'account': 'account_to', } df.rename(columns=cols, inplace=True) log.info("{} columns: {}".format(filename, df.columns)) df['created_date'] = pd.to_datetime(df['created_date'], format="%y%m%d") df['trans_type'].replace({'PRIJEM': 'CR'}, inplace=True) # credit df['trans_type'].replace({'VYDAJ': 'DB'}, inplace=True) # debit df['trans_type'].replace({'VYBER': 'DB'}, inplace=True) # debit # operation # PREVOD NA UCET 208283 - remittance to another bank (REM) # PREVOD Z UCTU 65226 - collection from another bank (COL) # VKLAD 156743 - credit in cash (CRE) # VYBER 434918 - withdrawal in cash (WCA) # V<NAME> 8036 - credit card withdrawal (WCC) df['operation'].replace({'PREVOD NA UCET': 'REM'}, inplace=True) df['operation'].replace({'PREVOD Z UCTU': 'COL'}, inplace=True) df['operation'].replace({'VKLAD': 'CRE'}, inplace=True) df['operation'].replace({'VYBER': 'WCA'}, inplace=True) df['operation'].replace({'VYBER KARTOU': 'WCC'}, inplace=True) # category # DUCHOD 30338 - old-age pension # POJISTNE 18500 - insurance payment # SANKC. UROK 1577 - sanction interest if negative balance # SIPO 118065 - household # SLUZBY 155832 - payment for statement # UROK 183114 - interest credited # UVER 13580 - loan payment df['category'].replace({'DUCHOD': 'PEN'}, inplace=True) # pension df['category'].replace({'POJISTNE': 'INS'}, inplace=True) # insurance df['category'].replace({'SANKC. UROK': 'INB'}, inplace=True) # interest negative balance df['category'].replace({'SIPO': 'HSE'}, inplace=True) # household df['category'].replace({'SLUZBY': 'PST'}, inplace=True) # payment for statement df['category'].replace({'UROK': 'INC'}, inplace=True) # interest credited df['category'].replace({'UVER': 'LOA'}, inplace=True) # loan payment # print("operation: {}".format(df.groupby('operation').size())) # print("category: {}".format(df.groupby('category').size())) df['category'] = df['category'].replace(np.nan, 'UNK') df['category'] = df['category'].replace(' ', 'UNK') df['category'] = df['category'].replace('', 'UNK') df['operation'] = df['operation'].replace(np.nan, 'UNK') df['operation'] = df['operation'].replace(' ', 'UNK') df['operation'] = df['operation'].replace('', 'UNK') print("trans_type: {}".format(df.groupby('trans_type').size())) print("operation: {}".format(df.groupby('operation').size())) print("category: {}".format(df.groupby('category').size())) dtype = { 'trans_id': sqlt.Integer, 'account_id': sqlt.Integer, 'create_date': sqlt.Date, 'trans_type': sqlt.NCHAR(2), 'operation': sqlt.NCHAR(3), 'amount': sqlt.Numeric(10, 2), 'balance': sqlt.Numeric(10, 2), 'category': sqlt.NCHAR(3), 'bank_to': sqlt.NCHAR(2), 'account_to': sqlt.Integer, } log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) # df2 = df.iloc[269000:270000] # print("== df2 size: {}".format(len(df2))) # df2.to_sql('transaction2', con=conn, if_exists='append', index=False, dtype=dtype, chunksize=200) df.to_sql('transaction', con=conn, if_exists='append', index=False, dtype=dtype, chunksize=200) log.info('Finished data import for: {}'.format(filename)) def load_client(conn, filename): df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) print("== {} df size: {}".format(filename, len(df))) df.to_sql('client', con=conn, if_exists='append', index=False, dtype=dtype, chunksize=200) log.info('Finished data import for: {}'.format(filename)) def load_disposition(conn, filename): df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) print("== {} df size: {}".format(filename, len(df))) df.to_sql('disposition', con=conn, if_exists='append', index=False, dtype=dtype, chunksize=200) log.info('Finished data import for: {}'.format(filename)) def load_card(conn, filename): df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) print("== {} df size: {}".format(filename, len(df))) df.to_sql('card', con=conn, if_exists='append', index=False, dtype=dtype, chunksize=200) log.info('Finished data import for: {}'.format(filename)) def load_loan(conn, filename): """ CREATE TABLE loan ( loan_id number NOT NULL, account_id number NOT NULL, loan_date date NOT NULL, amount decimal(10, 2) NOT NULL, duration number, payments decimal(10, 2) NOT NULL, status char(1) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY(account_id) REFERENCES account (account_id) ); """ df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) print("== loan df size: {}".format(len(df))) cols = { 'date': 'loan_date', } df.rename(columns=cols, inplace=True) log.info("{} columns: {}".format(filename, df.columns)) df['loan_date'] = pd.to_datetime(df['loan_date'], format="%y%m%d") dtype = { 'loan_id': sqlt.Integer, 'account_id': sqlt.Integer, 'loan_date': sqlt.Date, 'amount': sqlt.Numeric(10, 2), 'duration': sqlt.Integer, 'payments': sqlt.Numeric(10, 2), 'status': sqlt.NCHAR(1), } log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) df.to_sql('loan', con=conn, if_exists='append', index=False, dtype=dtype) log.info('Finished data import for: {}'.format(filename)) #def load_loan(conn, filename): # df = pd.read_csv(filename, sep=';', low_memory=False, nrows=NROWS) # log.info("columns: {}".format(df.columns)) # # log.info('Starting data import for: {} ({} rows)'.format(filename, len(df))) # df.to_sql('loan', con=conn, if_exists='replace', index=False) # log.info('Finished data import for: {}'.format(filename)) def load_data(conn): print(f'load_data according to this config: {LOAD_CONFIG}') for key, val in LOAD_CONFIG.items(): if val and TABLE_REGION == key: load_region(conn, 'data/region.csv') if val and TABLE_DISTRICT == key: load_district(conn, 'data/district.csv') if val and TABLE_ACCOUNT == key: load_account(conn, 'data/account.asc') if val and TABLE_ORDER == key: load_order(conn, 'data/order.asc') if val and TABLE_TRANSACTION == key: load_transaction(conn, 'data/trans.csv') if val and TABLE_CLIENT == key: load_client(conn, 'data/client.asc') if val and TABLE_DISPOSITION == key: load_disposition(conn, 'data/disposition.asc') if val and TABLE_CARD == key: load_card(conn, 'data/card.asc') if val and TABLE_LOAN == key: load_loan(conn, 'data/loan.asc') <file_sep> run: yarn start <file_sep>#!/usr/bin/env python3 """ Simple script to test Oracle python driver @see https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html#quick-start-cx-oracle-installation https://blogs.oracle.com/oraclemagazine/perform-basic-crud-operations-using-cx-oracle-part-1 """ from config import settings import cx_Oracle from pprint import pprint def get_connection(): dsn = "{}/{}".format(settings.DB_HOST, settings.DB_SID) connection = cx_Oracle.connect(settings.DB_USER, settings.DB_PASS, dsn) return connection def create_table(conn): cursor = conn.cursor() sql = """ CREATE TABLE student ( id integer NOT NULL , first_name VARCHAR(32) NOT NULL , last_name VARCHAR(32) NOT NULL , PRIMARY KEY (id) ) """ try: result = cursor.execute(sql) pprint("create result: {}".format(result)) except Exception as exc: print("create_table - got exception: {}".format(exc)) finally: cursor.close() def insert_table(conn): cursor = conn.cursor() sql = """ INSERT INTO student (id, first_name, last_name) WITH names AS ( SELECT 1, 'Ruth', 'Fox' FROM dual UNION ALL SELECT 2, 'Isabelle', 'Squirrel' FROM dual UNION ALL SELECT 3, 'Justin', 'Frog' FROM dual UNION ALL SELECT 4, 'Lisa', 'Owl' FROM dual ) SELECT * FROM names """ try: cursor.execute(sql) conn.commit() except Exception as exc: print("insert_table - got exception: {}".format(exc)) finally: cursor.close() def read_table(conn): cursor = conn.cursor() sql = """ SELECT id, first_name, last_name FROM student WHERE id >= :id """ try: cursor.execute(sql, id=2) print("read_table:") for id, fname, lname in cursor: print("\nrow: ", id, fname, lname) finally: cursor.close() def main(): conn = get_connection() create_table(conn) insert_table(conn) read_table(conn) if __name__ == '__main__': main() <file_sep>-- https://stackoverflow.com/questions/15762585/mysql-query-to-get-trend-of-temperature CREATE TABLE temperature_log( ID INT NOT NULL, DT DATE NOT NULL, temperature DECIMAL(5,2) NOT NULL) ; -- https://www.oracletutorial.com/oracle-basics/oracle-date/ INSERT INTO temperature_log VALUES (50, TO_DATE('2013-03-27 07:56:05', 'YYYY/mm/dd hh24:mi:ss'), 27.25); INSERT INTO temperature_log VALUES (51, TO_DATE('2013-03-27 07:57:05', 'YYYY/mm/dd hh24:mi:ss'), 27.50); INSERT INTO temperature_log VALUES (52, TO_DATE('2013-03-27 07:58:05', 'YYYY/mm/dd hh24:mi:ss'), 27.60); INSERT INTO temperature_log VALUES (53, TO_DATE('2013-03-27 07:59:05', 'YYYY/mm/dd hh24:mi:ss'), 27.80); INSERT INTO temperature_log VALUES (54, TO_DATE('2013-03-27 08:00:05', 'YYYY/mm/dd hh24:mi:ss'), 27.70); INSERT INTO temperature_log VALUES (55, TO_DATE('2013-03-27 08:01:05', 'YYYY/mm/dd hh24:mi:ss'), 27.50); INSERT INTO temperature_log VALUES (56, TO_DATE('2013-03-27 08:02:05', 'YYYY/mm/dd hh24:mi:ss'), 27.25); INSERT INTO temperature_log VALUES (57, TO_DATE('2013-03-27 08:03:05', 'YYYY/mm/dd hh24:mi:ss'), 27.10); INSERT INTO temperature_log VALUES (58, TO_DATE('2013-03-27 08:04:05', 'YYYY/mm/dd hh24:mi:ss'), 26.9); INSERT INTO temperature_log VALUES (59, TO_DATE('2013-03-27 08:05:05', 'YYYY/mm/dd hh24:mi:ss'), 27.1); INSERT INTO temperature_log VALUES (60, TO_DATE('2013-03-27 08:06:05', 'YYYY/mm/dd hh24:mi:ss'), 27.25); INSERT INTO temperature_log VALUES (61, TO_DATE('2013-03-27 08:07:05', 'YYYY/mm/dd hh24:mi:ss'), 27.6); SELECT x.* , x.temperature - y.temperature diff , COUNT(*) cnt ,(x.temperature-y.temperature)/COUNT(*) trend FROM temperature_log x JOIN temperature_log y ON y.id < x.id GROUP BY x.id; <file_sep>from api.main import app from api.dbutils import fetch_data @app.route('/api/tableStats') def table_stats(): # q0 - total number of records in each table description = "This query returns the number of rows in each table" sql = """ SELECT 'ACCOUNT' table_name, COUNT(*) num_rows FROM dmelisso.ACCOUNT UNION ALL SELECT 'ORDER', COUNT(*) FROM dmelisso.ORDERS UNION ALL SELECT 'REGION_FULL', COUNT(*) FROM dmelisso.REGION_FULL UNION ALL SELECT 'DISTRICT', COUNT(*) FROM dmelisso.DISTRICT UNION ALL SELECT 'DISTRICT_DETAIL', COUNT(*) FROM dmelisso.DISTRICT_DETAIL UNION ALL SELECT 'DISTRICT_HISTORY', COUNT(*) FROM dmelisso.DISTRICT_HISTORY UNION ALL SELECT 'DISTRICT_POPULATION', COUNT(*) FROM dmelisso.DISTRICT_POPULATION UNION ALL SELECT 'TRANSACTIONS', COUNT(*) FROM dmelisso.TRANSACTIONS UNION ALL SELECT 'CLIENT', COUNT(*) FROM dmelisso.CLIENT UNION ALL SELECT 'CARD', COUNT(*) FROM dmelisso.CARD UNION ALL SELECT 'DISPOSITION', COUNT(*) FROM dmelisso.DISPOSITION """ return fetch_data(sql, description) @app.route('/api/getSumTransBalanceMonthByGenderV2') def transaction_balance(): # From q1 description = "This query returns the sum of transaction balance by gender" sql = """ SELECT TO_CHAR(t.created_DATE, 'YYYY-MM') AS month, c.gender, SUM(t.balance) AS sum_balance FROM dmelisso.client c JOIN dmelisso.disposition d ON c.client_id = d.client_id JOIN dmelisso.transactions t ON t.account_id = d.account_id GROUP BY TO_CHAR(created_DATE, 'YYYY-MM'), gender ORDER BY TO_CHAR(created_DATE, 'YYYY-MM') """ json_data = fetch_data(sql, description) return json_data @app.route('/api/getNumCardsIssued/') @app.route('/api/getNumCardsIssued/<min_age>') @app.route('/api/getNumCardsIssued/<min_age>/<region_name>') def card_stats(min_age=0, region_name=None): # From q2 description = "This query returns the number of cards issued." # subtitle = "Api data filters: min_age, region_name" where_region = '' if region_name is not None: # add extra restriction where_region = f" AND region_name = '{region_name}'" # TODO: select AVG(INHABITANTS) AVG_IHABITANTS sql = f""" SELECT TO_CHAR(issued, 'YYYY-MM') month , COUNT(*) num_rows FROM dmelisso.CARD cr JOIN dmelisso.DISPOSITION d ON d.disp_id = cr.disp_id JOIN dmelisso.CLIENT c ON c.client_id = d.client_id JOIN dmelisso.DISTRICT dist ON dist.DISTRICT_ID = c.DISTRICT_ID LEFT JOIN dmelisso.REGION_FULL r ON r.REGION_ID = dist.REGION_ID WHERE 1999 - EXTRACT(YEAR FROM BIRTH_NUMBER) > {min_age} {where_region} GROUP BY TO_CHAR(issued, 'YYYY-MM') ORDER BY 1 """ return fetch_data(sql, description) @app.route('/api/getLoanAvgCountForAgeGroups') def loan_stats(): # From q3 description = """ This query returns the average loan monthy payment, and the number of loans issued each month for different age groups""" # Note: includes even the months without data sql = """ SELECT X.AGE_GROUP, X.MONTH, Y.AVG_PAYMENTS, Y.NUM_LOANS FROM ( SELECT * FROM (SELECT 'g60' AGE_GROUP FROM DUAL UNION ALL SELECT 'g30-60' FROM DUAL UNION ALL SELECT 'g0-30' FROM DUAL ) GRP CROSS JOIN ( WITH t as ( select date '1993-07-05' init, date '1998-12-08' final from dual ) select to_char(add_months(trunc(init, 'mm'), level - 1), 'RRRR-MM') MONTH from t connect by level <= months_between(final, init) + 1 ) ORDER BY GRP.AGE_GROUP, MONTH ) X LEFT JOIN ( -- average payments for age groups SELECT CASE WHEN 1999 - EXTRACT(YEAR FROM BIRTH_NUMBER) >= 60 THEN 'g60' WHEN 1999 - EXTRACT(YEAR FROM BIRTH_NUMBER) >= 30 THEN 'g30-60' ELSE 'g0-30' END AS AGE_GROUP , TO_CHAR(START_DATE, 'YYYY-MM') AS LOAN_CREATED_MONTH , AVG(PAYMENTS) AS AVG_PAYMENTS , COUNT(*) AS NUM_LOANS -- , AVG(AMOUNT) AS AVG_AMOUNT -- , AVG(DURATION) AS AVG_DURATION FROM dmelisso.LOAN L JOIN dmelisso.DISPOSITION D ON D.account_id = L.account_id JOIN dmelisso.CLIENT c ON c.client_id = d.client_id WHERE -- can filter by age at the time of data collection 1999 - EXTRACT(YEAR FROM BIRTH_NUMBER) > 10 AND D.TYPE = 'OWNER' GROUP BY CASE WHEN 1999 - EXTRACT(YEAR FROM BIRTH_NUMBER) >= 60 THEN 'g60' WHEN 1999 - EXTRACT(YEAR FROM BIRTH_NUMBER) >= 30 THEN 'g30-60' ELSE 'g0-30' END , TO_CHAR(START_DATE, 'YYYY-MM') ORDER BY 1, 2 ) Y ON Y.AGE_GROUP = X.AGE_GROUP AND Y.LOAN_CREATED_MONTH = X.MONTH ORDER BY X.AGE_GROUP, X.MONTH """ return fetch_data(sql, description) <file_sep>from api.main import app from api.dbutils import fetch_data_as_json, fetch_data @app.route('/api/getTotalAmountOfLoansPerDistrict') def transaction_balance1(): # From q1 description = "Group the loan by district and calculate the total amount of loan on each date in each district" sql = """ SELECT SUM(LOAN.amount) As LOAN_SUM, TO_CHAR(loan.start_DATE, 'YYYY-MM') AS month, DISTRICT_detail.district_id FROM dmelisso.LOAN LOAN JOIN dmelisso.account ACCOUNT ON ACCOUNT.account_id = LOAN.account_id JOIN dmelisso.DISTRICT_detail ON DISTRICT_detail.district_id = ACCOUNT.district_id GROUP BY TO_CHAR(loan.start_DATE, 'YYYY-MM'), DISTRICT_detail.district_id ORDER BY TO_CHAR(loan.start_DATE, 'YYYY-MM') """ json_data = fetch_data(sql, description) return json_data @app.route('/api/getTotalAmountOfCreditCardsIssuedPerMonth') def transaction_balance2(): # From q1 description = "Calculate the amount of cards issued on each month" sql = """ SELECT COUNT(CARD.card_id) AS Number_Of_Cards, TO_CHAR(CARD.issued, 'YYYY-MM') AS month FROM dmelisso.CARD JOIN dmelisso.DISPOSITION ON DISPOSITION.disp_id = CARD.disp_id JOIN dmelisso.ACCOUNT ON ACCOUNT.account_id = DISPOSITION.account_id GROUP BY TO_CHAR(CARD.issued, 'YYYY-MM') ORDER BY TO_CHAR(CARD.issued, 'YYYY-MM') """ json_data = fetch_data(sql, description) return json_data <file_sep>from flask import Flask, escape, request app = Flask(__name__) @app.route('/') def hello(): name = request.args.get("name", "World") return f'Hello, {escape(name)}!' @app.route('/stats') def stats(): name = request.args.get("table", None) if name is not None: return f'Table {escape(table)} stats' return 'All tables...' <file_sep> -- this file is for MySQL (does not work for Oracle) CREATE TABLE account ( account_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, district_id bigint(20) unsigned NOT NULL, frequency char(2) NOT NULL, created_date date NOT NULL DEFAULT '0000-00-00', PRIMARY KEY (account_id), KEY `district` (district_id), KEY `created_frequency` (created_date, frequency) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE card ( card_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, disp_id bigint(20) unsigned NOT NULL, card_type char(2) NOT NULL, issued_date date NOT NULL DEFAULT '0000-00-00', PRIMARY KEY (card_id), KEY `disp_id` (disp_id), KEY `issued_type` (issued_date, card_type) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE client ( client_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, district_id bigint(20) unsigned NOT NULL, birth_date date NOT NULL DEFAULT '0000-00-00', gender char(1) NOT NULL, PRIMARY KEY (client_id), KEY `district` (district_id), KEY `birth_gender` (birth_date, gender) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE disposition ( disp_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, client_id bigint(20) unsigned NOT NULL, account_id bigint(20) unsigned NOT NULL, disp_type char(1) NOT NULL, PRIMARY KEY (disp_id), KEY `client` (client_id), KEY `account` (account_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- https://www.draw.io/#G1_l03368IH17grcnq7wuqdmr-PtJPH85g -- https://en.wikipedia.org/wiki/Districts_of_the_Czech_Republic -- https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html CREATE TABLE district( district_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, region_id bigint(20) unsigned NOT NULL, district_name varchar(64) NOT NULL, PRIMARY KEY (district_id), KEY `region` (region_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /* df_loan.groupby('status').agg(['count']); loan_id account_id date amount duration payments count count count count count count status A 203 203 203 203 203 203 B 31 31 31 31 31 31 C 403 403 403 403 403 403 D 45 45 45 45 45 45 */ CREATE TABLE loan ( loan_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, account_id bigint(20) unsigned NOT NULL, loan_date date NOT NULL DEFAULT '0000-00-00', duration int(11) unsigned NOT NULL, payments decimal(10,2) unsigned NOT NULL, status char(1) NOT NULL, PRIMARY KEY (loan_id), KEY `account_date` (account_id, loan_date) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /* Category: df_order.groupby('k_symbol').agg(['count']); order_id account_id bank_to account_to amount count count count count count k_symbol 1379 1379 1379 1379 1379 LEASING 341 341 341 341 341 POJISTNE 532 532 532 532 532 SIPO 3502 3502 3502 3502 3502 UVER 717 717 717 717 717 */ CREATE TABLE account_order ( order_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, account_id bigint(20) unsigned NOT NULL, bank_to char(2) NOT NULL, account_to bigint(20) unsigned NOT NULL, amount decimal(10,2) unsigned NOT NULL, category char(3) NOT NULL DEFAULT 'N/A', PRIMARY KEY (order_id), KEY `account_id` (account_id), KEY `account_to` (account_to), KEY `category` (category) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /* >>> df_trans['amount'].min() 0.0 >>> df_trans['amount'].max() 87400.0 df_trans['balance'].min() -41125.7 >>> df_trans['balance'].max() 209637.0 Operation: PREVOD NA UCET 208283 - remittance to another bank (REM) PREVOD Z UCTU 65226 - collection from another bank (COL) VKLAD 156743 - credit in cash (CRE) VYBER 434918 - withdrawal in cash (WCA) VYBER KARTOU 8036 - credit card withdrawal (WCC) Category: DUCHOD 30338 - old-age pension POJISTNE 18500 - insurance payment SANKC. UROK 1577 - sanction interest if negative balance SIPO 118065 - household SLUZBY 155832 - payment for statement UROK 183114 - interest credited UVER 13580 - loan payment */ CREATE TABLE transaction ( trans_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, account_id bigint(20) unsigned NOT NULL, created_date date NOT NULL DEFAULT '0000-00-00', trans_type char(2) NOT NULL, -- CR+=credit, DB=-debit operation char(3) NOT NULL, amount decimal(10,2) unsigned NOT NULL, balance decimal(10,2) NOT NULL, category char(3) NOT NULL DEFAULT 'N/A', bank_to char(2) NOT NULL, account_to bigint(20) unsigned NOT NULL, PRIMARY KEY (trans_id), KEY `account_id` (account_id), KEY `created_type` (created_date, trans_type), KEY `operation` (operation), KEY `amount` (amount) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <file_sep> # Setup & Run yarn install yarn start # Creating the app $ brew install yarn $ yarn --version 1.22.4 $ node --version v12.16.2 $ yarn global add create-react-app $ create-react-app app --template typescript # Success! Created app at /Volumes/dev/dbms/app # Inside that directory, you can run several commands: # yarn start # Starts the development server. # yarn build # Bundles the app into static files for production. # yarn test # Starts the test runner. # yarn eject # Removes this tool and copies build dependencies, configuration files # and scripts into the app directory. If you do this, you can’t go back! # We suggest that you begin by typing: # cd app # yarn start # Happy hacking! # GYP error https://stackoverflow.com/questions/18425379/how-to-set-pythons-default-version-to-3-x-on-os-x $ lsa /usr/local/bin/python lrwxr-xr-x 1 andreisura admin 38B Feb 6 01:17 /usr/local/bin/python -> ../Cellar/python@2/2.7.17_1/bin/python $ unlink /usr/local/bin/python ln -s /usr/local/bin/python3 /usr/local/bin/python <file_sep>flask: # env FLASK_APP=web.py flask run env FLASK_APP=api/main.py FLASK_ENV=development flask run import: python berka.py x: dtruss -f -t open python myfile.py <file_sep>from api.main import app from flask import url_for def has_no_empty_params(rule): defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments) @app.route('/api') def api(): """ Helper page to list all GET routes """ links = [] for rule in app.url_map.iter_rules(): # Kep only GET routes that do not require parameters if "GET" in rule.methods and has_no_empty_params(rule): url = url_for(rule.endpoint, **(rule.defaults or {})) # links.append((url, rule.endpoint)) links.append(url) links = sorted(links, reverse=False) links_li = ['<li><a href="{}">{}</a></li>'.format(x, x) for x in links] body = '<ul>{}</ul>'.format("\n".join(links_li)) return f""" <html> <head> <title> List of API endpoints </title> </head> <body> {body} </body> </html> """ <file_sep> -- render two lines: M/F SELECT c.gender, SUM(t.balance) AS SUM_of_balance, TO_CHAR(t.created_DATE, 'YYYY-MM') AS Month FROM dmelisso.client c JOIN dmelisso.disposition d ON c.client_id = d.client_id JOIN dmelisso.transactions t ON t.account_id = d.account_id GROUP BY gender, TO_CHAR(created_DATE, 'YYYY-MM') ORDER BY gender, TO_CHAR(created_DATE, 'YYYY-MM'); <file_sep>-- Transactions trend from urban/non-urban districts SELECT count(trans_id) as TRANS_NUM, URBAN_RANK, MONTH_INTERVAL FROM (SELECT TRANS_ID, NTILE(2) OVER (ORDER BY RATIO_URBAN DESC) AS URBAN_RANK, EXTRACT(MONTH FROM CREATED_DATE) || '-' || EXTRACT(YEAR FROM CREATED_DATE) AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS NATURAL JOIN DMELISSO.ACCOUNT NATURAL JOIN DMELISSO.DISPOSITION NATURAL JOIN DMELISSO.CLIENT NATURAL JOIN DMELISSO.DISTRICT_DETAIL) T group by MONTH_INTERVAL, URBAN_RANK; -- Transactions trend from (HIG,MIG,LIG) neighborhood districts SELECT count(trans_id) as TRANS_NUM, INCOME_GROUP_RANK, MONTH_INTERVAL FROM (SELECT TRANS_ID, NTILE(3) OVER (ORDER BY SALARY_AVERAGE DESC) AS INCOME_GROUP_RANK, EXTRACT(MONTH FROM CREATED_DATE) || '-' || EXTRACT(YEAR FROM CREATED_DATE) AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS NATURAL JOIN DMELISSO.ACCOUNT NATURAL JOIN DMELISSO.DISPOSITION NATURAL JOIN DMELISSO.CLIENT NATURAL JOIN DMELISSO.DISTRICT_DETAIL) T group by MONTH_INTERVAL, INCOME_GROUP_RANK; -- Trend of card usage by type SELECT count(trans_id) as TRANS_NUM, CARD_TYPE, MONTH_INTERVAL FROM (SELECT TRANS_ID, C.TYPE as card_type, EXTRACT(MONTH FROM CREATED_DATE) || '-' || EXTRACT(YEAR FROM CREATED_DATE) AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS T JOIN DMELISSO.DISPOSITION D ON D.ACCOUNT_ID = T.ACCOUNT_ID JOIN DMELISSO.CARD C ON D.DISP_ID = C.DISP_ID) T group by MONTH_INTERVAL, CARD_TYPE; -- Trend of transaction by bracket of transaction amount, as in higher amount vs mid amount vs low amount account holders SELECT count(trans_id) as TRANS_NUM, TRANS_AMOUNT_RANK, MONTH_INTERVAL FROM (SELECT TRANS_ID, NTILE(3) OVER (ORDER BY AMOUNT DESC) AS TRANS_AMOUNT_RANK, EXTRACT(MONTH FROM CREATED_DATE) || '-' || EXTRACT(YEAR FROM CREATED_DATE) AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS NATURAL JOIN DMELISSO.ACCOUNT NATURAL JOIN DMELISSO.DISPOSITION NATURAL JOIN DMELISSO.CLIENT NATURAL JOIN DMELISSO.DISTRICT_DETAIL) T group by MONTH_INTERVAL, TRANS_AMOUNT_RANK; -- Trend of transaction by bracket of balance, as in higher balance vs mid balance vs low balance account holders SELECT count(trans_id) as TRANS_NUM, ACCOUNT_BALANCE_RANK, MONTH_INTERVAL FROM (SELECT T.TRANS_ID, ACCOUNT_BALANCE_RANK, EXTRACT(MONTH FROM T.CREATED_DATE) || '-' || EXTRACT(YEAR FROM T.CREATED_DATE) AS MONTH_INTERVAL FROM (SELECT ACCOUNT_ID, NTILE(3) OVER (ORDER BY AVG_ACCOUNT_BALANCE DESC) AS ACCOUNT_BALANCE_RANK FROM (SELECT ACCOUNT_ID, AVG(BALANCE) AS AVG_ACCOUNT_BALANCE FROM DMELISSO.TRANSACTIONS group by ACCOUNT_ID)) ACCOUNT_BALANCE_DETAILS JOIN DMELISSO.TRANSACTIONS T ON ACCOUNT_BALANCE_DETAILS.ACCOUNT_ID = T.ACCOUNT_ID) E GROUP BY MONTH_INTERVAL, ACCOUNT_BALANCE_RANK; <file_sep> # Tasks - Shangde order.asc - Srija disp.asc, client.asc (this is fun one too) - Mukul loan.asc - Dimitrios region (have fun) - Andrei district.asc, trans.csv (account done?) # TA feedback -5. For the relation between disposition and card, the cardinality specified by the ER is 1:1. The SQL implementation for `card` has card_id as a primary key and `disp_id` as a foreign key. This does not ensure a 1:1 relationship. As the relationship is 1:1, having `disp_id` as the foreign key and primary key in `card` will solve this. `card_id` is not required as the relationship is 1:1, `disp_id` by itself will be enough to identify every tuple in card. The same applies for all 1:1 relations like `client` to `disposition` also. As the relation is 1:1, `disp_id` will be able to uniqule identify every client. <file_sep># Intro This repository stores code developed for the Spring 2020 DBMS class @ University of Florida # Group 25 members - <NAME> - <EMAIL> - <NAME> - <EMAIL> - <NAME> - <EMAIL> - <NAME> - <EMAIL> - <NAME> - <EMAIL> # Contributing - Login/CreateAccount @ github.com - fork the repo https://github.com/indera/dbms - clone the fork git clone <EMAIL>:YOUR_USERNAME/dbms.git - write code - create pull request ## Git ssh key https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent $ eval "$(ssh-agent -s)" $ ssh-add -K ~/.ssh/id_rsa # Setup - install python --> see https://realpython.com/installing-python/ - check if python is installed $ python --version ==> Python 3.7.6 - create a virtual environment $ python3 -m venv env - activate the virtual environment $ source ./env/bin/activate - install dependencies $ pip install -r requirements.txt - configure the two values in config/settings.py $ cp config/settings.py.template config/settings.py - run a simple test (creates table `student` and inserts/reads data) $ python test_oracle.py # Run Flask App to provide API service cd api && flask run --no-debugger # Sqlalchemy info https://docs.sqlalchemy.org/en/13/dialects/oracle.html # Import Czech Bank Financial Data (aka berka dataset) - Download the zip filefrom http://lisp.vse.cz/pkdd99/berka.htm and extract it to the `dbms/data` folder - Create the tables using the file: `schema/create_oracle.sql` - Run the import $ python berka.py # Help <EMAIL> https://it.cise.ufl.edu/wiki/Main_Page # TODO - Add foreign key constraints - Add support to create the tables automatically $ python berka.py --create - Print some basic table stats (number of rows, date ranges covered...) $ python berka.py --stats <file_sep>from api.main import app from api.dbutils import fetch_data_as_json import time # TODO: remove if not used @app.route('/api/login') def login(): return {'status': 'success', 'loginTime': time.time()} # TODO: remove if not used @app.route('/api/getTransactionDetails') def getTransactionDetails(): sql = """ SELECT * FROM DMELISSO.ACCOUNT A JOIN DMELISSO.TRANSACTIONS T ON T.ACCOUNT_ID=A.ACCOUNT_ID NATURAL JOIN DMELISSO.DISPOSITION D NATURAL JOIN DMELISSO.CLIENT C FETCH NEXT 100 ROWS ONLY """ json_data = fetch_data_as_json(sql) return json_data @app.route('/api/getSumTransBalanceMonthByGender') def getQuery1Details(): sql = """ SELECT TO_CHAR(t.created_DATE, 'YYYY-MM') AS Month, c.gender, SUM(t.balance) AS SUM_of_balance FROM dmelisso.client c JOIN dmelisso.disposition d ON c.client_id = d.client_id JOIN dmelisso.transactions t ON t.account_id = d.account_id GROUP BY TO_CHAR(created_DATE, 'YYYY-MM'), gender ORDER BY TO_CHAR(created_DATE, 'YYYY-MM') """ json_data = fetch_data_as_json(sql, 2000) return json_data def getQuery2Details(): sql = """ SELECT c.gender, SUM(t.balance) AS SUM_of_balance, TO_CHAR(t.created_DATE, 'YYYY-MM') AS Month FROM dmelisso.client c JOIN dmelisso.disposition d ON c.client_id = d.client_id JOIN dmelisso.transactions t ON t.account_id = d.account_id GROUP BY gender, TO_CHAR(created_DATE, 'YYYY-MM') ORDER BY gender, TO_CHAR(created_DATE, 'YYYY-MM') """ json_data = fetch_data_as_json(sql) return json_data @app.route('/api/getTransTrendUrbanNonUrban') def getQuery5_1Details(): sql = """ SELECT count(trans_id) as TRANS_NUM, URBAN_RANK, MONTH_INTERVAL FROM (SELECT TRANS_ID, NTILE(2) OVER (ORDER BY RATIO_URBAN DESC) AS URBAN_RANK, TO_DATE(EXTRACT(MONTH FROM CREATED_DATE) || '-' ||EXTRACT(YEAR FROM CREATED_DATE) ,'mm-yyyy') AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS NATURAL JOIN DMELISSO.ACCOUNT NATURAL JOIN DMELISSO.DISPOSITION NATURAL JOIN DMELISSO.CLIENT NATURAL JOIN DMELISSO.DISTRICT_DETAIL ) T GROUP BY MONTH_INTERVAL, URBAN_RANK ORDER BY MONTH_INTERVAL """ json_data = fetch_data_as_json(sql, 2000) return json_data @app.route('/api/getTransTrendOfIncomeWiseGroupedDistricts') def getQuery5_2Details(): sql = """ SELECT count(trans_id) as TRANS_NUM, INCOME_GROUP_RANK, MONTH_INTERVAL FROM (SELECT TRANS_ID, NTILE(3) OVER (ORDER BY SALARY_AVERAGE DESC) AS INCOME_GROUP_RANK, TO_DATE(EXTRACT(MONTH FROM CREATED_DATE) || '-' ||EXTRACT(YEAR FROM CREATED_DATE) ,'mm-yyyy') AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS NATURAL JOIN DMELISSO.ACCOUNT NATURAL JOIN DMELISSO.DISPOSITION NATURAL JOIN DMELISSO.CLIENT NATURAL JOIN DMELISSO.DISTRICT_DETAIL) T group by MONTH_INTERVAL, INCOME_GROUP_RANK ORDER BY MONTH_INTERVAL""" json_data = fetch_data_as_json(sql, 2000) return json_data @app.route('/api/getCardUsageTrendByType') def getQuery5_3Details(): sql = """ SELECT count(trans_id) as TRANS_NUM, CARD_TYPE, MONTH_INTERVAL FROM (SELECT TRANS_ID, C.TYPE AS card_type, TO_DATE(EXTRACT(MONTH FROM CREATED_DATE) || '-' ||EXTRACT(YEAR FROM CREATED_DATE), 'mm-yyyy') AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS T JOIN DMELISSO.DISPOSITION D ON D.ACCOUNT_ID = T.ACCOUNT_ID JOIN DMELISSO.CARD C ON D.DISP_ID = C.DISP_ID) T group by MONTH_INTERVAL, CARD_TYPE ORDER BY MONTH_INTERVAL""" json_data = fetch_data_as_json(sql, 1000) return json_data @app.route('/api/getTransactionTrendByAmount') def getQuery5_4Details(): sql = """ SELECT count(trans_id) as TRANS_NUM, TRANS_AMOUNT_RANK, MONTH_INTERVAL FROM ( SELECT TRANS_ID, NTILE(3) OVER (ORDER BY AMOUNT DESC) AS TRANS_AMOUNT_RANK, TO_DATE(EXTRACT(MONTH FROM CREATED_DATE) || '-' ||EXTRACT(YEAR FROM CREATED_DATE), 'mm-yyyy') AS MONTH_INTERVAL FROM DMELISSO.TRANSACTIONS NATURAL JOIN DMELISSO.ACCOUNT NATURAL JOIN DMELISSO.DISPOSITION NATURAL JOIN DMELISSO.CLIENT NATURAL JOIN DMELISSO.DISTRICT_DETAIL) T GROUP BY MONTH_INTERVAL, TRANS_AMOUNT_RANK ORDER BY MONTH_INTERVAL """ json_data = fetch_data_as_json(sql, 1000) return json_data @app.route('/api/getTransactionTrendByBalanceOfAccountHolder') def getQuery5_5Details(): sql = """ SELECT COUNT(trans_id) as TRANS_NUM, ACCOUNT_BALANCE_RANK, MONTH_INTERVAL FROM (SELECT T.TRANS_ID, ACCOUNT_BALANCE_RANK, TO_DATE(EXTRACT(MONTH FROM CREATED_DATE) || '-' ||EXTRACT(YEAR FROM CREATED_DATE) ,'mm-yyyy') AS MONTH_INTERVAL FROM (SELECT ACCOUNT_ID, NTILE(3) OVER (ORDER BY AVG_ACCOUNT_BALANCE DESC) AS ACCOUNT_BALANCE_RANK FROM (SELECT ACCOUNT_ID, AVG(BALANCE) AS AVG_ACCOUNT_BALANCE FROM DMELISSO.TRANSACTIONS group by ACCOUNT_ID)) ACCOUNT_BALANCE_DETAILS JOIN DMELISSO.TRANSACTIONS T ON ACCOUNT_BALANCE_DETAILS.ACCOUNT_ID = T.ACCOUNT_ID) E GROUP BY MONTH_INTERVAL, ACCOUNT_BALANCE_RANK ORDER BY MONTH_INTERVAL """ json_data = fetch_data_as_json(sql, 1000) return json_data <file_sep># flake8: noqa from flask import Flask # https://flask.palletsprojects.com/en/1.1.x/quickstart/ app = Flask(__name__) # Please do not modify this file, modify the modules listed below instead from api import routes_extra from api import routes_mukul from api import routes_andrei from api import routes_dimitri from api import routes_srija from api import routes_shangde <file_sep> -- select * from USER_TABLESPACES; CREATE TABLE region( region_id number NOT NULL, region_name varchar(100) NOT NULL, region_capital varchar(100) NOT NULL, region_area float NOT NULL, region_population number NOT NULL, region_gdp float NOT NULL, region_website varchar(100), latitude number, longitute number, PRIMARY KEY (region_id) ); CREATE TABLE district( district_id number NOT NULL, region_id number NOT NULL, district_name varchar(64) NOT NULL, PRIMARY KEY (district_id), FOREIGN KEY(region_id) REFERENCES region (region_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE district_detail( district_id number NOT NULL, cities number NOT NULL, salary_average float NOT NULL, ratio_urban float NOT NULL, ratio_entrepreneurs float NOT NULL, UNIQUE (district_id), FOREIGN KEY(district_id) REFERENCES district (district_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE district_population( district_id number NOT NULL, inhabitants number NOT NULL, municipalities_500 number NOT NULL, municipalities_2k number NOT NULL, municipalities_10k number NOT NULL, municipalities_10k_above number NOT NULL, UNIQUE (district_id), FOREIGN KEY(district_id) REFERENCES district (district_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE district_history( district_id number NOT NULL, year number NOT NULL, crimes number, ratio_unemployment number, UNIQUE (district_id, year), FOREIGN KEY(district_id) REFERENCES district (district_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE account ( account_id number NOT NULL, district_id number NOT NULL, frequency char(2) NOT NULL, created_date date NOT NULL, PRIMARY KEY (account_id), FOREIGN KEY(district_id) REFERENCES district (district_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE account_order ( order_id number NOT NULL, account_id number NOT NULL, bank_to char(2) NOT NULL, account_to number NOT NULL, amount decimal(10,2) NOT NULL, category char(3) NOT NULL, PRIMARY KEY (order_id), FOREIGN KEY(account_id) REFERENCES account (account_id) INITIALLY DEFERRED DEFERRABLE, FOREIGN KEY(account_to) REFERENCES account (account_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE transaction ( trans_id number NOT NULL, account_id number NOT NULL, created_date date NOT NULL, trans_type char(2) NOT NULL, -- CR+=credit, DB=-debit operation char(3) NOT NULL, amount decimal(10,2) NOT NULL, balance decimal(10,2) NOT NULL, category char(3) NOT NULL, bank_to char(2), account_to number, PRIMARY KEY (trans_id), FOREIGN KEY(account_id) REFERENCES account (account_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE client ( client_id number NOT NULL, district_id number NOT NULL, birth_date date NOT NULL, gender char(1) NOT NULL, PRIMARY KEY (client_id), FOREIGN KEY(district_id) REFERENCES district (district_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE disposition ( disp_id number NOT NULL, client_id number NOT NULL, account_id number NOT NULL, disp_type char(1) NOT NULL, PRIMARY KEY (disp_id), FOREIGN KEY(client_id) REFERENCES client (client_id) INITIALLY DEFERRED DEFERRABLE, FOREIGN KEY(account_id) REFERENCES account (account_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE card ( card_id number NOT NULL, disp_id number NOT NULL, card_type char(2) NOT NULL, issued_date date NOT NULL, PRIMARY KEY (card_id), FOREIGN KEY(disp_id) REFERENCES disposition (disp_id) INITIALLY DEFERRED DEFERRABLE ); CREATE TABLE loan ( loan_id number NOT NULL, account_id number NOT NULL, loan_date date NOT NULL, amount decimal(10, 2) NOT NULL, duration number, payments decimal(10, 2) NOT NULL, status char(1) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY(account_id) REFERENCES account (account_id) INITIALLY DEFERRED DEFERRABLE ); <file_sep>from api.main import app from api.dbutils import fetch_data_as_json <file_sep>import React, {Component} from 'react' import axios from 'axios'; import {Line} from 'react-chartjs-2'; export class LinechartQuery5Part4 extends Component { constructor(props) { super(props); this.state = {Data: {}}; } componentDidMount() { axios.get("api/getTransactionTrendByAmount") .then(res => { console.log(res); const records = res.data; /* * { "trans_num": 24, "trans_amount_rank": 1, "month_interval": "1-1993" } * */ let dates = []; let transNumHighAmount = []; let transNumMediumAmount = []; let transNumLowAmount = []; records.forEach(record => { dates.push(record.month_interval); if (record.trans_amount_rank === 1) { transNumHighAmount.push(record.trans_num); transNumMediumAmount.push(null); transNumLowAmount.push(null); } else { if (record.trans_amount_rank === 2) { transNumHighAmount.push(null); transNumMediumAmount.push(record.trans_num); transNumLowAmount.push(null); } else { transNumHighAmount.push(null); transNumMediumAmount.push(null); transNumLowAmount.push(record.trans_num); } } }); this.setState({ Data: { labels: dates, datasets: [ { label: 'Large amount transaction trend', data: transNumHighAmount, fill: false, lineTension: 0.3, backgroundColor: "rgba(225,0,0,0.4)", borderColor: "red", // The main line color borderCapStyle: 'square', borderDash: [], // try [5, 15] for instance borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "black", pointBackgroundColor: "white", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "brown", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Medium amount transaction trend', data: transNumMediumAmount, fill: false, lineTension: 0.3, backgroundColor: "rgba(167,105,0,0.4)", borderColor: "rgb(167, 105, 0)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, }, { label: 'Low amount transaction trend', data: transNumLowAmount, fill: false, lineTension: 0.3, backgroundColor: "rgba(105,167,0,0.4)", borderColor: "green", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "white", pointBackgroundColor: "black", pointBorderWidth: 1, pointHoverRadius: 8, pointHoverBackgroundColor: "brown", pointHoverBorderColor: "yellow", pointHoverBorderWidth: 2, pointRadius: 4, pointHitRadius: 10, spanGaps: true, } ] } }); }) } render() { return ( <div> <Line data={this.state.Data} options={{maintainAspectRatio: true}}/> </div> ) } } export default LinechartQuery5Part4 <file_sep>from api.main import app from api.dbutils import fetch_data sql2 = """ SELECT D.TYPE , R.REGION_NAME , count(*) AS num_accounts , TO_CHAR(A.CREATED_DATE, 'YYYY-MM') month FROM dmelisso.DISPOSITION D JOIN dmelisso.ACCOUNT A ON A.ACCOUNT_ID = A.ACCOUNT_ID JOIN dmelisso.CLIENT C ON C.CLIENT_ID = A.ACCOUNT_ID JOIN dmelisso.DISTRICT D ON D.ACCOUNT_ID = A.ACCOUNT_ID JOIN dmelisso.REGION_FULL R ON R.REGION_ID = D.REGION_ID GROUP BY D.TYPE, R.REGION_NAME, TO_CHAR(A.CREATED_DATE, 'YYYY-MM') ORDER BY D.TYPE, R.REGION_NAME, TO_CHAR(A.CREATED_DATE, 'YYYY-MM') """ @app.route('/api/getNumAccountsOpenByDispositionAndRegion') def num_accounts_for_dispositions(): # From q4 description = "Number of accounts open for disposition types (owner/disponent) and region" sql = """ SELECT R.REGION_NAME , count(*) AS num_accounts , TO_CHAR(A.CREATED_DATE, 'YYYY-MM') month FROM dmelisso.DISPOSITION D JOIN dmelisso.ACCOUNT A ON A.ACCOUNT_ID = A.ACCOUNT_ID JOIN dmelisso.CLIENT C ON C.CLIENT_ID = A.ACCOUNT_ID JOIN dmelisso.DISTRICT D ON D.ACCOUNT_ID = A.ACCOUNT_ID JOIN dmelisso.REGION_FULL R ON R.REGION_ID = D.REGION_ID WHERE D.TYPE = 'OWNER' GROUP BY TO_CHAR(A.CREATED_DATE, 'YYYY-MM') , R.REGION_NAME ORDER BY TO_CHAR(A.CREATED_DATE, 'YYYY-MM') """ json_data = fetch_data(sql, description) return json_data @app.route('/api/getNumAccountsOpenByDispositionAndRegionDisponent') def num_accounts_for_dispositions_disp(): # From q4 description = "Number of accounts open for disposition types (owner/disponent) and region" sql = """ SELECT R.REGION_NAME , count(*) AS num_accounts , TO_CHAR(A.CREATED_DATE, 'YYYY-MM') month FROM dmelisso.DISPOSITION D JOIN dmelisso.ACCOUNT A ON A.ACCOUNT_ID = A.ACCOUNT_ID JOIN dmelisso.CLIENT C ON C.CLIENT_ID = A.ACCOUNT_ID JOIN dmelisso.DISTRICT D ON D.ACCOUNT_ID = A.ACCOUNT_ID JOIN dmelisso.REGION_FULL R ON R.REGION_ID = D.REGION_ID WHERE D.TYPE = 'DISPONENT' GROUP BY TO_CHAR(A.CREATED_DATE, 'YYYY-MM') , R.REGION_NAME ORDER BY TO_CHAR(A.CREATED_DATE, 'YYYY-MM') """ json_data = fetch_data(sql, description) return json_data <file_sep> -- account CREATE INDEX district_id ON account(district_id); CREATE INDEX created_date ON account(created_date); -- transaction CREATE INDEX trans_created_date ON transaction(created_date, trans_type); CREATE INDEX trans_amount ON transaction(amount); CREATE INDEX trans_balance ON transaction(balance); CREATE INDEX trans_category ON transaction(category); -- client CREATE INDEX birth_date ON client(birth_date); -- disposition CREATE INDEX disp_type ON disposition(disp_type); -- card CREATE INDEX issued_date_card_type ON card(issued_date, card_type); -- loan CREATE INDEX loan_date ON loan(loan_date); <file_sep>-- https://stackoverflow.com/questions/1799128/oracle-if-table-exists DROP TABLE account CASCADE CONSTRAINTS; DROP TABLE account_order CASCADE CONSTRAINTS; DROP TABLE card CASCADE CONSTRAINTS; DROP TABLE client CASCADE CONSTRAINTS; DROP TABLE disposition CASCADE CONSTRAINTS; DROP TABLE district CASCADE CONSTRAINTS; DROP TABLE district_detail; DROP TABLE district_history; DROP TABLE district_population; DROP TABLE loan; DROP TABLE region CASCADE CONSTRAINTS; DROP TABLE transaction; -- for login DROP TABLE app_user; <file_sep>#!/usr/bin/env python3 """ This script is used to create the SQL tables and import the rows for the `berka` dataset Note: to add your username/password you need to copy and modify the template file first $ cp config/settings.py.template config/settings.py $ vim config/settings.py """ import utils def main(): conn = utils.get_connection_oracle() utils.load_data(conn) if __name__ == '__main__': main()
1c17ac889c3830e269afd7924201e2347667849d
[ "SQL", "Markdown", "JavaScript", "Makefile", "Python", "Text" ]
32
Markdown
indera/dbms
dc6cf1a93cc0d8b314d6737a29b89791ee47d56a
8171e400203d54744474281c21e92397b2470745
refs/heads/master
<file_sep>a=[2,2] def fun(): a.append(2) fun() print(a)<file_sep># Car-Price-Prediction-Streamlit A Car Price Prediction web app based on Random Forest Regressor created using Streamlit. <br> The web app can be used to predict the market value for used cars that can help both buyers and sellers.<br><br> For more details about the dataset check out [here](https://www.kaggle.com/nehalbirla/vehicle-dataset-from-cardekho) <br><br> You can check out the web app [here](https://car-price-prediction-streamlit.herokuapp.com/)! ## Snapshots ![](https://github.com/Amal4m41/Car-Price-Prediction-Streamlit/blob/master/carPriceStreamlit.png) <file_sep># 1. Library imports from os import name from numpy.core import numeric import streamlit as st import datetime # import pandas as pd, numpy as np, import pickle from streamlit.proto.NumberInput_pb2 import NumberInput mRegressorModel=None #De-serializing def deserializeAndLoadModel(): global mRegressorModel with open('random_forrest_regression_model.pkl','rb') as f: mRegressorModel=pickle.load(f) # year=1&present_price=2&kms=3&fuel_type=cng&owner=dealer&transmission=manual # present_price: float = Form(...), kms: float = Form(...),fuel_type: str = Form(...), seller: str = Form(...),transmission:str = Form(...), owner: str = Form(...) def predict_output(yearOfPurchase,present_price,kms,fuelCheckedValue,sellerCheckedValue,transmissionCheckedValue,ownerCheckedValue): Kms_Driven=kms Owner=[0 if(ownerCheckedValue=='First Owner') else 1 ] Seller_Type_Individual=[1 if(sellerCheckedValue=='Individual') else 0 ] Age=datetime.datetime.now().year-yearOfPurchase fuel=[1 if(i==fuelCheckedValue) else 0 for i in ['Diesel','Petrol']] #[0 0] means fuel is of type CNG Transmission_Manual=[1 if(transmissionCheckedValue=='Manual') else 0 ] # Present_Price Kms_Driven,Owner,Age,Fuel_Type_Diesel,Fuel_Type_Petrol,Seller_Type_Individual,Transmission_Manual lst=[present_price,Kms_Driven]+Owner+[Age]+fuel+Seller_Type_Individual+Transmission_Manual # print(lst) predicted_val=mRegressorModel.predict([lst])[0] #2d list # print(predicted_val) #it's a list of length 1 return predicted_val def main(): deserializeAndLoadModel() currentYear=datetime.datetime.now().year st.title("Car Price Prediction") html_code=""" <div style="background-color:purple;padding:10px"> <h2 style="color:white;text-align:center">Streamlit Car Price Prediction ML App</h2> </div><br><br> """ st.markdown(html_code,unsafe_allow_html=True) # yearOfPurchase=st.text_input("Year Of Purchase","eg: "+str(currentYear)) yearOfPurchase=st.number_input("Year Of Purchase",value=currentYear,min_value=1950) presentPrice=st.number_input("Present Price(in lakhs)",help="Price in lakhs",min_value=0.5,value=1.0) kmsDriven=st.number_input("KMS Driven",min_value=0.0,value=0.0) fuelTypes=["Petrol","Diesel","CNG"] fuelCheckedValue=st.radio("Fuel Type ",fuelTypes,index=0) #setting the first option to be checked by default # st.write(fuelCheckedValue) # if(fuelCheckedValue=="CNG"): # st.write("Great Choice") sellerTypes=["Individual","Dealer"] sellerCheckedValue=st.radio("Seller ",sellerTypes,index=0) #setting the first option to be checked by default # st.write(sellerCheckedValue) transmissionTypes=["Manual","Automatic"] transmissionCheckedValue=st.radio("Transmission ",transmissionTypes,index=0) #setting the first option to be checked by default # st.write(ownerCheckedValue) ownerTypes=["First Owner","Second Owner"] ownerCheckedValue=st.radio("Owner ",ownerTypes,index=0) #setting the first option to be checked by default # st.write(ownerCheckedValue) if st.button("Calculate Selling Price"): # st.write([yearOfPurchase,presentPrice,kmsDriven,fuelCheckedValue,sellerCheckedValue,transmissionCheckedValue,ownerCheckedValue]) predictedValueForSellingPrice=predict_output(yearOfPurchase,presentPrice,kmsDriven,fuelCheckedValue,sellerCheckedValue,transmissionCheckedValue,ownerCheckedValue) st.success("Predicted Selling Price in Lakhs : "+ str(int((predictedValueForSellingPrice*10000))/10000)) #limiting to 4 decimal places if __name__=="__main__": main()
cbc67ee0cbf9f4d233440523b56894becb9b4efd
[ "Markdown", "Python" ]
3
Python
Amal4m41/Car-Price-Prediction-Streamlit
20a4495675bcaa80efaa66da33cd221a3d4e1661
4679c2343996f1a76ee53c2458bc713eaae53583
refs/heads/master
<repo_name>chayao2015/break_captcha<file_sep>/training.py #! /usr/bin/env python # -*- coding: utf-8 -*- """ @Author: _defined @Time: 2019/8/12 19:02 @Description: """ import os import tensorflow as tf import numpy as np from tensorflow.python.ops.ctc_ops import (ctc_loss, ctc_beam_search_decoder) from settings import (config, DataMode) from DataLoader import DataLoader from model import build_model from logger import event_logger SVAED_MODEL_DIR = './savedModel/{}'.format(config.dataset) if not os.path.exists(SVAED_MODEL_DIR): os.makedirs(SVAED_MODEL_DIR) CHECKPOINT_DIR = './checkpoints/{}'.format(config.dataset) if not os.path.exists(CHECKPOINT_DIR): os.makedirs(CHECKPOINT_DIR) def train(): """ train model :return: """ model, base_model, seq_step_len = build_model() print('seq_step_len ', seq_step_len) train_dataset = DataLoader(DataMode.Train).load_batch_from_tfrecords() val_dataset = DataLoader(DataMode.Val).load_batch_from_tfrecords() latest_ckpt = tf.train.latest_checkpoint(CHECKPOINT_DIR) start_epoch = 0 if latest_ckpt: start_epoch = int(latest_ckpt.split('-')[1].split('.')[0]) print('start epoch at ', start_epoch) model.load_weights(latest_ckpt) event_logger.info('model resumed from: {}, start at epoch: {}'.format(latest_ckpt, start_epoch)) else: event_logger.info('passing resume since weights not there. training from scratch') def _validation(): """ validate the model's acc :return: acc """ _val_losses = [] _val_accuracy = [] for _batch, _data in enumerate(val_dataset): _images, _labels = _data _input_length = np.array(np.ones(len(_images)) * int(seq_step_len)) _label_length = np.array(np.ones(len(_images)) * config.max_seq_len) _loss = model.evaluate([_images, _labels, _input_length, _label_length], _labels, verbose=0) _acc = _compute_acc(_images, _labels, _input_length) _val_losses.append(_loss) _val_accuracy.append(_acc) return np.mean(_val_losses), np.mean(_val_accuracy) def _compute_acc(_images, _labels, _input_length): """ :param _images: a batch of image, [samples, w, h, c] :param _labels: :param _input_length: :return: acc """ _y_pred = base_model.predict_on_batch(x=_images) # print(_y_pred) # (64, 9, 37) _decoded_dense, _ = tf.keras.backend.ctc_decode(_y_pred, _input_length, greedy=True, beam_width=5, top_paths=1) _error_count = 0 for pred, real in zip(_decoded_dense[0], _labels): str_real = ''.join([config.characters[x] for x in real if x != -1]) str_pred = ''.join([config.characters[x] for x in pred if x != -1]) # print(str_real, str_pred) if str_pred != str_real: _error_count += 1 _acc = (len(_labels) - _error_count) / len(_labels) return _acc # start training progress for epoch in range(start_epoch, config.epochs): for batch, data in enumerate(train_dataset): images, labels = data input_length = np.array(np.ones(len(images)) * int(seq_step_len)) label_length = np.array(np.ones(len(images)) * config.max_seq_len) train_loss = model.train_on_batch(x=[images, labels, input_length, label_length], y=labels) # logging result every 10-batch. (about 10 * batch_size images) if batch % 10 == 0: train_acc = _compute_acc(images, labels, input_length) val_loss, val_acc = _validation() print('Epoch: [{epoch}/{epochs}], iter: {batch}, train_loss: {train_loss}, train_acc: {train_acc}, ' 'val_loss: {val_loss}, val_acc: {val_acc}'.format(epoch=epoch + 1, epochs=config.epochs, batch=batch, train_loss=train_loss, train_acc=train_acc, val_loss=val_loss, val_acc=val_acc)) ckpt_path = os.path.join(CHECKPOINT_DIR, 'CRNNORC-{epoch}'.format(epoch=epoch + 1)) model.save_weights(ckpt_path) base_model.save(os.path.join(SVAED_MODEL_DIR, '{}_model.h5'.format(config.dataset))) if __name__ == '__main__': train() <file_sep>/README.md # Break Captcha ## 如何使用 - 首先安装依赖的包`pip install -r requirements.txt` 需要注意的是,这里使用的是`tensorflow 2.0`, 需要使用较新的`cuda`和`cudnn`。我的环境使用的是`cuda 10` 以及`cudnn 7.5 `。供大家参考。 - 需要在`congig.yaml`文件中配置好相关参数,包括数据集名称、路径,所需的数据预处理操作以及训练使用的模型。 - `python make_dataset.py`创建tfrecord文件,然后执行`python training.py`开始训练。 <file_sep>/model.py #! /usr/bin/env python # -*- coding: utf-8 -*- """ @Author: _defined @Time: 2019/8/6 16:38 @Description: """ import os from tensorflow.python.keras.layers import * from tensorflow.python.keras.optimizers import Adam from tensorflow.python.keras.models import Model from tensorflow.python.keras.regularizers import l2 from tensorflow.python.keras import backend as K from tensorflow.python.keras.utils import plot_model from networks import ( ResNet50, CNN5, BiGRU, BiLSTM ) from settings import config __all__ = ['build_model'] def ctc_lambda_func(args): y_pred, labels, input_length, label_length = args # the 2 is critical here since the first couple outputs of the RNN tend to be garbage y_pred = y_pred[:, :, :] return K.ctc_batch_cost(labels, y_pred, input_length, label_length) def build_model(): """ build CNN-RNN model :return: """ cnn_type = config.cnn if config.cnn in ['CNN5', 'ResNet50'] else 'CNN5' rnn_type = config.rnn if config.rnn in ['BiGRU', 'BiLSTM'] else 'BiLSTM' input_shape = (config.resize[0], config.resize[1], config.channel) inputs = Input(shape=input_shape) # CNN layers x = CNN5(inputs) if cnn_type == 'CNN5' else ResNet50(inputs) conv_shape = x.get_shape() x = Reshape(target_shape=(int(conv_shape[1]), int(conv_shape[2] * conv_shape[3])))(x) # concat Bi-RNN layers to encode and decode sequence x = BiLSTM(x, use_gpu=config.use_gpu) if rnn_type == 'BiLSTM' else BiGRU(x, use_gpu=config.use_gpu) predictions = TimeDistributed(Dense(config.n_class, kernel_initializer='he_normal', activation='softmax'))(x) base_model = Model(inputs=inputs, outputs=predictions) # CTC_loss labels = Input(name='the_labels', shape=[config.max_seq_len, ], dtype='float32') input_length = Input(name='input_length', shape=[1], dtype='int64') label_length = Input(name='label_length', shape=[1], dtype='int64') loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')( [predictions, labels, input_length, label_length]) model = Model(inputs=[inputs, labels, input_length, label_length], outputs=[loss_out]) model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=Adam(lr=1e-4)) if not os.path.exists('./plotModel'): os.makedirs('./plotModel') plot_model(model, './plotModel/{}-{}_model.png'.format(cnn_type, rnn_type), show_shapes=True) plot_model(base_model, './plotModel/{}-{}_base_model.png'.format(cnn_type, rnn_type), show_shapes=True) return model, base_model, int(conv_shape[1])
25eca190b570efb29d3c517d0a114089263582fb
[ "Markdown", "Python" ]
3
Python
chayao2015/break_captcha
1e6a4fbdf246ef21d41ae6d7bac0282b17575cdf
78cc865ea4fb16140d6919afeac41f07e54e3cae
refs/heads/main
<repo_name>NivinAnil/gitandgithub<file_sep>/sdmwork.py print("sdm work")<file_sep>/README.md # CUSAT Workshop # Prerequisites - Signup for https://github.com/ - [Fork below repository](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) https://github.com/sarithdm/gitandgithub # Linux Users/Linux users with Windows Subsystem for Linux 1. Install git sudo apt update sudo apt install git 2. Clone repository git clone https://github.com/Your-Github-Username/gitandgithub.git 3. Go to the directory gitandgithub, add a sample file and run following commands git add . git commit -m "My Work" git push 4. You will be asked to authenticate Enter username and password of Github account. Check for your file in https://github.com/Your-Github-Username/gitandgithub If you are able to see it, Prerequisites is completed # Windows Users with Visual Studio Code 1. Install https://code.visualstudio.com/ 2. Clone repository git clone https://github.com/Your-Github-Username/gitandgithub.git 3. You can add new file to your repository and save. E.g mywork.py 4. Go to the directory gitandgithub, add a sample file and run following commands git add . git commit -m "My Work" git push 5. You will be asked to authenticate Option 1: Directly sign in with browser Option 2: Got to Settings > Developer settings > Personal access tokens Create a new token and paste it. Sample token: <KEY>9 Check for your file in https://github.com/Your-Github-Username/gitandgithub If you are able to see it, Prerequisites is completed <file_sep>/commands.md # Commands git add . git commit -m "Adding to the repository" git push git pull git branch git checkout -b branch1 git push --set-upstream origin branch1 git merge branch1 To set your global username/email configuration: git config --global user.name "<NAME>" git config --global user.email "<EMAIL>" To set repository-specific username/email configuration: git config user.name "<NAME>" git config user.email "<EMAIL>" Verify your configuration by displaying your configuration file: cat .git/config <file_sep>/program.py mylist = [1,2,3,4] for item in mylist: print(item) print("Adding this line to Python") print("Next Line")
90c97f4c99b1b968eca501ad49d1824a4542bb19
[ "Markdown", "Python" ]
4
Python
NivinAnil/gitandgithub
fd8231133ef31e634873a2f6a28cb7e41b1d71f9
dc37d3a63a123e93f80e74072d662a46bce54f3f
refs/heads/master
<file_sep>package Stage2; public class EnemyBase { //동물의 공격을 받으면 체력이 깍인다. int strength = 100; } <file_sep>package Stage2; public class Jingjing extends Enemy{ @Override public void enemyInitialize() { strength = 7; speed = 20; attackInterval = 700; attackPower = 1; enemyKind = "jingjing"; ImageURL = "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\animal VS enemy\\jingjing.png"; } } <file_sep>package Stage2; public class EnemyAttack extends Thread { boolean running = true; int enemyNum = 0; int attackPower = 0; int attackInterval = 0; int whatNum = 0; Thread enemyMove; String animalKind = ""; String enemyKind = ""; EnemyAttackInterval enemyAttackInterval; EnemyAttack(int enemyNum, int attackPower, int attackInterval, String enemyKind, Thread enemyMove) { this.enemyNum = enemyNum; this.attackPower = attackPower; this.attackInterval = attackInterval; this.enemyKind = enemyKind; this.enemyMove = enemyMove; } @Override public void run() { while (running) { try { if (Animal_VS_Enemy.enemyImage.get(enemyNum).getX() <= Animal_VS_Enemy.ANIMALBASE_X) { // 해적의 x이 0이 아닌데 0으로 출력되고 적의 기지쪽에서 해적이 멈추는 오류가 있어 예외처리하기 위한 코드 if (Animal_VS_Enemy.enemyImage.get(enemyNum).getX() != 0) { // 동물 기지의 체력을 깍는다. 기지는 동물번호나 적의 번호가 필요없기 때문에 0을 넣어두었다. if (enemyAttackInterval == null) { enemyAttackInterval = new EnemyAttackInterval(enemyNum, 0, attackPower, Animal_VS_Enemy.animalBase.strength, attackInterval, "동물기지"); enemyAttackInterval.start(); } } } if(enemyKind == "jingjing" || enemyKind == "bandit" || enemyKind == "piracy") { for (int i = 0; i < Animal_VS_Enemy.animalImage.size(); i++) { try { // 동물이 범위 안에 들어왔을 때 if (Animal_VS_Enemy.enemyImage.get(enemyNum).getX() <= Animal_VS_Enemy.animalImage.get(i).getX() + 15 && Animal_VS_Enemy.enemyImage.get(enemyNum).getX() >= Animal_VS_Enemy.animalImage.get(i).getX() - 10) { // System.out.println("동물이 범위 안에 들어옴"); // 해당 동물의 체력을 깍는다. // i의 클래스가 돼지라면 몇번째 돼지인지 찾고 그 돼지의 체력을 감소시킨다 whatNum = 0; if ((Animal_VS_Enemy.animalList.get(i).getClass()).toString() .equals("class Stage2.Pig")) { for (int j = 0; j < i; j++) { if (Animal_VS_Enemy.animalList.get(j).getClass().toString() .equals("class Stage2.Pig")) { whatNum++; } } animalKind = Animal_VS_Enemy.pigList.get(whatNum).animalKind; } else if ((Animal_VS_Enemy.animalList.get(i).getClass()).toString() .equals("class Stage2.Rabbit")) { for (int j = 0; j < i; j++) { if (Animal_VS_Enemy.animalList.get(j).getClass().toString() .equals("class Stage2.Rabbit")) { whatNum++; } } animalKind = Animal_VS_Enemy.rabbitList.get(whatNum).animalKind; } else if ((Animal_VS_Enemy.animalList.get(i).getClass()).toString() .equals("class Stage2.Chick")) { for (int j = 0; j < i; j++) { if (Animal_VS_Enemy.animalList.get(j).getClass().toString() .equals("class Stage2.Chick")) { whatNum++; } } animalKind = Animal_VS_Enemy.chickList.get(whatNum).animalKind; } else if ((Animal_VS_Enemy.animalList.get(i).getClass()).toString() .equals("class Stage2.Goat")) { for (int j = 0; j < i; j++) { if (Animal_VS_Enemy.animalList.get(j).getClass().toString() .equals("class Stage2.Goat")) { whatNum++; } } animalKind = Animal_VS_Enemy.goatList.get(whatNum).animalKind; } if (enemyAttackInterval == null) { enemyAttackInterval = new EnemyAttackInterval(enemyNum, i, attackPower, whatNum, attackInterval, animalKind); enemyAttackInterval.start(); } }else if(enemyAttackInterval != null){ enemyAttackInterval = null; sleep(800); } } catch (IndexOutOfBoundsException f) { // System.out.println("범위내에 동물이 없습니다."); } if (Animal_VS_Enemy.enemyImage.get(enemyNum).getX() <= Animal_VS_Enemy.minimiImage[i].getX() + 10 && Animal_VS_Enemy.enemyImage.get(enemyNum).getX() >= Animal_VS_Enemy.minimiImage[i].getX() - 10) { Animal_VS_Enemy.minimiImage[i].setLocation(-500, -500); } } } synchronized (this) { if (Animal_VS_Enemy.enemyImage.get(enemyNum).getX() == 1500 && Animal_VS_Enemy.enemyImage.get(enemyNum).getY() == 1500) { //System.out.println("쓰레드 종료 적 죽음"); wait(); } } Thread.sleep(100); } catch (InterruptedException e) { running = false; } } } } <file_sep>package Stage2; public class Rabbit extends Animal{ @Override public void animalInitialize() { strength = 15; speed = 30; attackInterval = 800; attackPower = 1; animalKind = "rabbit"; ImageURL = "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\animal VS enemy\\rabbit.png"; } } <file_sep>package Stage2; import java.util.Random; public class AnimalMove extends Thread { Random random = new Random(); int speed = 0; int animalNum = 0; String animalKind = ""; boolean running = true; boolean isMoveOnce = false;//염소를 움직일 때 사용 AnimalMove(int animalNum, int speed, String animalKind) { this.animalNum = animalNum; this.speed = speed; this.animalKind = animalKind; } @Override public void run() { Animal_VS_Enemy.animalImage.get(animalNum).setLocation(60, 400); Animal_VS_Enemy.animalhealthBarImage.get(animalNum).setLocation(60, 380); synchronized (this) { while (running) { try { if(animalKind == "rabbit" || animalKind == "pig" || animalKind == "chick") { Animal_VS_Enemy.animalImage.get(animalNum).setLocation(Animal_VS_Enemy.animalImage.get(animalNum).getX() + 5, 400); Animal_VS_Enemy.animalhealthBarImage.get(animalNum).setLocation(Animal_VS_Enemy.animalImage.get(animalNum).getX() + 10, 380); //적기지 근처에 도착한 후 if (Animal_VS_Enemy.animalImage.get(animalNum).getX() >= Animal_VS_Enemy.ENEMYBASE_X) { //적기지가 무너진 상태가 아니라면 if(Animal_VS_Enemy.enemyBaseImage.getX() != 1500) { //쓰레드를 일정시간동안 멈춘다 wait(10000); } } } if(animalKind == "pig" || animalKind == "chick") { for (int i = 0; i < Animal_VS_Enemy.enemyImage.size(); i++) { // 적이 범위 안에 들어왔을 때 if (Animal_VS_Enemy.animalImage.get(animalNum).getX() >= Animal_VS_Enemy.enemyImage.get(i).getX() - 15 && Animal_VS_Enemy.animalImage.get(animalNum).getX() <= Animal_VS_Enemy.enemyImage.get(i).getX() + 5) { wait(3000); } } } if(animalKind == "goat") { if (isMoveOnce == false) { Animal_VS_Enemy.animalImage.get(animalNum).setLocation(Animal_VS_Enemy.animalImage.get(animalNum).getX() + random.nextInt(50), 400); Animal_VS_Enemy.animalhealthBarImage.get(animalNum).setLocation(Animal_VS_Enemy.animalImage.get(animalNum).getX(), 380); isMoveOnce = true; } } //동물이 죽은 장소에 있었을 때 if (Animal_VS_Enemy.animalImage.get(animalNum).getX() == -500 && Animal_VS_Enemy.animalImage.get(animalNum).getY() == -500) { wait(); } Thread.sleep(speed); } catch (InterruptedException e) { running = false; } } } } } <file_sep>package Stage2; public class Goat extends Animal{ int attackSpeed = 0; @Override public void animalInitialize() { strength = 5; speed = 100; attackInterval = 5000; attackPower = 1; attackSpeed = 80; animalKind = "goat"; ImageURL = "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\animal VS enemy\\goat.png"; Bullets.bulletsNum++; BulletMove.totalBulletsNum = BulletMove.totalBulletsNum + Bullets.NUM_OF_BULLETS; } } <file_sep>package Stage2; public abstract class Enemy { int strength = 0; int speed = 0; int attackPower = 0; int attackInterval = 0; String enemyKind = ""; String ImageURL = ""; public abstract void enemyInitialize(); } <file_sep>package Stage1; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import Stage2.main; public class Vegetable_VS_Enemy { GameVictory gameVictory = new GameVictory(10);// 적의 수를 인수로 두었다. GameOver gameOver = new GameOver(); IncreaseMana IncreaseMana = new IncreaseMana(); static SpawnEnemy SpawnEnemy = new SpawnEnemy(); static int[] vegetableX = new int[100]; static int[] vegetableY = new int[100]; final int TILE_WIDTH = 67; final int TILE_HEIGHT = 84; int tileHorizontalLength = 223; int tileVerticalLength = 79; int tileInterval = 70; // 타일 간격 static int mana = 30; String selectedVegetables = ""; String vegetableImageURL = ""; public JFrame frame; static JPanel Stage1GameScene = new JPanel() { public void paintComponent(Graphics g) { Dimension d = getSize(); ImageIcon image = new ImageIcon("./image/vegetableVSenemyBackGround.PNG"); g.drawImage(image.getImage(), 0, 0, d.width, d.height, this); } }; static JPanel gameVictoryScene = new JPanel(); static JPanel gameOverScene = new JPanel(); JButton[] tile = new JButton[45]; JButton cabbageButton = new JButton(); JButton carrotButton = new JButton(); JButton eggplantButton = new JButton(); JButton beetButton = new JButton(); JButton redbeetButton = new JButton(); JButton gameStartButton = new JButton(); JButton NextRoundButton = new JButton(); JButton robbyButton = new JButton(); JButton exitText = new JButton(); static JLabel manaText = new JLabel(); static JLabel[] bulletImage = new JLabel[500]; static JLabel[] enemyImage = new JLabel[10]; static JLabel[] healthBarBackground = new JLabel[10]; static JLabel[] healthBarImage = new JLabel[10]; JLabel stageText = new JLabel(); JLabel gameVictoryImage = new JLabel(); JLabel victoryText = new JLabel(); JLabel gameOverImage = new JLabel(); JLabel reasonLosingText = new JLabel(); public void vegetableVSenemy() { frame = new JFrame(); frame.setBounds(100, 100, 1200, 700); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Save Garden"); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.getContentPane().setLayout(null); Stage1GameScene.setBounds(0, 0, 1196, 672); frame.getContentPane().add(Stage1GameScene); Stage1GameScene.setLayout(null); stageText.setText("Stage 1"); stageText.setFont(new Font("굴림", Font.BOLD, 30)); stageText.setHorizontalAlignment(SwingConstants.CENTER); stageText.setBounds(811, 10, 223, 68); Stage1GameScene.add(stageText); manaText.setText("마나 : " + mana); manaText.setHorizontalAlignment(SwingConstants.CENTER); manaText.setFont(new Font("굴림", Font.BOLD, 20)); manaText.setBounds(993, 25, 179, 44); Stage1GameScene.add(manaText); // 적 이미지 초기화 for (int i = 0; i < enemyImage.length; i++) { Stage1GameScene.add(enemyImage[i] = new JLabel()); enemyImage[i].setBounds(870, 1000, 100, 100); } // 체력바 초기화 for (int i = 0; i < healthBarBackground.length; i++) { Stage1GameScene.add(healthBarImage[i] = new JLabel()); healthBarImage[i].setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\healthbar_red.png")); healthBarImage[i].setBounds(2000, 2000, 36, 4); Stage1GameScene.add(healthBarBackground[i] = new JLabel()); healthBarBackground[i].setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\healthbar_white.png")); healthBarBackground[i].setBounds(2000, 2000, 36, 4); } // 총알 초기화 for (int i = 0; i < bulletImage.length; i++) { Stage1GameScene.add(bulletImage[i] = new JLabel()); bulletImage[i].setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\cabbageBullet.png")); bulletImage[i].setBounds(-500, -500, 12, 12); } // 타일 초기화 for (int i = 0; i < tile.length; i++) { Stage1GameScene.add(tile[i] = new JButton()); if (i < 9) { tileVerticalLength = 79; tile[i].setBounds(tileHorizontalLength, tileVerticalLength, TILE_WIDTH, TILE_HEIGHT); } else if ((i >= 9) && (i < 18)) { tileVerticalLength = 170; tile[i].setBounds(tileHorizontalLength, tileVerticalLength, TILE_WIDTH, TILE_HEIGHT); } else if ((i >= 18) && (i < 27)) { tileVerticalLength = 254; tile[i].setBounds(tileHorizontalLength, tileVerticalLength, TILE_WIDTH, TILE_HEIGHT); } else if ((i >= 27) && (i < 36)) { tileVerticalLength = 342; tile[i].setBounds(tileHorizontalLength, tileVerticalLength, TILE_WIDTH, TILE_HEIGHT); } else if ((i >= 36) && (i < 45)) { tileVerticalLength = 430; tile[i].setBounds(tileHorizontalLength, tileVerticalLength, TILE_WIDTH, TILE_HEIGHT); } tileHorizontalLength = tileInterval + tileHorizontalLength; tile[i].setFocusPainted(false); tile[i].setContentAreaFilled(false); tile[i].setBorderPainted(false); if ((i + 1) % 9 == 0) { tileHorizontalLength = 223; } } // 채소 생성버튼 cabbageButton.setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\cabbage.png")); cabbageButton.setBounds(12, 588, 103, 58); cabbageButton.setFocusPainted(false); cabbageButton.setContentAreaFilled(false); cabbageButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedVegetables = "cabbage"; } }); Stage1GameScene.add(cabbageButton); carrotButton.setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\carrot.png")); carrotButton.setBounds(137, 588, 103, 58); carrotButton.setFocusPainted(false); carrotButton.setContentAreaFilled(false); carrotButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedVegetables = "carrot"; } }); Stage1GameScene.add(carrotButton); beetButton.setIcon( new ImageIcon("C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\beat.png")); beetButton.setBounds(265, 588, 103, 58); beetButton.setFocusPainted(false); beetButton.setContentAreaFilled(false); beetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedVegetables = "beet"; } }); Stage1GameScene.add(beetButton); redbeetButton.setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\redbeet.png")); redbeetButton.setBounds(395, 588, 103, 58); redbeetButton.setFocusPainted(false); redbeetButton.setContentAreaFilled(false); redbeetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedVegetables = "redbeet"; } }); Stage1GameScene.add(redbeetButton); eggplantButton.setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\eggplant.png")); eggplantButton.setBounds(528, 588, 103, 58); eggplantButton.setFocusPainted(false); eggplantButton.setContentAreaFilled(false); eggplantButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedVegetables = "eggplant"; } }); Stage1GameScene.add(eggplantButton); // 채소 선택 버튼을 누른 후 타일을 선택하면 선택한 타일에 해당 채소가 생성된다. for (int i = 0; i < tile.length; i++) { tile[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 현재 마나의 수가 채소 생성에 필요한 최소 마나의 수보다 적으면 생성하지 못한다. if (mana >= 7) { if (selectedVegetables == "cabbage") { Cabbage cabbage = new Cabbage(); cabbage.plantiInitialize(); vegetableImageURL = cabbage.ImageURL; cabbage.attack(); cabbage.instalPlants(); } else if (selectedVegetables == "carrot") { Carrot carrot = new Carrot(); carrot.plantiInitialize(); vegetableImageURL = carrot.ImageURL; carrot.attack(); carrot.instalPlants(); } else if (selectedVegetables == "beet") { Beet beet = new Beet(); beet.plantiInitialize(); vegetableImageURL = beet.ImageURL; beet.attack(); beet.instalPlants(); } else if (selectedVegetables == "redbeet") { Redbeet redbeet = new Redbeet(); redbeet.plantiInitialize(); vegetableImageURL = redbeet.ImageURL; redbeet.attack(); redbeet.instalPlants(); } else if (selectedVegetables == "eggplant") { Eggplant eggplant = new Eggplant(); eggplant.plantiInitialize(); vegetableImageURL = eggplant.ImageURL; eggplant.attack(); eggplant.instalPlants(); } for (int i = 0; i < tile.length; i++) { if (e.getSource() == tile[i]) { if (tile[i].getIcon() == null) { // 선택한 타일에 채소 이미지가 들어간다 tile[i].setIcon(new ImageIcon(vegetableImageURL)); // 타일의 좌표값을 구한다 (총알의 위치를 선정하기 위해). vegetableX[Bullets.bulletsNum] = tile[i].getX(); vegetableY[Bullets.bulletsNum] = tile[i].getY(); manaText.setText("마나 : " + mana); } else { // System.out.println("이미 채소가 있습니다"); } } } } } }); } gameStartButton.setText("게임 준비 완료"); gameStartButton.setFont(new Font("굴림", Font.BOLD, 15)); gameStartButton.setBounds(12, 10, 138, 42); gameStartButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { gameStartButton.setVisible(false); SpawnEnemy.start(); IncreaseMana.start(); gameVictory.start(); gameOver.start(); } }); Stage1GameScene.add(gameStartButton); // 게임 승리 씬 gameVictoryScene.setBounds(0, 0, 1196, 672); frame.getContentPane().add(gameVictoryScene); gameVictoryScene.setLayout(null); NextRoundButton.setText("다음 라운드로 가기"); NextRoundButton.setFont(new Font("굴림", Font.BOLD, 20)); NextRoundButton.setBounds(300, 500, 300, 60); gameVictoryScene.add(NextRoundButton); robbyButton.setText("로비로 가기"); robbyButton.setFont(new Font("굴림", Font.BOLD, 20)); robbyButton.setBounds(650, 500, 300, 60); robbyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { main lobby = new main(); lobby.lobby(); lobby.frame.setVisible(true); } }); gameVictoryScene.add(robbyButton); gameVictoryImage.setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\GameSuccess.png")); gameVictoryImage.setHorizontalAlignment(SwingConstants.CENTER); gameVictoryImage.setBounds(22, 129, 1162, 230); gameVictoryScene.add(gameVictoryImage); victoryText.setText("당신은 집을 무사히 지켰습니다"); victoryText.setFont(new Font("굴림", Font.BOLD, 20)); victoryText.setHorizontalAlignment(SwingConstants.CENTER); victoryText.setBounds(0, 369, 1196, 121); gameVictoryScene.add(victoryText); // 게임 오버 씬 gameOverScene.setBounds(0, 0, 1196, 672); frame.getContentPane().add(gameOverScene); gameOverScene.setLayout(null); gameOverImage.setIcon(new ImageIcon( "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\game_over.png")); gameOverImage.setHorizontalAlignment(SwingConstants.CENTER); gameOverImage.setBounds(373, 5, 450, 368); gameOverScene.add(gameOverImage); exitText.setText("게임종료"); exitText.setForeground(Color.GRAY); exitText.setFont(new Font("굴림", Font.BOLD, 20)); exitText.setBounds(385, 569, 426, 68); exitText.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); gameOverScene.add(exitText); reasonLosingText.setText("당신은 집을 지키지 못했습니다."); reasonLosingText.setFont(new Font("굴림", Font.BOLD, 20)); reasonLosingText.setHorizontalAlignment(SwingConstants.CENTER); reasonLosingText.setBounds(0, 424, 1196, 83); gameOverScene.add(reasonLosingText); // 게임 시작시 화면 Stage1GameScene.setVisible(true); gameVictoryScene.setVisible(false); gameOverScene.setVisible(false); } } <file_sep>package Stage1; import java.util.ArrayList; public class Beet extends Vegetable{ // Beet의 특징 - 총알의 속도는 느리지만 발사 간격이 좁다. ArrayList<Bullets> beetbullets = new ArrayList<Bullets>(); @Override public void plantiInitialize() { attackSpeed = 80; attackInterval = 1300; necessaryMana = 5; Plants = "beet"; ImageURL = "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\beat.png"; } @Override public void attack() { Bullets beetBullets = new Bullets(attackSpeed,attackInterval); beetbullets.add(beetBullets); beetBullets.start(); Bullets.bulletsNum++; BulletMove.totalBulletsNum = BulletMove.totalBulletsNum + Bullets.NUM_OF_BULLETS; } } <file_sep>package Stage2; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JLabel; public class SpawnEnemy extends Thread { Random random = new Random(); boolean running = true; int randomEnemy = 0; int randomSpawnTime = 0; int minTime = 6000; int maxTime = 10000; static int enemyNum = 0; String enemyImageURL = ""; @Override synchronized public void run() { while (running) { try { randomEnemy = random.nextInt(4); randomSpawnTime = random.nextInt(maxTime - minTime + 1) + minTime; Thread.sleep(randomSpawnTime); Animal_VS_Enemy.enemyImage.add(new JLabel()); Animal_VS_Enemy.enemyhealthBarImage.add(new JLabel()); if (randomEnemy == 0) { Bandit bandit = new Bandit(); bandit.enemyInitialize(); Animal_VS_Enemy.enemyList.add(bandit); Animal_VS_Enemy.banditList.add(bandit); enemyImageURL = bandit.ImageURL; EnemyMove enemyMove = new EnemyMove(enemyNum, bandit.speed, bandit.enemyKind); enemyMove.start(); EnemyAttack enemyAttack = new EnemyAttack(enemyNum, bandit.attackPower, bandit.attackInterval, bandit.enemyKind, enemyMove); enemyAttack.start(); } else if (randomEnemy == 1) { Piracy piracy = new Piracy(); piracy.enemyInitialize(); Animal_VS_Enemy.enemyList.add(piracy); Animal_VS_Enemy.piracyList.add(piracy) ; enemyImageURL = piracy.ImageURL; EnemyMove enemyMove = new EnemyMove(enemyNum, piracy.speed, piracy.enemyKind); enemyMove.start(); EnemyAttack enemyAttack = new EnemyAttack(enemyNum, piracy.attackPower, piracy.attackInterval, piracy.enemyKind,enemyMove); enemyAttack.start(); } else if (randomEnemy == 2) { Jingjing jingjing = new Jingjing(); jingjing.enemyInitialize(); Animal_VS_Enemy.enemyList.add(jingjing); Animal_VS_Enemy.jingjingList.add(jingjing); enemyImageURL = jingjing.ImageURL; EnemyMove enemyMove = new EnemyMove(enemyNum, jingjing.speed, jingjing.enemyKind); enemyMove.start(); EnemyAttack enemyAttack = new EnemyAttack(enemyNum, jingjing.attackPower, jingjing.attackInterval, jingjing.enemyKind, enemyMove); enemyAttack.start(); } else if (randomEnemy == 3) { Thief thief = new Thief(); thief.enemyInitialize(); Animal_VS_Enemy.enemyList.add(thief); Animal_VS_Enemy.thiefList.add(thief); enemyImageURL = thief.ImageURL; EnemyMove enemyMove = new EnemyMove(enemyNum, thief.speed, thief.enemyKind); enemyMove.start(); EnemyAttack enemyAttack = new EnemyAttack(enemyNum, thief.attackPower, thief.attackInterval, thief.enemyKind, enemyMove); enemyAttack.start(); } Animal_VS_Enemy.Stage2GameScene.add(Animal_VS_Enemy.enemyImage.get(enemyNum)); Animal_VS_Enemy.enemyImage.get(enemyNum).setBounds(1200, 400, 70, 80); Animal_VS_Enemy.enemyImage.get(enemyNum).setIcon(new ImageIcon(enemyImageURL)); Animal_VS_Enemy.Stage2GameScene.add(Animal_VS_Enemy.enemyhealthBarImage.get(enemyNum)); Animal_VS_Enemy.enemyhealthBarImage.get(enemyNum).setBounds(1200, 350, 36, 4); Animal_VS_Enemy.enemyhealthBarImage.get(enemyNum).setIcon(new ImageIcon("C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\healthbar_red.png")); enemyNum++; //만약 적기지가 무너졌으면 생성을 그만한다. if(Animal_VS_Enemy.enemyBaseImage.getX() == 1500) { wait(); } } catch (InterruptedException e) { running = false; } } } } <file_sep>package Stage1; public class EnemyMove extends Thread{ int speed = 0; int enemyNum = 0; boolean running = true; EnemyMove(int enemyNum, int speed){ this.enemyNum = enemyNum; this.speed = speed; } @Override public void run() { while (running) { try { //적의 위치가 적의 대기장소가 아니라면 if(Vegetable_VS_Enemy.enemyImage[enemyNum].getX() != 2000 && Vegetable_VS_Enemy.enemyImage[enemyNum].getY() != 2000) { //적의 위치와 체력바의 위치를 왼쪽으로 옮긴다. Vegetable_VS_Enemy.enemyImage[enemyNum].setLocation(Vegetable_VS_Enemy.enemyImage[enemyNum].getX() - 5,Vegetable_VS_Enemy.enemyImage[enemyNum].getY()); Vegetable_VS_Enemy.healthBarImage[enemyNum].setLocation(Vegetable_VS_Enemy.enemyImage[enemyNum].getX() - 5, Vegetable_VS_Enemy.enemyImage[enemyNum].getY() + 80); Vegetable_VS_Enemy.healthBarBackground[enemyNum].setLocation(Vegetable_VS_Enemy.enemyImage[enemyNum].getX() - 5,Vegetable_VS_Enemy.enemyImage[enemyNum].getY() + 80); } Thread.sleep(speed); } catch (InterruptedException e) { running = false; } } } } <file_sep>package Stage1; import java.util.ArrayList; public class Eggplant extends Vegetable{ // eggplant의 특징 - carrot의 업그레이드 버전, 공격속도가 빠르지만 공격 간격이 넓다 ArrayList<Bullets> eggplantbullets = new ArrayList<Bullets>(); @Override public void plantiInitialize() { attackSpeed = 10; attackInterval = 2000; necessaryMana = 7; Plants = "eggplant"; ImageURL = "C:\\Users\\dayou\\OneDrive\\바탕 화면\\팀노바\\자바gui게임\\vegatable VS enemy\\eggplant.png"; } @Override public void attack() { Bullets eggplantBullets = new Bullets(attackSpeed,attackInterval); eggplantbullets.add(eggplantBullets); eggplantBullets.start(); Bullets.bulletsNum++; BulletMove.totalBulletsNum = BulletMove.totalBulletsNum + Bullets.NUM_OF_BULLETS; } } <file_sep>package Stage1; public class EnemyHealthBar extends Thread { //적의 체력관리와 체력바 업데이트 //적마다 하나씩 가지고 있는 멀티 쓰레드. boolean running = true; int strength = 0; int DamagedNum = 0; int enemyNum = 0; int barWidth = 0; EnemyHealthBar(int strength, int enemyNum){ this.strength = strength; this.enemyNum = enemyNum; } public void run() { while (running) { try { for (int i = 0; i < Vegetable_VS_Enemy.bulletImage.length; i++) { // 총알의과 적이 같은 타일일 때 총알의 x값이 적의 x값보다 크다면 (총알이 적에게 닿았다면) if ((Vegetable_VS_Enemy.bulletImage[i].getX() >= Vegetable_VS_Enemy.enemyImage[enemyNum].getX()) && (Vegetable_VS_Enemy.bulletImage[i].getY() == Vegetable_VS_Enemy.enemyImage[enemyNum].getY() + 60)) { // 총알x값이 적의 좌표 아주 뒤에 있지 않을 때 (적 뒤에 있는 총알로 인해 체력이 깍이지 않도록) if (Vegetable_VS_Enemy.bulletImage[i].getX() <= Vegetable_VS_Enemy.enemyImage[enemyNum].getX() + 50) { // 적에게 닿은 총알은 대기위치로 이동 Vegetable_VS_Enemy.bulletImage[i].setLocation(1300, Vegetable_VS_Enemy.bulletImage[i].getY()); // 밭은 데미지를 더한다 //System.out.println(DamagedNum); DamagedNum++; // 적의 체력바의 길이를 체력바의 길이/전체체력 + 1 만큼 줄인다. (반올림 문제로 피가 덜 깍일 때가 있어 +1을 했다.) barWidth = (Vegetable_VS_Enemy.healthBarImage[enemyNum].getWidth() / strength) +1; Vegetable_VS_Enemy.healthBarImage[enemyNum].setSize( Vegetable_VS_Enemy.healthBarImage[enemyNum].getWidth() - barWidth, Vegetable_VS_Enemy.healthBarImage[enemyNum].getHeight()); // 밭은 데미지가 체력과 같다면 if (strength < DamagedNum) { // 받은 데미지를 초기화하고 DamagedNum = 0; // 적 이미지와 체력이미지를 대기장소로 이동시킨다. Vegetable_VS_Enemy.enemyImage[enemyNum].setLocation(2000, 2000); Vegetable_VS_Enemy.healthBarImage[enemyNum].setLocation(2000, 2000); Vegetable_VS_Enemy.healthBarBackground[enemyNum].setLocation(2000, 2000); } } } } Thread.sleep(100); } catch (InterruptedException e) { } } } } <file_sep>package Stage1; public class GameOver extends Thread { //게임 오버를 체크하는 쓰레드 boolean running = true; @Override public synchronized void run() { while (running) { try { for (int i = 0; i < Vegetable_VS_Enemy.enemyImage.length; i++) { //적이 집에 도착했다면 if (Vegetable_VS_Enemy.enemyImage[i].getX() < 100) { //게임오버가 된다 Vegetable_VS_Enemy.Stage1GameScene.setVisible(false); Vegetable_VS_Enemy.gameOverScene.setVisible(true); } } Thread.sleep(100); } catch (InterruptedException e) { running = false; } } } } <file_sep>package Stage2; public class Minimis extends Thread { MinimiMove[] minimiMove = new MinimiMove[NUM_OF_MINIMIS]; final static int NUM_OF_MINIMIS = 3; // 염소 한마리가 생성될 때 생성되는 총알의 수 static int minimisNum = 0; // minimis클래스의 수 int attackInterval = 300; int attackPower = 1; int animalNum = 0; int whatNum = 0; int maxStrengthTarget = 0; boolean running = true; Minimis(int animalNum) { this.animalNum = animalNum; } @Override public void run() { for (int i = 0; i < minimiMove.length; i++) { minimiMove[i] = new MinimiMove(i, animalNum); minimiMove[i].start(); } final int whatNumMinimis = minimisNum; // 몇번째 미니미 클래스인지 - 몇번째 클래스인가에 따라 담당하는 minimiImage[]가 달라진다. while (running) { try { for (int i = minimiMove.length * whatNumMinimis - NUM_OF_MINIMIS; i < minimiMove.length * whatNumMinimis; i++) { for (int j = 0; j < Animal_VS_Enemy.enemyImage.size(); j++) { // 미니미의 주의에 적이 있다면 if (Animal_VS_Enemy.minimiImage[i].getX() >= Animal_VS_Enemy.enemyImage.get(j).getX() - 10 && Animal_VS_Enemy.minimiImage[i].getX() <= Animal_VS_Enemy.enemyImage.get(j).getX() + 10) { // 적에게 닿은 미니미는 대기 장소로 이동 Animal_VS_Enemy.minimiImage[i].setLocation(-500, Animal_VS_Enemy.minimiImage[i].getY()); // 미니미의 공격을 맞은 적을 찾고 그 적의 체력을 깍는다. whatNum = 0; if ((Animal_VS_Enemy.enemyList.get(j).getClass()).toString() .equals("class Stage2.Bandit")) { for (int k = 0; k < j; k++) { if (Animal_VS_Enemy.enemyList.get(k).getClass().toString() .equals("class Stage2.Bandit")) { whatNum++; } } maxStrengthTarget = 23; if (Animal_VS_Enemy.banditList.get(whatNum).strength > 0) { Animal_VS_Enemy.banditList.get(whatNum).strength = Animal_VS_Enemy.banditList .get(whatNum).strength - attackPower; if (Animal_VS_Enemy.enemyhealthBarImage.get(j).getWidth() < 0) { if (Animal_VS_Enemy.banditList.get(whatNum).strength > 0) { Animal_VS_Enemy.enemyhealthBarImage.get(j).setSize(5, 4); } } } else { Animal_VS_Enemy.enemyImage.get(j).setLocation(1500, 1500); Animal_VS_Enemy.enemyhealthBarImage.get(j).setLocation(1500, 1500); } } else if ((Animal_VS_Enemy.enemyList.get(j).getClass()).toString() .equals("class Stage2.Thief")) { for (int k = 0; k < j; k++) { if (Animal_VS_Enemy.enemyList.get(k).getClass().toString() .equals("class Stage2.Thief")) { whatNum++; } } maxStrengthTarget = 12; if (Animal_VS_Enemy.thiefList.get(whatNum).strength > 0) { Animal_VS_Enemy.thiefList.get(whatNum).strength = Animal_VS_Enemy.thiefList .get(whatNum).strength - attackPower; if (Animal_VS_Enemy.enemyhealthBarImage.get(j).getWidth() < 0) { if (Animal_VS_Enemy.thiefList.get(whatNum).strength > 0) { Animal_VS_Enemy.enemyhealthBarImage.get(j).setSize(5, 4); } } } else { Animal_VS_Enemy.enemyImage.get(j).setLocation(1500, 1500); Animal_VS_Enemy.enemyhealthBarImage.get(j).setLocation(1500, 1500); } } else if ((Animal_VS_Enemy.enemyList.get(j).getClass()).toString() .equals("class Stage2.Jingjing")) { for (int k = 0; k < j; k++) { if (Animal_VS_Enemy.enemyList.get(k).getClass().toString() .equals("class Stage2.Jingjing")) { whatNum++; } } if (Animal_VS_Enemy.jingjingList.get(whatNum).strength > 0) { Animal_VS_Enemy.jingjingList.get(whatNum).strength = Animal_VS_Enemy.jingjingList .get(whatNum).strength - attackPower; maxStrengthTarget = 7; if (Animal_VS_Enemy.enemyhealthBarImage.get(j).getWidth() < 0) { if (Animal_VS_Enemy.jingjingList.get(whatNum).strength > 0) { Animal_VS_Enemy.enemyhealthBarImage.get(j).setSize(5, 4); } } } else { Animal_VS_Enemy.enemyImage.get(j).setLocation(1500, 1500); Animal_VS_Enemy.enemyhealthBarImage.get(j).setLocation(1500, 1500); } } else if ((Animal_VS_Enemy.enemyList.get(j).getClass()).toString() .equals("class Stage2.Piracy")) { for (int k = 0; k < j; k++) { if (Animal_VS_Enemy.enemyList.get(k).getClass().toString() .equals("class Stage2.Piracy")) { whatNum++; } } if (Animal_VS_Enemy.piracyList.get(whatNum).strength > 0) { Animal_VS_Enemy.piracyList.get(whatNum).strength = Animal_VS_Enemy.piracyList .get(whatNum).strength - attackPower; maxStrengthTarget = 13; if (Animal_VS_Enemy.enemyhealthBarImage.get(j).getWidth() < 0) { if (Animal_VS_Enemy.piracyList.get(whatNum).strength > 0) { Animal_VS_Enemy.enemyhealthBarImage.get(j).setSize(5, 4); } } } else { Animal_VS_Enemy.enemyImage.get(j).setLocation(1500, 1500); Animal_VS_Enemy.enemyhealthBarImage.get(j).setLocation(1500, 1500); } } int barWidth = maxStrengthTarget / attackPower; Animal_VS_Enemy.enemyhealthBarImage.get(j).setSize( Animal_VS_Enemy.enemyhealthBarImage.get(j).getWidth() - barWidth, Animal_VS_Enemy.enemyhealthBarImage.get(j).getHeight()); } } } Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
782d9595645a19f1b004c889651cbaeffab67208
[ "Java" ]
15
Java
GuGaYoung/SaveGarden
7169b3ccf8412fee0810650ee522ec02c980e90e
53f01fdb880089cc9c04dc7f73da69ef655f4215
refs/heads/main
<repo_name>FluidTrack/MOA_Tester<file_sep>/Assets/Scripts/BluetoothManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Text; public class BluetoothManager : MonoBehaviour { public static BluetoothManager GetInstance() { return GameObject.Find("MainCanvas").GetComponent<BluetoothManager>(); } public string DeviceName = "TouchW32_9E"; public string MacAddress = ""; public string ServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"; public string SendUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"; public string ReceiveUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"; public ProtocolHandler Protocol; public Text DebugText; public enum States { None, Scan, Connect, Subscribe, Unsubscribe, Disconnect, Communication, } internal bool _workingFoundDevice = true; internal bool _connected = false; internal float _timeout = 0f; internal States _state = States.None; internal bool _foundID = false; void Reset() { _workingFoundDevice = false; // used to guard against trying to connect to a second device while still connecting to the first _connected = false; _timeout = 0f; _state = States.None; _foundID = false; MacAddress = null; } public void SetState(States newState, float timeout) { _state = newState; _timeout = timeout; } void StartProcess() { DebugText.text = "Initializing..."; Reset(); BluetoothLEHardwareInterface.Initialize(true, false, () => { SetState(States.Scan, 0.1f); DebugText.text = "Initialized"; }, (error) => { //AlertHandler.GetInstance().Pop_Error("BT Init실패"); BluetoothLEHardwareInterface.Log("Error: " + error); ScanPanelHandler.GetInstance().BlindControl(false); }); } // Use this for initialization void Start() { DebugText.text = ""; } public void OnConnectStart(string deviceName, string macAddress, string serviceUUID, string sendUUID, string receiveUUID) { ScanPanelHandler.GetInstance().BlindControl(true); DeviceName = deviceName; MacAddress = macAddress; ServiceUUID = serviceUUID; SendUUID = sendUUID; ReceiveUUID = receiveUUID; StartProcess(); } // Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: DebugText.text = "Scanning for " + DeviceName + " devices..."; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { // we only want to look at devices that have the name we are looking for // this is the best way to filter out devices if (name.Contains(DeviceName)) { _workingFoundDevice = true; // it is always a good idea to stop scanning while you connect to a device // and get things set up BluetoothLEHardwareInterface.StopScan(); // add it to the list and set to connect to it MacAddress = address; DebugText.text = "Found " + DeviceName; SetState(States.Connect, 2f); MainPanelHandler.GetInstance().Connect(); _workingFoundDevice = false; } }, null, false, false); break; case States.Connect: // set these flags _foundID = false; DebugText.text = "Connecting to " + DeviceName; // note that the first parameter is the address, not the name. I have not fixed this because // of backwards compatiblity. // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout // large enough that it will be finished enumerating before you try to subscribe or do any other operations. BluetoothLEHardwareInterface.ConnectToPeripheral(MacAddress, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { // if we have found the characteristic that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (IsEqual(characteristicUUID, ReceiveUUID)) { _connected = true; /* 김동현 편집 부분 시작 */ StartCoroutine(ConnectAndQuery()); /* 김동현 편집 부분 끝 */ SetState(States.Subscribe, 2f); AlertHandler.GetInstance().Pop_Con(); MainPanelHandler.GetInstance().BlindControl(true); ScanPanelHandler.GetInstance().BlindControl(false); ScanPanelHandler.GetInstance().OnCloseButton(); } } }, (disconnectedAddress) => { ScanPanelHandler.GetInstance().BlindControl(false); MainPanelHandler.GetInstance().BlindControl(false); BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress); AlertHandler.GetInstance().Pop_Discon(DeviceName); }); break; case States.Subscribe: //======================================== BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(MacAddress, ServiceUUID, ReceiveUUID, (notifyAddress, notifyCharacteristic) => { DebugText.text = " "; _state = States.None; // read the initial state of the button BluetoothLEHardwareInterface.ReadCharacteristic(MacAddress, ServiceUUID, ReceiveUUID, (characteristic, bytes) => { //Protocol.ParsingBytes(bytes); }); }, (address, characteristicUUID, bytes) => { if (_state != States.None) { // some devices do not properly send the notification state change which calls // the lambda just above this one so in those cases we don't have a great way to // set the state other than waiting until we actually got some data back. // The esp32 sends the notification above, but if yuor device doesn't you would have // to send data like pressing the button on the esp32 as the sketch for this demo // would then send data to trigger this. DebugText.text = " "; _state = States.None; } // we received some data from the device Protocol.ParsingBytes(bytes); }); //======================================== break; case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(MacAddress, ServiceUUID, ReceiveUUID, null); SetState(States.Disconnect, 4f); break; case States.Disconnect: if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(MacAddress, (address) => { BluetoothLEHardwareInterface.DeInitialize(() => { MainPanelHandler.GetInstance().Disconnect(); _connected = false; _state = States.None; }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { MainPanelHandler.GetInstance().Disconnect(); _state = States.None; }); } break; } } } } string FullUUID(string uuid) { return "0000" + uuid + "-0000-1000-8000-00805F9B34FB"; } bool IsEqual(string uuid1, string uuid2) { if (uuid1.Length == 4) uuid1 = FullUUID(uuid1); if (uuid2.Length == 4) uuid2 = FullUUID(uuid2); return ( uuid1.ToUpper().Equals(uuid2.ToUpper()) ); } public void SetCurrentTime() { var data = ProtocolHandler.SetTimerToCurrent(); SendBytes(data); } public void SetTime(int year, int month, int day, int hour, int min, int sec) { var data = ProtocolHandler.SetTimer(year,month,day,hour,min,sec); SendBytes(data); } public void QueryBattery() { var data = ProtocolHandler.QueryBattery(); SendBytes(data); } /* 김동현 편집 부분 시작 */ public void QueryHistory() { var data = ProtocolHandler.GetHistory(); SendBytes(data); } public void SetRedLED() { var data = ProtocolHandler.GetRedLEDOn(); SendBytes(data); } public void SetGreenLED() { var data = ProtocolHandler.GetGreenLEDOn(); SendBytes(data); } public void SetBlueLED() { var data = ProtocolHandler.GetBlueLEDOn(); SendBytes(data); } public void SetVibrate() { var data = ProtocolHandler.GetVibrateOn(); SendBytes(data); } IEnumerator ConnectAndQuery() { yield return new WaitForSeconds(3f); QueryHistory(); } /* 김동현 편집 부분 끝 */ void SendString(string value) { var data = Encoding.UTF8.GetBytes(value); // notice that the 6th parameter is false. this is because the TouchW32 doesn't support withResponse writing to its characteristic. // some devices do support this setting and it is prefered when they do so that you can know for sure the data was received by // the device BluetoothLEHardwareInterface.WriteCharacteristic(MacAddress, ServiceUUID, SendUUID, data, data.Length, false, (characteristicUUID) => { BluetoothLEHardwareInterface.Log("Write Succeeded"); }); } void SendByte(byte value) { byte[] data = new byte[] { value }; // notice that the 6th parameter is false. this is because the TouchW32 doesn't support withResponse writing to its characteristic. // some devices do support this setting and it is prefered when they do so that you can know for sure the data was received by // the device BluetoothLEHardwareInterface.WriteCharacteristic(MacAddress, ServiceUUID, SendUUID, data, data.Length, false, (characteristicUUID) => { BluetoothLEHardwareInterface.Log("Write Succeeded"); }); } void SendBytes(byte[] data) { if(!_connected) { AlertHandler.GetInstance().Pop_Alert("모아밴드와 연결을 먼저 해 주세요"); return; } // notice that the 6th parameter is false. this is because the TouchW32 doesn't support withResponse writing to its characteristic. // some devices do support this setting and it is prefered when they do so that you can know for sure the data was received by // the device BluetoothLEHardwareInterface.WriteCharacteristic(MacAddress, ServiceUUID, SendUUID, data, data.Length, false, (characteristicUUID) => { BluetoothLEHardwareInterface.Log("Write Succeeded"); }); } } <file_sep>/Assets/Scripts/DeviceListHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DeviceListHandler : MonoBehaviour { private BluetoothManager BT; public Text DeviceName; public Text MacAddress; public AudioClip sound; public void OnEnable() { BT = GameObject.Find("MainCanvas").GetComponent <BluetoothManager>(); } public void Init(int index,string deviceName, string macAddress) { this.GetComponent<RectTransform>().transform.localPosition = new Vector2(0f, -120f * index); MacAddress.text = macAddress; DeviceName.text = deviceName; } public void OnClickConnectButton() { if (ScanPanelHandler.GetInstance().isLocked) ScanPanelHandler.GetInstance().ScanButtonClick(); else BluetoothLEHardwareInterface.StopScan(); Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(sound); BT.OnConnectStart(DeviceName.text,"", "6e400001-b5a3-f393-e0a9-e50e24dcca9e", "6e400002-b5a3-f393-e0a9-e50e24dcca9e", "6e400003-b5a3-f393-e0a9-e50e24dcca9e"); } } <file_sep>/Assets/Scripts/MainPanelHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainPanelHandler : MonoBehaviour { public Animator TimeSettingPanel; public Animator ScanPanel; public Text ScanButtonText; public Text BTStateText; public Image ScanButtonIcon; public Button ScanButton; public Sprite Link; public Sprite Unlink; public bool isPanelOpened = false; public Color BlueColor; public Color BlueColor2; public Color RedColor; public Color RedColor2; public GameObject HistoryPanel; public GameObject RealtimePanel; public RectTransform HistoryRect; public RectTransform RealtimeRect; public ScrollRect HistoryScroll; public ScrollRect RealtimeScroll; public GameObject WaterLog; public GameObject PooLog; public GameObject PeeLog; private List<GameObject> HistoryList; private List<GameObject> RealtimeList; public AudioClip LogCreateSound; public GameObject Blind; public GameObject Opening; public enum LOG_TYPE { WATER,POO,PEE }; public static MainPanelHandler GetInstance() { return GameObject.Find("MainPanel").GetComponent<MainPanelHandler>(); } public void Awake() { HistoryList = new List<GameObject>(); RealtimeList = new List<GameObject>(); Opening.SetActive(true); } public void ScanButtonClick() { if (isPanelOpened) return; if (!BluetoothManager.GetInstance()._connected) { isPanelOpened = true; ScanPanel.SetBool("isOpen", true); } else { BluetoothManager.GetInstance() .SetState(BluetoothManager.States.Disconnect, 0.1f); } } public void TimeButtonClick() { if (isPanelOpened) return; if (!BluetoothManager.GetInstance()._connected) { AlertHandler.GetInstance().Pop_Alert("모아밴드와 연결을 먼저 해 주세요"); return; } isPanelOpened = true; TimeSettingPanel.SetBool("isOpen", true); } public void BatteryButtonClick() { if (isPanelOpened) return; BluetoothManager.GetInstance().QueryBattery(); } public void BlindControl(bool value) { Blind.SetActive(value); if (value) StartCoroutine(MaxWait()); } IEnumerator MaxWait() { yield return new WaitForSeconds(3f); Blind.SetActive(false); } public void AddHistoryLog(LOG_TYPE type, string timeStamp) { GameObject target = null; switch (type) { case LOG_TYPE.WATER: target = Instantiate(WaterLog, HistoryPanel.transform); break; case LOG_TYPE.POO: target = Instantiate(PooLog, HistoryPanel.transform); break; case LOG_TYPE.PEE: target = Instantiate(PeeLog, HistoryPanel.transform); break; } Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(LogCreateSound); HistoryList.Add(target); int index = HistoryList.Count; target.GetComponent<LogHandler>().Init(index-1, timeStamp); HistoryRect.sizeDelta = new Vector2(1200f, 80f * ( index)); HistoryScroll.verticalNormalizedPosition = 0f; } public void AddRealtimeLog(LOG_TYPE type, string timeStamp) { GameObject target = null; switch (type) { case LOG_TYPE.WATER: target = Instantiate(WaterLog, RealtimePanel.transform); break; case LOG_TYPE.POO: target = Instantiate(PooLog, RealtimePanel.transform); break; case LOG_TYPE.PEE: target = Instantiate(PeeLog, RealtimePanel.transform); break; } Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(LogCreateSound); RealtimeList.Add(target); int index = RealtimeList.Count; target.GetComponent<LogHandler>().Init(index-1, timeStamp); RealtimeRect.sizeDelta = new Vector2(1200f, 80f * ( index)); RealtimeScroll.verticalNormalizedPosition = 0f; } public void ClearHistoryLog() { int length = HistoryList.Count; for(int i = 0; i < length; i++) Destroy(HistoryList[i]); HistoryList.Clear(); HistoryRect.sizeDelta = new Vector2(1200f, 0f); } public void ClearRealtimeLog() { int length = RealtimeList.Count; for (int i = 0; i < length; i++) Destroy(RealtimeList[i]); RealtimeList.Clear(); HistoryRect.sizeDelta = new Vector2(1200f, 0f); } public void Connect() { ColorBlock colorBlock = new ColorBlock(); colorBlock.normalColor = RedColor; colorBlock.highlightedColor = RedColor; colorBlock.pressedColor = RedColor2; colorBlock.selectedColor = RedColor; ScanButtonText.text = "모아밴드 연결 해제"; ScanButtonIcon.sprite = Unlink; colorBlock.colorMultiplier = 1; colorBlock.fadeDuration = 0.1f; ScanButton.colors = colorBlock; BTStateText.text = BluetoothManager.GetInstance().DeviceName; } public void Disconnect() { ColorBlock colorBlock = new ColorBlock(); colorBlock.normalColor = BlueColor; colorBlock.highlightedColor = BlueColor; colorBlock.pressedColor = BlueColor2; colorBlock.selectedColor = BlueColor; ScanButtonText.text = "모아밴드 연결 시작"; ScanButtonIcon.sprite = Link; colorBlock.colorMultiplier = 1; colorBlock.fadeDuration = 0.1f; ScanButton.colors = colorBlock; BTStateText.text = "블루투스 미연결"; ClearHistoryLog(); ClearRealtimeLog(); } } <file_sep>/Assets/Scripts/PopUpHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PopUpHandler : MonoBehaviour { public Text SubText; public Animator anim; public void Start() { anim = this.GetComponent<Animator>(); } } <file_sep>/Assets/Scripts/VibrateButtonHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class VibrateButtonHandler : MonoBehaviour { public void OnClicked() { if (BluetoothManager.GetInstance()._connected) { BluetoothManager.GetInstance().SetVibrate(); } } } <file_sep>/Assets/Scripts/LEDButtonHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class LEDButtonHandler : MonoBehaviour { public void OnRedClicked() { if (BluetoothManager.GetInstance()._connected) { BluetoothManager.GetInstance().SetRedLED(); } } public void OnGreenClicked() { if (BluetoothManager.GetInstance()._connected) { BluetoothManager.GetInstance().SetGreenLED(); } } public void OnBlueClicked() { if (BluetoothManager.GetInstance()._connected) { BluetoothManager.GetInstance().SetBlueLED(); } } } <file_sep>/README.md # 🚧 MOA_Tester MOABAND Test application for android <img src="https://github.com/FluidTrack/MOA_Tester/blob/main/DOC/Screenshot_20201230-181736_FluidTrackTest.jpg?raw=true" width="40%"> <file_sep>/Assets/Scripts/LogHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LogHandler : MonoBehaviour { public Text TimeStamp; public Text IndexText; public void Init(int index,string timeStamp) { this.GetComponent<RectTransform>().transform.localPosition = new Vector2(0f,-80f * index); TimeStamp.text = timeStamp; IndexText.text = ( index + 1 ).ToString(); } } <file_sep>/Assets/Scripts/ProtocolHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Text; using System; public class ProtocolHandler : MonoBehaviour { public BluetoothManager BT; public MainPanelHandler Main; public Text DebugText; public static string testString = ""; public void ParsingBytes(byte[] bytes) { int length = bytes.Length; byte cmd = bytes[0]; //DebugText.text += "1 ▶"; //for(int i = 0; i < length; i++) { // DebugText.text += bytes[i].ToString(); // if (i != length - 1) DebugText.text += "-"; //} //DebugText.text += "\n"; switch (cmd) { //============================================================================== // 타임존 변경 Confirm //============================================================================== case 0x03: AlertHandler.GetInstance().Pop_Msg("모아밴드의 시간이 성공적으로 변경됨."); break; //============================================================================== // 배터리 확인 //============================================================================== case 0x07: if (bytes[3] == 0) AlertHandler.GetInstance().Pop_BatInfo((int)bytes[2]); else AlertHandler.GetInstance().Pop_ChargeBat((int)bytes[2]); break; //============================================================================== // 배터리 부족 Alert //============================================================================== case 0x12: if (bytes[3] == 0) AlertHandler.GetInstance().Pop_LowBat((int)bytes[2]); break; //============================================================================== // Button Input //============================================================================== case 0x24: string stamp = GetCurrentTimeStamp(); switch(bytes[6]) { case 3: Main.AddRealtimeLog(MainPanelHandler.LOG_TYPE.POO,stamp); break; case 1: Main.AddRealtimeLog(MainPanelHandler.LOG_TYPE.WATER,stamp); break; case 2: Main.AddRealtimeLog(MainPanelHandler.LOG_TYPE.PEE,stamp); break; } break; //============================================================================== // History //============================================================================== case 0x27: if(bytes[1] == 0) { MainPanelHandler.GetInstance().BlindControl(false); } else { int Length = ( bytes[1] ) / 5; for (int i = 0; i < length; i++) { string historyStamp = MakeTimeStamp(bytes[2 + 5 * i], bytes[3 + 5 * i], bytes[4 + 5 * i], bytes[5 + 5 * i]); switch (bytes[6 + 5 * i]) { case 3: Main.AddHistoryLog(MainPanelHandler.LOG_TYPE.POO, historyStamp); break; case 1: Main.AddHistoryLog(MainPanelHandler.LOG_TYPE.WATER, historyStamp); break; case 2: Main.AddHistoryLog(MainPanelHandler.LOG_TYPE.PEE, historyStamp); break; } } } break; default: break; } } static public byte[] SetTimerToCurrent() { DateTime now = DateTime.Now; byte[] bytes = new byte[10]; bytes[0] = 0x03; bytes[1] = 8; bytes[2] = (byte)now.Year; bytes[3] = (byte)(now.Month); bytes[4] = (byte)now.Day; bytes[5] = (byte)now.Hour; bytes[6] = (byte)now.Minute; bytes[7] = (byte)now.Second; bytes[8] = 0; bytes[9] = 0; return bytes; } static public byte[] SetTimer(int year, int month, int day, int hour, int min, int sec) { DateTime now = DateTime.Now; byte[] bytes = new byte[10]; bytes[0] = 0x03; bytes[1] = 8; bytes[2] = (byte)year; bytes[3] = (byte)month; bytes[4] = (byte)day; bytes[5] = (byte)hour; bytes[6] = (byte)min; bytes[7] = (byte)sec; bytes[8] = 0; bytes[9] = 0; return bytes; } static public byte[] QueryBattery() { DateTime now = DateTime.Now; byte[] bytes = new byte[2]; bytes[0] = 0x07; bytes[1] = 0; return bytes; } public string GetCurrentTimeStamp() { DateTime now = DateTime.Now; string result = now.Year + "-"; result += (now.Month) + "-"; result += now.Day + " "; result += now.Hour + ":"; result += now.Minute + ":"; result += now.Second + ""; return result; } public string MakeTimeStamp(byte day, byte hour, byte min, byte sec) { int day_int = ( day / 16 ) * 10 + day % 16; int hour_int = ( hour / 16 ) * 10 + hour % 16; int min_int = ( min / 16 ) * 10 + min % 16; int sec_int = ( sec / 16 ) * 10 + sec % 16; DateTime now = DateTime.Now; return MakeTimeStamp(now.Year, ( now.Month ), day_int, hour_int, min_int, sec_int); } public string MakeTimeStamp(int day, int hour, int min, int sec) { DateTime now = DateTime.Now; return MakeTimeStamp(now.Year, ( now.Month ), day, hour, min, sec); } public string MakeTimeStamp(int year,int month,int day, int hour, int min, int sec) { return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec; } /* 김동현 편집 부분 시작 */ static public byte[] GetHistory() { byte[] bytes = new byte[2]; bytes[0] = 0x27; bytes[1] = 0; return bytes; } static public byte[] GetRedLEDOn() { byte[] bytes = new byte[3]; bytes[0] = 0x44; bytes[1] = 1; bytes[2] = 1; return bytes; } static public byte[] GetGreenLEDOn() { byte[] bytes = new byte[3]; bytes[0] = 0x44; bytes[1] = 1; bytes[2] = 2; return bytes; } static public byte[] GetBlueLEDOn() { byte[] bytes = new byte[3]; bytes[0] = 0x44; bytes[1] = 1; bytes[2] = 3; return bytes; } static public byte[] GetVibrateOn() { byte[] bytes = new byte[2]; bytes[0] = 0x45; bytes[1] = 0; return bytes; } /* 김동현 편집 부분 끝 */ } <file_sep>/Assets/Scripts/ScanPanelHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScanPanelHandler : MonoBehaviour { private MainPanelHandler MainPanel; private static ScanPanelHandler Instance; private Animator anim; internal bool isLocked = false; public Color BlueColor; public Color BlueColor2; public Color RedColor; public Color RedColor2; public Button ScanButton; public Text ScanButtonText; public GameObject Blind; public GameObject DeviceObjectPrefabs; public Transform ScrollView; public ScrollRect Scroll; public List<GameObject> DeviceList; public Animator RingAnim; public static ScanPanelHandler GetInstance() { return Instance; } public void Start() { Instance = this; MainPanel = MainPanelHandler.GetInstance(); anim = this.GetComponent<Animator>(); DeviceList = new List<GameObject>(); } public void BlindControl(bool value) { Blind.SetActive(value); } public void OnCloseButton() { if (isLocked) return; MainPanel.isPanelOpened = false; anim.SetBool("isOpen", false); } public void ScanButtonClick() { ColorBlock colorBlock = new ColorBlock(); if(!isLocked) { colorBlock.normalColor = RedColor; colorBlock.highlightedColor = RedColor; colorBlock.pressedColor = RedColor2; colorBlock.selectedColor = RedColor; ScanButtonText.text = "주변 BLE 기기 탐색 종료"; int listLength = DeviceList.Count; for(int i = 0; i < listLength; i ++) Destroy(DeviceList[i]); DeviceList.Clear(); BluetoothLEHardwareInterface.Initialize(true, false, () => { BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { if(name.Contains("Touch")) { DeviceList.Add(Instantiate(DeviceObjectPrefabs,ScrollView)); DeviceList[DeviceList.Count - 1].GetComponent<DeviceListHandler>() .Init(DeviceList.Count-1,name,address); RectTransform view = ScrollView.gameObject.GetComponent<RectTransform>(); view.sizeDelta = new Vector2(800f,120f * DeviceList.Count); Scroll.verticalNormalizedPosition = 0f; } }, null); }, (error) => { AlertHandler.GetInstance().Pop_Error("BT 스캐너 에러"); BluetoothLEHardwareInterface.Log("BLE Error: " + error); }); } else { colorBlock.normalColor = BlueColor; colorBlock.highlightedColor = BlueColor; colorBlock.pressedColor = BlueColor2; colorBlock.selectedColor = BlueColor; ScanButtonText.text = "주변 BLE 기기 탐색 시작"; RectTransform view = ScrollView.gameObject.GetComponent<RectTransform>(); BluetoothLEHardwareInterface.StopScan(); } colorBlock.colorMultiplier = 1; colorBlock.fadeDuration = 0.1f; ScanButton.colors = colorBlock; isLocked = !isLocked; RingAnim.SetBool("RingRing",isLocked); } } <file_sep>/Assets/Scripts/OpeningHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class OpeningHandler : MonoBehaviour { public bool DoOpening = true; public AudioClip openingSound; public void Start() { if (!DoOpening) Destroy(this.gameObject); else StartCoroutine(Timer()); } IEnumerator Timer() { Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(openingSound); yield return new WaitForSeconds(3.5f); Destroy(this.gameObject); } } <file_sep>/Assets/Scripts/AlertHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AlertHandler : MonoBehaviour { public PopUpHandler [] Popup; public AudioClip LOW_BAT; public AudioClip CHARGE_BAT; public AudioClip BAT_INFO; public AudioClip CON; public AudioClip ALERT; public AudioClip ERROR; public AudioClip DISCON; public AudioClip MSG; public enum POPUPS { LOW_BAT, CHARGE_BAT, BAT_INFO, CON, ALERT, ERROR, DISCON, MSG, }; public bool isPopped = false; IEnumerator popCheck() { isPopped = true; yield return new WaitForSeconds(3f); isPopped = false; } public static AlertHandler GetInstance() { GameObject go = GameObject.Find("MainCanvas"); return go.GetComponent<AlertHandler>(); } public void Pop_LowBat(int bat) { Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(LOW_BAT); Popup[0].SubText.text = "모아밴드의 배터리 잔량이 얼마 남지 않았습니다.\n" + "배터리 잔량 : " + bat + "%"; Popup[0].anim.SetTrigger("Pop"); StartCoroutine(popCheck()); } public void Pop_ChargeBat(int percent) { if (isPopped) return; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(CHARGE_BAT); Popup[1].SubText.text = "모아밴드 배터리 잔량 : " + percent + "%"; Popup[1].anim.SetTrigger("Pop"); StartCoroutine(popCheck()); } public void Pop_BatInfo(int percent) { if (isPopped) return; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(BAT_INFO); Popup[2].SubText.text = "모아밴드 배터리 잔량 : " + percent + "%"; Popup[2].anim.SetTrigger("Pop"); StartCoroutine(popCheck()); } public void Pop_Con() { if (isPopped) return; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(CON); Popup[3].anim.SetTrigger("Pop"); StartCoroutine(popCheck()); } public void Pop_Alert(string alert) { Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(ALERT); Popup[4].SubText.text = alert; Popup[4].anim.SetTrigger("Pop"); StartCoroutine(popCheck()); } public void Pop_Error(string error) { Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(ERROR); Popup[5].SubText.text = error; Popup[5].anim.SetTrigger("Pop"); StartCoroutine(popCheck()); } public void Pop_Discon(string name) { Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(DISCON); if (isPopped) return; Popup[6].anim.SetTrigger("Pop"); Popup[6].SubText.text = name + " 모아밴드와\n연결이 끊어졌습니다."; StartCoroutine(popCheck()); } public void Pop_Msg(string str) { Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(MSG); Popup[7].anim.SetTrigger("Pop"); Popup[7].SubText.text = str; StartCoroutine(popCheck()); } } <file_sep>/Assets/Scripts/TimeSettingPanelHandler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TimeSettingPanelHandler : MonoBehaviour { private MainPanelHandler MainPanel; private Animator anim; private bool isLocked = false; public Text CurrentTimeStamp; public InputField Text_Year; public InputField Text_Month; public InputField Text_Day; public InputField Text_Hour; public InputField Text_Min; public InputField Text_Sec; public Text Notice; public AudioClip Beep; public void Start() { MainPanel = MainPanelHandler.GetInstance(); anim = this.GetComponent<Animator>(); System.DateTime now = System.DateTime.Now; Text_Year.text = now.Year + ""; Text_Month.text = (now.Month) + ""; Text_Day.text = now.Day + ""; Text_Hour.text = now.Hour + ""; Text_Min.text = now.Minute + ""; Text_Sec.text = "0"; StartCoroutine(tictock()); } IEnumerator tictock() { while(true) { System.DateTime now = System.DateTime.Now; string str = now.Year + "년"; str += ( now.Month ) + "월"; str += now.Day + "일\n"; str += now.Hour + "시"; str += now.Minute + "분"; str += now.Second + "초"; CurrentTimeStamp.text = str; yield return new WaitForSeconds(1f); } } public void OnCurrentTimeButton() { BluetoothManager.GetInstance().SetCurrentTime(); OnCloseButton(); } private int[] NormalYearDaysList = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private int[] LeafYearDaysList = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static bool isLeafYear(int year) { if (( year % 4 ) == 0) { if (( year % 100 ) == 0) { if (( year % 400 ) == 0) { return true; } else return false; } else return true; } else return false; } public void OnTimeButton() { try { int yyyy = int.Parse(Text_Year.text); bool isLeaf = isLeafYear(yyyy); yyyy -= 2000; int[] dayList = ( isLeaf ) ? LeafYearDaysList : NormalYearDaysList; int MM = int.Parse(Text_Month.text); int dd = int.Parse(Text_Day.text); int hh = int.Parse(Text_Hour.text); int mm = int.Parse(Text_Min.text); int ss = int.Parse(Text_Sec.text); if (yyyy < 0) { Notice.text = "2000년 이상을 입력하세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } else if (MM < 1 || MM > 12) { Notice.text = "1월부터 12월로 입력하세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } else if (dd < 1 || dd > dayList[MM - 1]) { Notice.text = "정확한 날짜를 입력해주세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } else if (hh < 0 || hh > 23) { Notice.text = "정확한 시간(H)을 입력해주세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } else if (mm < 0 || mm > 59) { Notice.text = "정확한 시간(M)을 입력해주세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } else if (ss < 0 || ss > 59) { Notice.text = "정확한 시간(S)을 입력해주세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } BluetoothManager.GetInstance().SetTime(yyyy, MM, dd, hh, mm, ss); OnCloseButton(); } catch (System.Exception e) { e.ToString(); Notice.text = "정확히 입력해주세요."; Camera.main.gameObject.GetComponent<AudioSource>().PlayOneShot(Beep); return; } } public void OnCloseButton() { if (isLocked) return; MainPanel.isPanelOpened = false; anim.SetBool("isOpen", false); } }
d41176b79013bbbf03bc2d2cf0bef465346736bd
[ "Markdown", "C#" ]
13
C#
FluidTrack/MOA_Tester
6ac67deec494502d4c6feebb15ef2d8d320a6708
32a569493b94e15c1676250f37e57f39c982e362
refs/heads/master
<file_sep>using System; using System.IO; using System.ServiceProcess; using System.Management; using System.Timers; namespace DriveLoggerService { public partial class DriveLogger : ServiceBase { static string logPath = ""; private static string BuildDriveList() { string msg = ""; DriveInfo[] drives = DriveInfo.GetDrives(); string nl = Environment.NewLine; foreach (DriveInfo d in drives) { msg += "Drive " + d.Name + nl; msg += "\tType: " + d.DriveType + nl; if (d.IsReady) { msg += "\tSTATUS The drive is ready." + nl; } else { msg += "\tSTATUS The drive is not ready." + nl; msg += "\tERROR Unable to provide more information." + nl; } } return msg; } private static string BuildMessage(bool insert) { string msg = ""; if (insert) { msg = "USB EVENT-> New plug in." + Environment.NewLine; } else { msg = "USB EVENT-> Deviced removed." + Environment.NewLine; } msg += "Drive List: " + Environment.NewLine; msg += BuildDriveList(); msg += Environment.NewLine; return msg; } private static void WriteLog(string msg) { string currentText = File.ReadAllText(logPath); currentText += msg; File.WriteAllText(logPath, currentText); } private static void CheckPath() { if (!File.Exists(logPath)) { File.Create(logPath).Close(); } } public DriveLogger() { InitializeComponent(); } protected override void OnStart(string[] args) { try { logPath = "C:\\devicelog.txt"; CheckPath(); String initMsg = "[STATUS] The logger has started." + Environment.NewLine; initMsg += "Initial Drive List: " + Environment.NewLine; initMsg += BuildDriveList(); initMsg += Environment.NewLine; WriteLog(initMsg); var insertWatcher = new ManagementEventWatcher(); var insertQuery = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); insertWatcher.EventArrived += Watcher_EventArrived; insertWatcher.Query = insertQuery; insertWatcher.Start(); var rmWatcher = new ManagementEventWatcher(); var rmQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); rmWatcher.EventArrived += RmWatcher_EventArrived; rmWatcher.Query = rmQuery; rmWatcher.Start(); Timer timer = new Timer(); timer.Interval = 10000; timer.Elapsed += new ElapsedEventHandler(this.OnTimer); timer.Start(); } catch (Exception e) { } } protected override void OnStop() { } public void OnTimer(object sender, ElapsedEventArgs args) { CheckPath(); } private static void Watcher_EventArrived(object sender, EventArrivedEventArgs e) { String msg = BuildMessage(true); WriteLog(msg); } private static void RmWatcher_EventArrived(object sender, EventArrivedEventArgs e) { String msg = BuildMessage(false); WriteLog(msg); } } }
ddf14ba125d303ae29884973cee23138477b43f4
[ "C#" ]
1
C#
patrickf2000/watchdog
71a67b0337ffa7c108cc3cc88458f621a52e961e
9f5ecbdc7145f74eba4102b788e4c7699e18acb6
refs/heads/master
<repo_name>vainyksi/spring-config-server-example<file_sep>/config-server/src/main/resources/setup-config-repo.sh #!/bin/bash cd ././../../../ if [ ! -d config-repo ]; then mkdir config-repo fi git init echo "message = Hello world greeter.name = Jack devices = device1, device2, device3" > a-bootiful-client.properties git add a-bootiful-client.properties git commit -m "upload a-bootiful-client config" echo '# An employee record name: <NAME> job: Developer skill: Elite employed: True foods: - Apple - Orange - Strawberry - Mango languages: perl: Elite python: Elite pascal: Lame education: | 4 GCSEs 3 A-Levels BSc in the Internet of Things config: { "name": "CHANGEME", "description": "CHANGEME", "environment": "CHANGEME", "secret_file": "CHANGEME", "run_sequentially": false, "orchestration": "ha_controller_n_compute", "nodes": [ { "fqdn": "CHANGEME", "password": "<PASSWORD>", "identity_file": "CHANGEME", "quit_on_error": true, "run_order_number": 1, "runlist": [ "role[ibm-os-ha-controller-node]" ] }, { "fqdn": "CHANGEME", "password": "<PASSWORD>", "identity_file": "CHANGEME", "quit_on_error": true, "run_order_number": 1, "runlist": [ "role[ibm-os-ha-controller-node]" ] }, { "fqdn": "CHANGEME", "password": "<PASSWORD>", "identity_file": "CHANGEME", "quit_on_error": true, "run_order_number": 1, "runlist": [ "role[ibm-os-ha-controller-node]" ] }, { "fqdn": "CHANGEME", "password": "<PASSWORD>", "identity_file": "CHANGEME", "quit_on_error": true, "run_order_number": 10, "runlist": [ "role[ibm-os-compute-node-kvm]" ] }, ] }' > client3.yaml git add client3.yaml git commit -m "upload client3 config" <file_sep>/config-server/src/main/resources/application.properties server.port=8888 spring.cloud.config.server.git.uri=${HOME}/projects/private/spring-config-server-example/config-server/config-repo
2b49c7a97cbbbc7a175d9aa5c0c7f472cc9d8930
[ "INI", "Shell" ]
2
Shell
vainyksi/spring-config-server-example
2695883c02a3ee06d3e1c763af008b05b53b39d0
4b61c31e64d5ceb2312025eca60def1bdec968b0
refs/heads/main
<file_sep>import React from "react"; import cleanb from "../../icons/cleanb.svg"; import clean from "../../icons/clean.svg"; import blackfilter from "../../icons/blackfilter.png"; import close from "../../icons/close.png"; import filledfilter from "../../icons/filledfilter.png"; import "./FilterTopDrawer.css"; import { filterData } from "../../data"; import { data } from "../../data"; export const FilterTopDrawer = ({ setIsOpen, setDataCards, setSubtitle }) => { function onClick() { setIsOpen(false); } function filterCards() { setDataCards(filterData); setIsOpen(false); setSubtitle("(Iniciado, De la A a la Z)"); } function cleanFilters() { setDataCards(data); setIsOpen(false); setSubtitle("(Todos)"); } return ( <div className="FilterTopDrawer"> <div className="FilterTopDrawer-Header"> <div className="FilterTopDrawer-Header-Title"> <img src={blackfilter} alt="blackfilter" width="20px" height="20px" /> <div style={{ paddingLeft: "10px" }}>Filtros y ordén</div> <div className="FilterTopDrawer-Header-SubTitle">(Iniciado, De la A a la Z)</div> </div> <button className="FilterTopDrawer-Header-CloseBtn" onClick={onClick}> <img src={close} alt="close" width="24px" height="24px" /> </button> </div> <div className="FilterTopDrawer-Content"> <div className="FilterTopDrawer-Content-Options"> <div className="FilterTopDrawer-Content-Options-Title">Estado:</div> <div className="FilterTopDrawer-Content-Select-Wrapper"> <select className="FilterTopDrawer-Content-Select"> <option className="FilterTopDrawer-Content-Select-Options">Iniciado</option> </select> </div> </div> <div className="FilterTopDrawer-Content-Options"> <div className="FilterTopDrawer-Content-Options-Title">Nombre:</div> <div className="FilterTopDrawer-Content-Select-Wrapper"> <select className="FilterTopDrawer-Content-Select"> <option className="FilterTopDrawer-Content-Select-Options">A a la Z</option> </select> </div> </div> <div className="FilterTopDrawer-Content-Options"> <div className="FilterTopDrawer-Content-Options-Title">Fecha:</div> <div className="FilterTopDrawer-Content-Select-Wrapper"> <select className="FilterTopDrawer-Content-Select"> <option className="FilterTopDrawer-Content-Select-Options">Escoge una opción</option> </select> </div> </div> <div className="FilterTopDrawer-Content-Options"> <div className="FilterTopDrawer-Content-Options-Title">Tamaño:</div> <div className="FilterTopDrawer-Content-Select-Wrapper"> <select className="FilterTopDrawer-Content-Select"> <option className="FilterTopDrawer-Content-Select-Options">Escoge una opción</option> </select> </div> </div> </div> <div className="FilterTopDrawer-Footer"> <button className="FilterTopDrawer-Footer-Limpiar" onClick={cleanFilters}> <img src={cleanb} alt="cleanb" width="24px" height="24px" className="BtnLimpiar" /> <img src={clean} alt="clean" width="24px" height="24px" className="BtnLimpiarBlanco" /> <div style={{ paddingLeft: "10px" }}>Limpiar filtros</div> </button> <button className="FilterTopDrawer-Footer-Aplicar" onClick={filterCards}> <img src={filledfilter} alt="filledfilter" width="24px" height="24px" /> <div style={{ paddingLeft: "10px" }}>Aplicar Filtros</div> </button> </div> </div> ); }; <file_sep>import image from './images/58eb7ba7263dc-1050x656.jpg' export const data = [ { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'No Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: true, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Detenido', date: '03/04/21', people: 18, name: '<NAME>', wishlist: true, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Finalizado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'No Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'No Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Detenido', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Finalizado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Finalizado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, ] export const filterData = [ { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: true, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: true, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: true, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, { state: 'Iniciado', date: '03/04/21', people: 18, name: '<NAME>', wishlist: false, address: 'Dirección del proyecto, ubicación', price: '2.000.030 USD', size: '960m2', progress: '81%', ppc: '15%', pcr: '46%', image: image }, ]<file_sep>import React from "react"; export const Footer = () => { return <div style={{ display: "flex", left: "0", bottom: "0", backgroundColor: "#153236", width: "100%", height: "20px" }}></div>; };
f4effd66436be60e1e878e48bf2cb8bfdf59bb65
[ "JavaScript" ]
3
JavaScript
malenagoni/from-figma-to-reactapp
694c0f2d4d7b2e60a20788d31cc53c23459778c9
378e70457be589d10a55f71c955f30db82bf51fe
refs/heads/main
<repo_name>JasonVolkoff/Random_Word_Generator<file_sep>/random_word_generator_project/random_word/views.py from django.shortcuts import render, redirect from django.utils.crypto import get_random_string # Create your views here. def index(request): # initialize variables if not in session if "counter" not in request.session or "randomWord" not in request.session: request.session["counter"] = 0 request.session["randomWord"] = "Click below for a random string." return render(request, 'index.html') def random_word(request): if request.method == "POST": # increment counter and assign random string to session request.session['counter'] += 1 request.session['randomWord'] = get_random_string(length=14) return redirect('/') def reset(request): # reset session variables request.session.flush() return redirect('/')
3204bc8d5b21d810a564076e9a994ff0c6c61ee0
[ "Python" ]
1
Python
JasonVolkoff/Random_Word_Generator
b1f98dcc0f4122831ad99b2acee1783ce854a92b
5e41f0a5dc51669d19ad597737ccee67fe1a3372
refs/heads/master
<repo_name>brootware/cs50<file_sep>/pset1/water.c #include <stdio.h> #include <cs50.h> int main (void) { int minutes; do { printf("how long do you shower?\n"); minutes = get_int(); } while(minutes < 0); //TODO getting input from above 0 minutes. printf("Minutes: %i\n", minutes); printf("Bottles: %i\n", minutes * 12); //TODO converting minutes to bottle of water }<file_sep>/pset1/greedy.c #include <stdio.h> #include <cs50.h> #include <math.h> #define QUARTER 25 #define DIME 10 #define NICKLE 5 #define PENNY 1 int main (void) { float change = 0; do { printf("How much change is owed? \n"); change = get_float(); } while(change < 0); //TODO getting only positive input from user int cents = round(change * 100); //round and convert to cents int n = 0; //number of coins used. while (cents > 0) { if(cents >= QUARTER) { n += cents / QUARTER; cents -= QUARTER * (cents / QUARTER); } else if(cents >= DIME) { n += cents / DIME; cents -= DIME * (cents/DIME); } else if (cents >= NICKLE) { n += cents / NICKLE; cents -= NICKLE * (cents / NICKLE); } else { n += cents; cents = 0; } } printf("%d\n", n); } <file_sep>/pset1/mario.c #include <stdio.h> #include <cs50.h> int main (void) { int height; do { printf("height: "); height = get_int(); } while(height < 0 || height > 23); //TODO getting input value from user with a range inclusive of 0 from 23 for (int i = 0; i < height; i ++) { for (int n = i; n < height-1; n++) { printf(" "); //Drawing Spaces } for (int n = 0; n < i+2; n++) { printf("#"); //Drawing Hashes } printf("\n"); } //TODO looping and drawing half pyramid }<file_sep>/README.md # cs50 All the contents from lectures and problem set solutions for reference
90c0f39fc2b125f4cc282cb5be5979d47eb65490
[ "Markdown", "C" ]
4
C
brootware/cs50
c4019bae78ae204ac1ee5dfa664f6d66298d59ae
6eef7d9d9828df02b40eefce167b63514eb9e185
refs/heads/master
<file_sep>package com.starylwu.Integer; /** * @Auther: Wuyulong * @Date: 2018/9/16 19:44 * @Description: 二进制算法 */ public class BinaryIntegerAlgorithm { /** * 计算num所对应的二进制数中的1的个数 * @param num * @return */ public static int countBit(int num){ int count = 0; for (;num > 0; count++){ num &= num - 1; } return count; } /** * 获取num所对应的二进制数 第 i 位的值是否为0 * @param num * @param index 从0开始 * @return 返回 true | false */ public static boolean getBit(int num, int index){ if (index > Integer.toBinaryString(num).length() - 1){ throw new ArrayIndexOutOfBoundsException("index is more than num's binary length, num=[" + num + "], index=[" + index + "]."); } return (num & (1 << index)) == 0; } /** * 将num所对应的二进制的数中的index位设置为1 * @param num * @param index * @return 设置后的num */ public static int setBitOne(int num, int index){ if (index > Integer.toBinaryString(num).length() - 1){ throw new ArrayIndexOutOfBoundsException("index is more than num's binary length, num=[" + num + "], index=[" + index + "]."); } return num | (1 << index); } /** * 将num所对应的二进制的数中的index位设置为0 * @param num * @param index * @return 设置后的num */ public static int setBitZero(int num, int index){ if (index > Integer.toBinaryString(num).length() - 1){ throw new ArrayIndexOutOfBoundsException("index is more than num's binary length, num=[" + num + "], index=[" + index + "]."); } return num & (~(1 << index)); } public static void main(String[] args) { int num = 6; System.out.println(countBit(num)); System.out.println(getBit(num, 2)); } } <file_sep>package com.starylwu.linklist; /** * @Author: WuYuLong * @Date: Create in 17:13 2018/10/10 * @DESC: 1.单链表的插入、删除、查询 * 2.链表目前存储int类型的值 */ public class SinglyLinkedList { /** * 定义链表头 */ private Node head; /** * 插入(插入到尾部) */ public void add(int value){ Node node = new Node(value, null); if (head == null){ head = node; } else { if (head.next == null){ head.next = node; return; } Node last = head; while (last.next.next != null){ last = last.next; } last.next.next = node; } } /** * 插入(插入到头部) * @param value */ public void addBeforeHeader(int value){ Node node = new Node(value, null); if (head == null){ head = node; } else { node.next = head; head = node; } } /** * 删除 * @param value */ public void delete(int value){ if (head == null){ return; } Node p = head; Node q = null; while (p != null && p.data != value){ q = p; p = p.next; } if (p == null){ return; } if (q == null){ head = head.next; } else { q.next = q.next.next; } } /** * 根据下标获取值 * @param index * @return */ public int get(int index){ if (head == null){ return -1; } int count = 0; Node p = head; while (count < index){ p = p.next; count ++; } if (p == null){ throw new ArrayIndexOutOfBoundsException("index [" + index + "]."); } return p.data; } /** * 获取链表中的第一个值 * @return */ public int getFirst(){ if (head == null){ return -1; } return head.data; } /** * 获取链表中的最后一个值 * @return */ public int getLast(){ if (head == null){ return -1; } Node p = head; while (p.next != null){ p = p.next; } return p.data; } /** * 打印 */ public void print(){ Node p = head; while (p != null){ System.out.print(p.data + " "); p = p.next; } System.out.println(); } public static class Node{ private int data; private Node next; public Node(int data, Node next) { this.data = data; this.next = next; } public Node(int data) { this.data = data; } public int getData() { return data; } } }
feecaffdf3c9a4998d44a3baa7181ae0091d9434
[ "Java" ]
2
Java
star-lywu/string-algorithm
1a2b3e140f055286f0fbbb1749f9c519d1d31823
5d1577dd99610659376c5167f25f23f7da77cc7b
refs/heads/master
<file_sep>'use strict'; const crypto = require('crypto'); const querystring = require('querystring'); const readline = require('readline'); const util = require('util'); const chalk = require('chalk'); const { DateTime, Duration } = require('luxon'); const fetch = require('node-fetch'); const OAuth = require('oauth-1.0a'); const config = require('./config.js'); const sleep = util.promisify(setTimeout) const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); async function question(prompt) { return new Promise(resolve => rl.question(prompt, line => resolve(line))); } function chalkRedIf(text, red) { return red ? chalk.red(text) : text; } const oauth = OAuth({ consumer: { key: config.consumerKey, secret: config.consumerSecret, }, signature_method: 'HMAC-SHA1', hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64'), }); async function getRequestToken() { const url = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob'; const headers = oauth.toHeader(oauth.authorize({ url, method: 'POST', })); const response = await fetch(url, { method: 'POST', headers, }); const responseText = await response.text(); if (!response.ok) { throw responseText; } const responseBody = querystring.parse(responseText); console.debug(responseBody); return { key: responseBody.oauth_token, secret: responseBody.oauth_token_secret, }; } function getAuthorizeUrl(requestToken) { const url = new URL('https://api.twitter.com/oauth/authorize'); url.searchParams.append('oauth_token', requestToken.key); return url.href; } async function getAccessToken(requestToken, pin) { const url = `https://api.twitter.com/oauth/access_token?oauth_token=${requestToken.key}&oauth_verifier=${pin}` const headers = oauth.toHeader(oauth.authorize({ url, method: 'POST', })); const response = await fetch(url, { method: 'POST', headers, }); const responseText = await response.text(); if (!response.ok) { throw responseText; } const responseBody = querystring.parse(responseText); console.debug(responseBody); return { accessToken: { key: responseBody.oauth_token, secret: responseBody.oauth_token_secret, }, userId: responseBody.user_id, screenName: responseBody.screen_name, }; } async function fetchApi(url, accessToken, init) { const headers = oauth.toHeader(oauth.authorize({ url, method: init?.method || 'GET', }, accessToken)); if (init && init.body) { init.body = JSON.stringify(init.body); } const response = await fetch(url, { headers: { ...headers, Accept: 'application/json', 'Content-Type': 'application/json', }, ...init, }); const responseBody = await response.json(); if (!response.ok) { throw responseBody; } console.debug(responseBody); return responseBody; } async function main() { const requestToken = await getRequestToken(); const authorizeUrl = getAuthorizeUrl(requestToken); console.log(`Please open ${authorizeUrl} and authorize this application.`); const pin = (await question('PIN: ')).trim(); const { accessToken, userId } = await getAccessToken(requestToken, pin); const followers = (await fetchApi(`https://api.twitter.com/1.1/followers/list.json?user_id=${userId}&count=200`, accessToken)).users; const friendIds = (await fetchApi(`https://api.twitter.com/1.1/friends/ids.json?user_id=${userId}&count=5000`, accessToken)).ids; for (const follower of followers) { if (friendIds.includes(follower.id)) { continue; } const screenName = follower.screen_name; const isGeneratedScreenName = /^[A-Za-z_]+[0-9]{8,}$/u.test(screenName); const isProtected = follower.protected; const friendsCount = follower.friends_count; const followersCount = follower.followers_count; const friendFollowerRatio = friendsCount / (followersCount || 1); const hasTooManyFriends = followersCount > 10 ? friendFollowerRatio > 10 : friendFollowerRatio > 100; const tweetsCount = follower.statuses_count; const hasTooFewTweets = tweetsCount < 10; const createdAt = DateTime.fromFormat(follower.created_at, 'EEE MMM dd HH:mm:ss ZZZ y'); const age = DateTime.now().diff(createdAt); const isTooYoung = age < Duration.fromObject({ months: 1 }); const unwantedFlags = [isGeneratedScreenName, isProtected, hasTooManyFriends, hasTooFewTweets, isTooYoung]; const isLikelyUnwanted = unwantedFlags.some(it => it); console.log('================================================================================'); console.log(`${follower.name}${follower.verified ? ' 🛡' : ''}${isProtected ? ` ${chalk.bgRed('🔒')}` : ''} (@${chalkRedIf(screenName, isGeneratedScreenName)})`); if (follower.description) { console.log(follower.description); } if (follower.url) { console.log(follower.url); } console.log(`🧑 ${chalkRedIf(`${friendsCount} / ${followersCount}`, hasTooManyFriends)} ⏱️ ${chalkRedIf(createdAt.toLocaleString(DateTime.DATE_FULL), isTooYoung)}${follower.location ? ` 📍 ${follower.location}` : ''} 🐦 ${chalkRedIf(tweetsCount, hasTooFewTweets)}`); console.log(`https://twitter.com/${screenName}`); console.log(`Unwanted score: ${unwantedFlags.filter(it => it).length}/${unwantedFlags.length}`); console.log('================================================================================'); let shouldRemoveFollower = null; while (shouldRemoveFollower === null) { const line = await question(`Remove follower? (${isLikelyUnwanted ? 'Y/n' : 'y/N'}): `); const response = line.trim().toLowerCase(); switch (response) { case 'y': shouldRemoveFollower = true; break; case 'n': shouldRemoveFollower = false; break; case '': shouldRemoveFollower = isLikelyUnwanted; break; } } if (shouldRemoveFollower) { await fetchApi(`https://api.twitter.com/1.1/blocks/create.json?user_id=${follower.id_str}&skip_status=1`, accessToken, { method: 'POST' }); await sleep(3000); await fetchApi(`https://api.twitter.com/1.1/blocks/destroy.json?user_id=${follower.id_str}&skip_status=1`, accessToken, { method: 'POST' }); } } } (async function () { try { await main(); } catch (e) { console.error(e); process.exit(-1); } })(); <file_sep># Twitter Unwanted Follower Remover Semi-automatic command line tool for removing unwanted followers on Twitter. ## Usage ```bash npm install npm start ``` ## License MIT <file_sep>'use strict'; module.exports = { consumerKey: '', consumerSecret: '', };
104ac72fcd4e448bf26653eb0cc0cf39ce927b36
[ "JavaScript", "Markdown" ]
3
JavaScript
zhanghai/twitter-unwanted-follower-remover
3a4ddd4438d4ae12253fa5514feb0070f2e1d7ef
4ef5174baefa1ec0041b8edaf3e129eaed40ce53
refs/heads/master
<repo_name>KingAmirTheHunter/ProxyChecker<file_sep>/ProxCHK.sh #!/bin/bash echo "Enter Path to portscan resualt: " read POSCPath POSCPath="$(while read line; do echo $line; done < $POSCPath)" for n in $POSCPath do echo "Working on $n file name now" OUTPUT="$(curl -Is --proxy $n http://askubuntu.com | head -1)" #echo "${OUTPUT}" if [[ "${OUTPUT}" = *"HTTP/1.1 403 Forbidden"* ]] then echo "Olala" fi done
8f7b40de32f9aa5ab26910c7f347e9c6db9ae009
[ "Shell" ]
1
Shell
KingAmirTheHunter/ProxyChecker
7c25e093e64f3d4834fe6cc2f87f77b9a9902cfa
ab3a91cacd48e7f89dcd359cc8f1da82719cc54c
refs/heads/main
<repo_name>devtamer/password-generator-js<file_sep>/README.md # Command Line Password Generator Node.js command line app to generate random passwords ## Usage enter directory ``` cd password-generator-js ``` Install dependencies ``` npm install ``` Run file ``` node index (options) || newpass (options) ``` To create a symlink to run "passgen" from anywhere ``` npm link # Now you can run passwordgenerator (options) # To remove symlink npm unlink ``` ## Options | Short | Long | Description | | ----- | ----------------- | ------------------------------- | | -l | --length <number> | length of password (default: 12) | | -s | --save | save password to passwords.txt | | -nn | --no-numbers | remove numbers | | -ns | --no-symbols | remove symbols | | -p | --reset | remove all the passwords from the txt file | | -b | --batch <number> | allows for generating unlimited passwords at once (will save to text file by default) | | -h | --help | display help for command | | -V | --version | Show the version | <file_sep>/utils/batchPasswords.js const os = require('os') const createPassword = require('./createPassword') const batchPasswords = (batch) => { let arry = []; for (let i = 0; i < batch; i++) { arry.push((i + 1) + " : " + createPassword() + os.EOL) } return arry.join(" "); } module.exports = batchPasswords;
01c346c84eb8759868ca7eae60bb8cc31ba0c31c
[ "Markdown", "JavaScript" ]
2
Markdown
devtamer/password-generator-js
8e928aac9fd56bd3b669d43dae372ec7d5029023
7df0292061fa513fa91f56b86330b74444dbc013
refs/heads/master
<file_sep><?php require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); require('connect.php'); $app->get( '/', function() { $query = mysql_query("SELECT * FROM links"); $html = ""; while ($row = mysql_fetch_assoc($query)) { $id = $row['id']; $linkTitle = $row['linkTitle']; $linkUrl = $row['linkUrl']; $html .= <<<HTML <p><a href="$linkUrl" target=_blank>$linkTitle</a> | <a href="/changeLink/$id">Change</a> | <a class="delete-link" data-id="$id"> Delete</a></p> HTML; } echo <<<HTML <form action="/uploadLink" method="POST"> <p>Link Title</p> <input type="text" name="linkTitle"> <p>Link URL</p> <input type="text" name="linkUrl"> <br> <input type="submit" value="Submit Link"> </form> <h1>List of Links</h1> $html <script src="/jquery.js"></script> <script> $(document).ready(function() { $('.delete-link').click(function() { var id = $(this).attr('data-id'); $.ajax({ type: 'DELETE', url: '/deleteLink/' + id, success: function() { location.reload(); } }); }); }); </script> HTML; } ); $app->post( '/uploadLink', function() { $linkTitle = $_POST['linkTitle']; $linkUrl = $_POST['linkUrl']; mysql_query("INSERT INTO links (`linkTitle`, `linkUrl`) VALUES ('$linkTitle', '$linkUrl')"); global $app; $app->redirect('/'); } ); $app->get( '/changeLink/:id', function($id) { $query = mysql_query("SELECT * FROM links WHERE id = '$id'"); while ($row = mysql_fetch_assoc($query)) { $linkTitle = $row['linkTitle']; $linkUrl = $row['linkUrl']; } echo <<<HTML <p>Link Title</p> <input type="text" class="linkTitle" value="$linkTitle"> <input type="text" class="linkUrl" value="$linkUrl"> <input type="button" value="Change Link" class="changeLinkButton"> <script src="/jquery.js"></script> <script> $(document).ready(function() { $('.changeLinkButton').click(function() { var title = $('.linkTitle').val(); var url = $('.linkUrl').val(); $.ajax({ url: '/changeLink/$id', type: 'PATCH', data: { linkTitle: title, linkUrl: url }, success: function() { window.location.assign('/'); } }); }); }); </script> HTML; } ); $app->patch( '/changeLink/:id', function($id) { global $app; $request = $app->request(); $data = $request->params(); $linkTitle = $data['linkTitle']; $linkUrl = $data['linkUrl']; mysql_query("UPDATE links SET linkTitle = '$linkTitle', linkUrl = '$linkUrl' WHERE id = '$id'"); } ); $app->delete( '/deleteLink/:id', function($id) { mysql_query("DELETE FROM links WHERE id = '$id'"); } ); $app->run(); <file_sep><?php //Variables for connecting to your database. //These variable values come from your hosting account. $hostname = "localhost"; $username = "udemytes_webapp"; $dbname = "udemytes_webapp"; //These variable values need to be changed by you before deploying $password = "<PASSWORD>"; //Connecting to your database mysql_connect($hostname, $username, $password) or die("error connecting to mysql"); mysql_select_db($dbname) or die("error connecting to database"); ?>
af2f7a9424603ad33cc0c17de3206662f032c8f6
[ "PHP" ]
2
PHP
Chris-Cates/Build-Powerful-RESTful-applications-in-ONE-hour
9394bd301ad69ce56492c9ffba692b2cc70c7f3a
90ac3114e56658c192e19ae8baa1c21e0d71925c
refs/heads/master
<repo_name>litespeeder/docsis-scripts<file_sep>/bin/cm-info #!/usr/bin/env bash CMTS_SNMP_COMMUNITY=public CM_SNMP_COMMUNITY=private usage() { cat << EOF usage: $0 options This script gets Cable Modem RF and SNR levels. More scripts at https://github.com/martinclaro/docsis-scripts/ OPTIONS: -h Show this message -r ipaddr CMTS IP address -k text CMTS SNMP Community (default: ${CMTS_SNMP_COMMUNITY}) -m mac CM MAC address -c text CM SNMP Community (default: ${CM_SNMP_COMMUNITY}) EOF } while getopts “hr:k:m:c:” OPTION do case $OPTION in h) usage exit 1 ;; r) CMTS_IPADDR=$OPTARG ;; k) CMTS_SNMP_COMMUNITY=$OPTARG ;; m) CM_MAC=`echo "$OPTARG" | tr '[:upper:]' '[:lower:]' | sed -e 's,[^a-f0-9],,g'` CM_MAC_OID=`printf "%d.%d.%d.%d.%d.%d" 0x${CM_MAC:0:2} 0x${CM_MAC:2:2} 0x${CM_MAC:4:2} 0x${CM_MAC:6:2} 0x${CM_MAC:8:2} 0x${CM_MAC:10:2}` ;; c) CM_SNMP_COMMUNITY=$OPTARG ;; f) CM_READ_FW=1 ;; ?) usage exit 1 ;; esac done if [ "no${CMTS_IPADDR}" == "no" ] || [ "no${CM_MAC}" == "no" ] || [ "no${CMTS_SNMP_COMMUNITY}" == "no" ]; then usage exit 1 fi printf "\nLoading information... Please wait... " # Force to Unload MIBs export MIBS="" # Loading OIDs SNMP_SYS_DESCR_OID=".1.3.6.1.2.1.1.1.0" # SNMPv2-MIB::sysDescr.0 SNMP_SYS_OBJECTID_OID=".1.3.6.1.2.1.1.2.0" # SNMPv2-MIB::sysObjectID.0 SNMP_SYS_UPTIME_OID=".1.3.6.1.2.1.1.3.0" # DISMAN-EVENT-MIB::sysUpTimeInstance.0 SNMP_SYS_CONTACT_OID=".1.3.6.1.2.1.1.4.0" # SNMPv2-MIB::sysContact.0 SNMP_SYS_NAME_OID=".1.3.6.1.2.1.1.5.0" # SNMPv2-MIB::sysName.0 SNMP_SYS_LOCATION_OID=".1.3.6.1.2.1.1.6.0" # SNMPv2-MIB::sysLocation.0 DOCSIS_CAPABILITY_OID=".1.3.6.1.2.1.10.127.1.1.5.0" # DOCS-IF-MIB::docsIfDocsisBaseCapability.0 CM_SW_ADMIN_STATUS_OID=".1.3.6.1.2.1.69.1.3.3.0" # DOCS-CABLE-DEVICE-MIB::docsDevSwAdminStatus.0 CM_SW_OPER_STATUS_OID=".1.3.6.1.2.1.69.1.3.4.0" # DOCS-CABLE-DEVICE-MIB::docsDevSwOperStatus.0 CMTS_SYSDESCR=`snmpget -v 2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" ${SNMP_SYS_DESCR_OID} | head -1` CMTS_SYSNAME=`snmpget -v 2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" ${SNMP_SYS_NAME_OID}` CMTS_D3_BONDING=0 CMTS_DOCSIS_CAPABILITY=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnvqU "${CMTS_IPADDR}" "${DOCSIS_CAPABILITY_OID}"` case $CMTS_DOCSIS_CAPABILITY in docsis10|1) CMTS_DOCSIS_CAPABILITY=1.0 ;; docsis11|3) CMTS_DOCSIS_CAPABILITY=1.1 ;; docsis20|3) CMTS_DOCSIS_CAPABILITY=2.0 ;; docsis30|4) CMTS_DOCSIS_CAPABILITY=3.0 CMTS_D3_BONDING=1 ;; docsis31|5) CMTS_DOCSIS_CAPABILITY=3.1 CMTS_D3_BONDING=1 ;; *) CMTS_DOCSIS_CAPABILITY=Unknown CMTS_D3_BONDING=1 ;; esac CM_INDEX_OID=".1.3.6.1.2.1.10.127.1.3.7.1.2.${CM_MAC_OID}" CM_INDEX=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" "${CM_INDEX_OID}" | sed -e 's,[^0-9],,g'` if [ "no${CM_INDEX}" == "no" ]; then echo "ERROR: Could not retreive Cable Modem ifIndex from CMTS for ${CM_MAC:0:4}.${CM_MAC:4:4}.${CM_MAC:8:4}. Exiting..." exit 2 fi CM_IPADDR_OID=".1.3.6.1.2.1.10.127.1.3.3.1.3.${CM_INDEX}" # DOCS-IF-MIB::docsIfCmtsCmStatusIpAddress.X CM_RF_DS_OID=".1.3.6.1.2.1.10.127.1.1.1.1.6.3" # DOCS-IF-MIB::docsIfDownChannelPower.3 CM_RF_DS_OID_D3=".1.3.6.1.2.1.10.127.1.1.1.1.6" # DOCS-IF3-MIB::docsIfDownChannelPower.Y CM_RF_US_OID=".1.3.6.1.2.1.10.127.1.2.2.1.3.2" # DOCS-IF-MIB::docsIfCmStatusTxPower.2 CM_RF_US_OID_D3=".1.3.6.1.4.1.4491.2.1.20.1.2.1.1" # DOCS-IF3-MIB::docsIf3CmStatusUsTxPower.Y CM_SNR_DS_OID=".1.3.6.1.2.1.10.127.1.1.4.1.5.3" # DOCS-IF-MIB::docsIfSigQSignalNoise.3 CM_SNR_DS_OID_D3=".1.3.6.1.2.1.10.127.1.1.4.1.5" # DOCS-IF-MIB::docsIfSigQSignalNoise.Y CM_SNR_US_OID=".1.3.6.1.2.1.10.127.1.3.3.1.13.${CM_INDEX}" # DOCS-IF-MIB::docsIfCmtsCmStatusSignalNoise.X CM_SNR_US_OID_D3=".1.3.6.1.4.1.4491.2.1.20.1.4.1.4.${CM_INDEX}" # DOCS-IF3-MIB::docsIf3CmtsCmUsStatusSignalNoise.X CM_IP4ADDR_OID_D3=".1.3.6.1.4.1.4491.2.1.20.1.3.1.5.${CM_INDEX}" # DOCS-IF3-MIB::docsIf3CmtsCmRegStatusIPv4Addr.X CM_IP6ADDR_OID_D3=".1.3.6.1.4.1.4491.2.1.20.1.3.1.3.${CM_INDEX}" # DOCS-IF3-MIB::docsIf3CmtsCmRegStatusIPv6Addr.X # Reading Values CM_IP4ADDR=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" "${CM_IPADDR_OID}" | sed -e 's,[^0-9\.],,g'` CM_IP6ADDR=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" "${CM_IP6ADDR_OID_D3}" | grep -vi '^no such' | sed -e 's,[^0-9a-f\:],,g'` if [ "no${CM_IP4ADDR}" != "no" ] && [ "no${CM_IP4ADDR}" != "no0.0.0.0" ]; then CM_IPADDR=${CM_IP4ADDR} else CM_IP4ADDR=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" "${CM_IP4ADDR_OID_D3}" | sed -e 's,[^0-9\.],,g'` # CM_IP6ADDR=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Onvq "${CMTS_IPADDR}" "${CM_IP6ADDR_OID_D3}" | sed -e 's,[^0-9a-f\:],,g'` if [ "no${CM_IP4ADDR}" != "no" ] && [ "no${CM_IP4ADDR}" != "no0.0.0.0" ]; then CM_IPADDR=${CM_IP4ADDR} elif [ "no${CM_IP6ADDR}" != "no" ] && [ "no${CM_IP6ADDR}" != "no0:0:0:0:0:0:0:0" ]; then CM_IPADDR=udp6:${CM_IP6ADDR} else echo "ERROR: Could not retreive Cable Modem IP address for ${CM_MAC:0:4}.${CM_MAC:4:4}.${CM_MAC:8:4}. Exiting..." exit 3 fi fi if [ "no${CM_IP4ADDR}" == "no" ] || [ "no${CM_IP4ADDR}" == "no0.0.0.0" ]; then CM_IP4ADDR="No IPv4 Available" fi if [ "no${CM_IP6ADDR}" == "no" ] || [ "no${CM_IP6ADDR}" == "no0:0:0:0:0:0:0:0" ]; then CM_IP6ADDR="No IPv6 Available" fi CM_RFP_DS_BONDING=0 CM_RFP_US_BONDING=0 CM_SNR_DS_BONDING=0 CM_SNR_US_BONDING=0 CM_D3_BONDING=0 CM_DOCSIS_CAPABILITY=`snmpget -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnvqU "${CM_IPADDR}" "${DOCSIS_CAPABILITY_OID}"` case $CM_DOCSIS_CAPABILITY in docsis10|1) CM_DOCSIS_CAPABILITY=1.0 ;; docsis11|3) CM_DOCSIS_CAPABILITY=1.1 ;; docsis20|3) CM_DOCSIS_CAPABILITY=2.0 ;; docsis30|4) CM_DOCSIS_CAPABILITY=3.0 CM_D3_BONDING=1 ;; docsis31|5) CM_DOCSIS_CAPABILITY=3.1 CM_D3_BONDING=1 ;; *) CM_DOCSIS_CAPABILITY=Unknown CM_D3_BONDING=1 ;; esac if [ ${CM_D3_BONDING} -eq 0 ]; then CM_RF_DS=`snmpget -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CM_IPADDR} ${CM_RF_DS_OID} | awk '{printf "%0.1f",$1/10}' 2>/dev/null` CM_RF_US=`snmpget -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CM_IPADDR} ${CM_RF_US_OID} | awk '{printf "%0.1f",$1/10}' 2>/dev/null` CM_SNR_DS=`snmpget -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CM_IPADDR} ${CM_SNR_DS_OID} | awk '{printf "%0.1f",$1/10}' 2>/dev/null` CM_SNR_US=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CMTS_IPADDR} ${CM_SNR_US_OID} | awk '{printf "%0.1f",$1/10}' 2>/dev/null` else CM_RF_DS_DA=`snmpgetnext -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CM_IPADDR} ${CM_RF_DS_OID_D3} | grep "^${CM_RF_DS_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` while [ "no${CM_RF_DS_DA}" != "no" ]; do CM_RFP_DS_BONDING=$[ ${CM_RFP_DS_BONDING} + 1 ] CM_RFP_DS_B[ ${CM_RFP_DS_BONDING} ]=`echo "${CM_RF_DS_DA}" | awk '{printf "%4s",$2}'` CM_RF_DS_OID_D3_LAST=`echo "${CM_RF_DS_DA}" | awk '{print $1}'` CM_RF_DS_DA=`snmpgetnext -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CM_IPADDR} ${CM_RF_DS_OID_D3_LAST} | grep "^${CM_RF_DS_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` done CM_RF_US_DA=`snmpgetnext -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CM_IPADDR} ${CM_RF_US_OID_D3} | grep "^${CM_RF_US_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` while [ "no${CM_RF_US_DA}" != "no" ]; do CM_RFP_US_BONDING=$[ ${CM_RFP_US_BONDING} + 1 ] CM_RFP_US_B[ ${CM_RFP_US_BONDING} ]=`echo "${CM_RF_US_DA}" | awk '{printf "%4s",$2}'` CM_RF_US_OID_D3_LAST=`echo "${CM_RF_US_DA}" | awk '{print $1}'` CM_RF_US_DA=`snmpgetnext -v2c -c "${CM_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CM_IPADDR} ${CM_RF_US_OID_D3_LAST} | grep "^${CM_RF_US_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` done CM_SNR_DS_DA=`snmpgetnext -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CM_IPADDR} ${CM_SNR_DS_OID_D3} | grep "^${CM_SNR_DS_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` while [ "no${CM_SNR_DS_DA}" != "no" ]; do CM_SNR_DS_BONDING=$[ ${CM_SNR_DS_BONDING} + 1 ] CM_SNR_DS_B[ ${CM_SNR_DS_BONDING} ]=`echo "${CM_SNR_DS_DA}" | awk '{printf "%4s",$2}'` CM_SNR_DS_OID_D3_LAST=`echo "${CM_SNR_DS_DA}" | awk '{print $1}'` CM_SNR_DS_DA=`snmpgetnext -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CM_IPADDR} ${CM_SNR_DS_OID_D3_LAST} | grep "^${CM_SNR_DS_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` done CM_SNR_US_DA=`snmpgetnext -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CMTS_IPADDR} ${CM_SNR_US_OID_D3} | grep "^${CM_SNR_US_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` if [ "no${CM_SNR_US_DA}" != "no" ]; then while [ "no${CM_SNR_US_DA}" != "no" ]; do CM_SNR_US_BONDING=$[ ${CM_SNR_US_BONDING} + 1 ] CM_SNR_US_B[ ${CM_SNR_US_BONDING} ]=`echo "${CM_SNR_US_DA}" | awk '{printf "%4s",$2}'` CM_SNR_US_OID_D3_LAST=`echo "${CM_SNR_US_DA}" | awk '{print $1}'` CM_SNR_US_DA=`snmpgetnext -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnqU ${CMTS_IPADDR} ${CM_SNR_US_OID_D3_LAST} | grep "^${CM_SNR_US_OID_D3}\." | grep -vi 'no such' | awk '{printf "%s %0.1f",$1,$2/10}' 2>/dev/null` done else CM_SNR_US_B[1]=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CMTS_IPADDR} ${CM_SNR_US_OID_D3}.1 | awk '{printf "%0.1f",$1/10}' | sed -e 's,^0\.0$,,g' 2>/dev/null` CM_SNR_US_B[2]=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CMTS_IPADDR} ${CM_SNR_US_OID_D3}.2 | awk '{printf "%0.1f",$1/10}' | sed -e 's,^0\.0$,,g' 2>/dev/null` CM_SNR_US_B[3]=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CMTS_IPADDR} ${CM_SNR_US_OID_D3}.3 | awk '{printf "%0.1f",$1/10}' | sed -e 's,^0\.0$,,g' 2>/dev/null` CM_SNR_US_B[4]=`snmpget -v2c -c "${CMTS_SNMP_COMMUNITY}" -m all -Ih -OnvqU ${CMTS_IPADDR} ${CM_SNR_US_OID_D3}.4 | awk '{printf "%0.1f",$1/10}' | sed -e 's,^0\.0$,,g' 2>/dev/null` for I in `seq 1 4`; do CM_SNR_US_B[ $I ]=`echo "${CM_SNR_US_B[ $I ]:- }" | awk '{printf "%4s",$1}'` done fi fi # Get Vendor / Model / Firmware from CM CM_SYSDESCR=`snmpget -v 2c -c "${CM_SNMP_COMMUNITY}" -m all -Onvq "${CM_IPADDR}" .1.3.6.1.2.1.1.1.0 | grep '<<' 2>/dev/null` CM_HWREV=`echo "${CM_SYSDESCR}" | sed -e 's,.*<<\(.*\)>>.*,\1,g' | sed -e 's,^.*[Hh][Ww]_[Rr][Ee][Vv]:,,g' | sed -e 's,;.*$,,g' | sed -e 's,^ ,,g' | sed -e 's, $,,g'` CM_VENDOR=`echo "${CM_SYSDESCR}" | sed -e 's,.*<<\(.*\)>>.*,\1,g' | sed -e 's,^.*[Vv][Ev][Nn][Dd][Oo][Rr]:,,g' | sed -e 's,;.*$,,g' | sed -e 's,^ ,,g' | sed -e 's, $,,g'` CM_ROM=`echo "${CM_SYSDESCR}" | sed -e 's,.*<<\(.*\)>>.*,\1,g' | sed -e 's,^.*[Bb][Oo][Oo][Tt][Rr]:,,g' | sed -e 's,;.*$,,g' | sed -e 's,^ ,,g' | sed -e 's, $,,g'` CM_FIRM=`echo "${CM_SYSDESCR}" | sed -e 's,.*<<\(.*\)>>.*,\1,g' | sed -e 's,^.*[Ss][Ww]_[Rr][Ee][Vv]:,,g' | sed -e 's,;.*$,,g' | sed -e 's,^ ,,g' | sed -e 's, $,,g'` CM_MODEL=`echo "${CM_SYSDESCR}" | sed -e 's,.*<<\(.*\)>>.*,\1,g' | sed -e 's,^.*[Mm][Oo][Dd][Ee][Ll]:,,g' | sed -e 's,;.*$,,g' | sed -e 's,^ ,,g' | sed -e 's, $,,g'` # Status SW_ADMIN_STATUS=`snmpget -v 2c -c "${CM_SNMP_COMMUNITY}" -Ih -Onvq -m all ${CM_IPADDR} ${CM_SW_ADMIN_STATUS_OID} 2>/dev/null` SW_OPER_STATUS=`snmpget -v 2c -c "${CM_SNMP_COMMUNITY}" -Ih -Onvq -m all ${CM_IPADDR} ${CM_SW_OPER_STATUS_OID} 2>/dev/null` # Print Results printf "DONE!\n\n" cat << EOF ### Cable Modem ${CM_MAC:0:4}.${CM_MAC:4:4}.${CM_MAC:8:4} ### ### CMTS CMTS System Description: ${CMTS_SYSDESCR} CMTS System Name: ${CMTS_SYSNAME} CMTS DOCSIS Capability: ${CMTS_DOCSIS_CAPABILITY} ### Cable Modem CM DOCSIS Capability: ${CM_DOCSIS_CAPABILITY} EOF if [ ${CM_D3_BONDING} -eq 0 ] || [ ${CMTS_D3_BONDING} -eq 0 ]; then cat << EOF ### Cable Modem RF/SNR Levels Cable Modem IP address: ${CM_IP4ADDR} / ${CM_IP6ADDR} Downstream Power Level: ${CM_RF_DS:-N/A} dBmV Upstream Power Level: ${CM_RF_US:-N/A} TenthdBmV Downstream SNR: ${CM_SNR_DS:-N/A} TenthdB Upstream SNR: ${CM_SNR_US:-N/A} TenthdB EOF else cat << EOF ### Cable Modem RF/SNR Levels Cable Modem IP address: ${CM_IP4ADDR} / ${CM_IP6ADDR} Channel Bonding: Ch 1 | Ch 2 | Ch 3 | Ch 4 | Ch 5 | Ch 6 | Ch 7 | Ch 8 Downstream Power Level: ${CM_RFP_DS_B[1]:- } | ${CM_RFP_DS_B[2]:- } | ${CM_RFP_DS_B[3]:- } | ${CM_RFP_DS_B[4]:- } | ${CM_RFP_DS_B[5]:- } | ${CM_RFP_DS_B[6]:- } | ${CM_RFP_DS_B[7]:- } | ${CM_RFP_DS_B[8]:- } dBmV Upstream Power Level: ${CM_RFP_US_B[1]:- } | ${CM_RFP_US_B[2]:- } | ${CM_RFP_US_B[3]:- } | ${CM_RFP_US_B[4]:- } | ${CM_RFP_US_B[5]:- } | ${CM_RFP_US_B[6]:- } | ${CM_RFP_US_B[7]:- } | ${CM_RFP_US_B[8]:- } TenthdBmV Downstream SNR: ${CM_SNR_DS_B[1]:- } | ${CM_SNR_DS_B[2]:- } | ${CM_SNR_DS_B[3]:- } | ${CM_SNR_DS_B[4]:- } | ${CM_SNR_DS_B[5]:- } | ${CM_SNR_DS_B[6]:- } | ${CM_SNR_DS_B[7]:- } | ${CM_SNR_DS_B[8]:- } TenthdB Upstream SNR: ${CM_SNR_US_B[1]:- } | ${CM_SNR_US_B[2]:- } | ${CM_SNR_US_B[3]:- } | ${CM_SNR_US_B[4]:- } | ${CM_SNR_US_B[5]:- } | ${CM_SNR_US_B[6]:- } | ${CM_SNR_US_B[7]:- } | ${CM_SNR_US_B[8]:- } TenthdB EOF fi cat << EOF ### Current Firmware Vendor: ${CM_VENDOR:-N/A} Model: ${CM_MODEL:-N/A} Hardware Version: ${CM_HWREV:-N/A} Software Version: ${CM_FIRM:-N/A} Boot ROM Version: ${CM_ROM:-N/A} ### Firmware Management Admin Status: ${SW_ADMIN_STATUS:-N/A} Operational Status: ${SW_OPER_STATUS:-N/A} EOF exit 0 <file_sep>/bin/cm-reset #!/usr/bin/env bash CM_SNMP_COMMUNITY=private usage() { cat << EOF usage: $0 options This script reboots a Cable Modem. More scripts at https://github.com/martinclaro/docsis-scripts/ OPTIONS: -h Show this message -i ipaddr CM IP address -c text CM SNMP Community (default: ${CM_SNMP_COMMUNITY}) EOF } while getopts “hi:c:” OPTION do case $OPTION in h) usage exit 1 ;; i) CM_IPADDR=$OPTARG ;; c) CM_SNMP_COMMUNITY=$OPTARG ;; ?) usage exit 1 ;; esac done if [ "no${CM_IPADDR}" == "no" ]; then usage exit 1 fi CM_RESETNOW_OID=".1.3.6.1.2.1.69.1.1.3.0" echo "" echo "### DOCS-CABLE-DEVICE-MIB::docsDevResetNow - ${CM_RESETNOW_OID} ###" echo "" snmpset -v2c -c "${CM_SNMP_COMMUNITY}" -m all -On ${CM_IPADDR} ${CM_RESETNOW_OID} i 1 echo "" exit 0<file_sep>/README.md docsis-scripts ============== DOCSIS &amp; PacketCable Scripts.<file_sep>/bin/cm-dev-log #!/usr/bin/env bash IPADDR=$1 echo "" echo "### DOCS-CABLE-DEVICE-MIB::docsDevEvText - .1.3.6.1.2.1.69.1.5.8.1.7 ###" echo "" snmpbulkwalk -v2c -c private -m all -Onvq $IPADDR .1.3.6.1.2.1.69.1.5.8.1.7 echo "" exit 0<file_sep>/bin/macaddr-format #!/usr/bin/env bash usage() { cat << EOF usage: $0 options This script format a given MAC address to different formats. More scripts at https://github.com/martinclaro/docsis-scripts/ OPTIONS: -h Show this message -m mac MAC address EOF } while getopts “hm:” OPTION do case $OPTION in h) usage exit 1 ;; m) CM_MAC=`echo "$OPTARG" | tr '[:upper:]' '[:lower:]' | sed -e 's,[^a-f0-9],,g'` ;; ?) usage exit 1 ;; esac done if [ "no${CM_MAC}" == "no" ]; then usage exit 1 fi # Showtime CM_MAC_F1=`printf "%s:%s:%s:%s:%s:%s" ${CM_MAC:0:2} ${CM_MAC:2:2} ${CM_MAC:4:2} ${CM_MAC:6:2} ${CM_MAC:8:2} ${CM_MAC:10:2}` CM_MAC_F2=`printf "%s.%s.%s" ${CM_MAC:0:4} ${CM_MAC:4:4} ${CM_MAC:8:4}` CM_MAC_OID=`printf "%d.%d.%d.%d.%d.%d" 0x${CM_MAC:0:2} 0x${CM_MAC:2:2} 0x${CM_MAC:4:2} 0x${CM_MAC:6:2} 0x${CM_MAC:8:2} 0x${CM_MAC:10:2}` cat << EOF MAC 1...: ${CM_MAC_F1} MAC 2...: ${CM_MAC_F2} OID.....: ${CM_MAC_OID} EOF exit 0<file_sep>/bin/oui-search #!/usr/bin/env bash usage() { cat << EOF usage: $0 <oui> This script retrieves OUI information from IEEE.org website. More scripts at https://github.com/martinclaro/docsis-scripts/ EOF } OUI_IN=`echo "${1}" | tr '[:upper:]' '[:lower:]' | sed -e 's,[^a-f0-9],,g'` OUI=${OUI_IN:0:6} if [ "x${OUI}" == "x" ]; then usage exit 1 fi TMP=`mktemp /tmp/oui-search.XXXXXX` curl --request POST \ --data "x=${OUI}&submit2=Search" \ -o "${TMP}" \ --silent \ http://standards.ieee.org/cgi-bin/ouisearch cat "${TMP}" | sed -e :a -e 's/<[^>]*>//g;/</N;//ba' rm -f "${TMP}" exit 0
0c1444a1ae693c6c7316b05d0664c67be6a123ae
[ "Markdown", "Shell" ]
6
Shell
litespeeder/docsis-scripts
b98c1497c4caf57044cceb09a8d6e2f9634c8d01
fd5b4fddba9a2dcc5f6d5c9c7e56dbd39b00ff6c
refs/heads/master
<repo_name>suprMax/expressjs-boilerplate<file_sep>/server/middleware/react.js const React = require('react'); const { renderToString } = require('react-dom/server'); const { StaticRouter } = require('react-router'); const { createLocation } = require('history'); const { Provider } = require('react-redux'); const { runResolver, renderRoutes } = require('react-router-manager'); const createStore = require('../../client/store'); const createRouter = require('../../client/modules/routes'); const { setError } = require('../../client/components/error_handler/state').actions; const { setRoute } = require('../../client/modules/routes/state').actions; const renderContent = ({ routes, store, location, context }) => { const routeComponents = renderRoutes(routes); const routerComponent = React.createElement(StaticRouter, { location, context }, routeComponents); const storeComponent = React.createElement(Provider, { store }, routerComponent); return renderToString(storeComponent); }; const renderPage = (res, store, context, content) => { const statusCode = context.statusCode || 200; Object.assign(res.locals.state, store.getState()); res.status(statusCode).render('index', { content }); }; const renderError = (res, store) => { const state = store.getState(); Object.assign(res.locals.state, state); res.status(state.error.statusCode || 500).render('index'); }; const prerender = (req, res) => { const store = createStore(); const { routes } = createRouter(store); const location = createLocation(req.url); const handleError = (error) => { store.dispatch(setError(error)); console.error(`Request ${req.url} failed to fetch data:`, error); renderError(res, store); }; const getLocals = (details) => ({ ...details, store, location }); const matchPage = () => { const context = {}; const content = renderContent({ routes, store, context, location: req.url }); if (context.url) return res.redirect(context.statusCode || 302, context.url); renderPage(res, store, context, content); }; store.dispatch(setRoute(req.path)); Promise.all(runResolver(routes, req.path, getLocals)).then(matchPage).catch(handleError); }; module.exports = () => prerender; <file_sep>/client/containers/wrapper/index.es import { PureComponent } from 'react'; import { fetchWrapperData } from './state'; class Wrapper extends PureComponent { componentDidMount() { // Fetch additional information here console.log('Wrapper mounted'); } render() { return this.props.children; } } // Fetch on server side here Wrapper.resolver = ({ store }) => store.dispatch(fetchWrapperData()); export default Wrapper; <file_sep>/build/utils.js const config = require('uni-config'); const { spawn } = require('child_process'); const { resolve: pathResolve } = require('path'); const chalk = require('chalk'); const ROOT_PATH = `${pathResolve(`${__dirname}/..`)}/`; const utils = { isBuild() { return process.argv[2] === 'build'; }, pathNormalize(path) { return `${path.replace(`${__dirname}/../`, '').replace(ROOT_PATH, '')}`; }, benchmarkReporter(action, startTime) { console.log(chalk.magenta(`${action} in ${((Date.now() - startTime) / 1000).toFixed(2)}s`)); }, watchReporter(path) { console.log(chalk.cyan(`File ${path} changed, flexing 💪`)); }, errorReporter(e) { console.log(chalk.bold.red(`Build error!\n${e.stack || e}`)); if (utils.isBuild()) process.exit(1); }, run(string, options = {}) { const [command, ...args] = string.split(' '); const executor = (resolve, reject) => { let output = ''; let errors = ''; const stream = spawn(command, args, options.options); const handleData = (chunk) => { output += chunk; if (!options.silent) process.stdout.write(chunk); }; const handleError = (chunk) => { errors += chunk; if (!options.silent) process.stderr.write(chunk); }; const handleExit = (exitCode) => { const result = { exitCode, output, errors }; if (exitCode) return reject(result); return resolve(result); }; stream.stdout.on('data', handleData); stream.stderr.on('data', handleError); stream.on('exit', handleExit); }; return new Promise(executor); }, getReplacementRules() { return [ { from: /config\.debug/g, to: config.debug }, { from: /config\.sandbox/g, to: config.sandbox }, { from: /process\.browser/g, to: true }, ]; }, }; module.exports = utils; <file_sep>/build/styles.js const gulp = require('gulp'); const config = require('uni-config'); const utils = require('./utils'); const source = `${__dirname}/../styles/index.styl`; const stylusOptions = { errors: config.debug, sourcemaps: config.debug, paths: [ `${__dirname}/../client`, `${__dirname}/../node_modules`, ], 'include css': true, urlfunc: 'embedurl', linenos: config.debug, rawDefine: { $publicRoot: `${__dirname}/../${config.build.public_root}`, }, }; const process = (options = {}) => { const startTime = Date.now(); const name = 'app.css'; const executor = (resolve) => { const stream = gulp .src(source) .pipe(require('gulp-stylus')(stylusOptions)) .pipe(require('gulp-postcss')([ require('autoprefixer')(), require('postcss-flexbugs-fixes'), ])) .on('error', utils.errorReporter) .pipe(require('gulp-rename')(name)) .pipe(gulp.dest(`${__dirname}/../${config.build.assets_location}`)) .on('end', () => { utils.benchmarkReporter(`Stylusified ${utils.pathNormalize(source)}`, startTime); resolve(name); }); if (options.pipe) options.pipe(stream); }; return new Promise(executor); }; module.exports = process; <file_sep>/client/containers/home/index.es import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { renderRedirect } from 'react-router-manager'; import ErrorCatcher from '../../components/error_handler'; import ErrorBoundary from '../../components/error_boundary'; import { fetchHomeData } from './state'; class HomePage extends PureComponent { constructor(props) { super(props); this.state = { redirect: false }; this.handleUpdate = this.handleUpdate.bind(this); } componentDidMount() { // Fetch additional information here console.log('Home page mounted'); } handleUpdate({ target: { checked } }) { this.setState({ redirect: checked }); } render() { const { homeData, wrapperData } = this.props; const { redirect } = this.state; if (redirect) return renderRedirect({ to: '/prompt', statusCode: 307 }); return ( <ErrorBoundary> <div className="HomePage"> It works! <Link to="/prompt">Prompt?</Link> <pre>{JSON.stringify({ homeData, wrapperData }, null, 2)}</pre> <label> <input type="checkbox" checked={redirect} onChange={this.handleUpdate} /> Delayed redirect </label> <ErrorCatcher /> </div> </ErrorBoundary> ); } } // Fetch on server side here HomePage.resolver = ({ store }) => store.dispatch(fetchHomeData()); const mapStateToProps = ({ homeData, wrapperData }) => ({ homeData, wrapperData }); export default connect(mapStateToProps)(HomePage); <file_sep>/client/containers/home/state.es const FETCH_HOME_DATA = 'FETCH_HOME_DATA'; const getAsyncAction = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout)); export const fetchHomeData = () => ((dispatch) => { dispatch({ type: FETCH_HOME_DATA }); return getAsyncAction(1000).then( () => dispatch({ type: `${FETCH_HOME_DATA}_RESOLVED` }), () => dispatch({ type: `${FETCH_HOME_DATA}_REJECTED` }), ); }); export const reducer = (state = {}, action) => { switch (action.type) { case `${FETCH_HOME_DATA}_RESOLVED`: { return { loadedTimes: (state.loadedTimes || 0) + 1 }; } default: { return state; } } }; <file_sep>/README.md ExpressJS Boilerplate ===================== ExpressJS boilerplate with SSR React SPA frontend. Includes Babel, Redux and React Router. ## Usage: 1. Install NodeJS: It is recommended to install NodeJS with a native installer via [NodeJS.org website](https://nodejs.org/). If you prefer using Homebrew (`brew install node`), it will break your NPM installation. Here's a [fix](https://gist.github.com/DanHerbert/9520689). 2. Install dependencies: `npm install` 3. Start server: `npm start` and navigate your browser to [http://localhost:3000/](http://localhost:3000/) 4. ??? 5. PROFIT ## Production mode: `npm run production` Supported environment variables: ```` NODE_ENV(string): environment to use, like 'production' PORT(int): port to bind to SANDBOX(bool): run in sandboxed mode - useful for running fake production environment ```` Read through source for more information. ## License [MIT](http://opensource.org/licenses/MIT) © [<NAME>](http://max.degterev.me/) <file_sep>/client/containers/prompt/index.es import React, { PureComponent } from 'react'; import { Link } from 'react-router-dom'; import ErrorBoundary from '../../components/error_boundary'; class PromptPage extends PureComponent { constructor(props) { super(props); this.state = { prevent: true, delay: true }; this.handleNavigate = this.handleNavigate.bind(this); } componentDidMount() { // Fetch additional information here console.log('Prompt page mounted'); this.unblock = this.props.history.block(this.handleNavigate); } componentWillUnmount() { this.unblock(); } handleNavigate(location, action, callback) { const { prevent, delay } = this.state; console.warn(`Attempting to navigate to ${location.pathname}`, this.state); if (!delay) return !prevent; setTimeout(() => callback(!prevent), 1500); } handleUpdate(prop) { return ({ target: { checked } }) => this.setState({ [prop]: checked }); } render() { const { prevent, delay } = this.state; return ( <ErrorBoundary> <div className="PromptPage"> Try navigating away, I dare you! <label> <input type="checkbox" checked={prevent} onChange={this.handleUpdate('prevent')} /> Prevent navigation? </label> <label> <input type="checkbox" checked={delay} onChange={this.handleUpdate('delay')} /> Delay? </label> <Link to="/">Home page</Link> </div> </ErrorBoundary> ); } } export default PromptPage; <file_sep>/client/components/error_handler/index.es import React from 'react'; import { connect } from 'react-redux'; const ErrorCatcher = ({ error }) => { if (!error) return null; return <pre className="ErrorCatcher">{JSON.stringify(error, null, 2)}</pre>; }; const mapStateToProps = ({ error }) => ({ error }); export default connect(mapStateToProps)(ErrorCatcher); <file_sep>/gulpfile.js const config = require('uni-config'); const gulp = require('gulp'); const MINIFICATION_RULES = { suffix: '.min', }; const ASSETS_LOCATION = `${__dirname}/${config.build.assets_location}`; const SERVER_BUILD_LOCATION = `${__dirname}/.compiled`; gulp.task('clean', () => require('del')([ASSETS_LOCATION])); gulp.task('clean:server', () => require('del')([SERVER_BUILD_LOCATION])); gulp.task('scripts', () => require('./build/scripts')()); gulp.task('scripts:server', () => require('./build/server')(SERVER_BUILD_LOCATION)); gulp.task('styles', () => require('./build/styles')()); gulp.task('decache:styles', () => ( gulp .src([ `${ASSETS_LOCATION}/*.css`, `!${ASSETS_LOCATION}/*.min.*`, `!${ASSETS_LOCATION}/*.min-*`, ]) .pipe(require('gulp-css-decache')({ base: `${__dirname}/public`, logMissing: true, })) .pipe(gulp.dest(ASSETS_LOCATION)) )); gulp.task('minify:scripts', () => ( gulp .src([ `${ASSETS_LOCATION}/*.js`, `!${ASSETS_LOCATION}/*.min.*`, `!${ASSETS_LOCATION}/*.min-*`, ]) .pipe(require('gulp-minify')({ mangle: true, compress: { drop_console: true }, output: { max_line_len: 64000 }, })) .pipe(require('gulp-rename')(MINIFICATION_RULES)) .pipe(gulp.dest(ASSETS_LOCATION)) )); gulp.task('minify:styles', () => ( gulp .src([ `${ASSETS_LOCATION}/*.css`, `!${ASSETS_LOCATION}/*.min.*`, `!${ASSETS_LOCATION}/*.min-*`, ]) .pipe(require('gulp-clean-css')({ processImport: false, keepSpecialComments: 0, aggressiveMerging: false, })) .pipe(require('gulp-rename')(MINIFICATION_RULES)) .pipe(gulp.dest(ASSETS_LOCATION)) )); gulp.task('hashify', () => { const rev = require('gulp-rev'); return gulp .src(`${ASSETS_LOCATION}/*.min.*`) .pipe(rev()) .pipe(gulp.dest(ASSETS_LOCATION)) .pipe(rev.manifest('hashmap.json')) .pipe(gulp.dest(ASSETS_LOCATION)); }); gulp.task('compress', () => ( gulp .src([ `${ASSETS_LOCATION}/*-*.min.*`, `!${ASSETS_LOCATION}/*.gz`, ]) .pipe(require('gulp-gzip')()) .pipe(gulp.dest(ASSETS_LOCATION)) )); const buildSequence = [ 'clean', gulp.parallel('scripts', 'styles'), 'decache:styles', gulp.parallel('minify:scripts', 'minify:styles'), 'hashify', 'compress', ]; const compileSequence = [ 'clean', gulp.parallel('scripts', 'styles'), ]; gulp.task('build', gulp.series(...buildSequence)); gulp.task('compile', gulp.series(...compileSequence)); gulp.task('compile:server', gulp.series('clean:server', 'scripts:server')); gulp.task('lint', () => require('./build/linters')().lintRun()); gulp.task('lint:scripts', () => require('./build/linters')().lintScripts()); gulp.task('lint:styles', () => require('./build/linters')().lintStyles()); gulp.task('lint:tofile', () => require('./build/linters')().lintRun({ toFile: true })); gulp.task('default', () => { // Gotta make sure each of these functions returns a promise const compileScripts = require('./build/scripts'); const promises = [ compileScripts('polyfills.js'), compileScripts('app.js', { watch: true }), require('./build/styles')(), ]; return Promise.all(promises).then(require('./build/watcher')); }); <file_sep>/server/middleware/locals.js const config = require('uni-config'); const pick = require('lodash/pick'); const serialize = require('serialize-javascript'); const asset = require('../../build/assetmanager'); const injectLocals = (req, res, next) => { const locals = { config, pick, asset, serialize, // used by Pug to have unminified output pretty: config.debug, state: {}, }; Object.assign(res.locals, locals); next(); }; module.exports = () => injectLocals; <file_sep>/client/containers/testroute/index.es import React, { PureComponent } from 'react'; import ErrorCatcher from '../../components/error_handler'; import ErrorBoundary from '../../components/error_boundary'; class TestRoute extends PureComponent { componentDidMount() { // Fetch additional information here console.log('TestRoute page mounted'); } render() { console.warn('TestRoute render', this.props); return ( <ErrorBoundary> <div className="TestRoute"> This is testroute {this.props.match.params.name} </div> {this.props.children} <ErrorCatcher /> </ErrorBoundary> ); } } // Fetch on server side here TestRoute.resolver = ({ match }) => { console.warn('Resolver in TestRoute', match); return Promise.resolve(); }; export default TestRoute; <file_sep>/client/modules/routes/index.es export default () => { const routes = [ { path: '*', // Needed for the fetch to work, OK to leave empty for routes that don't load data component: require('../../containers/wrapper'), routes: [ { path: '/', exact: true, component: require('../../containers/home'), }, { path: '/testroute/:id(\\d+)', exact: false, component: require('../../containers/testroute'), routes: [ { path: '/testroute/:id(\\d+)/:name', component: require('../../containers/testroute'), }, { to: '/youfailed', }, ], }, { path: '/prompt', component: require('../../containers/prompt'), }, { from: '/redirect', to: '/', statusCode: 307, }, { path: '/onenter', onEnter() { return { statusCode: 307, to: '/redirectedfromonenter' }; }, render() { return 'AwesomeRoute!'; }, }, { component: require('../../containers/error_404'), statusCode: 404, }, ], }, ]; return { routes }; }; <file_sep>/build/watcher.js const gulp = require('gulp'); const config = require('uni-config'); const utils = require('./utils'); const nodemonOptions = { script: 'app.js', ext: 'js json es', watch: [ 'config/*', 'server/*', ], ignore: [ 'build/*', 'test/*', 'vendor/*', ], }; const clientFiles = [ 'client/*', ]; if (config.server.prerender) { nodemonOptions.watch = nodemonOptions.watch.concat(clientFiles); } else { nodemonOptions.ignore = nodemonOptions.ignore.concat(clientFiles); } // can dick around checking if port is up, but fuck it const SERVER_RESTART_TIME = 1500; const watcher = () => { const livereload = require('tiny-lr'); const compileScripts = require('./scripts'); const compileStyles = require('./styles'); let nodemonRestarts = 0; // relative paths required for watch/Gaze to detect changes in new files const scripts = [ 'client/**/*.es', 'vendor/**/*.es', 'client/**/*.js', 'vendor/**/*.js', 'client/**/*.json', 'vendor/**/*.json', '!client/polyfills.es', ]; const stylesheets = [ 'client/**/*.styl', 'styles/**/*.styl', 'styles/**/*.css', 'vendor/**/*.css', ]; const templates = [ 'templates/**/*.pug', ]; livereload().listen(); const nodemon = require('nodemon')(nodemonOptions); const handleReload = (name) => livereload.changed(name); const handleNoPrerenderReload = (name) => { if (!config.server.prerender) handleReload(name); }; const handleServerReload = () => setTimeout(() => handleReload('server.js'), SERVER_RESTART_TIME); gulp.watch(scripts).on('change', (path) => { const options = { watch: true }; utils.watchReporter(path); compileScripts('app.js', options).then(handleNoPrerenderReload); }); gulp.watch(stylesheets).on('change', (path) => { utils.watchReporter(path); compileStyles().then(handleReload); }); gulp.watch(templates).on('change', (path) => { utils.watchReporter(path); handleServerReload(); }); nodemon.on('start', () => { if (nodemonRestarts) handleServerReload(); nodemonRestarts += 1; }); nodemon.on('restart', (files = []) => { files.map(utils.pathNormalize).forEach(utils.watchReporter); }); nodemon.on('log', (log) => { console.log(log.colour); }); }; module.exports = watcher; <file_sep>/server/index.js const app = require('express')(); const config = require('uni-config'); const { middleware: gracefulMiddleware, start: gracefulStart } = require('gracefultools'); const setRequestHandlers = () => { app.use(require('express-domain-middleware')); app.use(gracefulMiddleware()); app.use(require('middleware-sanitizeurl')({ log: true })); app.use(require('morgan')(config.debug ? 'dev' : 'combined')); // Static middleware is not needed in production, but still loaded for debug purposes, // E.g. running production mode locally if (config.sandbox) { app.use(require('serve-favicon')(`${__dirname}/../public/favicon.ico`)); app.use(require('serve-static')(`${__dirname}/../public`, { redirect: false })); } app.use(require('middleware-trailingslash')()); app.use(require('./middleware/locals')()); if (config.debug) app.use(require('connect-livereload')()); // This middleware has to go right before catchall because it ends requests if (config.server.prerender) app.use(require('./middleware/react')()); app.get('*', require('./controllers/default')()); if (config.debug) app.use(require('errorhandler')({ dumpExceptions: true, showStack: true })); }; const startListening = () => { const host = process.env.HOST || config.server.host; const port = parseInt(process.env.PORT, 10) || config.server.port || 3000; // usually sitting behind nginx app.enable('trust proxy'); app.disable('x-powered-by'); app.set('port', port); app.set('views', `${__dirname}/../templates`); app.set('view engine', 'pug'); if (config.debug) app.set('json spaces', 2); setRequestHandlers(); gracefulStart(app, { host, port }); }; module.exports = startListening; <file_sep>/build/server.js const gulp = require('gulp'); const fs = require('fs'); const path = require('path'); const utils = require('./utils'); const process = (targetFolder) => { const base = `${__dirname}/..`; const createFolder = () => { const startTime = Date.now(); const promise = utils.run(`mkdir -p ${targetFolder}`); promise .then(() => utils.benchmarkReporter(`Created ${targetFolder}`, startTime)) .catch(utils.errorReporter); return promise; }; const createSymlinks = () => { const startTime = Date.now(); const folders = [ 'build', 'public', 'templates', 'vendor', ]; const promises = folders.map((dir) => ( utils.run(`ln -s ../${dir} ${dir}`, { options: { cwd: targetFolder } }) )); const promise = Promise.all(promises); promise .then(() => utils.benchmarkReporter(`Created symlinks for ${folders.join(', ')}`, startTime)) .catch(utils.errorReporter); return promise; }; const copyFiles = () => { const startTime = Date.now(); const executor = (resolve) => { gulp .src([ `${base}/client/**/*.js`, `${base}/server/**/*.js`, ], { base }) .on('error', utils.errorReporter) .pipe(gulp.dest(targetFolder)) .on('end', () => { utils.benchmarkReporter('Copied source files', startTime); resolve(); }); }; return new Promise(executor); }; const compileBabel = (dir) => { const startTime = Date.now(); const source = path.resolve(`${base}/${dir}`); const target = path.resolve(`${targetFolder}/${dir}`); const command = `babel ${source} --out-dir ${target}`; const promise = utils.run(command, { silent: true }); promise .then(() => utils.benchmarkReporter(`Compiled es files in ${dir}`, startTime)) .catch(utils.errorReporter); return promise; }; const createLauncher = () => { const startTime = Date.now(); const content = 'require(\'./server\')();'; const destination = path.resolve(`${targetFolder}/app.js`); const executor = (resolve) => { const complete = (error) => { utils.benchmarkReporter('Launcher file created', startTime); if (error) utils.errorReporter(error); resolve(); }; fs.writeFile(destination, content, complete); }; return new Promise(executor); }; const startTime = Date.now(); const promise = createFolder().then(() => Promise.all([ createSymlinks(), copyFiles(), compileBabel('./client'), compileBabel('./server'), createLauncher(), ])); promise.then(() => utils.benchmarkReporter('Server compilation complete', startTime)); return promise; }; module.exports = process; <file_sep>/client/store.es import config from 'uni-config'; import { createStore, applyMiddleware, combineReducers } from 'redux'; const reducers = { route: require('./modules/routes/state').reducer, error: require('./components/error_handler/state').reducer, homeData: require('./containers/home/state').reducer, wrapperData: require('./containers/wrapper/state').reducer, }; const middleware = [ require('redux-thunk').default, ]; if (config.debug) { middleware.push(require('redux-immutable-state-invariant').default()); } if (config.sandbox) { const loggerOptions = { duration: true }; if (!process.browser) { const extras = { duration: true, colors: false, level: { prevState() { return false; }, nextState() { return false; }, action() { return 'log'; }, error() { return 'error'; }, }, }; Object.assign(loggerOptions, extras); } middleware.push(require('redux-logger').createLogger(loggerOptions)); } const createFromState = (initialState) => ( createStore(combineReducers(reducers), initialState, applyMiddleware(...middleware)) ); export default createFromState; <file_sep>/client/components/error_handler/state.es import config from 'uni-config'; export const types = { ERROR_SET: 'ERROR_SET', }; export const actions = { setError(payload) { if (config.debug && payload instanceof Error) console.error(payload.stack); return { type: types.ERROR_SET, payload }; }, }; export const reducer = (state = null, action) => { switch (action.type) { case types.ERROR_SET: { return action.payload; } default: { return state; } } }; <file_sep>/config/default.js module.exports = { build: { assets_location: 'public/assets', public_root: 'public', }, server: { prerender: false, }, }; <file_sep>/client/containers/error_404/index.es import React from 'react'; const Error404 = () => ( <div className="Error404"> Error404 page </div> ); export default Error404;
dbaaa0205347c097703d6ea4c6e2c9094d84b6ed
[ "JavaScript", "Markdown" ]
20
JavaScript
suprMax/expressjs-boilerplate
42016b6d3a873fe61c27b3d795191430c8aed44f
f8f5af6f161ba9fa14b296f5ffa2cc1ca13463d2
refs/heads/master
<repo_name>lbolla/learning-go<file_sep>/Q4_2.go package main import ( "fmt" "unicode/utf8" ) func main() { const s string = "asSASA ddd dsjkdsjs dk" fmt.Println(len([]byte(s)), utf8.RuneCount([]byte(s))) } <file_sep>/Q2_3.go package main import "fmt" func main() { const n = 10 var a [n]int for i := 0; i < n; i++ { a[i] = i } fmt.Printf("%v\n", a) } <file_sep>/Q4_3.go package main import ( "fmt" ) func main() { var s string = "asSASA ddd dsjkdsjs dk" fmt.Println(s) c := []rune(s) r := []rune("abc") for i := 0; i < len(r); i++ { c[4 + i] = r[i] } fmt.Println(string(c)) } <file_sep>/Q2_2.go package main import "fmt" func main() { i := 0 L: fmt.Printf("%d\n", i) i++ if i < 10 { goto L } } <file_sep>/README.md learning-go =========== Code from Learning Go book (http://www.miek.nl/files/go/).
dc213edbcbe8c2f8ccc7ed3ca6b6eef64624dbd0
[ "Markdown", "Go" ]
5
Go
lbolla/learning-go
4606bb3973aa0c5f002a0930531c88e02162fab6
680b0c95e5a5ec3a1475868b828c3f80f96527f8