branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>#coding:utf8
"""
Author : zhangwenqi
Description : 读取excel内容
CreateTime : 2019-08-05
"""
import openpyxl
class ObtainEexcel():
def __init__(self,filename,sheetname):
self.filename = filename
self.handxl = openpyxl.load_workbook(filename)
self.sheet = self.handxl.get_sheet_by_name(sheetname)
self.row_no = self.sheet.max_row
self.column_no = self.sheet.max_column
"""获取所有的sheet名称"""
def obtain_sheets_name(self):
return self.handxl.get_sheet_names()
"""获取表格内容"""
def obtain_table_value(self,row,column):
return self.sheet.cell(row=row,column=column).value
"""写入表格内容"""
def set_table_value(self, row, column,value):
self.sheet.cell(row=row, column=column).value = value
"""获取所有行数据"""
def obtain_table_rows_value(self):
list_rows_value = []
for i in self.sheet.iter_rows():
list_rows_value.append([j.value for j in i])
return list_rows_value
"""获取所有列数据"""
def obtain_table_columns_value(self):
list_columns_value = []
for i in self.sheet.iter_cols():
list_columns_value.append([j.value for j in i])
return list_columns_value
"""通过表名标题去找对应数据"""
def obtain_position_by_table(self,table_name):
tables = self.sheet.iter_rows().__next__()
return [i.value for i in tables].index(table_name)+1
def obtain_values_by_position(self,table_name,target_value):
position = self.obtain_position_by_table(table_name)
list_values = self.obtain_table_rows_value()
result_values = []
for i in list_values:
if i[position-1] == target_value:
result_values.append(i)
return result_values
def table_values_sort(self,table_name,values):
position = self.obtain_position_by_table(table_name)
return sorted(values,key=lambda x:x[position-1])
"""保存excel"""
def save(self):
self.handxl.save(self.filename)
self.handxl.close()<file_sep>from flask import Blueprint
target_cycle_summary = Blueprint('target_cycle_summary', __name__)
# 查询目标库
@target_cycle_summary.route('/query_name/<user_name>', methods=['GET'])
def query_by_name(user_name):
return "hello1"<file_sep>#coding:utf8
"""
Author : zhangwenqi
Description : http请求发送工具
CreateTime : 2019-08-05
"""
import requests
from conf import test_jar_conf
from common.result import ResultMessage
class ObtainRequests():
def __init__(self,url,method,headers=None,query=None,body=None,body_type=None):
self.url = url
self.method = method
self.headers = headers
self.query = query
self.body = body
self.body_type = body_type
"""
Description : 发请求实体
CreateTime : 2019-08-05
"""
def obtain_requests(self):
method = self.method.upper()
if self.body_type is not None and isinstance(self.body_type,str):
self.body_type = self.body_type.upper()
code = self._check_requests_parame(self.url,self.method,self.headers,self.query,self.body,self.body_type)
respons = None
result_message = ResultMessage()
if code != test_jar_conf.API_REQUESTS_SUCCESS_CODE:
result_message.errcode = code
return result_message.result()
if method == "GET":
if self.headers is not None:
if self.query is not None:
respons = requests.get(self.url,headers=self.headers,params=self.query)
else:
if self.query is not None:
respons = requests.get(self.url,params=self.query)
else:
respons = requests.get(self.url)
if method == "POST":
if self.headers is not None:
if self.query is not None:
if self.body is not None:
if self.body_type == "JSON":
#body = json.dumps(body)
respons = requests.post(self.url,headers=self.headers,params=self.query,json=self.body)
elif self.body_type == "FORM":
respons = requests.post(self.url,headers=self.headers,params=self.query,data=self.body)
else:
respons = requests.post(self.url, headers=self.headers, params=self.query)
else:
if self.body is not None:
if self.body_type == "JSON":
#body = json.dumps(body)
respons = requests.post(self.url,headers=self.headers,json=self.body)
elif self.body_type == "FORM":
respons = requests.post(self.url,headers=self.headers,data=self.body)
else:
respons = requests.post(self.url, headers=self.headers)
else:
if self.query is not None:
if self.body is not None:
if self.body_type == "JSON":
# body = json.dumps(body)
respons = requests.post(self.url, params=self.query, json=self.body)
elif self.body_type == "FORM":
respons = requests.post(self.url, params=self.query, data=self.body)
else:
respons = requests.post(self.url ,params=self.query)
else:
if self.body is not None:
if self.body_type == "JSON":
# body = json.dumps(body)
respons = requests.post(self.url, json=self.body)
elif self.body_type == "FORM":
respons = requests.post(self.url, data=self.body)
else:
respons = requests.post(self.url)
result_message.data = respons
result_message.errcode = code
return result_message
"""
Description : 校验请求参数准确性方法
CreateTime : 2019-08-05
"""
@staticmethod
def _check_requests_parame(url,method,headers=None,query=None,body=None,body_type=None):
if not isinstance(url,str):
return test_jar_conf.API_REQUESTS_URL_TYPE_ERROR_CODE
if not url.startswith("http://") and not url.startswith("https://"):
return test_jar_conf.API_REQUESTS_URL_TYPE_ERROR_CODE
if not isinstance(method,str):
return test_jar_conf.API_REQUESTS_METHOD_CONTENT_ERROR_CODE
if method not in test_jar_conf.API_REQUESTS_METHOD_LIST:
return test_jar_conf.API_REQUESTS_METHOD_CONTENT_ERROR_CODE
if headers is not None:
if isinstance(headers, str):
try:
headers = eval(headers)
if not isinstance(headers,dict):
return test_jar_conf.API_REQUESTS_HEADER_CONTENT_ERROR_CODE
except:
return test_jar_conf.API_REQUESTS_HEADER_CONTENT_ERROR_CODE
elif not isinstance(headers, dict):
return test_jar_conf.API_REQUESTS_HEADER_CONTENT_ERROR_CODE
if query is not None:
if isinstance(query, str):
try:
query = eval(query)
if not isinstance(query, dict):
return test_jar_conf.API_REQUESTS_QUERY_CONTENT_ERROR_CODE
except:
return test_jar_conf.API_REQUESTS_QUERY_CONTENT_ERROR_CODE
elif not isinstance(query, dict):
return test_jar_conf.API_REQUESTS_QUERY_CONTENT_ERROR_CODE
if body is not None:
if isinstance(body, str):
try:
body = eval(body)
if not isinstance(body, dict):
return test_jar_conf.API_REQUESTS_BODY_CONTENT_ERROR_CODE
except:
return test_jar_conf.API_REQUESTS_BODY_CONTENT_ERROR_CODE
elif not isinstance(body, dict):
return test_jar_conf.API_REQUESTS_BODY_CONTENT_ERROR_CODE
if not body_type in test_jar_conf.API_REQUESTS_BODY_TYPE_LIST:
return test_jar_conf.API_REQUESTS_BODY_TYPE_ERROR_CODE
return test_jar_conf.API_REQUESTS_SUCCESS_CODE
if __name__ == "__main__":
o = ObtainRequests("http://www.didi.com","GET")
print(o.obtain_requests().data.text)<file_sep>#coding:utf8
"""
Author : zhangwenqi
Description : 定义统一返回结果
CreateTime : 2019-08-21
"""
import json
class ResultMessage:
def __init__(self):
#响应状态码
self.__errcode = None
#响应结果
self.__message = None
#传输数据
self.__data = None
@property
def errcode(self):
return self.__errcode
@property
def message(self):
return self.__message
@property
def data(self):
return self.__data
@errcode.setter
def errcode(self,errcode):
if isinstance(errcode,int):
self.__errcode = errcode
else:
raise TypeError("需要传入整型")
@message.setter
def message(self,message):
if isinstance(message,str):
self.__message = message
else:
raise TypeError("需要传入字符串")
@data.setter
def data(self,data):
self.__data = data
def result(self):
dict_result = {"errcode":self.__errcode,"message":self.__message,"data":self.__data}
return json.dumps(dict_result)<file_sep># -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.automap import automap_base
class BaseDao(object):
#数据库表对象
__base_class = None
#数据库表名
_table_name = None
#数据库配置
_db_conf = None
@staticmethod
def init(app):
print(app)
BaseDao._db_conf = app
def __init__(self,encoding='utf-8', echo=False):
self._engine = create_engine(BaseDao._db_conf.config.get("SQLALCHEMY_DATABASE_URI"), encoding=encoding, echo=echo)
session_class = sessionmaker(self._engine)
self._session = session_class()
def _table_query(self, table_name):
""" 避免重复加载,同时只是用execute时,不加载以下内容 """
if self.__base_class is None:
self.__base_class = automap_base()
self.__base_class.prepare(self._engine, reflect=True)
if hasattr(self.__base_class.classes, table_name):
table = getattr(self.__base_class.classes, table_name)
return self._session.query(table)
else:
raise KeyError(f"未搜寻到表: {table_name}")
def execute_sql(self, sql_str, ft = {}):
"""
执行sql语句,区分查询跟修改操作
cursor支持fetchall(),fetchone(),fetchmany(),rowcount
"""
sql_str = sql_str.format(**ft).strip().replace("\n", "").replace("\t", "")
if sql_str.startswith("select"):
cursor = self._engine.execute(sql_str)
return cursor
try:
affect_row = self._engine.execute(sql_str).rowcount
self._session.commit()
return affect_row
except Exception as e:
self._session.rollback()
self.close()
raise e
def execute_many_sql(self, many_sql, ft,separator=";"):
""" 执行多条sql, sql语句之间使用;号分割,方便执行多条修改语句 """
sql_list = many_sql.format(**ft).strip().replace("\n", "").replace("\t", "").split(separator)
sql_list = [sql for sql in sql_list if sql.strip() != ""]
for sql_str in sql_list:
self.execute_sql(sql_str,ft)
def delete(self, ft=None):
""" 表名 + dict(key=word), 根据ft条件删除数据 """
ft = {} if ft is None else ft
delete_row = self._table_query(self._table_name).filter_by(**ft).delete()
self._session.commit()
return delete_row
def first(self, ft=None):
""" 一行数据 """
ft = {} if ft is None else ft
first_row = self._table_query(self._table_name).filter_by(**ft).first()
return first_row
def all(self, ft=None):
""" 所有数据 """
ft = {} if ft is None else ft
all_row = self._table_query(self._table_name).filter_by(**ft).all()
return all_row
def count(self, ft=None):
""" 行数 """
ft = {} if ft is None else ft
rowcount = self._table_query(self._table_name).filter_by(**ft).count()
return rowcount
def close(self):
self._session.close()
# def param_check(self,data,type = BaseDao._CHECKOUT_TYPE_TABLES):
# if type == BaseDao._CHECKOUT_TYPE_TABLES:
# for j in data:
# for i in self.__user_dict.keys():
# if i not in j.keys():
# return False
# elif type == BaseDao._CHECKOUT_TYPE_TABLE:
# for i in data.keys():
# if i not in self.__user_dict.keys():
# return False
# return True
# #校验单条数据
# _CHECKOUT_TYPE_TABLE = "table"
# #校验多条数据
# _CHECKOUT_TYPE_TABLES = "tables"
#设置表对象
_SET_TYPE_TABLE = "table"
#设置现成数据
_SET_TYPE_TABLE_DATA = "table_data"
if __name__ == '__main__':
pass
<file_sep>"""
"""
from dao.system_user_info_dao import UserInfo
from common.result import ResultMessage
from conf import test_jar_conf
import json
class SystemUserInfoService:
result_message = ResultMessage()
def __init__(self):
self.user_info = UserInfo()
def find_user_info_by_id(self,id):
result = self.user_info.find_by_id(id)
return result
def update_user_info(self,user_info):
result = None
if not user_info.get("id"):
result = self.user_info.insert_user(user_info)
return result
update_user_info = self.user_info.find_by_id(user_info["id"])
if update_user_info:
result = self.user_info.update_user_by_id(user_info)
return result
def delete_user_info(self,id):
user_info = {"delete_status":1,"id":id}
result = self.user_info.update_user_by_id(user_info)
return result
if __name__ == "__main__":
pass
# SystemUserInfoService.find_user_info_by_id(1)<file_sep>from flask import Blueprint,request
from service.system_user_info_service import SystemUserInfoService
import json
from common.result import ResultMessage
from conf import test_jar_conf
system_user_info = Blueprint('system_user_info', __name__)
@system_user_info.route('/get/<id>', methods=['GET'])
def get(id):
result_message = ResultMessage()
system_user_info_service = SystemUserInfoService()
result = system_user_info_service.find_user_info_by_id(id)
result_message.data = result
result_message.errcode = test_jar_conf.SUCCESS_CODE
return result_message.result()
@system_user_info.route('/update', methods=['POST'])
def update():
result_message = ResultMessage()
user_info = json.loads(request.get_data(as_text=True))
system_user_info_service = SystemUserInfoService()
result = system_user_info_service.update_user_info(user_info)
result_message.data = result
result_message.errcode = test_jar_conf.SUCCESS_CODE
return result_message.result()
@system_user_info.route('/delete/<id>', methods=['GET'])
def delete(id):
result_message = ResultMessage()
system_user_info_service = SystemUserInfoService()
result = system_user_info_service.delete_user_info(id)
result_message.data = result
result_message.errcode = test_jar_conf.SUCCESS_CODE
return result_message.result()
<file_sep>from dao.base_dao import BaseDao
import copy
class UserInfo(BaseDao):
__user_dict = {"id":None,"user_name":None,"group_id":None,"email":None,"password":<PASSWORD>,"delete_status":None}
_table_name = "system_user"
def find_by_id(self,id = None):
user_data = BaseDao.first(self,{"id":id,"delete_status":0})
return self.__set_user(user_data)
def find_by_condition(self,ft = None):
user_list = []
user_data = BaseDao.all(self,ft)
for i in user_data:
user = self.__set_user(i)
user_list.append(copy.copy(user))
return user_list
def all(self):
user_list = []
user_data = BaseDao.all(self)
for i in user_data:
user = self.__set_user(i)
user_list.append(copy.copy(user))
return user_list
def insert_users(self,user_list):
for user_info in user_list:
self.insert_user(user_info)
def insert_user(self,user_info):
sql_str = "INSERT INTO system_user (user_name,group_id,email,password) VALUES ('{user_name}','{group_id}','{email}','{password}');"
return self.execute_sql(sql_str,user_info)
def update_user_by_id(self,modify):
condition = {"id":modify.pop("id")}
return self.update_users(modify,condition)
def update_users(self,modify,condition):
sql_str = "UPDATE system_user SET "
for i in modify.keys():
sql_str += "%s = '%s'," % (i,modify[i])
sql_str = sql_str[:-1] + " where "
for i in condition.keys():
sql_str += "%s = '%s' AND" % (i,condition[i])
sql_str = sql_str[:-3]+";"
print(sql_str)
return self.execute_sql(sql_str)
def __set_user(self,user_data,type=BaseDao._SET_TYPE_TABLE):
if not user_data:
return
if type == BaseDao._SET_TYPE_TABLE:
UserInfo.__user_dict["id"] = user_data.id
UserInfo.__user_dict["user_name"] = user_data.user_name
UserInfo.__user_dict["group_id"] = user_data.group_id
UserInfo.__user_dict["email"] = user_data.email
UserInfo.__user_dict["password"] = <PASSWORD>
UserInfo.__user_dict["delete_status"] = user_data.delete_status
return UserInfo.__user_dict
else:
UserInfo.__user_dict["user_name"] = user_data.user_name
UserInfo.__user_dict["group_id"] = user_data.group_id
UserInfo.__user_dict["email"] = user_data.email
UserInfo.__user_dict["password"] = <PASSWORD>
UserInfo.__user_dict["delete_status"] = user_data.delete_status
return UserInfo.__user_dict
if __name__ == "__main__":
m = "mysql+pymysql://root:123@localhost:3306/atlantis?charset=utf8mb4"
UserInfo.db_conf = m
u = UserInfo()
print(u.find_by_id(1))
u.update_users({"name":"ztb1","email":"test1"},{"id":2})
# print(u.find_by_condition({"name":"2"}))
# u.insert_users([{"id1":2,"name":"2","business_id":2,"email":"2","pwd":1,"status":1,"company_name":1},{"id":3,"name":"3","business_id":'3',"email":'3',"pwd":'3',"status":'3',"company_name":'3'}])
# print(l)
<file_sep>from flask import Flask
from dao.base_dao import BaseDao
from conf import config
from controller.system_user_info import system_user_info
from controller.target_cycle_summary import target_cycle_summary
from controller.obtain_target_summary import obtain_target_summary
app = Flask(__name__)
# 引入配置文件中的相关配置
app.config.from_object(config.config["development"])
# 配置db
BaseDao.init(app)
# 注册蓝图,并指定其对应的前缀(url_prefix)
app.register_blueprint(system_user_info, url_prefix="/system_user_info")
app.register_blueprint(target_cycle_summary, url_prefix="/target_cycle_summary")
app.register_blueprint(obtain_target_summary, url_prefix="/obtain_target_summary")
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000, debug=True)
<file_sep>import openpyxl
def func(s):
for i in s:
print("%s:%s" % (i,s[i]))
if __name__ == "__main__":
s = {"sign":"44549876042bc0cce5f57fd1432e6b92","company_id":"8968336369328084993","out_order_id":"21666097","callback_status":"10001","order_id":"611986578947567258","order_source":"1","new_order":"{\"order_id\":\"14110766\"}","msg":"","test_function":"OrderStatusCallbackTest_testAppRestartOrder#"}
func(s)
# file = r"/Users/didi/Desktop/111.xlsx"
# wb = openpyxl.load_workbook(file)
# wb.create_sheet("3")
# d = {}
# st = wb["1"]
# n = st.max_row
# for i in range(2,n+1):
# v = (lambda x: x.strip() if x else x)(st["A%s" % i].value)
# if v:
# if v not in d:
# d[v] = {"j1":st["B%s" % i].value,"b":"1","j2":"","j3":""}
# else:
# if d[v]["j1"] != st["B%s" % i].value:
# d[v]["j3"] = st["B%s" % i].value
# d[v]["b"] = "2"
# st = wb["2"]
# n = st.max_row
# for i in range(2,n+1):
# v = (lambda x: x.strip() if x else x)(st["A%s" % i].value)
# if v:
# if v not in d:
# d[v] = {"j1":st["B%s" % i].value,"b":"1","j2":"","j3":""}
# else:
# if d[v]["j1"] != st["B%s" % i].value:
# d[v]["j2"] = st["B%s" % i].value
# d[v]["b"] = "2"
# st = wb["3"]
# n = 2
# for i in d:
# st["A%s" % n] = i
# st["B%s" % n] = d[i]["j1"]
# st["C%s" % n] = d[i]["j2"]
# st["D%s" % n] = d[i]["j3"]
# st["E%s" % n] = d[i]["b"]
# n += 1
# wb.save(file)<file_sep>from flask import Blueprint
obtain_target_summary = Blueprint('obtain_target_summary', __name__)
# 查询目标库
@obtain_target_summary.route('/query_name/<name>', methods=['GET'])
def query_by_name(name):
return "hello3"+name<file_sep>#coding:utf8
"""
Author : zhangwenqi
Description : testjJar全量配置
CreateTime : 2019-08-05
"""
#外部域名
#成功状态码
SUCCESS_CODE = 0
#参数类型错误状态码
PARAMETER_TYPE_ERROR = 1001
#参数缺失错误
PARAMETER_MISSING_ERROR = 1002
#请求失败
REQUEST_FAILURE_ERROR = 1010
#http请求发送工具配置
#成功
API_REQUESTS_SUCCESS_CODE = 2000
#请求url格式错误
API_REQUESTS_URL_TYPE_ERROR_CODE = 2001
#方法内容错误
API_REQUESTS_METHOD_CONTENT_ERROR_CODE = 2002
#主体内容错误
API_REQUESTS_BODY_CONTENT_ERROR_CODE = 2003
#请求头错误
API_REQUESTS_HEADER_CONTENT_ERROR_CODE = 2004
#主体格式错误
API_REQUESTS_BODY_TYPE_ERROR_CODE = 2005
#QUERY格式错误
API_REQUESTS_QUERY_CONTENT_ERROR_CODE = 2006
#请求主体类型
API_REQUESTS_BODY_TYPE_LIST = ["FORM","JSON",None]
#HTTP请求方法
API_REQUESTS_METHOD_LIST = ["POST","GET","DELETE","PUT","HEAD"]<file_sep>import os
BASEDIR = os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir))
class Config:
"""base config"""
# SECRET_KEY = os.environ.get('SECRET_KEY') or 'secret key'
# SQLALCHEMY_COMMIT_ON_TEARDOWN = True
# SQLALCHEMY_TRACK_MODIFICATIONS = True
# FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN')
FLASKY_MAIL_SENDED = '<EMAIL>' # 发件人地址
FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]' # 邮件主题前缀
class ProductionConfig(Config):
"""运行环境配置"""
DEBUG = True
DIALCT = 'mysql'
DRIVER = "pymysql"
USERNAME = 'root'
PASSWORD = '<PASSWORD>!@#'
HOST = 'localhost'
PORT = '3306'
DBNAME = 'practice'
SQLALCHEMY_DATABASE_URI = '{}://{}:{}@{}:{}/{}?charset=utf8mb4'.format(DIALCT, USERNAME, PASSWORD, HOST,PORT, DBNAME)
SQLALCHEMY_TRACK_MODIFICATIONS = True # 没有此配置会导致警告
class DevelopmentConfig(Config):
"""运行环境配置"""
DEBUG = True
DIALCT = 'mysql'
DRIVER = "pymysql"
USERNAME = 'root'
PASSWORD = '<PASSWORD>'
HOST = 'localhost'
PORT = '3306'
DBNAME = 'practice'
SQLALCHEMY_DATABASE_URI = '{}://{}:{}@{}:{}/{}?charset=utf8mb4'.format(DIALCT, USERNAME, PASSWORD, HOST, PORT,
DBNAME)
SQLALCHEMY_TRACK_MODIFICATIONS = True # 没有此配置会导致警告
config = {
'development': DevelopmentConfig,
'testing': ProductionConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
if __name__ == "__main__":
print(ProductionConfig.SQLALCHEMY_DATABASE_URI) | 6efe2ef6f6aefdd579dfc65e44c0ec5f401376cc | [
"Python"
] | 13 | Python | 18616703217/practice | 7ae213eb93ad966b2edf67d377be8721e5e7b872 | 6e1154b441f3950984048a4b8d6789794d45f62e | |
refs/heads/master | <file_sep># TowerDefense for BlackBerry10!
The scope is to create a simple and easy game for all those Tower defense lovers.
--
Why do this?
Because we though it would be fun to make our own tower defense game while learning to increase our skills as a group.
I'm using the following to develop this :
* Phaser.io
* Blackberry Webworks
* TypeScript
* HTML5
* CSS3
Learn Phaser!
https://phaser.io/learn
It is recommended you download, install and run webworks to run this. However, you can go into the www/ folder and run that however way you'd like.
What's a BlackBerry WebWorks app? Follow this link to BlackBerry's Dev page to find out!
http://developer.blackberry.com/html5/documentation/v2_2/what_is_a_webworks_app.html
<file_sep>//new Game(width, height, renderer, parent, state, transparent, antialias, physicsConfig)
//var game = new Phaser.Game(window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio, Phaser.AUTO, '', {preload: preload, create: create, update: update});
var game = new Phaser.Game(1350, 1080, Phaser.AUTO, '', {preload: preload, create: create, update: update});
//for future purposes, to scale game based on pixel ratio
var scaleRatio = window.devicePixelRatio / 3;
//var logo;
var background;
var creep;
function preload(){
//game.load.type('assetName', 'location/in/filesystem', width, height);
//game.load.image('logo', 'assets/phaser-logo-small.png');
game.load.spritesheet('creep', 'assets/creeps/creep_noWeapon.png', 200, 163);
game.load.image('background1', 'assets/maps/Maps1.png', 1080, 1350);
}
function create(){
//Arcade Physics - i.e. It enables motion
game.physics.startSystem(Phaser.Physics.ARCADE);
//Sets Background at 0x0(Top Left Corner)
game.add.sprite(0, 0, 'background1');
//Logo
//logo = game.add.sprite(game.world.centerX, game.world.centerY, 'logo');
//logo.scale.setTo(scaleRatio, scaleRatio);
//creeep
creep = game.add.sprite(game.world.centerX, game.world.centerY, 'creep');
//creep.scale.setTo(scaleRatio, scaleRatio);
//Gives Creep ability to Move and other physics related qualities
game.physics.arcade.enable(creep);
//Sets the Animation sequence for the creep
//assetName.animations.add('animationName', [Frames], fps, loop?)
creep.animations.add('left', [0, 1], 5, true);
creep.animations.add('right', [3, 4], 5, true);
//Add Keyboard Manager
cursors = game.input.keyboard.createCursorKeys();
}
function update(){
//Stops creep motion on the x axis
creep.body.velocity.x = 0;
//Checks for arrow presses and acts accordingly
if(cursors.left.isDown)
{
creep.body.velocity.x = -150;
creep.animations.play('left');
}
else if (cursors.right.isDown)
{
creep.body.velocity.x = 150;
creep.animations.play('right');
}
else
{
creep.animations.stop();
creep.frame = 2;
}
} | 09c9a5a0161da84eff3501036ecea0c8af35e8e3 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dtuivs/TowerDefenseForBlackBerry | 68849fdf64fd8834c7b68bf769cf8a0b4f70baf5 | 5cd0250adbc0496795926133cb3d57a3049a8d5a | |
refs/heads/master | <repo_name>cssko/UC-CourseCatalog<file_sep>/README.md
# UC-CourseCatalog
*A central course catalog for the University of Cincinnati*
All things considered the University of Cincinnati has a fairly navigable [website](www.uc.edu). However, one common complaint by staff and students both has been a lack of a central course catalog. Each college within the university typically has this information somewhere, but it isn't always up–to–date. There's also the [Course Planning Guide](http://webapps.uc.edu/registrar/courseplanningguide/SemesterCoursePlanningGuide.aspx), but this has a clunky interface.
My goal here is to provide a central and easily searchable course catalog. Users will search using a course number (e.g. MATH1061) and be provided with a course title and description.
<file_sep>/courseScraper.py
import random
import time
import sqlite3
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import selenium.webdriver.support.ui as UI
def insert_class_info(course_id, discipline, course_title, course_desc, credit_hours, fall_availability,
spring_availability, summer_availability, alt_yr, grad):
""" Inserts or updates course information in sqlite3 database.
:param course_id: Course ID
:param discipline: Discipline the course falls under
:param course_title: Title of course
:param course_desc: Description of course
:param credit_hours: Number of credit hours for course
:param fall_availability: Fall semester availability of course
:param spring_availability: Spring semester availability of course
:param summer_availability: Summer semester availability of course
:param alt_yr: Alternating Year availability for course
:return:
"""
cursor.execute("INSERT OR REPLACE INTO coursecatalog_course VALUES (?,?,?,?,?,?,?,?,?,?)", (
course_id, discipline, course_title, course_desc, credit_hours, fall_availability, spring_availability,
summer_availability, alt_yr, grad))
conn.commit()
return
def get_course_information(course_id, link, links, skipped_rows, discipline):
""" Gets course information for current course.
:param course_id: Course ID of the current course
:param link: Link for the current Course ID
:param links: List of links
:param skipped_rows: Number of skipped rows, based on pagination.
:param discipline: Discipline
:return:
"""
popup = driver.window_handles[1]
driver.switch_to.window(popup)
course_title = unicode((driver.find_element_by_id("CourseTitle")).text).strip()
course_desc = unicode(driver.find_element_by_id("CourseDes").text).strip(course_id).strip()
time.sleep(2 + (random.random() * 3))
driver.close()
driver.switch_to.window(driver.window_handles[0])
# Make a list of the column items for the current row being worked on.
info = driver.find_elements_by_css_selector('#ctl00_StaticPlaceHolder_CourseGridView '
'tr:nth-child(' + str((links.index(link) + skipped_rows)) + ') td+ td')
credit_hours = info[1].text
fall_availability = info[2].text.replace(" ", "N").replace("ConsultNDepartment", "Consult Department")
spring_availability = info[3].text.replace(" ", "N").replace("ConsultNDepartment", "Consult Department")
summer_availability = info[4].text.replace(" ", "N").replace("ConsultNDepartment", "Consult Department")
alt_yr = info[5].text.replace(" ", "N").replace("ConsultNDepartment", "Consult Department")
insert_class_info(course_id, discipline, course_title, course_desc, credit_hours, fall_availability,
spring_availability, summer_availability, alt_yr, graduate_level)
return
def navigate_courses(discipline):
""" Moves through the courses in a discipline.
Changes pages if needed.
:param discipline: Current discipline
:return:
"""
try: # Checks for links at the top of the class table, which will only exist if there are more than one page.
driver.find_element_by_css_selector('tr+ tr td:nth-child(2) a')
pagination = True
except NoSuchElementException:
# To my knowledge selenium lacks the ability to determine if an element exists without looking for it
# and throwing an exception if it does not.
pagination = False
pages = 1
cont = True
while cont:
links = driver.find_elements_by_partial_link_text(str(discipline))
# If the discipline is PD then webdriver is going to want to click on 'Save PDF' and throw itself off.
# This way we save itself the trouble.
if discipline == "PD":
for i in links:
if i.text == "Save to PDF":
del links[links.index(i)]
break
# If there is more than one page we want to start a row lower than otherwise.
if pagination:
skipped_rows = 3
else:
skipped_rows = 2
for link in links:
if links.__sizeof__() < 1:
cont = False
break
time.sleep(3 + (random.random() * 2))
course_id = str(link.text)
link.click()
get_course_information(course_id, link, links, skipped_rows, discipline)
if pagination:
try: # Attempts to click on link that matches pages
pages += 1
if pages == 11:
driver.execute_script("javascript:__doPostBack('ctl00$StaticPlaceHolder$CourseGridView'"
",'Page$11')") # Page 11 is a special snowflake and has the text '...'
else:
next_page = driver.find_element_by_link_text(str(pages))
next_page.click()
except NoSuchElementException:
# Returns to the first page and breaks out of loop. Going back to the first page is necessary with how
# the university's site works. If you go from one discipline to another, and they both have multiple
# pages, you can end up on a later page
driver.execute_script("javascript:__doPostBack('ctl00$StaticPlaceHolder$CourseGridView','Page$1')")
cont = False
elif not pagination:
driver.execute_script("javascript:__doPostBack('ctl00$StaticPlaceHolder$CourseGridView','Page$1')")
cont = False
time.sleep(2 + (random.random() * 2))
# time.sleep(5 + (random.random() * 5))
return
def get_disciplines():
""" Creates list of disciplines from drop down menu.
:return: list of disciplines
"""
disciplines = []
disc_values = UI.Select(
driver.find_element_by_xpath('//*[@id="ctl00_StaticPlaceHolder_DisciplineDDL"]'))
for option in disc_values.options:
disciplines.append(option.get_attribute("value"))
del disciplines[0] # The first option in the drop down list is blank and needs to be discarded
# Prompt asking if you've already successfully completed some scraping and you wish to start at a
# different discipline.
start = raw_input('Input starting discipline: ').upper()
for i in range(0, disciplines.index(start)):
del disciplines[0]
return disciplines
def select_grad_level():
""" Prompts for desired graduate level.
:return: String containing U or G. """
grad = raw_input('Select graduate level.\nEnter U for undergraduate or G for graduate: ').upper()
cont = True
while cont:
if grad == 'U' or grad == 'G':
cont = False
else:
grad = raw_input('Incorrect input. Please enter either U or G: ').upper()
Select(driver.find_element_by_id("ctl00_StaticPlaceHolder_GradTypeDDL")).select_by_value(grad)
return grad
def main():
global graduate_level
grad = select_grad_level()
# Here we take the users input in the form of a single letter string and expand it out into the full word
# For readabilities sake.
if grad == 'U':
graduate_level = 'undergraduate'
elif grad == 'G':
graduate_level = 'graduate'
disciplines = get_disciplines()
for discipline in disciplines:
Select(driver.find_element_by_id("ctl00_StaticPlaceHolder_DisciplineDDL")).select_by_value(discipline)
time.sleep(2 + (random.random() * 3))
print('Working on ' + discipline + " now!")
navigate_courses(discipline)
driver.close()
if __name__ == '__main__':
url = "http://webapps.uc.edu/registrar/courseplanningguide/SemesterCoursePlanningGuide.aspx"
while 1:
browser = raw_input('Enter desired browser, either phantomjs or chrome: ').lower()
if browser == 'chrome':
path_to_chromedriver = "./chromedriver"
driver = webdriver.Chrome(executable_path=path_to_chromedriver)
driver.get(url)
break
elif browser == 'phantomjs':
dcap = dict()
dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
"(KHTML, like Gecko) Chrome/15.0.87")
path_to_phantomjs = './phantomjs'
driver = webdriver.PhantomJS(executable_path=path_to_phantomjs, desired_capabilities=dcap)
driver.get(url)
break
# else:
# raw_input('Please enter either "chrome" or "phantomjs": ')
conn = sqlite3.connect("coursedata.db")
cursor = conn.cursor()
main()
| 078e34215cf03cda562c8b8a5defaa1045250afd | [
"Markdown",
"Python"
] | 2 | Markdown | cssko/UC-CourseCatalog | 2e0366fd7391ef06c8b6fbd7cde9f3402c315c26 | 9a8e4cdc4a8aa38286f688259e8dfcecbc87a8ad | |
refs/heads/master | <repo_name>JenSarela/SCL009-data-lovers<file_sep>/README.md
# *Data Lovers*
## *CodePoke*
## *Índice*
* [CodePoke](#CodePoke)
* [Resumen del producto](#CodePoke)
* [Definición del producto](#definición-del-producto)
* [Proceso del diseño](#proceso-del-diseño)
* [Encuesta aplicada](#parte-)
* [Prototipo de baja fidelidad](#prototipos)
* [Interacción en Terreno](# )
* [Prototipo de alta Fidelidad](#checklist)
* [Conclusiones](#CodePoke)
* [Aquí puedes visualizar nuestro trello](https://trello.com/b/Zv0LsmpF/data-love)
*
## *1. CodePoke*
Es un proyecto encargado por Laboratoria que consiste en
construir una interfaz complementaria, amigable y entendible por el usuario de la aplicacion Pokémon GO.
<img src="https://i.ibb.co/C7ZS8PF/pokemongo.jpg" alt="pokemongo" border="0">
Pokémon GO es un videojuego de realidad aumentada basado en la localización desarrollado por Niantic, Inc.12 para dispositivos iOS y Android. Es un videojuego gratuito pero contiene microtransacciones. El juego consiste en buscar y capturar personajes de la saga Pokémon escondidos en ubicaciones del mundo real y luchar con ellos, lo que implica desplazarse físicamente por las calles de la ciudad para progresar. La aplicación comporta un elemento de interacción social, ya que promueve reuniones físicas de los usuarios en distintas ubicaciones de sus poblaciones.
## *2. Resumen del proyecto*
En este proyecto *construiremos una página web para visualizar un_conjunto de datos_* que se adecuaran a las necesidades de nuestro usuario tipo.
Se eligió pokémon data.
* [Pokémon](src/data/pokemon/pokemon.json):
En este set encontrarás una lista con los 151 Pokémon de la región de Kanto,
junto con sus respectivas estadísticas usadas en el juego [Pokémon GO](https://pokemongolive.com).
El objetivo principal de este proyecto es que aprendamos a diseñar y construir una
interfaz web donde se pueda visualizar y manipular data, entendiendo lo que el
usuario necesita.
* Aplicar y profundizar todo lo que aprendiste en el proyecto anterior.
* Pensar en las *necesidades de los usuarios* para crear historias de usuario.
* Escribir y trabajar con *historias de usuario*, sus definiciones de
terminado (definition of done) en la organización y planificación de tu
trabajo.
* Definir qué data y de qué forma mostrarla en el producto, basándote en
tu *entendimiento del usuario*.
* Crear productos que sigan los *principios básicos de diseño visual* y
las *heurísticas de usabilidad*.
* Iterar el diseño del producto, basándote en los resultados de los
*tests de usabilidad*.
* Manipular *arreglos (arrays) y objetos (objects)*.
* *Manipular el DOM* (agregar elementos dinámicamente basados en la data).
* *Manejar eventos del DOM* para permitir interacción con el usuario
(filtrado, ordenado, ...).
* Entender los beneficios y complejidades de *trabajar en equipo* en un
ambiente de incertidumbre.
Nuestro objetivo final es una página web que permita *visualizar la data,filtrarla, ordenarla y hacer algún calculo agregado*.
Como cálculo agregado de la data se muestra información aún más relevante para los usuarios. Nuestra opción de cálculo estadístico es mostrar la cantidad de pokémons de cada tipo.
## * Proceso del diseño*
Una vez que definida nuestra area de interés, es con el usuario tipo donde centraremos el trabajo ya que necesitaremos su retroalimentación y luego podremos construir la interfaz que le ayude a interactuar y entender mejor esos datos.
Para ésto se difundió una encuesta cuyo posterior análisis sirvio para realizar bocetos de baja fidelidad, con los que se realizaron entrevistas en terreno a usuarios de la aplicación
Pokémon Go.
Luego de la interaccion con los jugadores se logró definir historias de usuario más acotadas a sus necesidades, tambien se adquirió mucha información respecto de sus reales necesidades, sin embargo, con la data disponible no nos fue posible dar esa cobertura más amplia, específica y actualizada.
## * Encuesta aplicada*
Se realizó una encuesta de usuario con la intención de comprender mejor las preferencias y alcanzar los objetivos del proyecto en función de las necesidades de los usuarios y así analizar los aspectos en que debíamos enfocarnos.
La encuesta se dirigió a jugadores activos de la aplicación Pokémon Go.
https://forms.gle/CGWiLdH5KgDmoQU99
<a href="https://ibb.co/P45KTwg"><img src="https://i.ibb.co/P45KTwg/Captura-de-pantalla-2.png" alt="Captura-de-pantalla-2" border="0"></a>
<a href="https://ibb.co/qyLpBh6"><img src="https://i.ibb.co/qyLpBh6/Captura-de-pantalla-4.png" alt="Captura-de-pantalla-4" border="0"></a>
<a href="https://ibb.co/D1Vfg8Y"><img src="https://i.ibb.co/D1Vfg8Y/Captura-de-pantalla-6.png" alt="Captura-de-pantalla-6" border="0"></a>
### * Análisis de resultados *
<img src="https://i.ibb.co/9TgJd19/Captura-de-pantalla-30.png" alt="Captura-de-pantalla-30" border="0">
Al identificar el rango etario de nuestros usuarios se aprecia que mas del 50% de la muestra se encuentra entre 23 y 32 años y el 12% a niños entre 12 y 15 años.
<img src="https://i.ibb.co/xJ9CNVP/Captura-de-pantalla-32.png" alt="Captura-de-pantalla-32" border="0">
Existe un 9% más de hombres que mujeres que juegan Pokémon Go.
<img src="https://i.ibb.co/TKW8f3Z/Captura-de-pantalla-34.png" alt="Captura-de-pantalla-34" border="0">
Mayoritariamente los usuarios desacargan la aplicación por entretención y otros generalmente mayores de 28 años por nostalgia de la serie animada Pokémon.
<img src="https://i.ibb.co/zn4N5Bm/Captura-de-pantalla-36.png" alt="Captura-de-pantalla-36" border="0">
Los datos que los usuarios querían acceder son la evolución, el tipo y las debilidades de los pokemons mayoritariamente.
<img src="https://i.ibb.co/5cH9rPv/Captura-de-pantalla-38.png" alt="Captura-de-pantalla-38" border="0">
Como sumatoria más del 60% de los usuarios juegan más de tres veces a la semana, mientras que el 25% lo hace todos los dias.
<img src="https://i.ibb.co/cr8KX86/Captura-de-pantalla-23.png" alt="Captura-de-pantalla-23" border="0">
Para esta pregunta abierta se obtuvieron datos generales, pero que nos sirvieron posteriormente para realizar entrevistas y testeos de baja fidelidad.
<img src="https://i.ibb.co/wdYj5ML/Captura-de-pantalla-25.png" alt="Captura-de-pantalla-25" border="0">
El 81%, es decir, la mayoría de los usuarios ha competido en gimnasios, un espacio virtual de batallas entre los pokemons seleccionados por los jugadores de acuerdo a sus poderes y debilidades.
<img src="https://i.ibb.co/41WfvCV/Captura-de-pantalla-28.png" alt="Captura-de-pantalla-28" border="0">
El 76% de los usuarios es capaz de identificar pokémons por su número.
### * Prototipos de baja fidelidad *
<a href="https://ibb.co/vZSVpHN"><img src="https://i.ibb.co/vZSVpHN/Whats-App-Image-2019-05-09-at-09-29-07.jpg" alt="Whats-App-Image-2019-05-09-at-09-29-07" border="0"></a>
<a href="https://ibb.co/gM13cBB"><img src="https://i.ibb.co/gM13cBB/Whats-App-Image-2019-05-09-at-09-29-08.jpg" alt="Whats-App-Image-2019-05-09-at-09-29-08" border="0"></a>
<a href="https://ibb.co/N9KQpZW"><img src="https://i.ibb.co/N9KQpZW/Whats-App-Image-2019-05-09-at-09-29-15.jpg" alt="Whats-App-Image-2019-05-09-at-09-29-15" border="0"></a>
<a href="https://ibb.co/R2t58Km"><img src="https://i.ibb.co/R2t58Km/Whats-App-Image-2019-05-09-at-09-29-14.jpg" alt="Whats-App-Image-2019-05-09-at-09-29-14" border="0"></a>
<a href="https://ibb.co/RbsWg3V"><img src="https://i.ibb.co/RbsWg3V/Whats-App-Image-2019-05-09-at-09-29-09.jpg" alt="Whats-App-Image-2019-05-09-at-09-29-09" border="0"></a>
### * Interaccion en terreno*
Se hizo una visita al parque forestal situado en la comuna de Santiago y se abordó a jugadores de la aplicación Pokémon Go.
<img src="https://i.ibb.co/K96yrR5/Captura-de-pantalla-43.png" alt="Captura-de-pantalla-43" border="0">
https://youtu.be/nJ9pbH1Typ8
<img src="https://i.ibb.co/bPbxhjZ/Captura-de-pantalla-41.png" alt="Captura-de-pantalla-41" border="0">
https://youtu.be/13rQFdUCMds
## *Historias de Usuario*
Los usuarios de CodePoke son jugadores activos de la aplicacion
Pokémon Go.
*Como* jugador principiante
*Quiero* seleccionar los pokemons
de tipo agua.
*Para* conocer mejor las caracteristicas de mis pokémons.
*Como* jugador avanzado
*Quiero* filtrar pokémons por sus debilidades.
*Para* tener mejor elegir los pokémons en una batalla de gimnasio.
*Como* jugador principiante,
*Quiero* ordenar los pokemones en orden alfabetico
*Para* llegar mas facil a aquello que estan al final de la lista.
*Resultado*
En el link siguiente puedes acceder a una demostración de la aplicación y experimentar con sus resultados y proceso de funcionamiento [link](https://jensarela.github.io/SCL009-data-lovers/src/index.html)
### * Prototipos de Alta fidelidad *
Desarrollado en Figma, y exportado a Zeplin [aquí puedes visualizar](https://scene.zeplin.io/project/5cd4bb0920f8ff5736ed32a5)
<file_sep>/test/data.spec.js
global.window = global;
global.assert = require('chai').assert;
require('../src/data');
require('./data.spec.js');
const dataPoke = [{
name: "Caterpie",
num: "010",
type: ["Bug"],
weaknesses: [
"Fire",
"Flying",
"Rock"
]
},
{
name: "Dragonite",
num: "149",
type: ["Dragon"],
weaknesses: [
"Ice",
"Rock",
"Dragon",
"Fairy"
]
},
{
name: "Squirtle",
num: "007",
type: ["Water"],
weaknesses: [
"Electric",
"Grass"
]
}
]
describe('pokedexType', () => {
it('debería ser una función', () => {
assert.equal(typeof pokedexType, 'function');
});
it('debería retornar elemento "Caterpie" para filtrar por tipo "Bug"', () => {
assert.deepEqual(window.pokedexType(dataPoke, "Bug"), [{
name: "Caterpie",
num: "010",
type: ["Bug"],
weaknesses: [
"Fire",
"Flying",
"Rock"
]
}])
});
})
describe('pokedexWeaknesses', () => {
it('debería ser una función', () => {
assert.equal(typeof pokedexWeaknesses, 'function');
});
it('debería retornar elemento "Dragonite" para filtrar por debilidad Ice"', () => {
assert.deepEqual(window.pokedexWeaknesses(dataPoke, "Ice"), [{
name: "Dragonite",
num: "149",
type: ["Dragon"],
weaknesses: [
"Ice",
"Rock",
"Dragon",
"Fairy"
]
}])
})
describe('sortCode', () => {
it('debería ser una función', () => {
assert.equal(typeof sortCode, 'function');
});
it('debería retornar el elemento Caterpie", "Dragonite" y "Squirtle" para ordenar de la "A a la Z"', () => {
assert.deepEqual(window.sortCode(dataPoke, "name", "az"), [{
name: "Caterpie",
num: "010",
type: ["Bug"],
weaknesses: [
"Fire",
"Flying",
"Rock"
]
},
{
name: "Dragonite",
num: "149",
type: ["Dragon"],
weaknesses: [
"Ice",
"Rock",
"Dragon",
"Fairy"
]
},
{
name: "Squirtle",
num: "007",
type: ["Water"],
weaknesses: [
"Electric",
"Grass"
]
}
])
});
it('debería retornar el elemento "Squirtle","Dragonite" y " Caterpie", para ordenar de la "Z a la A"', () => {
assert.deepEqual(window.sortCode(dataPoke, "name", "za"), [{
name: "Squirtle",
num: "007",
type: ["Water"],
weaknesses: [
"Electric",
"Grass"
]
}, {
name: "Dragonite",
num: "149",
type: ["Dragon"],
weaknesses: [
"Ice",
"Rock",
"Dragon",
"Fairy"
]
}, {
name: "Caterpie",
num: "010",
type: ["Bug"],
weaknesses: [
"Fire",
"Flying",
"Rock"
]
}
])
});
it('debería retornar el elemento "Squirtle"," Caterpie" y "Dragonite", para ordenar del "1 al 151"', () => {
assert.deepEqual(window.sortCode(dataPoke, "num", "asc"), [{
name: "Squirtle",
num: "007",
type: ["Water"],
weaknesses: [
"Electric",
"Grass"
]
}, {
name: "Caterpie",
num: "010",
type: ["Bug"],
weaknesses: [
"Fire",
"Flying",
"Rock"
]
}, {
name: "Dragonite",
num: "149",
type: ["Dragon"],
weaknesses: [
"Ice",
"Rock",
"Dragon",
"Fairy"
]
}])
});
})
})
it('debería retornar el elemento "Dragonite"," Caterpie" y "Squirtle" para ordenar del "151 al 1"', () => {
assert.deepEqual(window.sortCode(dataPoke, "num", "des"), [{
name: "Dragonite",
num: "149",
type: ["Dragon"],
weaknesses: [
"Ice",
"Rock",
"Dragon",
"Fairy"
]
}, {
name: "Caterpie",
num: "010",
type: ["Bug"],
weaknesses: [
"Fire",
"Flying",
"Rock"
]
}, {
name: "Squirtle",
num: "007",
type: ["Water"],
weaknesses: [
"Electric",
"Grass"
]
}])
})
describe('counterForType', () => {
it('debería ser una función', () => {
assert.equal(typeof counterForType, 'function');
});
it('debería retornar "1 Pokemon tipo "Water", para Water"', () => {
assert.deepEqual(window.counterForType(dataPoke, "Water", "type"), 1)
});
});
<file_sep>/src/data.js
const counterForType = (codePoke, condition, counterBy) => {
let resultCounter = codePoke.reduce((contador, codePoke) => {
if (codePoke[counterBy].includes(condition)) {
return contador + 1;
} else {
return contador;
}
}, 0)
return resultCounter;
}
window.counterForType = counterForType;
// FILTRADO POR TIPO
const pokedexType = (codePoke, condition) => {
const pokeByFilter = codePoke.filter(element => {
return element.type.includes(condition);
});
return pokeByFilter;
}
window.pokedexType = pokedexType;
// FILTRADO POR DEBILIDAD
const pokedexWeaknesses = (codePoke, conditionTwo) => {
const pokeByWeakness = codePoke.filter(element => {
return element.weaknesses.includes(conditionTwo);
});
return pokeByWeakness;
}
window.pokedexWeaknesses = pokedexWeaknesses;
//funcion ordenar : sort code => codepoke es la data; sortcodeby: es lo que quiero ordenar; sortcodeorder: es como lo voy a ordenar
const sortCode = (codePoke, sortCodeBy, sortCodeOrder) => {
const comparar = codePoke.sort((a, b) => {
return a[sortCodeBy].localeCompare(b[sortCodeBy])
})
if (sortCodeOrder === "az") {
return comparar;
}
if (sortCodeOrder === "za") {
return comparar.reverse();
}
if (sortCodeOrder === "asc") {
return comparar;
}
if (sortCodeOrder === "des") {
return comparar.reverse();
}
}
window.sortCode = sortCode;
<file_sep>/src/main.js
/* Manejo del DOM */
//declaramos una variable para llamar la data
const codePoke = window.POKEMON.pokemon;
// Recargamos página
document.getElementById("recharge").addEventListener("click", () => {
location.reload();
})
//mostrar toda la data a traves de una variable, tomando un id del body
let rootBody = document.getElementById("root");
//aqui llamamos a los pokemon solo por sus nombres en el orden que esta establecido en la data
let pokepoke = (codePoke) => {
for (let i = 0; i < codePoke.length; i++) {
rootBody.innerHTML +=
`<div class="col-sm-2">
<img src="${codePoke[i].img}" class="card-img-top" alt="Poke">
<div class="card-body">
<div class="col-sm-2">
<h5 class="card-title">${codePoke[i].name}</h5>
<h6 class="card-title">Número:${codePoke[i].num}</h6>
<p class="card-text">Tipo:${codePoke[i].type}</p>
</div>
</div>`
}
}
window.onload = pokepoke(codePoke);
// FILTRADO POR TIPO
let saveForType = document.getElementById("type");
saveForType.addEventListener("change", () => {
let condition = saveForType.options[saveForType.selectedIndex].value; // guarda seleccion usiario
//console.log(condition);
//COUNTER
let typeCounter = window.counterForType(codePoke, condition, "type");
let filter = window.pokedexType(codePoke, condition);
rootBody.innerHTML = "";
document.getElementById("cantPokes").innerHTML =
` <div class= "cantPokes col-12">Existen ${typeCounter} pokemon tipo ${condition}</div> `
filter.forEach(element => {
rootBody.innerHTML +=
`<div class="col-sm-2">
<img src="${element.img}" class="card-img-top" alt="Poke">
<div class="card-body">
<div class="col-sm-2">
<h5 class="card-title">${element.name}</h5>
<h6 class="card-title">Número:${element.num}</h6>
<p class="card-text">Tipo:${element.type}</p>
</div>
</div>`
})
});
// FILTRANDO POR DEBILIDADES
let saveForWeakness = document.getElementById("weaknesses");
saveForWeakness.addEventListener("change", () => {
let conditionTwo = saveForWeakness.options[saveForWeakness.selectedIndex].value;
//console.log(condition);
let filter = window.pokedexWeaknesses(codePoke, conditionTwo);
rootBody.innerHTML = "";
filter.forEach(element => {
rootBody.innerHTML +=
`<div class="col-sm-2">
<img src="${element.img}" class="card-img-top" alt="Poke">
<div class="card-body">
<div class="col-sm-2">
<h5 class="card-title">${element.name}</h5>
<h6 class="card-title">Número:${element.num}</h6>
<p class="card-text">Tipo:${element.type}</p>
</div>
</div>
</div>`
})
});
//SORT CORTITO
let ordenAs = document.getElementById("ascdesc");
ordenAs.addEventListener("change", () => {
let pokeSort = ordenAs.value;
let ordenPoke = "";
ordenPoke = window.sortCode(codePoke, "name", pokeSort);
rootBody.innerHTML = "";
ordenPoke.forEach(element => {
rootBody.innerHTML +=
`<div class="col-sm-2">
<img src="${element.img}" class="card-img-top" alt="Poke">
<div class="card-body">
<div class="col-sm-2">
<h5 class="card-title">${element.name}</h5>
<h6 class="card-title">Número:${element.num}</h6>
<p class="card-text">Tipo:${element.type}</p>
</div>
</div>
</div>`
})
})
let ordenDes = document.getElementById("num");
ordenDes.addEventListener("change", () => {
let pokeSortCode = ordenDes.value;
let orden = "";
orden = window.sortCode(codePoke, "num", pokeSortCode);
rootBody.innerHTML = "";
orden.forEach(element => {
rootBody.innerHTML +=
`<div class="col-sm-2">
<img src="${element.img}" class="card-img-top" alt="Poke">
<div class="card-body">
<div class="col-sm-2">
<h5 class="card-title">${element.name}</h5>
<h6 class="card-title">Número:${element.num}</h6>
<p class="card-text">Tipo:${element.type}</p>
</div>
</div>
</div>`
})
})
| 10d6cfdee1c1a7dc5ef5b4a92aac83a20acf3f4a | [
"Markdown",
"JavaScript"
] | 4 | Markdown | JenSarela/SCL009-data-lovers | 40021d1598ea9bf49342af34f79ee23cd6c4984a | c2beab743488840317716d0eda2704cf6c6a939a | |
refs/heads/master | <file_sep><?php
namespace App\DataTransformer;
use App\Entity\Recipe;
/**
* Class RecipeTransformer
*
* @package App\DataTransformer
*/
class RecipeTransformer
{
/**
* @param Recipe $recipe
*
* @return array
*/
public static function transform(Recipe $recipe)
{
return [
'title' => $recipe->getTitle(),
'ingredients' => $recipe->getIngredients()
];
}
/**
* @param Recipe[] $recipes
*
* @return array
*/
public static function transformList(array $recipes)
{
return array_map(
function (Recipe $recipe) {
return self::transform($recipe);
},
$recipes
);
}
}
<file_sep><?php
require_once __DIR__.'/vendor/autoload.php';
$app = new Silex\Application();
require_once __DIR__.'/config/dev.php';
require_once __DIR__.'/src/app.php';
<file_sep># Tech task
This is Silex application created for test proposed.
## Usage instructions
### Configure environment with Docker
As a precondition you have to install [Docker](https://docs.docker.com/engine/installation/) and [Docker Compose](https://docs.docker.com/compose/install/).
Download docker configuration:
`git clone <EMAIL>:dpcat237/pasishnyi-denys-docker-techtask-20170209.git`
Enter to `pasishnyi-denys-docker-techtask-20170209` and create `web` folder.
Inside of new folder download current repository `git clone <EMAIL>:dpcat237/pasishnyi-denys-techtask-20170209.git`.
```
mkdir pasishnyi-denys-docker-techtask-20170209/web && cd pasishnyi-denys-docker-techtask-20170209/web
git clone <EMAIL>:dpcat237/pasishnyi-denys-techtask-20170209.git
```
From the root of the docker configuration launch the container. This process will take some minutes to download configure the environment.
```
docker-compose up
```
Access to a container and download the required dependencies. For this, copy container ID running `docker ps`.
```
docker exec -it [container ID] bash
su www-data
cd pasishnyi-denys-techtask-20170209/ && composer install
```
Copy container's IP (you can use `ifconfig`) and add "`[copied IP] fridge.local`" at the end of the local hosts configuration `/etc/hosts`.
You can open in your browser: `http://fridge.local/api/v1/lunch`.
### Additional information
Application data is located in `pasishnyi-denys-docker-techtask-20170209/web/pasishnyi-denys-techtask-20170209/data/`.
### Steps to send a tweet
Add twitter credentials in `pasishnyi-denys-docker-techtask-20170209/web/pasishnyi-denys-techtask-20170209/config/prod.php`.
Example of the request:
```
POST: http://fridge.local/api/v1/twitter/tweet
Body: {"text":"Hotdog"}
```
<file_sep><?php
namespace App\Loader;
use App\Repository\IngredientRepository;
use App\Repository\RecipeRepository;
use App\Service\FridgeService;
use App\Service\TwitterService;
use Silex\Application;
/**
* Class ServicesLoader
*
* @package App\Loader
*/
class ServicesLoader
{
/** @var Application */
protected $app;
/**
* ServiceLoader constructor.
*
* @param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
public function bindServicesIntoContainer()
{
/** Repositories **/
$this->app['ingredient.repository'] = function () {
return new IngredientRepository($this->app["data.folder"]);
};
$this->app['recipe.repository'] = function () {
return new RecipeRepository($this->app["data.folder"]);
};
/** Services **/
$this->app['fridge.service'] = function () {
return new FridgeService($this->app['ingredient.repository'], $this->app['recipe.repository']);
};
$this->app['twitter.service'] = function () {
return new TwitterService($this->app['twitter.config']);
};
}
}
<file_sep><?php
namespace App\Controller;
use App\DataTransformer\RecipeTransformer;
use App\Service\FridgeService;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Class RecipeController
*
* @package App\Controller
*/
class RecipeController
{
/** @var FridgeService */
protected $fridgeService;
/**
* RecipeController constructor.
*
* @param FridgeService $fridgeService
*/
public function __construct(FridgeService $fridgeService)
{
$this->fridgeService = $fridgeService;
}
/**
* List of recipes
*
* @return JsonResponse
*/
public function listAction()
{
$recipes = $this->fridgeService->getValidRecipes();
return new JsonResponse(RecipeTransformer::transformList($recipes));
}
}
<file_sep><?php
//API
$app['api.version'] = "v1";
$app['api.endpoint'] = "/api";
$app['data.folder'] = "data";
//Twitter
$app['twitter.config'] = [
'consumer_key' => '',
'consumer_secret' => '',
'token' => '',
'token_secret' => '',
];
<file_sep><?php
namespace App\DataTransformer;
use App\Entity\Recipe;
use Mockery;
use Mockery\Mock;
use PHPUnit_Framework_TestCase;
/**
* Class RecipeTransformerTest
*
* @package App\DataTransformer
*/
class RecipeTransformerTest extends PHPUnit_Framework_TestCase
{
/**
* Tests single transform
*
* @param string $title
* @param array $ingredients
* @param array $expects
*
* @dataProvider singleTransformDataProvider
*/
public function testSingleTransform($title, $ingredients, $expects)
{
/** @var Recipe|Mock $recipe */
$recipe = Mockery::mock(Recipe::class);
$recipe->shouldReceive('getTitle')->andReturn($title);
$recipe->shouldReceive('getIngredients')->andReturn($ingredients);
$this->assertEquals($expects, RecipeTransformer::transform($recipe));
}
/**
* Data provider for testSingleTransform
*
* @return array
*/
public function singleTransformDataProvider()
{
return [
['Salad', ['Lettuce', 'Beetroot'], ['title' => 'Salad', 'ingredients' => ['Lettuce', 'Beetroot']]],
['Fry-up', ['Mushrooms', 'Bacon'], ['title' => 'Fry-up', 'ingredients' => ['Mushrooms', 'Bacon']]]
];
}
}
<file_sep><?php
namespace App\Service;
use Abraham\TwitterOAuth\TwitterOAuth;
/**
* Class TwitterService
*
* @package App\Service
*/
class TwitterService
{
/** @var TwitterOAuth */
private $twitterClient;
/**
* TwitterService constructor.
*
* @param array $twitterConfiguration
*/
public function __construct($twitterConfiguration)
{
if (!$twitterConfiguration['consumer_key'] || !$twitterConfiguration['consumer_secret']
|| !$twitterConfiguration['token'] || !$twitterConfiguration['token_secret']
) {
return;
}
$this->twitterClient = new TwitterOAuth(
$twitterConfiguration['consumer_key'],
$twitterConfiguration['consumer_secret'],
$twitterConfiguration['token'],
$twitterConfiguration['token_secret']
);
}
/**
* @param string $text
*/
public function sendTweet($text)
{
$text = (strlen($text) <= 140) ? $text : substr($text, 0, 140);
$this->twitterClient->post('statuses/update', ['status' => $text]);
}
}
<file_sep><?php
namespace App\Controller;
use Silex\Application;
use Silex\WebTestCase;
/**
* Class RecipeControllerTest
*
* @package App\Controller
*/
class RecipeControllerTest extends WebTestCase
{
public function testLunchEndpointWorks()
{
$client = $this->createClient();
$client->followRedirects(true);
$client->request('GET', '/api/v1/lunch');
$this->assertTrue($client->getResponse()->isOk());
}
public function createApplication()
{
$basePath = __DIR__.'/../../../../';
require_once $basePath.'vendor/autoload.php';
$app = new Application();
require $basePath.'config/dev.php';
require $basePath.'src/app.php';
return $app;
}
}
<file_sep><?php
namespace App\Repository;
/**
* Class BaseRepository
*
* @package App\Repository
*/
abstract class BaseRepository
{
/** @var string */
protected $basePath;
public function __construct($dataFolder)
{
$this->basePath = __DIR__.'/../../../'.$dataFolder;
}
/**
* @return array
*/
protected function getData()
{
if (!file_exists($this->getDataPath())) {
return [];
}
return json_decode(file_get_contents($this->getDataPath()), true)[$this->getDataName()];
}
/**
* @return string
*/
private function getDataPath()
{
return $this->basePath.'/'.$this->getDataName().'.json';
}
/**
* @return string
*/
abstract protected function getDataName();
}
<file_sep><?php
namespace App\Entity;
/**
* Class Recipe
*
* @package App\Entity
*/
class Recipe
{
/** @var string */
private $title;
/** @var array */
private $ingredients;
/**
* Recipe constructor.
*
* @param array $data
*/
public function __construct($data)
{
$this
->setTitle($data['title'])
->setIngredients($data['ingredients'])
;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* @return array
*/
public function getIngredients()
{
return $this->ingredients;
}
/**
* @param array $ingredients
*
* @return $this
*/
public function setIngredients($ingredients)
{
$this->ingredients = $ingredients;
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use App\Service\TwitterService;
use InvalidArgumentException;
use LogicException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class TwitterController
*
* @package App\Controller
*/
class TwitterController
{
/** @var TwitterService */
protected $twitterService;
/**
* TwitterController constructor.
*
* @param TwitterService $twitterService
*/
public function __construct(TwitterService $twitterService)
{
$this->twitterService = $twitterService;
}
/**
* @param Request $request
*
* @return Response
* @throws HttpException
* @throws LogicException
* @throws InvalidArgumentException
*/
public function tweetAction(Request $request)
{
$json = json_decode($request->getContent(), true);
if (!isset($json['text']) || !$json['text']) {
throw new HttpException(Response::HTTP_PRECONDITION_FAILED);
}
$this->twitterService->sendTweet($json['text']);
return new Response('', Response::HTTP_NO_CONTENT);
}
}
<file_sep><?php
namespace App\Service;
use App\Entity\Ingredient;
use App\Entity\Recipe;
use App\Repository\IngredientRepository;
use App\Repository\RecipeRepository;
use DateInterval;
use DateTime;
use Mockery;
use Mockery\Mock;
use PHPUnit_Framework_TestCase;
/**
* Class FridgeServiceTest
*
* @package App\Service
*/
class FridgeServiceTest extends PHPUnit_Framework_TestCase
{
/**
* Tests different data to check valid recipes
*
* @param array $ingredients
* @param array $recipes
* @param int $expectsCount
*
* @dataProvider testGetValidRecipesCountProvider
*/
public function testGetValidRecipesCount($ingredients, $recipes, $expectsCount)
{
$fridgeService = $this->getFridgeService($ingredients, $recipes);
$this->assertCount($expectsCount, $fridgeService->getValidRecipes());
}
/**
* Data provider for testGetValidRecipesCount
*
* @return array
*/
public function testGetValidRecipesCountProvider()
{
$bestBefore = new DateTime();
$bestBefore->add(DateInterval::createfromdatestring('+1 day'));
$useBy = new DateTime();
$useBy->add(DateInterval::createfromdatestring('+4 day'));
$bestBeforePast = new DateTime();
$bestBeforePast->add(DateInterval::createfromdatestring('-4 day'));
$useByPast = new DateTime();
$useByPast->add(DateInterval::createfromdatestring('-2 day'));
$return[] = [[], [], 0];
$return[] = [
[
new Ingredient(['title' => 'Ham', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Cheese', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Bread', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Lettuce', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Tomato', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Beetroot', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Tuna', 'best-before' => $bestBeforePast->format('Y-m-d'), 'use-by' => $useByPast->format('Y-m-d')]),
],
[
new Recipe(['title' => 'Ham and Cheese Toastie', 'ingredients' => ['Ham', 'Cheese', 'Bread']]),
new Recipe(['title' => 'Salad with tuna', 'ingredients' => ['Lettuce', 'Tomato', 'Beetroot', 'Tuna']]),
new Recipe(['title' => 'Salad', 'ingredients' => ['Lettuce', 'Tomato', 'Beetroot']]),
new Recipe(['title' => 'Fry-up', 'ingredients' => ['Bacon', 'Eggs', 'Mushrooms']]),
],
2
];
return $return;
}
/**
* Test order of recipes with products with past best-before date
*/
public function testGetValidRecipesOrder()
{
$bestBefore = new DateTime();
$intervalOne = DateInterval::createfromdatestring('+1 day');
$bestBefore->add($intervalOne);
$useBy = new DateTime();
$intervalTwo = DateInterval::createfromdatestring('+4 day');
$useBy->add($intervalTwo);
$bestBeforePast = new DateTime();
$bestBeforePast->add(DateInterval::createfromdatestring('-2 day'));
$ingredients = [
new Ingredient(['title' => 'Ham', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Cheese', 'best-before' => $bestBeforePast->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Bread', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Lettuce', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Tomato', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
new Ingredient(['title' => 'Beetroot', 'best-before' => $bestBefore->format('Y-m-d'), 'use-by' => $useBy->format('Y-m-d')]),
];
$recipes = [
new Recipe(['title' => 'Ham and Cheese Toastie', 'ingredients' => ['Ham', 'Cheese', 'Bread']]),
new Recipe(['title' => 'Salad', 'ingredients' => ['Lettuce', 'Tomato', 'Beetroot']]),
];
$fridgeService = $this->getFridgeService($ingredients, $recipes);
$this->assertEquals('Salad', end($recipes)->getTitle());
$validRecipes = $fridgeService->getValidRecipes();
$this->assertCount(2, $validRecipes);
$this->assertEquals('Ham and Cheese Toastie', end($validRecipes)->getTitle());
}
/**
* @param array $ingredients
* @param array $recipes
*
* @return FridgeService
*/
private function getFridgeService($ingredients, $recipes)
{
/** @var IngredientRepository|Mock $ingredientRepository */
$ingredientRepository = Mockery::mock(IngredientRepository::class);
$ingredientRepository->shouldReceive('getAll')->andReturn($ingredients);
/** @var RecipeRepository|Mock $recipeRepository */
$recipeRepository = Mockery::mock(RecipeRepository::class);
$recipeRepository->shouldReceive('getAll')->andReturn($recipes);
return new FridgeService($ingredientRepository, $recipeRepository);
}
}
<file_sep><?php
namespace App\Loader;
use App\Controller\RecipeController;
use App\Controller\TwitterController;
use Silex\Application;
use Silex\ControllerCollection;
/**
* Class RoutesLoader
*
* @package App
*/
class RoutesLoader
{
/** @var Application */
private $app;
/**
* RoutesLoader constructor.
*
* @param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
$this->instantiateControllers();
}
public function bindRoutesToControllers()
{
/** @var ControllerCollection $api */
$api = $this->app["controllers_factory"];
$api->get('/lunch', "recipe.controller:listAction");
$api->post('/twitter/tweet', "twitter.controller:tweetAction");
$this->app->mount($this->app["api.endpoint"].'/'.$this->app["api.version"], $api);
}
private function instantiateControllers()
{
$this->app['recipe.controller'] = function () {
return new RecipeController($this->app['fridge.service']);
};
$this->app['twitter.controller'] = function () {
return new TwitterController($this->app['twitter.service']);
};
}
}
<file_sep><?php
use App\Loader\RoutesLoader;
use App\Loader\ServicesLoader;
use Silex\Provider\AssetServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\HttpFragmentServiceProvider;
$app->register(new ServiceControllerServiceProvider());
$app->register(new AssetServiceProvider());
$app->register(new HttpFragmentServiceProvider());
//load services
$servicesLoader = new ServicesLoader($app);
$servicesLoader->bindServicesIntoContainer();
//load routes
$routesLoader = new RoutesLoader($app);
$routesLoader->bindRoutesToControllers();
return $app;
<file_sep><?php
namespace App\Entity;
use DateTime;
/**
* Class Ingredient
*
* @package App\Entity
*/
class Ingredient
{
/** @var string */
private $title;
/** @var DateTime */
private $bestBefore;
/** @var DateTime */
private $useBy;
/**
* Ingredient constructor.
*
* @param array $data
*/
public function __construct($data)
{
$this
->setTitle($data['title'])
->setBestBefore(new DateTime($data['best-before']))
->setUseBy(new DateTime($data['use-by']))
;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* @return DateTime
*/
public function getBestBefore()
{
return $this->bestBefore;
}
/**
* @param DateTime $bestBefore
*
* @return $this
*/
public function setBestBefore(DateTime $bestBefore)
{
$this->bestBefore = $bestBefore;
return $this;
}
/**
* @return DateTime
*/
public function getUseBy()
{
return $this->useBy;
}
/**
* @param DateTime $useBy
*
* @return $this
*/
public function setUseBy(DateTime $useBy)
{
$this->useBy = $useBy;
return $this;
}
}
<file_sep><?php
namespace App\Repository;
use App\Entity\Ingredient;
/**
* Class IngredientRepository
*
* @package App\Repository
*/
class IngredientRepository extends BaseRepository
{
const DATA_NAME = 'ingredients';
/**
* @return Ingredient[]
*/
public function getAll()
{
$collection = [];
$dataCollection = $this->getData();
if (!$dataCollection) {
return $collection;
}
foreach ($dataCollection as $itemData) {
$collection[] = new Ingredient($itemData);
}
return $collection;
}
/**
* @inheritdoc
*/
protected function getDataName()
{
return self::DATA_NAME;
}
}
<file_sep><?php
namespace App\Service;
use App\Entity\Ingredient;
use App\Entity\Recipe;
use App\Repository\IngredientRepository;
use App\Repository\RecipeRepository;
use DateTime;
/**
* Class FridgeService
*
* @package App\Service
*/
class FridgeService
{
const STATE_GOOD = 1;
const STATE_PAST_BY = 2;
const STATE_EXPIRED = 3;
/** @var IngredientRepository */
private $ingredientRepository;
/** @var RecipeRepository */
private $recipeRepository;
/**
* FridgeService constructor.
*
* @param IngredientRepository $ingredientRepository
* @param RecipeRepository $recipeRepository
*/
public function __construct(IngredientRepository $ingredientRepository, RecipeRepository $recipeRepository)
{
$this->ingredientRepository = $ingredientRepository;
$this->recipeRepository = $recipeRepository;
}
/**
* Returns recipes if fridge has not expired required products,
* sorting recipes with products which arrived at "best-before" date to the bottom
*
* @return Recipe[]
*/
public function getValidRecipes()
{
$ingredients = $this->ingredientRepository->getAll();
$recipes = $this->recipeRepository->getAll();
if (!$ingredients || !$recipes) {
return [];
}
return $this->filterRecipesByIngredientsState($recipes, $ingredients);
}
/**
* @param Recipe $recipe
* @param array $goodIngredients
* @param array $pastIngredients
*
* @return int
*/
private function checkRecipeIngredients(Recipe $recipe, $goodIngredients, $pastIngredients)
{
$pastBy = false;
foreach ($recipe->getIngredients() as $ingredientTitle) {
if (in_array($ingredientTitle, $pastIngredients)) {
$pastBy = true;
continue;
}
if (in_array($ingredientTitle, $goodIngredients)) {
continue;
}
return self::STATE_EXPIRED;
}
return ($pastBy) ? self::STATE_PAST_BY : self::STATE_GOOD;
}
/**
* @param Recipe[] $recipes
* @param Ingredient[] $ingredients
*
* @return Recipe[]
*/
private function filterRecipesByIngredientsState($recipes, $ingredients)
{
$goodRecipies = [];
$pastByRecipies = [];
list($goodIngredients, $pastIngredients) = $this->sortIngredientsByState($ingredients);
foreach ($recipes as $recipe) {
switch ($this->checkRecipeIngredients($recipe, $goodIngredients, $pastIngredients)) {
case self::STATE_GOOD:
$goodRecipies[] = $recipe;
break;
case self::STATE_PAST_BY:
$pastByRecipies[] = $recipe;
break;
}
}
return array_merge($goodRecipies, $pastByRecipies);
}
/**
* @param Ingredient[] $ingredients
*
* @return array
*/
private function sortIngredientsByState($ingredients)
{
$goodIngredients = [];
$pastIngredients = [];
$nowDate = new DateTime();
foreach ($ingredients as $ingredient) {
if ($nowDate < $ingredient->getBestBefore()) {
$goodIngredients[] = $ingredient->getTitle();
} elseif ($nowDate < $ingredient->getUseBy()) {
$pastIngredients[] = $ingredient->getTitle();
}
}
return [$goodIngredients, $pastIngredients];
}
}
| 3e720833c7e951dc0d7f8c820a2dfb5f6f6c52b9 | [
"Markdown",
"PHP"
] | 18 | PHP | dpcat237/pasishnyi-denys-techtask-20170209 | 5649081bf9229c81d1581ff2abadf889d35136a7 | 3f21fe5f97b8e5dacdec3e7b476154919f890ccf | |
refs/heads/master | <repo_name>alex-krash/jazoo<file_sep>/README.md
# jazoo - Zookeeper Client based on Spring-Shell
jazoo - is a modern cli for zookeeper base on spring-shell.
## Debug run (for developers)
```
mvn spring-boot:run -Dspring-boot.run.arguments=--server=localhost:2182
```
## Build
```
git clone https://github.com/vbabaev/jazoo.git
cd jazoo
mvn clean package
java -jar target/jazoo-*.jar --server=localhost:2181
jazoo@localhost:2181:/$ pwd
/
```
## Supported functionality
### cat $path
Prints contents of the given znode
```
jazoo@localhost:2181:/$ cat logs/log-001
log_line_1: err
log_line_1: inf
```
### cd $path
Sets current directory to $path
```
jazoo@localhost:2181:/$ pwd
/
jazoo@localhost:2181:/$ cd dir1
jazoo@localhost:2181:/dir1$ pwd
/dir1
```
### pwd (no arguments)
Returns current directory
```
jazoo@localhost:2181:/$ pwd
/
```
### ls [-l:--long] $path
Returns list of nodes by path
```
jazoo@localhost:2181:/$ ls -l
172 0 2019-08-30 15:54:37 /dir1
172 0 2019-08-30 15:54:37 /dir2
172 0 2019-08-30 15:54:37 /dir3
jazoo@localhost:2181:/$ ls
dir1
dir2
dir3
```
<file_sep>/src/main/java/dev/vbabaev/tools/jazoo/Client.java
package dev.vbabaev.tools.jazoo;
import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStyle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.shell.jline.PromptProvider;
@SpringBootApplication
public class Client {
public static void main(String[] args) {
new SpringApplicationBuilder()
.bannerMode(Banner.Mode.OFF)
.sources(Client.class)
.run(args);
}
@Bean
public PromptProvider myPromptProvider(PathResolver pathResolver, @Value("${server:localhost}") String server) {
return () -> new AttributedString("jazoo@" + server + ":" + pathResolver.getCurrent() + "$ ", AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW));
}
}
<file_sep>/src/main/java/dev/vbabaev/tools/jazoo/ConnectionPool.java
package dev.vbabaev.tools.jazoo;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("singleton")
public class ConnectionPool {
private final GenericObjectPool<ZooKeeperPoolable> pool;
public ConnectionPool(@Value("${server:localhost}") String connectionString, @Value("${timeout:10000}") int timeOut, @Value("${max-connections:10}") int maxConnections) {
PoolableConnectionFactory factory = new PoolableConnectionFactory(connectionString, timeOut);
GenericObjectPoolConfig<ZooKeeperPoolable> config = new GenericObjectPoolConfig<>();
config.setMaxTotal(maxConnections);
GenericObjectPool<ZooKeeperPoolable> pool = new GenericObjectPool<>(factory, config);
factory.setPool(pool);
this.pool = pool;
}
public ZooKeeperPoolable getConnection() throws InterruptedException {
try {
return pool.borrowObject();
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
}
}
<file_sep>/src/main/java/dev/vbabaev/tools/jazoo/PathResolver.java
package dev.vbabaev.tools.jazoo;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.util.Stack;
@Service
@Scope("singleton")
public class PathResolver {
private String current;
public PathResolver() {
this.current = "/";
}
public String resolveParts(String path) {
String[] parts = path.split("/");
Stack<String> stack = new Stack<>();
for (String part: parts) {
if (part.isEmpty()) continue;
if (part.equals(".")) continue;
if (part.equals("..")) {
stack.pop();
continue;
}
stack.push(part);
}
return "/" + String.join("/", stack);
}
public static String basename(String path) {
String[] parts = path.split("/");
StringBuilder stringBuilder = new StringBuilder("");
for (int i = 1; i < parts.length - 1; i++) {
stringBuilder.append("/").append(parts[i]);
}
return stringBuilder.toString();
}
public static String join(String basename, String filename)
{
return basename + (basename.equals("/") ? "": "/") + filename;
}
public static String filename(String path)
{
String result = path.replaceAll(basename(path), "");
if (result.equals("/")) return result;
return result.substring(1);
}
public String resolve(String path) {
String resolved;
if (path.startsWith("/")) {
resolved = trim(path);
} else {
resolved = current + (current.equals("/") ? "" : "/") + path;
}
return resolveParts(resolved);
}
public String set(String path) {
this.current = resolve(path);
return this.current;
}
public String getCurrent() {
return this.current;
}
private String trim(String path) {
if (path.equals("/")) return path;
if (path.endsWith("/")) return trim(path.substring(0, path.length() - 1));
return path;
}
}
<file_sep>/src/main/java/dev/vbabaev/tools/jazoo/command/CommandRemove.java
package dev.vbabaev.tools.jazoo.command;
import dev.vbabaev.tools.jazoo.PathResolver;
import dev.vbabaev.tools.jazoo.ZooKeeperConnection2;
import org.apache.zookeeper.KeeperException;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
import java.util.List;
@ShellComponent
public class CommandRemove {
private PathResolver resolver;
private ZooKeeperConnection2 connection;
public CommandRemove(ZooKeeperConnection2 connection, PathResolver resolver) {
this.connection = connection;
this.resolver = resolver;
}
@ShellMethod(key = "rm", value = "Create new file or updates mtime for the existing file")
public void remove(
@ShellOption(value = {"-r", "--recursive"}, arity = 0, defaultValue = "false") boolean recursive,
@ShellOption(value = {"-v", "--verbose"}, arity = 0, defaultValue = "false") boolean verbose,
@ShellOption(value = "") String path
) throws KeeperException, InterruptedException {
String resolvedPath = resolver.resolve(path);
if (!recursive) {
removeSingle(resolvedPath, verbose);
} else {
removeRecursive(resolvedPath, verbose);
}
}
private void removeSingle(String resolvedPath, boolean verbose) throws KeeperException, InterruptedException {
if (connection.listChildren(resolvedPath).size() > 0) {
throw new RuntimeException("Node " + resolvedPath + " is not empty");
}
connection.delete(resolvedPath);
if (verbose) {
System.out.println("Deleted " + resolvedPath);
}
}
private void removeRecursive(String resolvedPath, boolean verbose) throws KeeperException, InterruptedException {
List<String> children = connection.listChildren(resolvedPath);
for (String child: children) {
removeRecursive(child, verbose);
}
removeSingle(resolvedPath, verbose);
}
}
<file_sep>/src/main/java/dev/vbabaev/tools/jazoo/ListChildrenValueProvider.java
package dev.vbabaev.tools.jazoo;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.standard.ValueProvider;
import org.springframework.shell.standard.ValueProviderSupport;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class ListChildrenValueProvider extends ValueProviderSupport {
private ConnectionPool pool;
private PathResolver resolver;
public ListChildrenValueProvider(ConnectionPool pool, PathResolver resolver) {
this.pool = pool;
this.resolver = resolver;
}
@Override
public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints) {
String input = completionContext.currentWordUpToCursor();
int lastSlash = input.lastIndexOf("/");
String dir = lastSlash > -1 ? input.substring(0, lastSlash+1) : "";
String prefix = input.substring(lastSlash + 1, input.length());
try (ZooKeeperPoolable conn = pool.getConnection()) {
String parentDir = resolver.resolve(dir);
List<String> strings = conn.getChildren(parentDir, false);
List<CompletionProposal> retval = strings.stream().filter(s -> s.startsWith(prefix)).map(s -> new CompletionProposal(dir + s)).collect(Collectors.toList());
return retval;
} catch (Exception err) {
throw new RuntimeException(err);
}
}
}
<file_sep>/src/main/java/dev/vbabaev/tools/jazoo/PoolableConnectionFactory.java
package dev.vbabaev.tools.jazoo;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
class PoolableConnectionFactory implements PooledObjectFactory<ZooKeeperPoolable> {
private ObjectPool<ZooKeeperPoolable> pool;
private final String connectionString;
private final int sessionTimeout;
public PoolableConnectionFactory(String connectionString, int sessionTimeout) {
this.connectionString = connectionString;
this.sessionTimeout = sessionTimeout;
}
public void setPool(ObjectPool<ZooKeeperPoolable> pool) {
this.pool = pool;
}
@Override
public PooledObject<ZooKeeperPoolable> makeObject() throws Exception {
return new DefaultPooledObject<>(new ZooKeeperPoolable(connectionString, sessionTimeout, pool));
}
@Override
public void destroyObject(PooledObject<ZooKeeperPoolable> p) throws Exception {
p.getObject().reallyClose();
}
@Override
public boolean validateObject(PooledObject<ZooKeeperPoolable> p) {
return true;
}
@Override
public void activateObject(PooledObject<ZooKeeperPoolable> p) throws Exception {
}
@Override
public void passivateObject(PooledObject<ZooKeeperPoolable> p) throws Exception {
}
}
| be50fb71454d4704b34eec1a6013b05bdde33219 | [
"Markdown",
"Java"
] | 7 | Markdown | alex-krash/jazoo | 684fc3fd0686814f24849b0459ce3b2cc9a32c6a | 685215f2ac3b92fd2aa3fed28203a26c38e61f66 | |
refs/heads/master | <file_sep>//****************************************
// Ball Object
//****************************************
function Ball(speed, startPosX, startPosY)
{
this.x = startPosX;
this.y = startPosY;
this.vy = 1*1;
this.vx = 0.5*1;
this.radius = 8;
this.speed = 1;
}
// Define the draw function for the ball class
Ball.prototype.draw = function(canvas)
{
canvas.beginPath();
canvas.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
canvas.fillStyle = "rgb(130,130,130)";
canvas.fill();
canvas.strokeStyle = "white";
canvas.stroke();
canvas.closePath();
}
Ball.prototype.checkWallHits = function()
{
if (this.y+this.vy-this.radius<0) {
this.vy = -this.vy;
}
if (this.x+this.vx-this.radius<0 || this.x+this.vx+this.radius>game.width) {
this.vx = -this.vx;
}
}
Ball.prototype.checkClubHit = function()
{
if (this.y+this.vy+this.radius >= game.theClub.y && this.y+this.radius<=game.theClub.y){
if (this.x+this.vx+this.radius >= game.theClub.x && this.x+this.vx-this.radius <= game.theClub.x+game.theClub.width){
this.vy = -this.vy;
return ;
}
}
if ( (this.x+this.vx+this.radius>=game.theClub.x && this.x+this.radius<=game.theClub.x) ||
(this.x+this.vx-this.radius<=game.theClub.x+game.theClub.width && this.x-this.radius>=game.theClub.x+game.theClub.width)){
if ( (this.y+this.vy-this.radius<=game.theClub.y+game.theClub.height) && (this.y+this.y+this.radius>=game.theClub.y)){
this.vx = -this.vx;
return;
}
}
}
Ball.prototype.update = function()
{
// Check if the end of the screen is reached - eg. ball missed the club
if(this.y >= Game.height)
{
this.vy = 0;
this.vx = 0;
}
// Check if the ball hits an edge wall
this.checkWallHits();
// Check if the ball hits the club
this.checkClubHit();
// Update the ball position
this.x += this.vx * this.speed;
this.y += this.vy * this.speed;
}
| 91295df37fafd781cacc9d44bb2fe7ac2d346f61 | [
"JavaScript"
] | 1 | JavaScript | tphuc112358/Animation | 798ec09a30bfed96469dbf5dda47d47017ab9f01 | 6ec774b2e237f83706ecacbb717e484abfa1cf6a | |
refs/heads/master | <file_sep>###just do one thing.
Find the word under cursor for Sublime Text
### usage
Command: shifti
Keymap: shift+f7
<file_sep>import sublime
import sublime_plugin
class ShiftiCommand(sublime_plugin.TextCommand):
def run(self, edit):
selection = self.view.sel()[0]
if len(selection) == 0:
selection = self.view.word(selection)
text = self.view.substr(selection)
filepath = self.view.file_name()
# packages = sublime.packages_path()
args = {
"cmd": [
"grep",
'-n',
text,
filepath
]
}
self.view.window().run_command('exec', args)
| 6032bec1db40d966db4a0517420923e966e8aef9 | [
"Markdown",
"Python"
] | 2 | Markdown | yleo77/shifti | 1ee38a806d02820dfec7c2ff2e6e773e75fc6a40 | 982fe577e1937a9c290142893f1737464c87adfe | |
refs/heads/master | <repo_name>Patechoc/3Dslicer-extension-with-Docker<file_sep>/README.md
# 3Dslicer-extension-with-Docker
This is a demo to run, test, build extensions and package your own variant of 3DSlicer right from the latest released version (currently Slicer 4.4).
## How it works?
- [3DSlicer](http://www.slicer.org/) is built and compiled from source (with [CMake](http://www.cmake.org/)), and the result is stored on [DockerHub as a Docker image](https://registry.hub.docker.com/u/patrickmerlot/3dslicer-docker-image/).
- This image is pulled and we can run it or extend it locally within Docker.
- On top of that, [Wercker](http://wercker.com/) allows us to automate the test and deployement for every single 'push' made to this repository.
While Docker guarantees reliability and reproducibility without waiting for most of the dependencies to be installed and the code source to compile, Wercker allows continuous delivery of your applications, by testing and reporting for every single push to the repository (and [even locally after any file modification saved](http://blog.wercker.com/2015/05/15/Introducing-local-development.html)... hot topic!).
## Getting started
### Running 3Dslicer
To run Slicer on your machine.
Pull the Docker image, i.e. the source code of 3Dslicer already built and compiled:
```shell
$ sudo docker pull patrickmerlot/3dslicer-docker-image
```
and run the image (as an interactive Docker container), which is like entering a virtual environment where 3Dslicer is already installed from source and ready to run:
```shell
$ sudo docker run -t -i patrickmerlot/3dslicer-docker-image /bin/bash
...
$ bash-4.2# ls
...
$ bash-4.2# /myProject/Slicer/Slicer-SuperBuild-Debug/Slicer
...
$ exit
```
### Test 3Dslicer
### Modify/Extend 3Dslicer
### Package your variant
## Setting up your own Automation-driven development
- Create a new repository on GitHub. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub.
- Clone this repository and push it to your own Github/Bitbucket account.
```shell
$ git clone https://github.com/Patechoc/3Dslicer-extension-with-Docker.git
$ cd 3Dslicer-extension-with-Docker
```
- At the top of your GitHub repository's Quick Setup page, click to copy the remote repository URL.
- In Terminal, add the URL for the remote repository (<remote repository URL>, e.g. https://github.com/Patechoc/myNewSlicerExtension.git) where your local repository will be pushed.
```shell
$ git remote rm origin
$ git remote add origin <remote repository URL>
```
- Push the changes (or simply this clone untouched) from your local repository to GitHub.
```shell
$ git push origin master
```
- Sign up/Log in to your [Wercker account](https://app.wercker.com/)
- Register your Github account in the Settings if not already done
- Create a new application and follow the steps (Select a repository, ...) until you clicked on "Finish"
- In your new application, change the Wercker version to 5 ("Ewok"). In "Settings" > "Infrastructure stack", select "Infra Stack 5"/"Ewok". This allows Wercker to pull Docker images.
- You are done! Now every time you will "push" to your Github repo, Wercker will test your code following the steps detailled in wercker.yml<file_sep>/checkout.sh
#!/bin/bash
svn co http://svn.slicer.org/Slicer3/branches/Slicer-3-6 Slicer3
| e7fbcd893ec4ca3e6812f678744ab38923ca09e8 | [
"Markdown",
"Shell"
] | 2 | Markdown | Patechoc/3Dslicer-extension-with-Docker | 77a6deb95d6e7eff4eb1b1be42175bd38cfdf80a | 3e2110d5be37ecd871cd0e29fda5d0a78756d96b | |
refs/heads/master | <repo_name>watsabitz/DSRH<file_sep>/common/services/auth.js
angular
.module('Dsrh')
.factory('Auth', Auth);
Auth.$inject = ['$firebaseAuth', '$q', 'Database'];
function Auth($firebaseAuth, $q, Database){
const authObj = {};
//initialize the $firebaseAuth service
let auth = $firebaseAuth();
//append functions to the Auth service
authObj.auth = auth;
authObj.createUser = createUser;
authObj.addUser = addUser;
authObj.updateUser = updateUser;
authObj.deleteUser = deleteUser;
authObj.sendVerificationEmail = sendVerificationEmail;
authObj.signIn = signIn;
authObj.signOut = signOut;
authObj.resetPassword = resetPassword;
authObj.retrieveUserInfo = retrieveUserInfo;
/**
* Create user
*/
function createUser(user){
// create a chain of promises
// we let the caller to catch and treat the error in the controller
return auth.$createUserWithEmailAndPassword(user.email, user.password)
.then((firebaseUser) => {
log('User created');
// console.log('User: ', firebaseUser);
return this.addUser(user, firebaseUser.uid).then(() => {
log('User profile updated');
return this.sendVerificationEmail().then(() => {
log('Verification email sent');
//we don't want to log in the user if he does not have a verified email
return this.signOut().then(() => {
return $q.when(); // return a success promise
});
});
});
});
}
/**
* Update user
*/
function updateUser(user){
// retrieve the old username
var oldUsername = auth.$getAuth().displayName;
// delete only the username from the username list and then update the account profile and the database
return Database.deleteUser(user, oldUsername)
.then( ()=> {
return this.addUser(user);
});
}
/**
* Add user information in the database
*/
function addUser(userInfo, id){
// get the user profile data information
const user = auth.$getAuth();
// this information is different than the one which we manually store in the database
// and is strictly asociated with the user account
const userProfile = {
displayName: userInfo.displayName || ''
// photoURL: userInfo.photoURL || ''
};
// update user profile data
return user.updateProfile(userProfile)
//then create an object with the user information in the database;
.then( () => {
return Database.addUser(userInfo, id || user.uid);
});
}
/**
* Delete the currently signed-in in user
*/
function deleteUser(){
auth.$deleteUser()
.then(() => {
console.log('user deleted');
})
.catch((error) => {
console.log(error);
});
}
/**
* Send a verfication email when the account is created
*/
function sendVerificationEmail(){
//get the user information
const user = auth.$getAuth();
return user.sendEmailVerification();
}
/**
* Sign in with the email and the password
*/
function signIn(email, password){
return auth.$signInWithEmailAndPassword(email, password);
}
/**
* Sign out the current logged user
*/
function signOut(){
return auth.$signOut();
}
/**
* Reset email to reset the password
*/
function resetPassword(resetEmail){
return auth.$sendPasswordResetEmail(resetEmail);
}
/**
* Retrieve user information which was stored at authentification/update profile phase;
*/
function retrieveUserInfo(){
return Database.retrieveUserInfo(auth.$getAuth().uid);
}
return authObj;
}<file_sep>/common/services/snackBar.js
angular
.module("Dsrh")
.factory("SnackBar", snackBar);
function snackBar($timeout){
var SB = {};
SB.showMainInfoSnackbar = showMainInfoSnackbar;
function showMainInfoSnackbar(errorSnack = false, message = false, successSnack = false, changeTop = false){
const x = document.getElementById("mainInfoSnackbar");
if (message) {
x.textContent = message;
}
//orizontal align the snakcbar
var viewPortWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
x.style.right = `${viewPortWidth/2 - x.getBoundingClientRect().width/2}px`;
//vertical align the sidebar
// x.style.top = `${window.scrollY + 30}px`;
if(changeTop) {
x.style.setProperty("--top", `${window.scrollY + 30}px`)
} else {
x.style.setProperty("--top", `30px`);
}
//if it's an error snakbar make it red
if(errorSnack) {
x.style.backgroundColor = '#e24d52';
} else if (successSnack){
x.style.backgroundColor = '#119094';
} else {
x.style.backgroundColor = '#333';
}
//show the snakbar
x.className = "show";
// remove the "show" class to hide the snackBar
$timeout(function(){
x.className = x.className.replace("show", "");
}, 3000);
}
return SB;
}<file_sep>/common/directives/search/search.js
angular
.module("Dsrh")
.directive("searchDirective", searchDirective);
function searchDirective(Search, SnackBar){
function getTemplateUrl(elem, attrs){
return 'common/directives/search/' + attrs.templateName + 'SearchTemplate.html';
}
function searchController($filter, $scope, $state, $timeout){
const preloader = document.querySelector('#preloader');
preloader.style.display = "block";
/**
* Hotels
*/
// test to see if the init was made
// if not, make the initialization
// if(!Search.initDone){
Search.init()
.then(() => {
log('Search data successfully retrieved from database');
Search.initDone = true;
getSearchData();
preloader.style.display = "none";
})
.catch((error) => {
log('Search Data was not retrieved from database', error);
Search.initDone = false;
preloader.style.display = "none";
});
// } else {
// else directly get the data
// getSearchData();
// }
// get search data and put in on the scope
function getSearchData(){
log('Search data successfully loaded');
const data = ['cities', 'hotels', 'restaurants'];
if($scope.addToSearch) {
$scope.addToSearch.split(',').forEach( item => {
switch (item) {
case data[0] :
$scope[item] = Search.getCitiesList();
console.log('Cities:', $scope[item].length);
break;
case data[1] :
$scope[item] = Search.getHotelsList();
console.log('Hotels:', $scope[item].length);
break;
case data[2] :
$scope[item] = Search.getRestaurantsList();
console.log('Restaurants:', $scope[item].length);
break;
}
});
}
}
$scope.showSearchResult = false;
$scope.showSearchResultRest = false;
//get the search input position and put the search result div bellow it
//also, set the width of the div to the same length as the search
const searchInput = document.querySelector("input#searchedTextInput");
let searchInputPosition = searchInput.getBoundingClientRect();
const searchResult = document.querySelector("div#searchResult");
if(searchResult) searchResult.style.top = `${searchInputPosition.bottom + 12}px`;
if(searchResult) searchResult.style.width = `${searchInputPosition.width}px`;
//do the regex tests
function populateResultList(input, listToIterate, returnedListName){
const regExp1 = new RegExp(`^${input}`, 'gi');
const regExp2 = new RegExp(`(?!^)${input}`, 'gi');
let searchResult1 = [], searchResult2 = [];
$scope[listToIterate].forEach( (item) => {
if( regExp1.test(item) ) {
searchResult1.push(item);
} else if( regExp2.test(item) ) {
searchResult2.push(item);
}
});
$scope[returnedListName] = [...searchResult1, ...searchResult2];
}
function resetReturnedLists(){
$scope.returnedCities = null;
$scope.returnedHotels = null;
$scope.returnedRestaurants = null;
}
//this value needs to be different than null in order to make the search
//possible values: C,H,R type: city, hotel, restaurants
$scope.selectionType = Search.selectionType ? Search.selectionType : null;
//make the search
$scope.doInputSearch = function (type){
$scope.selectionType = null;
//update the search result div width
searchInputPosition = searchInput.getBoundingClientRect();
searchResult.style.width = `${searchInputPosition.width}px`;
//reset the list
resetReturnedLists();
//we make the search only if the user typed more than 1 character
if(type == 'H' && $scope.searchObj.searchedTerm.length > 1){
populateResultList($scope.searchObj.searchedTerm, 'cities', 'returnedCities');
if ($scope.hotels) populateResultList($scope.searchObj.searchedTerm, 'hotels', 'returnedHotels');
$scope.showSearchResult = true;
} else if (type == 'R' && $scope.searchObjRest.searchedTerm.length > 1){
populateResultList($scope.searchObjRest.searchedTerm, 'cities', 'returnedCities');
if ($scope.restaurants) populateResultList($scope.searchObjRest.searchedTerm, 'restaurants', 'returnedRestaurants');
$scope.showSearchResultRest = true;
}else {
$scope.showSearchResult = false;
$scope.showSearchResultRest = false;
}
};
$scope.selectOption = function(option, selectionType){
//C,H,R type: city, hotel, restaurants
$scope.selectionType = selectionType;
if(option == 'H'){
$scope.searchObj.searchedTerm = option;
} else if (option == 'R') {
$scope.searchObjRest.searchedTerm = option;
} else {
$scope.searchObjRest.searchedTerm = option;
$scope.searchObj.searchedTerm = option;
}
resetReturnedLists();
};
/**
* Search Bar
*/
//init date picker values;
var initalStartDate = $filter('date')(new Date(), 'dd MMM yyyy'); //creat initial start date as today; ex: 21 Oct 2017
var initalEndDate = $filter('date')(new Date().setDate(new Date().getDate() + 1), 'dd MMM yyyy'); //creat initial end date as today + 1 day
// init search bar values
if(Search.searchObj == null){
$scope.searchObj = {
searchedTerm : '',
startDate : initalStartDate,
endDate : initalEndDate,
rooms: [1]
};
} else{
$scope.searchObj = Search.searchObj;
}
/**
* DatePicker
*/
//get the pickers
var startDatePicker = $('#startDate').datepicker({
uiLibrary: 'bootstrap4',
iconsLibrary: 'fontawesome',
value: Search.searchObj ? Search.searchObj.startDate : initalStartDate, // set the input value
format: 'dd mmm yyyy',
weekStartDay: 1,
minDate: initalStartDate, // set the calendar value
change: updateFirstCalendarValue,
hide: function () {
startDatePickerVisible = false;
}
});
var endDatePicker = $('#endDate').datepicker({
uiLibrary: 'bootstrap4',
iconsLibrary: 'fontawesome',
value: Search.searchObj ? Search.searchObj.endDate : initalEndDate,
format: 'dd mmm yyyy',
weekStartDay: 1,
minDate: initalEndDate,
change: updateSecondCalendarValue,
hide: function () {
endDatePickerVisible = false;
}
});
//show the datePickers when clicking on the inputs
const startDateInput = document.querySelector('#startDate');
//if we have the element on the page (== we are in the hotels page and not in the restaurants page)
let startDatePickerVisible = false;
if(startDateInput) {
startDateInput.addEventListener('click', () => {
if (startDatePickerVisible) {
startDatePicker.hide();
startDatePickerVisible = false;
} else {
startDatePicker.show();
startDatePickerVisible = true;
}
});
}
const endDateInput = document.querySelector('#endDate');
let endDatePickerVisible = false;
if(endDateInput) {
endDateInput.addEventListener('click', () => {
if (endDatePickerVisible) {
endDatePicker.hide();
endDatePickerVisible = false;
} else {
endDatePicker.show();
endDatePickerVisible = true;
}
});
}
//update the first calendar values
function updateFirstCalendarValue(){
$scope.searchObj.startDate = this.value;
// change the the second date (increment it by one) if it's lower or equal than the one we selected in the first;
if (new Date(this.value) >= new Date(endDatePicker.value()) ){
var newValue = $filter('date')(new Date(this.value).setDate(new Date(this.value).getDate() + 1), 'dd MMM yyyy');
endDatePicker.value(newValue) ;
}
$scope.$apply(); // we integrate jquery library with angularJS framework
}
//update the second calendar values
function updateSecondCalendarValue(){
$scope.searchObj.endDate = this.value;
// change the the first date (decrement it by one) if it's higher or equal than the one we selected in the second;
if (new Date(this.value) <= new Date(startDatePicker.value())){
var newValue = $filter('date')(new Date(this.value).setDate(new Date(this.value).getDate() - 1), 'dd MMM yyyy');
startDatePicker.value(newValue) ;
}
$scope.$apply();
}
/**
* DropDown
*/
//set the maximum number or rooms
$scope.min = {
rooms: 0,
personsPerRoom: 1
};
$scope.max = {
rooms: 10,
personsPerRoom: 4
};
$scope.guestText = 'persoane';
$scope.updateGuestNumber = function(){
$scope.guestNumber = $scope.searchObj.rooms.reduce( (a, item) => {return a + item; }, 0);
$scope.guestText = $scope.guestNumber != 1 ? 'persoane' : 'persoana';
updateTextAndValues();
};
$scope.updateGuestNumber();
// update the text and values from the dropdown
function updateTextAndValues(){
$scope.roomsText = $scope.searchObj.rooms.length != 1 ? 'camere' : 'camera';
$scope.roomsAndGuests = `${$scope.searchObj.rooms.length} ${$scope.roomsText} - ${$scope.guestNumber} ${$scope.guestText}`;
$scope.activeRemove = {
rooms: $scope.searchObj.rooms.length == $scope.min.rooms ? false : true,
};
$scope.activeAdd = {
rooms: $scope.searchObj.rooms.length == $scope.max.rooms ? false : true,
};
}
updateTextAndValues();
$scope.decreasePersonsPerRoom = function(index){
if ($scope.searchObj.rooms[index] != $scope.min.personsPerRoom) {
$scope.searchObj.rooms[index] -= 1;
$scope.updateGuestNumber();
}
}
$scope.increasePersonsPerRoom = function(index){
if ($scope.searchObj.rooms[index] != $scope.max.personsPerRoom) {
$scope.searchObj.rooms[index] += 1;
$scope.updateGuestNumber();
}
}
// add/remove item in the dropdown when the user press on the '-' or '+' sign
$scope.changeItemQuantity = function(action, itemName){
if(itemName == 'rooms') {
if(action == 'increase' && $scope.searchObj.rooms.length < $scope.max.rooms){
$scope.searchObj.rooms.push(1);
$scope.updateGuestNumber();
} else if (action == 'decrease' && $scope.searchObj.rooms.length > $scope.min.rooms){
$scope.searchObj.rooms.splice($scope.searchObj.rooms.length-1, 1);
$scope.updateGuestNumber();
}
// setInsertAgeBox();
}
updateTextAndValues();
};
//called when the user tries to make a search
$scope.submitSearchForm = function(){
Search.searchObj = $scope.searchObj;
Search.selectionType = $scope.selectionType;
//replace undefined values with 0;
var rooms = $scope.searchObj.rooms.map(item => item ? item : 0);
var mainInfoMessage = null;
//if the user did not selected any option
//we prevent him from continue and we show him a warning
if(!$scope.selectionType){
switch($scope.templateName){
case ('hotels'):
mainInfoMessage = 'Va rugam sa introduceti un nume de oras sau hotel valid';
break;
default:
mainInfoMessage = 'Va rugam sa introduceti un nume de oras valid';
}
SnackBar.showMainInfoSnackbar(true, mainInfoMessage);
}else if(rooms.includes(0)){
mainInfoMessage = "Va rugam introduceti numarul de persoane in toate camerele";
SnackBar.showMainInfoSnackbar(true, mainInfoMessage);
}else if($scope.selectionType == "C"){
Search.getSearchData($scope.selectionType, $scope.searchObj.searchedTerm, rooms, $scope.searchObj.startDate, $scope.searchObj.endDate)
.then((response) =>{
Search.returnedData = response;
$state.go("hotelsCitySearchResult");
})
.catch((error) => {
console.error(error);
console.error('Could not retrieve CitiesHotelsRoomsData');
});
}else if($scope.selectionType == "H"){
Search.getSearchData($scope.selectionType, $scope.searchObj.searchedTerm, rooms, $scope.searchObj.startDate, $scope.searchObj.endDate)
.then((hotel) =>{
//go to the hotels details page
//transform the name of the hotel to "dash" style and then send it as parameter
$state.go('hotelDetails', {
hotelURL: $scope.searchObj.searchedTerm.trim().toLowerCase().replace(/\s/g, '-'),
hotelName: Object.keys(hotel)[0],
hotelDetails: Object.values(hotel)[0]
});
})
.catch((error) => {
console.error(error);
console.error('Could not retrieve CitiesHotelsRoomsData');
});
}
};
/**
* Restaurants
*/
$scope.submitSearchFormRest = function(){
Search.searchObjRest = $scope.searchObjRest;
Search.selectionType = $scope.selectionType;
var mainInfoMessage = null;
//if the user did not selected any option
//we prevent him from continue and we show him a warning
if(!$scope.searchObjRest.searchedTerm && ($scope.selectionType != 'R' || $scope.selectionType != 'C')){
switch($scope.templateName){
case ('restaurants'):
mainInfoMessage = 'Va rugam sa introduceti un nume de oras sau restaurant valid';
break;
default:
mainInfoMessage = 'Va rugam sa introduceti un nume de oras valid';
}
SnackBar.showMainInfoSnackbar(true, mainInfoMessage);
}else if($scope.selectionType == "R"){
Search.getSearchDataRest($scope.selectionType, $scope.searchObjRest)
.then((response) =>{
let restaurant = response[0];
// go to the Restaurants details page
// transform the name of the restaurant to "dash" style and then send it as parameter
$state.go('restaurantDetails', {
restaurantURL: $scope.searchObjRest.searchedTerm.trim().toLowerCase().replace(/\s/g, '-'),
restaurantName: restaurant.$id,
restaurantDetails: restaurant,
searchedObject: $scope.searchObjRest
});
})
.catch((error) => {
console.error(error);
console.error('Could not retrieve CitiesRestaurantsRoomsData');
});
}else if($scope.selectionType == "C"){
Search.getSearchDataRest($scope.selectionType + 'R', $scope.searchObjRest)
.then((response) =>{
Search.returnedData = response;
Search.searchedObject = $scope.searchObjRest;
$state.go('restaurantsCitySearchResult');
})
.catch((error) => {
console.error(error);
console.error('Could not retrieve CitiesRestaurantsRoomsData');
});
}
}
var initialRestDate = $filter('date')(new Date(), 'dd MMM yyyy');
if(Search.searchObjRest == null){
$scope.searchObjRest = {
searchedTerm : '',
restDate : initialRestDate,
restTime : '',
person: 1
};
} else{
$scope.searchObjRest = Search.searchObjRest;
}
//get the pickers
var restDatePicker = $('#restDate').datepicker({
uiLibrary: 'bootstrap4',
iconsLibrary: 'fontawesome',
value: initialRestDate, // set the input value
format: 'dd mmm yyyy',
weekStartDay: 1,
minDate: initialRestDate, // set the calendar value
change: updateRestCalendarValue,
hide: function () {
restDatePickerVisible = false;
}
});
$('#restTime').timepicker({
'scrollDefault': 'now' ,
'disableTextInput': true,
'timeFormat': 'H:i'
});
$timeout(function (){
let x = $('#restTime').timepicker('setTime', new Date());
$scope.searchObjRest.restTime = x.val();
$scope.$apply();
},100)
// $('#restTime').on('showTimepicker', function() {
// console.log()
// }
$('#restTime').on('changeTime', function() {
$scope.searchObjRest.restTime = $(this).val();
$scope.$apply();
});
$scope.personText = $scope.searchObjRest.person != 1 ? 'persoane' : 'persoana';
$scope.changeItemQuantityRest = function(action) {
if(action == 'decrease' && $scope.searchObjRest.person != 1){
$scope.searchObjRest.person --;
} else if (action == 'increase' && $scope.searchObjRest.person != 10){
$scope.searchObjRest.person ++;
}
$scope.personText = $scope.searchObjRest.person != 1 ? 'persoane' : 'persoana';
}
function updateRestCalendarValue(){
$scope.searchObjRest.restDate = this.value;
$scope.$apply();
}
}
return {
restrict: 'E',
templateUrl: getTemplateUrl,
controller: searchController,
replace: true,
scope: {
templateName: '@',
addToSearch: '@'
}
};
}<file_sep>/pages/restaurantsPages/restaurantsCitySearchResult/restaurantsCitySearchResult.js
angular
.module('Restaurants')
.controller("restaurantsCitySearchResultCtrl", restaurantsCitySearchResultCtrl);
function restaurantsCitySearchResultCtrl($scope, Search){
$scope.restaurants = Search.returnedData;
$scope.searchedObject = Search.searchedObject;
$scope.sortingOptions = [
{
label: "Crescator dupa nota",
criteria: '+userRating'
},
{
label: "Descrescator dupa nota",
criteria: '-userRating'
}
];
$scope.orderCriteria = '+userRating'
$scope.showError = $scope.restaurants.length == 0;
if($scope.showError){
$scope.errorMessage = "Ne pare rau dar nu am gasit mese disponibile in perioada selectata !";
}
}<file_sep>/common/directives/searchResultTile/searchResultTile.js
angular
.module("Dsrh")
.directive("searchResultTile", searchResultTile);
function searchResultTile(ERRORS, CURRENCIES){
function getTemplateUrl(elem, attrs){
return 'common/directives/searchResultTile/' + attrs.templateName + 'SearchResultTile.html';
}
function searchResultTileController($scope, $state){
//if we don't have an image show the default one
if(!$scope.itemValue.photos || !$scope.itemValue.photos.main){
$scope.itemValue.photos = {
main : ERRORS.IMAGE_NOT_FOUND
};
}
$scope.setProperCurrency = function(totalPrice){
//get the currency code
const [price, currencyCode] = totalPrice.split(" ");
//and use it to get the currency name
const currencyName = currencyCode ? CURRENCIES[currencyCode] : CURRENCIES.DEFAULT;
return `${price} ${currencyName}`;
}
//create an array based on stars numbers to iterate over it with ng-repeat
$scope.getStarsNumber = function(){
return new Array($scope.itemValue.stars);
};
$scope.goToHotel = function(){
//go to the hotels details page
//transform the name of the hotel to "dash" style and then send it as parameter
$state.go('hotelDetails', {
hotelURL: $scope.itemName.trim().toLowerCase().replace(/\s/g,'-'),
hotelName: $scope.itemName,
hotelDetails: $scope.itemValue,
});
};
$scope.goToRestaurant = function(){
//go to the restaurants details page
//transform the name of the restaurant to "dash" style and then send it as parameter
$state.go('restaurantDetails', {
restaurantURL: $scope.itemName.trim().toLowerCase().replace(/\s/g,'-'),
restaurantName: $scope.itemName,
restaurantDetails: $scope.itemValue,
searchedObject: $scope.searchedObject,
});
};
}
return {
restrict: "E",
templateUrl: getTemplateUrl,
controller: searchResultTileController,
// replace: true,
scope: {
templateName: "@",
itemName: "<",
itemValue: "<",
searchedObject:"<?"
}
};
}<file_sep>/common/filters/generalFilters.js
angular
.module("Dsrh")
.filter("generateDropDown", function($filter){
function price(a, b){
return a.price.split(' ')[0] - b.price.split(' ')[0];
}
return function(dropDownOptions, toBeRemoved, currentItemIndex){
//we need to make a deep copy of the array in order to not alter the source
const cToBeRemoved = angular.copy(toBeRemoved);
//we substract the current element from the 'toBeRemoved' list
cToBeRemoved.splice(currentItemIndex, 1);
//create a string with all of the options we want to remove
let toBeRemovedString = cToBeRemoved.reduce( (string, item) => string += JSON.stringify(item), '');
//keep only the options which are not included in the 'toBeRemovedString';
return dropDownOptions
.filter(option => !toBeRemovedString.includes(option.name))
.sort(price);
}
})
.filter("enhancedOrderBy", function(){
return function(results, criteria){
let asc = criteria.slice(0, 1) == '+' ? true : false;
let orderByCriteria = criteria.slice(1, criteria.length);
if(orderByCriteria !== "totalPrice"){
return results.sort( (a, b) => {
if(asc){
return a[orderByCriteria] - b[orderByCriteria];
} else {
return b[orderByCriteria] - a[orderByCriteria];
}
})
} else {
return results.sort( (a, b) => {
if(asc){
return Number(a[orderByCriteria].split(' ')[0]) - Number(b[orderByCriteria].split(' ')[0]);
} else {
return Number(b[orderByCriteria].split(' ')[0]) - Number(a[orderByCriteria].split(' ')[0]);
}
})
}
}
});
<file_sep>/pages/restaurantsPages/restaurantDetails/restaurantDetails.js
angular
.module('Restaurants')
.controller('restaurantDetailsCtrl', restaurantDetailsCtrl);
function restaurantDetailsCtrl(RestaurantDetails, $scope, $stateParams, $sce, Utilis, SnackBar, $timeout, Auth){
$scope.restaurantData = $stateParams;
$scope.firebaseUser = null;
//every time the authentification state of the user changes we update the scope
Auth.auth.$onAuthStateChanged((firebaseUser) => {
$scope.firebaseUser = firebaseUser && firebaseUser.emailVerified ? firebaseUser : null;
if(!firebaseUser) return;
RestaurantDetails.retrieveUserInfo(firebaseUser.uid).$loaded().then((data)=>{
$scope.userData = {};
$scope.userData.fullName = data.lastName + ' ' + data.firstName;
$scope.userData.email = data.email;
$scope.userData.phone = data.phone;
});
});
$scope.hasComments = Object.keys($scope.restaurantData.restaurantDetails.comments).length > 0 ? true : false;
if(!$scope.restaurantData.restaurantDetails.validTables){
$scope.errorMessage = "Ne pare rau dar nu am gasit mese disponibile in perioada selectata !";
}
$scope.sanitizeDescription = function(){
return $sce.trustAsHtml($scope.restaurantData.restaurantDetails.description);
};
$scope.getPersonsText = function (capacity){
return capacity > 1 ? 'persoane' : 'persoana';
};
//tranform the dates from the calendar to be the same as the ones received from the database
//from '25 May 20018" to "2018-05-25"
function transformDates(dateFromCalendar) {
let date = new Date(dateFromCalendar);
//we make sure to add a '0' to each date
//for example "2018-5-4" becomes "2018-05-04"
//otherwise ther will be a 2-3 hour diference between this date and the one which we receve from the databse when we transfomr them in miliseconds
return `${date.getFullYear()}-${date.getMonth()+1 < 10 ? '0' : ''}${date.getMonth()+1}-${date.getDate() < 10 ? '0' : ''}${date.getDate()}`;
}
$scope.restaurantData.searchedObject.restDate = transformDates($scope.restaurantData.searchedObject.restDate);
if ($scope.restaurantData.restaurantDetails.validTables)$scope.selectedTable = $scope.restaurantData.restaurantDetails.validTables[0];
//do the restaurant reservation
$scope.reservationMade = false;
$scope.makeRestaurantReservation = function() {
RestaurantDetails.makeRestaurantReservation($scope.restaurantData.restaurantName, $scope.selectedTable.tableName, $scope.restaurantData.searchedObject, $scope.userData)
.then( () => {
SnackBar.showMainInfoSnackbar(false, 'Rezervarea a fost facuta cu success', true, true);
$timeout(() => {
$scope.reservationMade = true;
}, 2000);
$timeout(() => {
$scope.showSuccess = true;
}, 4000);
})
.catch( err => {
SnackBar.showMainInfoSnackbar(true, 'A aparut o problema la efectuarea rezervarii');
console.log(err);
})
}
$scope.restaurantData.restaurantDetails.comments = RestaurantDetails.objectToSortedArray($scope.restaurantData.restaurantDetails.comments);
//calculate average rating of the comments
function calculateAverage(comments){
if(!comments) return;
return comments.reduce( (acc, item) => acc+=item.rating, 0)/comments.length;
}
$scope.ratingAverage = calculateAverage($scope.restaurantData.restaurantDetails.comments);
//round to specific precision (see MDN)
function precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
$scope.ratings = [0,1,2,3,4,5,6,7,8,9,10];
$scope.comment = {
rating: $scope.ratings[0]
};
$scope.changeLabel = function(label){
return label.replace('table', 'Masa ');
}
$scope.postCommentAndRatingRest = function(){
$scope.comment.userName = $scope.firebaseUser.displayName;
//create a "2018-05-29" date format and remove the time
$scope.comment.date = new Date().toISOString().split("T")[0];
//calculate the new rating
const avr = ($scope.ratingAverage + $scope.comment.rating ) / 2;
const newRating = precisionRound(avr, 1)
console.log(newRating)
//make a full copy of the comment because we will reset it
const commentCopy = angular.copy($scope.comment);
RestaurantDetails.postCommentAndRatingRest($scope.restaurantData.restaurantName, commentCopy, newRating)
.then(() => {
$scope.restaurantData.restaurantDetails.comments.unshift(commentCopy);
})
.catch((err) => {
SnackBar.showMainInfoSnackbar(true, 'A aparut o problema la postarea comentariului');
console.log(err);
});
//refersh the comment
$scope.comment = {
rating: $scope.ratings[0]
};
};
}<file_sep>/pages/restaurantsPages/mainPage/mainRestaurants.js
angular
.module("Restaurants", [])
.controller('mainRestaurantsCtrl', mainRestaurantsCtrl)
mainRestaurantsCtrl.$inject = ['$state'];
function mainRestaurantsCtrl($state){
};<file_sep>/common/constants/constants.js
let errors = {
IMAGE_NOT_FOUND: "https://firebasestorage.googleapis.com/v0/b/dsrh-dp.appspot.com/o/image_not_found.png?alt=media&token=<PASSWORD>"
};
let currencies = {
DEFAULT: 'lei',
RON: 'lei',
E: 'euro'
};
let hotel_facilities = {
wifi : ["WiFi gratuit inclus", "057-wifi.svg"],
trans_aero: ["transfer de la și/sau la aeroport", "035-taxi.svg"],
anim_comp: ["acceptă animale de companie", "073-information.svg"],
cam_nef: ["camere pentru nefumători", "066-no-smoking.svg"],
non_stop: ["recepţie deschisă nonstop", "024-open.svg"],
terasa: ["terasă", "018-coffee-cup.svg"],
bar: ["bar", "011-syrup.svg"],
piscina: ["piscină", "068-swimming-pool.svg"],
piscina_in: ["piscină interioară", "068-swimming-pool.svg"],
parcare: ["parcare", "047-parking.svg"],
spa_and_wellness: ["spa și centru de wellness", "042-towel.svg"],
fitness: ["centru de fitness", "045-dumbbell.svg"],
tv: ["TV", "069-television.svg"]
}
angular
.module("Dsrh")
.constant('ERRORS', errors)
.constant('CURRENCIES', currencies)
.constant('FACILITIES', hotel_facilities);<file_sep>/pages/hotelsPages/hotelsCitySearchResult/hotelsCitySearchResult.js
angular
.module('Hotels')
.controller("hotelsCitySearchResultCtrl", hotelsCitySearchResultCtrl);
function hotelsCitySearchResultCtrl($scope, Search){
$scope.hotels = [];
for(let key in Search.returnedData){
$scope.hotels.push(Search.returnedData[key]);
}
$scope.sortingOptions = [
{
label: "Crescator dupa nr. de stele",
criteria: '+stars'
},
{
label: "Descrescator dupa nr. de stele",
criteria: '-stars'
},
{
label: "Crescator dupa nota",
criteria: '+userRating'
},
{
label: "Descrescator dupa nota",
criteria: '-userRating'
},
{
label: "Crescator dupa pret",
criteria: '+totalPrice'
},
{
label: "Descrescator dupa pret",
criteria: '-totalPrice'
}
];
$scope.orderCriteria = '+stars'
$scope.showError = $scope.hotels.length == 0;
if($scope.showError){
$scope.errorMessage = "Ne pare rau dar nu am gasit camere disponibile in perioada selectata !";
}
}<file_sep>/common/services/utilis.js
angular
.module('Dsrh')
.factory('Utilis', Utilis);
function Utilis(CURRENCIES){
function transformCurrency(totalPrice){
//get the currency code
const [price, currencyCode] = totalPrice.split(" ");
//and use it to get the currency name
const currencyName = currencyCode ? CURRENCIES[currencyCode] : CURRENCIES.DEFAULT;
return `${price} ${currencyName}`;
}
let rObj = {};
rObj.transformCurrency = transformCurrency;
return rObj;
}<file_sep>/common/directives/search/searchFactory.js
angular
.module('Dsrh')
.factory("Search", Search);
function Search(Database){
const src = {};
src.init = init;
src.initDone = false;
src.cities = [];
src.getCitiesList = getCitiesList;
src.setCitiesList = setCitiesList;
src.hotels = [];
src.getHotelsList = getHotelsList;
src.setHotelsList = setHotelsList;
src.restaurants = [];
src.getRestaurantsList = getRestaurantsList;
src.setRestaurantsList = setRestaurantsList;
src.getSearchData = getSearchData;
src.getSearchDataRest = getSearchDataRest;
src.returnedData = null;
src.searchObj = null;
src.selectionType = null;
function init(){
return Promise.all([
getDbLists('getCitiesList','cities'),
getDbLists('getHotelsList','hotels'),
getDbLists('getRestaurantsList','restaurants')
]);
}
/**
* Retrieve cities list
*/
function getDbLists(listFunction, objectName) {
return new Promise(function(resolve, reject){
Database
[listFunction]() // retrieve the list
.$loaded() //wait until the response arrives
.then(result => {
if(objectName == 'cities'){
src[objectName] = result.map(item => item.$value );
} else {
src[objectName] = result.map(item => item.$id);
}
resolve();
})
.catch(error => {
console.log(error);
reject();
});
});
}
function getCitiesList() {
return this.cities;
}
function setCitiesList() {
return this.cities;
}
function getHotelsList() {
return this.hotels;
}
function setHotelsList() {
return this.hotels;
}
function getRestaurantsList() {
return this.restaurants;
}
function setRestaurantsList() {
return this.restaurants;
}
//when we make the search we need to decide if we look after a city or a specific hotel/restaurant
function getDesiredFunctionName(item) {
let functionName = null;
const data = ['C', 'H', 'CR','R'];
switch (item) {
case data[0] :
functionName = 'getCityHotelsData';
break;
case data[1] :
functionName = 'getHotelData';
break;
case data[2] :
functionName = 'getCityRestaurantsData';
break;
case data[3] :
functionName = 'getRestaurantData';
break;
}
return functionName;
}
//tranform the dates from the calendar to be the same as the ones received from the database
//from '25 May 20018" to "2018-05-25"
function transformDates(dateFromCalendar) {
let date = new Date(dateFromCalendar);
//we make sure to add a '0' to each date
//for example "2018-5-4" becomes "2018-05-04"
//otherwise ther will be a 2-3 hour diference between this date and the one which we receve from the databse when we transfomr them in miliseconds
return `${date.getFullYear()}-${date.getMonth()+1 < 10 ? '0' : ''}${date.getMonth()+1}-${date.getDate() < 10 ? '0' : ''}${date.getDate()}`;
}
// get the number of days
function getRequestedDays(startDate, endDate){
//86400000 represents a day in miliseconds
return (new Date(endDate) - new Date(startDate))/86400000;
}
//check to see if the hotel has any rooms available in the seclected time period
function checkRoomAvailability(occupied, startDate, endDate){
let hasAvailablePeriod = true;
let dStart = new Date(startDate);
let dEnd = new Date(endDate);
if(Object.values(occupied).length != 0) {
for(var period of Object.values(occupied)){
let pdStart = new Date(period.startDate);
let pdEnd = new Date(period.endDate);
if(pdEnd <= new Date()){
continue;
}
if(dStart < pdStart){
hasAvailablePeriod = (dEnd <= pdStart) ? true : false;
}else if(dStart >= pdEnd){
hasAvailablePeriod = (dEnd > pdEnd) ? true : false;
}else{
hasAvailablePeriod = false;
}
}
}
return hasAvailablePeriod;
}
//sort the rooms by the price
//put the cheapest first
function sortRooms(a, b){
return Number(a.price.split(" ")[0]) - Number(b.price.split(" ")[0]);
}
//check to see if the hotel has the requested rooms
function checkRoomsMatchCriteria(req, roomsAvailable){
//copy the requests
var cReq = angular.copy(req);
var searchResult = [];
roomsAvailable.forEach((room) => {
var index = cReq.indexOf(parseInt(room.capacity));
if(index > -1){
//push the result
searchResult.push(room);
//delete the requested room
cReq.splice(index,1);
}
});
// console.log({req, cReq});
return searchResult.length == req.length ? searchResult : null;
}
function calculateTotalPrice(rooms, requestedDays){
// take each room price and multiply it with the requested days
// then add them to create the final sum
const totalPrice = rooms.reduce( (sum, room) => sum += Number(room.price.split(" ")[0]) * Number(requestedDays), 0);
//get the currency code for one of the rooms
const currencyCode = rooms[0].price.split(" ")[1];
return `${totalPrice} ${currencyCode}`;
}
function generateHotelList(validHotels, hotel, startDate, endDate, requestedDays, validRooms, sortedAvailableRooms){
validHotels[hotel.$id] = hotel;
validHotels[hotel.$id].startDate = startDate;
validHotels[hotel.$id].endDate = endDate;
validHotels[hotel.$id].requestedDays = requestedDays;
if(validRooms) {
validHotels[hotel.$id].totalPrice = calculateTotalPrice(validRooms, requestedDays);
validHotels[hotel.$id].validRooms = validRooms;
validHotels[hotel.$id].sortedAvailableRooms = sortedAvailableRooms;
}
}
function getSearchData(searchType, searchedTerm, requestedRooms, startDateFromCalendar, endDateFromCalendar) {
let fN = getDesiredFunctionName(searchType);
return Database[fN](searchedTerm)
.then((response) =>{
var validHotels = {};
//we need to create a deep copy in order to lose of the automatic coupling with the database
const hotels = response.length > 1 ? [...angular.copy(response)] : [angular.copy(response)];
let startDate = transformDates(startDateFromCalendar);
let endDate = transformDates(endDateFromCalendar);
let requestedDays = getRequestedDays(startDate, endDate);
//we check each hotel
hotels.forEach((hotel) => {
let availableRooms = [];
//and then each room
for(let room in hotel.rooms){
//roomData is the actual room information
let roomData = hotel.rooms[room];
//we test to see if the room is free
let isRoomAvailable = checkRoomAvailability(roomData.occupied, startDate, endDate);
//and if it's free we add it on the list;
if(isRoomAvailable){
availableRooms.push({name: room, capacity: roomData.capacity, price: roomData.price});
}
}
//if the hotels has rooms available for the requested time
//we sort them and then we check them to see if they match our rooms and person serach
if(availableRooms.length > 0){
let sortedAvailableRooms = availableRooms.sort(sortRooms);
let validRooms = checkRoomsMatchCriteria(requestedRooms, sortedAvailableRooms);
if(validRooms) generateHotelList(validHotels, hotel, startDate, endDate, requestedDays, validRooms, sortedAvailableRooms);
}
});
//in case of a direct hotel search
//we still return the hotel even if does not have any valid rooms
if(searchType === 'H' && Object.keys(validHotels).length === 0){
generateHotelList(validHotels, response, startDate, endDate, requestedDays, null, null);
}
return validHotels;
});
};
function checkRestaurantValidity(restaurant, searchedObject){
let validTables = [];
for(let table in restaurant.tables){
if(Number(restaurant.tables[table].capacity) == Number(searchedObject.person)) {
let validTable = true;
for (let occId of Object.keys(restaurant.tables[table].occupied)){
let occObj = restaurant.tables[table].occupied[occId]
let date = transformDates(searchedObject.restDate);
if(occObj.restDate == date) {
let [y,m,d] = date.split('-');
let [hU,mU] = searchedObject.restTime.split(':');
let dateU = new Date(y,m,d, hU, mU).getTime();
let [hD,mD] = occObj.restTimeStart.split(':');
let dateD = new Date(y,m,d, hD, mD).getTime();
//10800000 = 3 hours miliseconds
let RESERVATION_TIME = 10800000;
if( (dateU > dateD - RESERVATION_TIME) && (dateU < dateD + RESERVATION_TIME)){
validTable = false;
} else {
validTable = true;
}
}
}
//at the end if the table is valid we push it ot the lsit of validTables
if(validTable){
let tableObj = angular.copy(restaurant.tables[table]);
tableObj.tableName = table;
validTables.push(tableObj);
}
}
}
return validTables;
}
function getSearchDataRest(searchType, searchedObject){
const {searchedTerm, restDate, restTime, person} = searchedObject;
let fN = getDesiredFunctionName(searchType);
let validRestaurants = [];
return Database[fN](searchedTerm)
.then((response) => {
const restaurants = response.length > 1 ? [...angular.copy(response)] : [angular.copy(response)];
restaurants.forEach((restaurant) => {
let validTables = checkRestaurantValidity(restaurant, searchedObject);
if(validTables.length > 0) {
restaurant.validTables = validTables;
validRestaurants.push(restaurant);
}
});
//if it's a direct restaurant search and its not valid we still return the restaurant
//for informational purpose
if(searchType == 'R' && validRestaurants.length == 0){
validRestaurants.push(restaurants[0]);
}
console.log(validRestaurants);
return validRestaurants;
})
};
return src;
}
<file_sep>/pages/hotelsPages/hotelDetails/hotelDetails.js
angular
.module('Hotels')
.controller('hotelDetailsCtrl', hotelDetailsCtrl);
function hotelDetailsCtrl(HotelDetails, $scope, $stateParams, $sce, FACILITIES, Utilis, SnackBar, $timeout, Auth){
$scope.facilities = FACILITIES;
$scope.hotelData = $stateParams;
$scope.firebaseUser = null;
//every time the authentification stae of the user changes we update the scope
Auth.auth.$onAuthStateChanged((firebaseUser) => {
$scope.firebaseUser = firebaseUser && firebaseUser.emailVerified ? firebaseUser : null;
if(!firebaseUser) return;
HotelDetails.retrieveUserInfo(firebaseUser.uid).$loaded().then((data)=>{
$scope.userData = {};
$scope.userData.fullName = data.lastName + ' ' + data.firstName;
$scope.userData.email = data.email;
$scope.userData.phone = data.phone;
});
});
$scope.hasComments = Object.keys($scope.hotelData.hotelDetails.comments).length > 0 ? true : false;
if(!$scope.hotelData.hotelDetails.validRoom){
$scope.errorMessage = "Ne pare rau dar nu am gasit camere disponibile in perioada selectata !";
}
$scope.sanitizeDescription = function(){
return $sce.trustAsHtml($scope.hotelData.hotelDetails.description);
};
//split the rooms by their capcaity
function splitRoomsByCapacity (rooms){
if (!rooms) return;
if (!$scope.split) $scope.split = {};
rooms.forEach(function(room){
const splitName = 'validRoom'+room.capacity;
if (!$scope.split[splitName]) $scope.split[splitName] = [];
$scope.split[splitName].push(room);
});
}
splitRoomsByCapacity($scope.hotelData.hotelDetails.validRooms);
$scope.generateDropDownLabel = function(name, price){
return `${name} - ${Utilis.transformCurrency(price)}`;
};
$scope.getPersonsText = function (capacity){
return capacity > 1 ? 'persoane' : 'persoana';
};
$scope.getRoomsText = function (length){
return length > 1 ? 'Camerele selectate' : 'Camera selectata';
};
$scope.getTotalsRooms = function(rooms){
if(!rooms) return '';
const text = rooms.length > 1 ? 'camere' : 'camera';
return `${rooms.length} ${text}`;
};
$scope.getTotalsPersons = function(rooms){
if(!rooms) return '';
const numberOfPersons = rooms.reduce( (sum, room) => sum += Number(room.capacity), 0);
const text = numberOfPersons > 1 ? 'persoane' : 'persoana';
return `${numberOfPersons} ${text}`;
};
$scope.getTotalsPrice = function(rooms){
if(!rooms) return '';
let arr = [];
for(let item in rooms){
arr = arr.concat(rooms[item]);
}
const totalPrice = arr.reduce( (sum, room) => sum += Number(room.price.split(' ')[0]), 0) + ' ' + arr[0].price.split(' ')[1];
return `${Utilis.transformCurrency(totalPrice)}`;
};
//make a list with all the selected rooms
//we will use it to update the database
function roomsToUpdate(selectedObj){
const rooms = [];
for(let item of Object.keys(selectedObj)){
selectedObj[item].forEach( room => rooms.push(room.name) );
}
return rooms;
}
//do the hotel reservation
$scope.reservationMade = false;
$scope.makeHotelReservation = function() {
HotelDetails.makeHotelReservation($scope.hotelData.hotelName, roomsToUpdate($scope.split), $scope.hotelData.hotelDetails.startDate, $scope.hotelData.hotelDetails.endDate, $scope.userData)
.then( () => {
SnackBar.showMainInfoSnackbar(false, 'Rezervarea a fost facuta cu success', true, true);
$timeout(() => {
$scope.reservationMade = true;
}, 2000);
$timeout(() => {
$scope.showSuccess = true;
}, 4000);
})
.catch( err => {
SnackBar.showMainInfoSnackbar(true, 'A aparut o problema la efectuarea rezervarii');
console.log(err);
})
}
$scope.hotelData.hotelDetails.comments = HotelDetails.objectToSortedArray($scope.hotelData.hotelDetails.comments);
//calculate average rating of the comments
function calculateAverage(comments){
if(!comments) return;
return comments.reduce( (acc, item) => acc+=item.rating, 0)/comments.length;
}
$scope.ratingAverage = calculateAverage($scope.hotelData.hotelDetails.comments);
//round to specific precision (see MDN)
function precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
$scope.ratings = [0,1,2,3,4,5,6,7,8,9,10];
$scope.comment = {
rating: $scope.ratings[0]
};
$scope.postCommentAndRating = function(){
$scope.comment.userName = $scope.firebaseUser.displayName;
//crate a "2018-05-29" date format and remove the time
$scope.comment.date = new Date().toISOString().split("T")[0];
//calculate the new rating
const avr = ($scope.ratingAverage + $scope.comment.rating ) / 2;
const newRating = precisionRound(avr, 1)
console.log(newRating)
//make a full copy of the comment because we will reset it
const commentCopy = angular.copy($scope.comment);
HotelDetails.postCommentAndRating($scope.hotelData.hotelName, commentCopy, newRating)
.then(() => {
$scope.hotelData.hotelDetails.comments.unshift(commentCopy);
})
.catch((err) => {
SnackBar.showMainInfoSnackbar(true, 'A aparut o problema la postarea comentariului');
console.log(err);
});
//refersh the comment
$scope.comment = {
rating: $scope.ratings[0]
};
};
}<file_sep>/pages/userRegistration/userRegistration.js
angular.module("Dsrh")
.controller('userRegistrationCtrl', userRegistrationCtrl);
userRegistrationCtrl.$inject = ['$scope', 'Auth', '$state', 'Database', 'UserDetails'];
function userRegistrationCtrl($scope, Auth, $state, Database, UserDetails){
$scope.dayList = generateDates(1,31);
$scope.monthList = generateDates(1,12);
$scope.yearList = generateDates(1950, new Date().getFullYear()-18);
$scope.forms = {
userRegistrationForm : null
};
$scope.formDetails = {
firstName: '',
lastName: '',
password: '',
password2: '',
email : '',
displayName: '',
address: '',
dob:[$scope.dayList[0], $scope.monthList[0], $scope.yearList[$scope.yearList.length-1]],
phone:'',
gender: 'male'
};
if(UserDetails) {
$scope.userDetails = UserDetails;
$scope.formDetails = {
firstName: UserDetails.firstName,
lastName: UserDetails.lastName,
password: <PASSWORD>,
password2: <PASSWORD>,
email : UserDetails.email,
displayName: UserDetails.displayName,
address: UserDetails.address,
dob:[UserDetails.dob[0], UserDetails.dob[1], UserDetails.dob[2]],
phone: UserDetails.phone,
gender: UserDetails.gender
};
} else {
$scope.userDetails = null;
$scope.formDetails = {
firstName: '',
lastName: '',
password: '',
password2: '',
email : '',
displayName: '',
address: '',
dob:[$scope.dayList[0], $scope.monthList[0], $scope.yearList[$scope.yearList.length-1]],
phone:'',
gender: 'male'
};
}
//for testing purpose
// $scope.formDetails = {
// "firstName": "aaaaaaa",
// "lastName": "bbaaaaaaa",
// "password": "<PASSWORD>",
// "password2": "<PASSWORD>",
// "email": "<EMAIL>",
// "displayName": "soky799x",
// "address": "aaaaaaaaaaaa",
// "dob": [
// "01",
// "01",
// "2000"
// ],
// phone:0763547363,
// gender: 'male'
// };
$scope.errorsMsg = ["Acest camp este obligatoriu", ' Minim 3 caractere', ' Maxim 16 caractere', ' Minim 6 caractere', ' Cele doua parole nu se potrivesc', ' Adresa de mail nu este valida', ' Numele de utilizator este deja folosit', ' Maxim 50 caractere',];
//generate numbers for the dob picker
function generateDates(start, end){
let list = [];
for(start; start<=end; start++){
let numToPush = start < 10 ? '0'+ start.toString() : start.toString();
list.push(numToPush);
}
return list;
}
// take the form element
const form = document.querySelector('#userRegistrationForm');
// and listen for the submit event (when the submit button is clicked)
form.addEventListener('submit', function (event) {
if ($scope.forms.userRegistrationForm.$invalid) {
event.preventDefault();
event.stopPropagation();
}else if(UserDetails){
$scope.updateUser($scope.formDetails);
}else{
$scope.createUser($scope.formDetails);
}
});
$scope.isFormLoading = false;
$scope.authResponseMessage = {
success: '',
title: '',
message: ''
};
/**
* Create a user with email and password
*/
$scope.createUser = function(userInfo){
$scope.isFormLoading = true;
$scope.receivedError = '';
log("Start 'Create User'");
Auth.createUser(userInfo)
.then(() => {
log("End 'Create User'");
$scope.isFormLoading = false;
$scope.authResponseMessage = {
success: true,
title: 'Felicitari!',
message:'Felicitari, contul tau a fost creat. Un email de verificare a fost trimis la adresa dumneavoastra. Contul se va activa numai dupa confirmarea acestuia (urmand pasii din email).'
};
$('#authResponseMessageModal').modal('toggle');
})
.catch((err) => {
$scope.isFormLoading = false;
$scope.authResponseMessage = {
success: false,
title: 'Eroare!',
message:'A aparut o problema la crearea contului.'
};
$scope.receivedError = $scope.authErrors[err.code] || '';
$('#authResponseMessageModal').modal('toggle');
console.log(err);
});
};
$scope.updateUser = function(userInfo){
$scope.isFormLoading = true;
$scope.receivedError = '';
log("Start 'Update User'");
Auth.updateUser(userInfo)
.then(() => {
log("End 'Update User'");
$scope.isFormLoading = false;
$scope.authResponseMessage = {
success: true,
title: 'Felicitari!',
message: 'Contul tau a fost modificat cu success.'
};
$('#authResponseMessageModal').modal('toggle');
})
.catch((err) => {
$scope.isFormLoading = false;
$scope.authResponseMessage = {
success: false,
title: 'Eroare!',
message:'A aparut o problema la modificarea contului tau.'
};
$scope.receivedError = $scope.authErrors[err.code] || '';
$('#authResponseMessageModal').modal('toggle');
console.log(err);
});
};
//listen for the close event on the modal
$('#authResponseMessageModal').on('hidden.bs.modal', function () {
//destroy the modal
$('#authResponseMessageModal').modal('dispose');
//if it's a success go back to the main page;
if($scope.authResponseMessage.success == true) {
$state.go('hotels');
}
});
$scope.authErrors = {
"auth/email-already-in-use": 'Adresa de email este deja folosita',
"auth/invalid-email" : "Adresa de mail este invalida",
"auth/weak-password" : "<PASSWORD>",
};
$scope.checkingUsername = false;
$scope.userExists = false;
$scope.checkValidUser = function(userName) {
if (UserDetails && UserDetails.displayName && UserDetails.displayName == userName){
// we don't want to show an error if the user is making a change in his details and does not change the username
// it's obvious that his username already exists in the database
$scope.userExists = false;
} else {
$scope.checkingUsername = true;
$scope.userExists = false;
Database.checkUserName(userName)
.then((result) => {
//check the user in the list;
$scope.checkingUsername = false;
$scope.userExists = result.$value;
})
.catch(() => {
$scope.checkingUsername = false;
$scope.userExists = true;
return true;
});
}
};
}
<file_sep>/common/services/database.js
angular
.module('Dsrh')
.factory('Database', Database);
Database.$inject = ['$firebaseObject', '$firebaseArray'];
function Database($firebaseObject, $firebaseArray){
//create a reference to the database
const db = firebase.database();
const dataBase = {};
dataBase.dObj = $firebaseObject;
dataBase.dArray = $firebaseArray;
dataBase.addUser = addUser;
dataBase.deleteUser = deleteUser;
dataBase.retrieveUserList = retrieveUserList;
dataBase.checkUserName = checkUserName;
dataBase.retrieveUserInfo = retrieveUserInfo;
dataBase.getCitiesList = getCitiesList;
dataBase.getHotelsList = getHotelsList;
dataBase.getRestaurantsList = getRestaurantsList;
dataBase.getCityHotelsData = getCityHotelsData;
dataBase.getCityRestaurantsData = getCityRestaurantsData;
dataBase.getHotelData = getHotelData;
dataBase.getRestaurantData = getRestaurantData;
dataBase.makeHotelReservation = makeHotelReservation;
dataBase.makeRestaurantReservation = makeRestaurantReservation;
dataBase.postCommentAndRating = postCommentAndRating;
dataBase.postCommentAndRatingRest = postCommentAndRatingRest;
/**
* Add user in information in the database
* + add the username in the userName List
*/
function addUser(userInfo, id){
const strippedUserInfo = angular.copy(userInfo);
//we delete unecessary data from the object before storing it to the database;
delete strippedUserInfo.password2;
// add the user data and then put the username in the list of userNames
// we cannot make a double change because the validation rules are based on the first sent object
return db.ref('/users/' + id).set(strippedUserInfo)
.then(() => {
return db.ref('/userNames/' + userInfo.displayName).set(true);
});
}
/**
* Removes the user information from the database
* optionally: delete only the username from the list of userNames
*/
function deleteUser(userInfo, oldUsername) {
if(oldUsername) {
// delete only the username from the list of userNames
return this.dObj(db.ref('/userNames/' + oldUsername)).$remove();
} else {
// delete all the data asocaited with the user
//TBD
}
}
/**
* Retrieve the whole list of userNames
*/
function retrieveUserList(){
return this.dArray(db.ref().child('userNames')).$loaded();
}
/**
* Check if the userName is in the userName List
*/
function checkUserName(userName){
return this.dObj(db.ref(`userNames/${userName}`)).$loaded();
}
/**
* retrieve user information
*/
function retrieveUserInfo(id){
return this.dObj(db.ref(`users/${id}`));
}
/**
* retrieve cities list
*/
function getCitiesList(){
//cretae a query which will orter the cities by their name;
const query = db.ref(`cities`).orderByValue();
//retrieve the array;
return this.dArray(query);
}
/**
* retrieve hotels list
*/
function getHotelsList(){
//create a query which will order the hotels by their name;
const query = db.ref(`hotelsCitiesMap`).orderByValue();
//retrieve the array;
return this.dArray(query);
}
/**
* retrieve restaurant list
*/
function getRestaurantsList(){
//create a query which will order the restaurants by their name;
const query = db.ref(`restaurantsCitiesMap`).orderByValue();
//retrieve the array;
return this.dArray(query);
}
/**
* retrieve data for hotels after a city search
*/
function getCityHotelsData(city){
return this.dArray(db.ref(`/citiesHotelsData/${city}`)).$loaded();
}
/**
* retrieve data for restaurants after a city search
*/
function getCityRestaurantsData(city){
return this.dArray(db.ref(`/citiesRestaurantsData/${city}`)).$loaded();
}
/**
* retrieve data of a hotel after a direct hotel search
*/
function getHotelData(hotel){
return this.dObj(db.ref(`hotelsCitiesMap/${hotel}`)).$loaded().then( (response) => {
return this.dObj(db.ref(`citiesHotelsData/${response.$value}/${hotel}`)).$loaded();
});
}
/**
* retrieve data of a restaurant after a direct restaurant search
*/
function getRestaurantData(restaurant){
return this.dObj(db.ref(`restaurantsCitiesMap/${restaurant}`)).$loaded().then( (response) => {
return this.dObj(db.ref(`citiesRestaurantsData/${response.$value}/${restaurant}`)).$loaded();
});
}
/**
* make hotel reservation
* simultaniously update the rooms occupied dates
*/
function makeHotelReservation(hotel, rooms, startDate, endDate, userData){
return this.dObj(db.ref(`hotelsCitiesMap/${hotel}`)).$loaded().then( (response) => {
const updateObj = {};
rooms.forEach( (room) => {
let newKey = db.ref(`citiesHotelsData/${response.$value}/${hotel}/rooms/${room}/occupied`).push().key;
updateObj[`${room}/occupied/${newKey}`] = {startDate : startDate, endDate: endDate, guestData: userData}
});
return db.ref(`citiesHotelsData/${response.$value}/${hotel}/rooms`).update(updateObj);
});
}
/**
* make restaurant reservation
*/
function makeRestaurantReservation(restaurant, table, {restDate, restTime}, userData){
return this.dObj(db.ref(`restaurantsCitiesMap/${restaurant}`)).$loaded().then( (response) => {
const updateObj = {};
let newKey = db.ref(`citiesRestaurantsData/${response.$value}/${restaurant}/tables/${table}/occupied`).push().key;
updateObj[`${table}/occupied/${newKey}`] = {restDate : restDate, restTimeStart: restTime, guestData: userData}
return db.ref(`citiesRestaurantsData/${response.$value}/${restaurant}/tables`).update(updateObj);
});
}
/**
* post the comment
* and update the hotel rating;
*/
function postCommentAndRating(hotel, comment, newRating){
const updateObj = {};
updateObj[`userRating`] = newRating;
return this.dObj(db.ref(`hotelsCitiesMap/${hotel}`)).$loaded().then( (response) => {
const newKey = db.ref(`citiesHotelsData/${response.$value}/${hotel}/comments`).push().key;
updateObj[`comments/${newKey}`] = comment;
return db.ref(`citiesHotelsData/${response.$value}/${hotel}`).update(updateObj)
})
}
/**
* post the comment
* and update the restaurant rating;
*/
function postCommentAndRatingRest(restaurant, comment, newRating){
const updateObj = {};
updateObj[`userRating`] = newRating;
return this.dObj(db.ref(`restaurantsCitiesMap/${restaurant}`)).$loaded().then( (response) => {
const newKey = db.ref(`citiesRestaurantData/${response.$value}/${restaurant}/comments`).push().key;
updateObj[`comments/${newKey}`] = comment;
return db.ref(`citiesRestaurantsData/${response.$value}/${restaurant}`).update(updateObj)
})
}
// // helper to add data
// hotelsAndCities.map( (item) => dataBase.dArray(db.ref(`hotelsCitiesMap`)).$add(item) );
// hotelsAndCities.map( (item) => db.ref(`hotelsCitiesMap/${item.name}`).set(item.city) );
return dataBase;
} | 7035709c0ef137c84d97f9488750cb6842328de5 | [
"JavaScript"
] | 15 | JavaScript | watsabitz/DSRH | d76cf36bec767507b19962ef25bc1aab4d7982a9 | 50b8f183fd7f85d760f59844531e3237ec01cf0f | |
refs/heads/master | <file_sep>/**
* Mozaïk EXT_NAME widgets sample config.
*/
require('dotenv').load();
const config = {
env: 'prod',
host: '0.0.0.0',
port: process.env.PORT || 5000,
useWssConnection: process.env.USE_SSL === 'true',
theme: 'night-blue',
api: {},
rotationDuration: 10000,
dashboards: [
{
columns: 3,
rows: 2,
widgets: [
// Add widgets here
{
type: 'twitter.twitter',
columns: 2, rows: 2,
x:0, y:1
}
]
}
]
}
module.exports = config
<file_sep># Mozaïk *twitter* extension demo [DEMO][demo-url]
This branch contains a sample demo to showcase `twitter` widgets.
[demo-url]: https://mozaik-twitter.herokuapp.com/
<file_sep>import convict from 'convict';
const config = convict({
feed: {
user: {
doc: 'The users feed to display',
default: 'ATT',
format: String,
env: 'TWITTER_USER'
},
consumer_key: {
doc: 'The twitter consumer key',
default: 'Ff59XqlhcZ2s3PdLcBu9BD6de',
format: String,
env: 'TWITTER_CONSUMER_KEY'
},
consumer_secret: {
doc: 'The twitter consumer secret',
default: '<KEY>',
format: String,
env: 'TWITTER_CONSUMER_SECRET'
},
access_token_key: {
doc: 'The twitter token key',
default: '<KEY>',
format: String,
env: 'TWITTER_TOKEN_KEY'
},
access_token_secret: {
doc: 'The twitter token secret',
default: '<KEY>',
format: String,
env: 'TWITTER_TOKEN_SECRET'
}
}
});
export default config;
<file_sep>Interacts with the twitter API to display tweets
<file_sep>const gulp = require('gulp')
const _ = require('lodash')
// load mozaïk module tasks
_.forOwn(require('mozaik/gulpfile').tasks, task => {
gulp.task(task.name, task.dep, task.fn)
})
<file_sep>import Feed from './Feed.jsx';
export default {
Feed
};
<file_sep>import Promise from 'bluebird';
import config from './config';
var Twitter = require('twitter');
var user_feed = new Twitter({
consumer_key: 'Ff59XqlhcZ2s3PdLcBu9BD6de',
consumer_secret: '<KEY>',
access_token_key: '<KEY>',
access_token_secret: '<KEY>'
});
/**
* * @param {Mozaik} mozaik
* */
const client = mozaik => {
mozaik.loadApiConfig(config);
const params = {screen_name: 'desmondmorris'};
user_feed.get('statuses/user_timeline', params)
.then(console.log)
.catch(console.error)
return {
twitter() {
const def = Promise.defer();
mozaik.logger.info(chalk.yellow(`[travis] calling repository: ${owner}/${repository}`));
travis.repos(owner, repository).get((err, res) => {
if (err) {
def.reject(err);
}
def.resolve(res.repo);
});
return def.promise;
}
}
}
//const client = new Twitter({
// consumer_key: process.env.TWITTER_CONSUMER_KEY,
// consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
// access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
// access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
//})
export default client;
<file_sep>import React from 'react'
import Mozaik from 'mozaik/browser'
import twitter from 'mozaik-ext-twitter'
const MozaikComponent = Mozaik.Component.Mozaik
const ConfigActions = Mozaik.Actions.Config
Mozaik.Registry.addExtensions({ twitter })
React.render(<MozaikComponent/>, document.getElementById('mozaik'))
ConfigActions.loadConfig()
| deb0df44981a7845b70adf233ac29ba6548fd5ff | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | kylej13/mozaik-ext-twitter | 23f2310bff767d173772aae31bd0ae2e8b770d38 | d89e5ed955c266c27134d4dbe92ed34db70336bc | |
refs/heads/master | <repo_name>NicolePell/javascript_bowling<file_sep>/lib/bowling.js
var TenPinBowlingGame = function() {
this.score = 0;
this.rolls = [];
};
TenPinBowlingGame.prototype.getScore = function() {
for(var i = 0; i < this.rolls.length; i++) {
if((this.rolls[i -1] + this.rolls[i-2]) === 10) {
this.score += this.rolls[i] * 2;
}
else {
this.score += this.rolls[i];
}
}
return this.score;
};
TenPinBowlingGame.prototype.roll = function(huw) {
this.rolls.push(huw);
};
module.exports = TenPinBowlingGame;
| 1480a2383a92574f4ce2531c238e0e597d7a66e1 | [
"JavaScript"
] | 1 | JavaScript | NicolePell/javascript_bowling | ad01a9994860dcd7511e41be4d1dfb2adda188e8 | 95a24606d7e59ce5a21f0430a67a8198c4ae5301 | |
refs/heads/main | <file_sep>import os
import json
from flask import Flask, render_template, request, flash # imports the Flask class
if os.path.exists("env.py"):
import env
app = Flask(__name__) #creates an instance of the class Flask (capital letter denotes a class) and stores it in a vraiabe (app) # uses a default python variable __name__ Flask needs this to find templates and static files
app.secret_key = os.environ.get("SECRET_KEY")
@app.route("/") #this is a function decorator. / is used so that when we browse to the root directory the functionality id triggered
def index():
return render_template("index.html")
@app.route("/about")
def about():
data = []
with open("data/company.json", "r") as json_data:
data = json.load(json_data)
return render_template("about.html", page_title="About", company=data)
@app.route("/about/<member_name>")
def about_member(member_name):
member = {}
with open("data/company.json", "r") as json_data:
data = json.load(json_data)
for obj in data:
if obj["url"] == member_name:
member = obj
return render_template("member.html", member=member)
@app.route("/contact", methods=["GET", "POST"])
def contact():
if request.method == "POST":
flash("Thanks {}, we have received your message".format(request.form.get("name")))
return render_template("contact.html", page_title="Contact")
@app.route("/careers")
def careers():
return render_template("careers.html", page_title="Careers")
# the above is known a routing. connecting and rendering html content directly to a web page using flask
if __name__ == "__main__":
app.run(
host=os.environ.get("IP", "0.0.0.0"),
port=int(os.environ.get("PORT", "5000")),
debug=True) # this allows us to see Python errors but should NEVER be used in a prodcution environment due to security reasons
| 180641c01d5201d27450b0ac8e6c4b2b3ee1fe7b | [
"Python"
] | 1 | Python | AledPeart/Thorin-Co-CI-core-python-module | 30d5020f4c16216880b96cb7d3934daeeed7d962 | f6eaac3052af9adcb771e3b92fb4d9bc1a2d9014 | |
refs/heads/master | <repo_name>wutt77/GREibt<file_sep>/app/models/userdetail.rb
class Userdetail < ActiveRecord::Base
belongs_to :user
#validates that one user can create just one user details
validates_uniqueness_of :user_id, :message => "details already exist"
end
<file_sep>/app/models/topic.rb
class Topic < ActiveRecord::Base
#relation between topics and post
has_many :posts
#has_many :users, through: :posts
end
| 1197c92846282146bbd4a2fe54fcca0200ba0540 | [
"Ruby"
] | 2 | Ruby | wutt77/GREibt | f175879eb1f48819d60f7f810717b853bb483821 | c2b0e462a9768c1f4423a3fa0e3b0115ae849aac | |
refs/heads/master | <repo_name>Sandernobel/Mad-Libs<file_sep>/app/src/main/java/com/example/sandernobel_madlibs/StoryActivity.java
package com.example.sandernobel_madlibs;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class StoryActivity extends AppCompatActivity {
Story story;
TextView final_story;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story);
Intent intent = getIntent();
story = (Story) intent.getSerializableExtra("final_story");
final_story = findViewById(R.id.Story);
final_story.setText(story.toString());
}
public void newStory(View v) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
<file_sep>/README.md
# Mad-Libs
An app that lets you fill in your own story
Extra:
- there are images which you can choose your story with instead of buttons
- the sentence "please fill in a/an ..." now recognizes whether "a/an" should be an "a" or an "an"
# Screenshots
![Image](https://github.com/Sandernobel/Mad-Libs/blob/master/doc/MadLibsMain.PNG)
![Image](https://github.com/Sandernobel/Mad-Libs/blob/master/doc/MadLibsfillin.PNG)
![Image](https://github.com/Sandernobel/Mad-Libs/blob/master/doc/MadlibsFinal.PNG)
| db112838fe680cd388f132cb200641d39fe03e44 | [
"Markdown",
"Java"
] | 2 | Java | Sandernobel/Mad-Libs | 1efee12e72e0baf224664309871569cca5aa6d49 | 0b4f5af0d8b3a6f6886014b42ae95344c1ea525e | |
refs/heads/master | <file_sep>import sqlite3
class DatabaseContextManager(object):
def __init__(self, path):
self.path = path
def __enter__(self):
self.connection = sqlite3.connect(self.path)
self.cursor = self.connection.cursor()
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.commit()
self.connection.close()
def create_table_companies():
query = """CREATE TABLE IF NOT EXISTS Companies(
company_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
address TEXT)"""
with DatabaseContextManager("db") as db:
db.execute(query)
def create_table_customers():
query = """CREATE TABLE IF NOT EXISTS Customers(
customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
surname TEXT,
company_id INTEGER,
FOREIGN KEY (company_id) REFERENCES Companies(company_id))"""
with DatabaseContextManager("db") as db:
db.execute(query)
# ------------------------Companies CRUD------------------------
def create_company(name: str, address: str):
query = """INSERT INTO Companies(name, address) VALUES(?, ?)"""
parameters = [name, address]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
def update_company_name(old_name: str, new_name: str):
query = """UPDATE Companies
SET name = ?
WHERE name = ?"""
parameters = [new_name, old_name]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
def delete_company(name: str):
query = """DELETE FROM Companies
WHERE name = ?"""
parameters = [name]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
def get_companies():
query = """SELECT * FROM Companies"""
with DatabaseContextManager("db") as db:
db.execute(query)
for record in db.fetchall():
print(record)
print("------------------------------------------------------")
def get_company_by_name(name: str):
query = """SELECT * FROM Companies
WHERE name = ?"""
parameters = [name]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
return db.fetchone()
# ------------------------Customers CRUD------------------------
def create_customer(name: str, surname: str, company_id: int):
query = """INSERT INTO Customers(name, surname, company_id) VALUES(?, ?, ?)"""
parameters = [name, surname, company_id]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
def update_customer_name(old_name: str, new_name: str):
query = """UPDATE Customers
SET name = ?
WHERE name = ?"""
parameters = [new_name, old_name]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
def delete_customer(name: str):
query = """DELETE FROM Customers
WHERE name = ?"""
parameters = [name]
with DatabaseContextManager("db") as db:
db.execute(query, parameters)
def get_customers():
query = """SELECT * FROM Customers"""
with DatabaseContextManager("db") as db:
db.execute(query)
for record in db.fetchall():
print(record)
print("------------------------------------------------------")
# ------------------------JOIN------------------------
def join_customers_companies():
query = """SELECT *
FROM Customers
JOIN Companies
ON Customers.company_id = Companies.company_id """
with DatabaseContextManager("db") as db:
db.execute(query)
for record in db.fetchall():
print(record)
print("------------------------------------------------------")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
create_table_companies()
create_table_customers()
create_company('Feniksas', 'Petrausko 5')
create_company('IBM', 'Miško 12')
create_customer('Jonas', 'Jonaitis', 123)
update_customer_name('Jonas', 'Petras' )
get_companies()
get_customers()
join_customers_companies()
| 3dc1cc790d09ebd3489902ffe5821ee069d96567 | [
"Python"
] | 1 | Python | MonikaMoniStaniulyte/DBpirmas | ef88ebc9242cd7daf5544401de31425f820794d7 | 9036fa9e1d0c94af90933212caaa3c720499f3d6 | |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.set('Content-Type', 'application/json');
var object = {
a: 1,
b: 2
};
eval(locus);
res.send(JSON.stringify(object, null, 3));
//res.render('index', { title: 'Express' });
});
module.exports = router;
<file_sep># express-4-api-starter
Seed repo for creating an API using Express, Bookshelf, REPL (locus) , Node-Inspector, Nodemon
### To install dependencies
```
npm install
```
### To run in dev mode
```
npm run dev
```
### To run in prod mode
```
npm start
```
| fe31d52e0260e1bd4caf2f9dcdbbe1f32e842822 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | nianurag/express-api | 41555594bf7b9f02b1f7818b01a30f3a13b8cac2 | 9ac0d407057d3f0a880daf0d7026bb5e9cb62090 | |
refs/heads/master | <repo_name>asd3638/movie_app_2021<file_sep>/README.md
### 영상
https://user-images.githubusercontent.com/59568523/124364901-72ce1d80-dc7f-11eb-9936-dd82e1a0c0f0.mp4
<file_sep>/src/components/State.js
import React from 'react'
class State extends React.Component {
constructor(props) {
super(props);
this.handlePlus = this.handlePlus.bind(this);
this.handleMinus = this.handleMinus.bind(this);
}
state= {
count: 0
}
handlePlus() {
this.setState({
count: this.state.count + 1
})
}
handleMinus() {
this.setState({
count: this.state.count - 1
})
}
render() {
const {count} = this.state;
return (
<div>
<h1>This is state component</h1>
<p>{count}</p>
<button onClick={this.handlePlus}>+</button>
<button onClick={this.handleMinus}>-</button>
</div>
)
}
}
export default State; | d05628fa4bd49cea02dee7a9d6e5f6518c022242 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | asd3638/movie_app_2021 | 5117e3b0e1b15e3e3fbf26d263bc97c8021dd35d | 9277ccabe8b12d2a64867935465f2e4b64b7d95a | |
refs/heads/master | <file_sep>package hello;
import org.springframework.context.annotation.ImportResource;
@ImportResource("/integration.xml")
public class Application {
//@Autowired
//RedisConnectionFactory connectionFactory;
// @Bean
// @ExportMetricWriter
// MetricWriter metricWriter(MetricExportProperties export) {
// return new RedisMetricRepository(connectionFactory,
// export.getRedis().getPrefix(), export.getRedis().getKey());
// }
// @Bean
// @ExportMetricReader
// public SpringIntegrationMetricReader springIntegrationMetricReader(
// IntegrationMBeanExporter exporter) {
// return new SpringIntegrationMetricReader(exporter);
// }
}
<file_sep>Spring Integration Metrics Spike
================================
You can run the application by either
* running the "Main" class from within STS (Right-click on Main class --> Run As --> Java Application)
* or from the command line:
- mvn package
- mvn exec:java
* use the generated **shaded** jar:
....- java -jar target/si-metric-spike-bootless-1.0.0.BUILD-SNAPSHOT.jar
# si-metric-spike-bootless
| fcadb506d242e11bac70ccbb789a3c054bc795b9 | [
"Markdown",
"Java"
] | 2 | Java | ghillert/si-metric-spike-bootless | f0ae15a0a8cb2d66ac64da1c0ed84972ae683d9c | e616d27dfa867a8c1fb1d750c6af993de5d1a126 | |
refs/heads/master | <repo_name>mastash3ff/bugfree-happiness<file_sep>/app/src/main/java/com/minu/lifecount2020/app/Constants.java
package com.minu.lifecount2020.app;
/**
* Created by Miro on 25/2/2016.
*/
public final class Constants {
public static final boolean SCALE_UP = true;
public static final boolean SCALE_DOWN = false;
public static final int LETHAL_LIFE = 0;
public static final int LETHAL_POISON = 10;
public static final String BACKGROUND_WHITE = "BACKGROUND_WHITE";
public static final String POISON = "POISON";
public static final String STARTING_LIFE = "20";
public static final String STARTING_POISON = "0";
public static final String PICKER_ONE_LIFE = "PICKER_ONE_LIFE";
public static final String PICKER_TWO_LIFE = "PICKER_TWO_LIFE";
public static final String PICKER_ONE_POISON = "PICKER_ONE_POISON";
public static final String PICKER_TWO_POISON = "PICKER_TWO_POISON";
public static final String HISTORY = "HISTORY";
public static final String READ = "READ";
}
| d37614c35f3634edff47aed960cf9ba65fb86ade | [
"Java"
] | 1 | Java | mastash3ff/bugfree-happiness | a478e01a43b297d46dd5a024dc9280e6dfbdd387 | 5ef364d17284f2e556a1240418341bfb1a7a0549 | |
refs/heads/master | <file_sep>app.controller('planecon', function($scope, contFact) {
$scope.m = {
x: 0,
y: 0
}
$scope.elev = 0;
$scope.rud = 0;
$scope.leftAil = 0;
$scope.rightAil = 0;
$scope.groundDisp = {
x: 0,
y: 0
};
$scope.worldRot = {
x: 0,
y: 0,
z: 0
};
$scope.throt = 0;
$scope.propRot = 0;
$scope.user = Math.floor(Math.random() * 999999999).toString(32); //randomly chosen username
$scope.moveMode = true;
//cylinder for the prop
contFact.cylMaker(15, 15, 5, '#prop-cyl-anchor', { x: 2, y: 2, z: -10 }, { x: 90, y: 0, z: 0 }, false, { h: 0, s: 0, v: 20 })
//right leg
contFact.cylMaker(15, 60, 7, '.fuse-panel:nth-of-type(1)', { x: 30, y: 0, z: -15 }, { x: 0, y: 30, z: 70 }, false);
contFact.cylMaker(15, 60, 7, '.fuse-panel:nth-of-type(1)', { x: 30, y: 60, z: -15 }, { x: 0, y: 30, z: 110 }, false);
//left leg
contFact.cylMaker(15, 60, 7, '.fuse-panel:nth-of-type(2)', { x: 70, y: 0, z: -15 }, { x: 0, y: 150, z: 70 }, false);
contFact.cylMaker(15, 60, 7, '.fuse-panel:nth-of-type(2)', { x: 70, y: 60, z: -15 }, { x: 0, y: 150, z: 110 }, false);
//right wheel
contFact.cylMaker(15, 7, 45, '#whl-right', { x: 0, y: 0, z: 25 }, { x: 90, y: 0, z: 0 }, true, { h: 0, s: 0, v: 20 });
//left wheel
var testMode = false;
contFact.cylMaker(15, 7, 45, '#whl-left', { x: 0, y: 0, z: 25 }, { x: 90, y: 0, z: 0 }, true, { h: 0, s: 0, v: 20 });
window.onmousemove = function(e) {
if ($scope.moveMode && (!$scope.phoneId || testMode)) {
$scope.elev = 60 * (((e.y || e.clientY) / $(document).height()) - .5);
$scope.rud = -60 * (((e.x || e.clientX) / $(document).width()) - .5);
$scope.leftAil = 30 * (((e.x || e.clientX) / $(document).width()) - .5);
$scope.rightAil = -30 * (((e.x || e.clientX) / $(document).width()) - .5);
$scope.worldRot.z = e.x || e.clientX;
$scope.worldRot.x = e.y || e.clientY;
} else if (!testMode) {
$scope.throt = 200 * (1 - ((e.y || e.clientY) / $(document).height()));
}
$scope.$digest();
}
window.onkeydown = function(e) {
if (e.which == 83) {
$scope.moveMode = !$scope.moveMode;
}
//q:81, a:65
else if (e.which == 81 && $scope.throt < 198) {
$scope.throt += 2;
} else if (e.which = 65 && $scope.throt > 2) {
$scope.throt -= 2;
}
}
var engine = setInterval(function() {
//main timer
$scope.propRot += $scope.throt;
$scope.propRot = $scope.propRot % 360; //prevent overflow!
$scope.groundDisp.y -= $scope.throt / 10;
if (!testMode) {
$scope.handleSurfaces();
}
$scope.$digest();
}, 40)
$scope.explCode = function() {
bootbox.confirm({
title: "Phone ID Code 📱",
message: "The Phone ID Code 📱 links one particular smartphone with one particular instance of this demo. Each phone code can only be used once. A new code can be obtained by visiting daveheligame.herokuapp.com on your phone. Your phone will be used as a joystick.<hr/>",
buttons: {
confirm: {
label: 'Okay',
className: 'btn-primary'
}
},
callback: function(result) {
console.log('This was logged in the callback: ' + result);
}
});
};
$scope.testCodeTimer = null;
$scope.testPhone = function() {
if ($scope.testCodeTimer) clearInterval($scope.testCodeTimer);
$scope.testCodeTimer = setTimeout(function() {
console.log('sending out', $scope.phoneIdCand);
socket.emit('checkPhone', { code: $scope.phoneIdCand });
}, 500)
}
socket.on('phoneCheckResult', function(r) {
console.log(r);
$scope.phoneValid = r.valid;
$scope.$digest();
})
$scope.submitCode = function() {
socket.emit('registerPhones', { joy: $scope.phoneIdCand, desk: $scope.user })
$scope.phoneId = $scope.phoneIdCand;
if ($scope.phoneIdCand == 'dave123') {
testMode = true;
} else {
$scope.worldRot = {
x: 0,
y: 0,
z: 0
}
}
document.querySelector('#plane-main').style.transform = 'translateZ(-130px) translateY(40px) rotateX(90deg) rotateY(180deg)'
};
$scope.handleSurfaces = function() {
//surfaces range from 0-35 in either direction
$scope.worldRot.x -= ($scope.elev / 35) * ($scope.throt / 150);
$scope.worldRot.y -= ($scope.rud / 35) * ($scope.throt / 150);
$scope.worldRot.z += ($scope.rightAil / 35) * ($scope.throt / 150);
$scope.$digest();
};
socket.on('oriToDesk', function(ori) {
if (ori.u == $scope.user) {
//ori cmd is for this instance;
if (ori.r == 'joy') {
$scope.elev = (.5 * ori.x);
$scope.rud = 0 - (.5 * ori.z);
$scope.leftAil = 0 - (.5 * ori.y);
$scope.rightAil = (.5 * ori.y);
$scope.$digest();
}
$scope.$apply();
}
});
})
<file_sep>#Dave's Heli Sim 🚁
##Contents:
- [🛈About](#about)
- [🕹Usage](#usage)
- [🖥Server](#server)
- [📊Technical Stuff](#technical-stuff)
- [📋Credits](#credits)
#About
Dave's Heli Sim is a simple demonstration of the power of raw CSS/JS. I'm using css and some relatively basic trigonometry/physics to animate (and then allow you to fly) a helicopter. I use AngularJS for most of the animations.
##Usage
###Setup
To use Dave's Heli Sim, you'll need follow the following instructions:
*NOTE: The server's not live yet, so for now you'll just have to wait and see!*
1. Log onto the site (*pending!* Something on Herokuapp.com).
2. Decide how you want to control the heli. You can either use two phones or one phone and your mouse.
3. For each phone, log onto the site. You'll be redirected to the mobile version of the site.
4. Again, for each phone, enter the code displayed on the phone under Phone Code in the box on the desktop version of the site.
5. Click "Done" on the desktop version.
6. Fly!
###Controls (phone📱)
- The **cyclic** is akin to the joystick in other aircraft: it controls, generally, speaking, the direction of the vehicle. Note that the initial position of your phone is considered the "neutral" point. Remember that **pitch** is forward and back tilt, **yaw** is left and right in a flat plane, while **roll** is left and right about an axis from nose to tail. When going around a corner, your car *yaws*, but it does not (hopefully!) *roll*.
- Roll left to increase lift on the right-facing blades, while decreasing it on the left-facing blades, thus pushing the aircraft left.
- Roll right to move to the right.
- Yaw left to simulate pushing the left pedal. This temporarily decreases the blade angle of the tail rotors. In turn, this increases the effect of the torque of the main rotors, thus turning the aircraft left.
- Yaw right to turn right.
- Pitch forward to increase the angle of the rear-facing blades, while decreasing the angle of the forward facing blade. This pushes the aircraft forward.
- Pitch backwards to push the aircraft backwards.
- The **collective** is generally the 'power' control. However, in most helicopters, the blades actually spin at a constant rate. Instead, it's the job of the collective to adjust the angle of the blades.
- Tilt backwards to decrease blade angle, and thus decrease lift.
- Tilt forwards to increase blade angle, and thus increase lift.
###Controls (mouse🖰)
*NOTE: if you're using a one button mouse, you will not be able to yaw your craft. Sorry!*
- **Cyclic**
- Move the mouse to the left temporarily to slide left.
- Move the mouse to the right to slide right.
- Move the mouse to forward to pitch forward and begin moving forward.
- Move the mouse backwards to pitch back, and begin sliding backwards.
- Finally, click the left and right mousebuttons to yaw left or right (i.e., use the rudder pedals);
- **Collective**
- Move the mouse forward to increase throttle.
- Move the mouse backwards to decrease throttle.
##Server
Currently, there is no live version of this app. However, it'll eventually be located (probably!) at *daveheligame.herokuapp.com*.
##Technical Stuff
Dave's Heli Game uses the following technologies:
- AngularJS for front-end responsiveness. Particularly, I'm using it to animate the different parts of the heli.
- The native deviceorientation API (`window.addeventlistener("deviceorientation",callback)`) to capture phone orientation information.
- NodeJS and ExpressJS on the back-end for the server.
- Websockets, via socket.io, to allow quick communication between the server, phones, and game.
- CSS3 for the 3d. I'm also using some of CSS3's filters (namely the `blur()` filter) to create a motion blur effect.
- Lots and lots of trigonometry and basic physics to control the aircraft's movement. I am *not* an aircraft person, so I'm only using what I can google! If it looks wrong, it probably is!
##Credits
Dave's Heli Game was written by me, [Dave](https://github.com/Newms34). Other various libraries/technologies are from their respective creators. I'm just usin em.<file_sep>app.factory('movFact', function($rootScope) {
var mouseStatus = [0, 0];
return {
handlePhoneCyc: function(o) {
var oriObj = {
FB: 30 * (o.x + 70) / 140,
RL: 30 * (o.y + 70) / 140,
pedals: 30 * (o.z + 70) / 140
};
return oriObj;
},
handlePhoneCol: function(o) {
return 30 * (o.x + 70) / 140;
},
handleMouseOri: function(x, y, w, h, z) {
var oriObj = {
FB: -15 * (y - z.y) / (h / 2),
RL: 15 * (x - z.x) / (w / 2)
};
return oriObj;
},
handleMouseThrot: function(y, h, z) {
return 15 + (30 * (z.y - y) / (h));
},
handleMousePedal: function(c, m) {
var ang = 0;
if (m && m == 1) {
//mousedown
//first, we deal with the case where both buttons are down:
if (c.button === 0 && mouseStatus[1]) {
mouseStatus[0] = 1;
ang = 0;
} else if (c.button == 2 && mouseStatus[0]) {
mouseStatus[1] = 1;
ang = 0;
} else if (c.button === 0) {
mouseStatus[0] = 1;
ang = -10;
} else {
mouseStatus[1] = 1;
ang = 10;
}
} else if (c.button === 0 && mouseStatus[1] == 1) {
mouseStatus[0] = 0;
ang = 10;
} else if (c.button == 2 && mouseStatus[0] == 1) {
mouseStatus[1] = 0;
ang = -10;
} else {
//no buttons currently down
mouseStatus = [0, 0];
return 0;
}
return ang;
}
};
});
| 3ec31740efab4ee72d977d0b5e46119d82a7c9e5 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Newms34/heli | 6dd1458ad2762e755fd57c50d816f204dfc8f950 | 06bfe595947267eff42bfae2fbeb5f4503fe545c | |
refs/heads/master | <file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Input from '../Input/Input';
import Button from '../Button/Button';
import classes from './SignUpBox.css';
const SignUpBox = (props) => {
const {
email,
isEmailValid,
emailChangeHandler,
password,
isPasswordValid,
passwordChangeHandler,
username,
isUsernameValid,
usernameChangeHandler,
repeatPassword,
isRepeatPasswordValid,
repeatPasswordChangeHandler,
submitTrigger,
submitDisabled,
} = props;
let emailValidationClass = classes.signUpBox__input;
let passwordValidationClass = classes.signUpBox__input;
let repeatPasswordValidationClass = classes.signUpBox__input;
let usernameValidationClass = classes.signUpBox__input;
if (isEmailValid === false) {
emailValidationClass = classes.signUpBox__emailNotValid;
}
if (isPasswordValid === false) {
passwordValidationClass = classes.signUpBox__passwordNotValid;
}
if (isRepeatPasswordValid === false) {
repeatPasswordValidationClass = classes.signUpBox__repeatPasswordNotValid;
}
if (isUsernameValid === false) {
usernameValidationClass = classes.signUpBox__usernameNotValid;
}
return (
<div className={classes.signUpBox}>
<div className={emailValidationClass}>
<p>
email:
</p>
<Input
maxLength="30"
value={email}
placeholder="..."
onChange={emailChangeHandler}
/>
</div>
<div className={usernameValidationClass}>
<p>
username:
</p>
<Input
maxLength="30"
value={username}
placeholder="..."
onChange={usernameChangeHandler}
/>
</div>
<div className={passwordValidationClass}>
<p>
password:
</p>
<Input
maxLength="30"
type="password"
value={password}
placeholder="..."
onChange={passwordChangeHandler}
/>
</div>
<div className={repeatPasswordValidationClass}>
<p>
repeat password:
</p>
<Input
maxLength="30"
type="password"
value={repeatPassword}
placeholder="..."
onChange={repeatPasswordChangeHandler}
/>
</div>
<div className={classes.signUpBox__button}>
<Button
onClick={submitTrigger}
disabled={submitDisabled}
>
Sign Up
</Button>
</div>
</div>
);
};
SignUpBox.propTypes = {
email: PropTypes.string.isRequired,
isEmailValid: PropTypes.bool.isRequired,
emailChangeHandler: PropTypes.func.isRequired,
password: <PASSWORD>.string.isRequired,
isPasswordValid: PropTypes.bool.isRequired,
passwordChangeHandler: PropTypes.func.isRequired,
username: PropTypes.string.isRequired,
isUsernameValid: PropTypes.bool.isRequired,
usernameChangeHandler: PropTypes.func.isRequired,
repeatPassword: PropTypes.string.isRequired,
isRepeatPasswordValid: PropTypes.bool.isRequired,
repeatPasswordChangeHandler: PropTypes.func.isRequired,
submitTrigger: PropTypes.func.isRequired,
submitDisabled: PropTypes.string.isRequired,
};
export default SignUpBox;
<file_sep>import React, { PureComponent } from 'react';
import Input from '../../components/Input/Input';
import Button from '../../components/Button/Button';
import classes from './ChangePassword.css';
class ChangePassword extends PureComponent {
state = {
newPasswordValue: '',
repeatNewPasswordValue: '',
newPasswordValidClass: null,
repeatNewPasswordValidClass: null,
newPasswordSubmitDisabeld: 'disabled',
}
newPasswordChangeHnadler = (event) => {
const { value } = event.target;
const { repeatNewPasswordValue } = this.state;
const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm;
let submitDisabled = 'disabled';
if (value.match(pattern) && value === repeatNewPasswordValue) {
submitDisabled = null;
}
if (!value.match(pattern)) {
this.setState({
newPasswordValue: value,
newPasswordValidClass: classes.notValidNewPassword,
newPasswordSubmitDisabeld: submitDisabled,
});
}
if (value.match(pattern)) {
this.setState({
newPasswordValue: value,
newPasswordValidClass: null,
newPasswordSubmitDisabeld: submitDisabled,
});
}
}
repeatNewPasswordChangeHnadler = (event) => {
const { value } = event.target;
const { newPasswordValue } = this.target;
const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm;
let submitDisabled = 'disabled';
if (value === newPasswordValue && newPasswordValue.match(pattern)) {
submitDisabled = null;
}
if (value !== newPasswordValue) {
this.setState({
repeatNewPasswordValue: value,
repeatNewPasswordValidClass: classes.notValidRepeatNewPassword,
newPasswordSubmitDisabeld: submitDisabled,
});
}
if (value === newPasswordValue) {
this.setState({
repeatNewPasswordValue: value,
repeatNewPasswordValidClass: null,
newPasswordSubmitDisabeld: submitDisabled,
});
}
}
submitNewPassword = () => {
console.log('NewPassword');
}
render() {
const {
newPasswordValue,
repeatNewPasswordValue,
newPasswordValidClass,
repeatNewPasswordValidClass,
newPasswordSubmitDisabeld,
} = this.state;
const {
newPasswordChangeHnadler,
repeatNewPasswordChangeHnadler,
submitNewPassword,
} = this;
return (
<div className={classes.changePassword}>
<p>
please input your new password:
</p>
<div className={newPasswordValidClass}>
<Input
maxLength="30"
type="password"
placeholder="<PASSWORD>"
value={newPasswordValue}
onChange={event => newPasswordChangeHnadler(event)}
/>
</div>
<p>
please repeat your new password:
</p>
<div className={repeatNewPasswordValidClass}>
<Input
maxLength="30"
type="password"
placeholder="<PASSWORD>"
value={repeatNewPasswordValue}
onChange={event => repeatNewPasswordChangeHnadler(event)}
/>
</div>
<Button
onClick={submitNewPassword}
disabled={newPasswordSubmitDisabeld}
>
submit
</Button>
</div>
);
}
}
export default ChangePassword;
<file_sep>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import AlbumsDisplayWithPage from '../../components/AlbumsDisplayWithPage/AbumsDisplayWithPage';
import classes from './UserAllRates.css';
class UserAllRates extends PureComponent {
state = {
albums,
page: 9,
totalPage: 20,
}
componentWillMount() {
const { albums } = this.props;
this.setState({
albums,
});
}
render() {
const {
albums,
page,
totalPage,
} = this.state;
return (
<div className={classes.userAllRates}>
<div className={classes.userAllRates__title}>
<p>
- My Rates -
</p>
</div>
<AlbumsDisplayWithPage
albums={albums}
page={page}
totalPage={totalPage}
baseUrl="/user/rates"
/>
</div>
);
}
}
const mapStateToProps = state => ({
albums: state.user.albums,
});
export default connect(mapStateToProps)(UserAllRates);
UserAllRates.propTypes = {
albums: PropTypes.arrayOf(PropTypes.object).isRequired,
};
const albums = [
{
id: '1',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '2',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '3',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '4',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '5',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '6',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '7',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '8',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '9',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '10',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '11',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '12',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: 'Le<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '13',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: 'Le<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '14',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: 'Leonard Cohen',
userRate: 3,
rating: '9.0',
},
{
id: '15',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '16',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: 'Leonard Cohen',
userRate: 3,
rating: '9.0',
},
{
id: '17',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '18',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '19',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '20',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
];
<file_sep>import React from 'react';
import Rate from '../../../assets/icon/rate';
import Labeling from '../../../assets/icon/label';
import Discuss from '../../../assets/icon/discuss';
import classes from './Intro.css';
const Intro = () => (
<div className={classes.intro}>
<p className={classes.intro__header}>
For True Music Lovers.
</p>
<div className={classes.intro__feature_1}>
<Rate />
<p>
Comment every single song.
</p>
</div>
<div className={classes.intro__feature_2}>
<Labeling />
<p>
Easy rating and labeling system.
</p>
</div>
<div className={classes.intro__feature_3}>
<Discuss />
<p>
Discuss with others only about music.
</p>
</div>
</div>
);
export default Intro;
<file_sep>import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Layouts from './components/Layouts/Layouts';
import Home from './containers/Home/Home';
import AlbumDetails from './containers/AlbumDetails/AlbumDetails';
import UserSign from './containers/UserSign/UserSign';
import UserDetails from './containers/UserDetails/UserDetails';
import UserAllRates from './containers/UserAllRates/UserAllRates';
import UserAllLabels from './containers/UserAllLabels/UserAllLabels';
import ForgetPassword from './containers/ForgetPassword/ForgetPassword';
import ChangePassword from './containers/ChangePassword/ChangePassword';
import ArtistDetails from './containers/ArtistDetails/ArtistDetails';
const App = () => (
<BrowserRouter>
<Layouts>
<Route path="/album" component={AlbumDetails} />
<Route path="/signin" component={UserSign} />
<Route path="/artist" component={ArtistDetails} />
<Route path="/forgetpassword" component={ForgetPassword} />
<Route path="/changepassword" component={ChangePassword} />
<Switch>
<Route path="/user/rates" component={UserAllRates} />
<Route path="/user/labels" component={UserAllLabels} />
<Route path="/user" component={UserDetails} />
</Switch>
<Route path="/" exact component={Home} />
</Layouts>
</BrowserRouter>
);
export default App;
<file_sep>import React, { PureComponent } from 'react';
import Input from '../../components/Input/Input';
import Button from '../../components/Button/Button';
import classes from './ForgetPassword.css';
class ForgetPassword extends PureComponent {
state = {
emailValue: '',
codeValue: '',
inputEmailClass: classes.displayShow,
inputCodeClass: classes.displayNone,
emailValidClass: null,
codeValidClass: null,
emailSubmitDisabled: 'disabled',
codeSubmitDisabeld: 'disabled',
}
emailChangeHnadler = (event) => {
const { value } = event.target;
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
if (!value.match(pattern)) {
console.log('here');
this.setState({
emailValue: value,
emailValidClass: classes.notValidEmail,
emailSubmitDisabled: 'disabled',
});
}
if (value.match(pattern)) {
this.setState({
emailValue: value,
emailValidClass: null,
emailSubmitDisabled: null,
});
}
}
codeChangeHnadler = (event) => {
const { value } = event.target;
if (value === '') {
this.setState({
codeValue: value,
codeValidClass: classes.notValidCode,
codeSubmitDisabeld: 'disabled',
});
}
if (value !== '') {
this.setState({
codeValue: value,
codeValidClass: null,
codeSubmitDisabeld: null,
});
}
}
submitEmail = () => {
console.log('email');
this.setState({
inputEmailClass: classes.displayNone,
inputCodeClass: classes.displayShow,
});
}
submitCode = () => {
console.log('code');
}
render() {
const {
emailValue,
codeValue,
inputEmailClass,
inputCodeClass,
codeSubmitDisabeld,
emailSubmitDisabled,
emailValidClass,
codeValidClass,
} = this.state;
const {
emailChangeHnadler,
submitEmail,
codeChangeHnadler,
submitCode,
} = this;
return (
<div className={classes.forgetPassword}>
<div className={inputEmailClass}>
<p>
please input your sign in email:
</p>
<div className={emailValidClass}>
<Input
maxLength="30"
placeholder="your email"
value={emailValue}
onChange={event => emailChangeHnadler(event)}
/>
</div>
<Button
onClick={submitEmail}
disabled={emailSubmitDisabled}
>
submit
</Button>
</div>
<div className={inputCodeClass}>
<p>
please input your verify code:
</p>
<div className={codeValidClass}>
<Input
maxLength="6"
placeholder="verify code"
value={codeValue}
onChange={event => codeChangeHnadler(event)}
/>
</div>
<Button
onClick={submitCode}
disabled={codeSubmitDisabeld}
>
submit
</Button>
</div>
</div>
);
}
}
export default ForgetPassword;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classes from './Textarea.css';
const Textarea = (props) => {
const {
maxLength,
value,
placeholder,
onChange,
inputLength,
} = props;
return (
<div className={classes.textarea}>
<textarea
className={classes.textarea_area}
maxLength={maxLength}
value={value}
placeholder={placeholder}
onChange={onChange}
/>
<p className={classes.textarea_length}>
{inputLength}
/
{maxLength}
</p>
</div>
);
};
Textarea.propTypes = {
maxLength: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
placeholder: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
inputLength: PropTypes.number.isRequired,
};
export default Textarea;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classes from './AlbumInfo.css';
const AlbumInfo = (props) => {
const {
albumCoverSrc,
albumName,
description,
genres,
musician,
numbersOfRatings,
rating,
tracks,
type,
year,
} = props;
const tracksList = tracks.map(track => (
<div
key={track.id}
className={classes.albumInfo__leftbar__tracks__single}
>
<p>
{track.id}
.
</p>
<p>
{track.name}
</p>
<p>
{track.duration}
</p>
</div>
));
return (
<div className={classes.albumInfo}>
<div className={classes.albumInfo__leftbar}>
<div className={classes.albumInfo__leftbar__cover}>
<img src={albumCoverSrc} alt="album cover" />
<p>
type:
{type}
</p>
</div>
<div className={classes.albumInfo__leftbar__tracks}>
<p className={classes.albumInfo__leftbar__tracks__title}>
tracks:
</p>
{tracksList}
</div>
</div>
<div className={classes.albumInfo__rightbar}>
<p className={classes.albumInfo__rightbar__albumName}>
{albumName}
</p>
<div className={classes.albumInfo__rightbar__details}>
<p>
artist:
{musician}
</p>
<p>
year:
{year}
</p>
<p>
genres:
{genres}
</p>
</div>
<div className={classes.albumInfo__rightbar__rating}>
<p className={classes.albumInfo__rightbar__rating__number}>
{rating}
</p>
<p>
from
{numbersOfRatings}
reviewers
</p>
</div>
<div className={classes.albumInfo__rightbar__description}>
<p className={classes.albumInfo__rightbar__description__title}>
Introduction:
</p>
<p className={classes.albumInfo__rightbar__description__content}>
{description}
</p>
</div>
</div>
</div>
);
};
AlbumInfo.propTypes = {
albumCoverSrc: PropTypes.string.isRequired,
albumName: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
genres: PropTypes.string.isRequired,
musician: PropTypes.string.isRequired,
numbersOfRatings: PropTypes.string.isRequired,
rating: PropTypes.string.isRequired,
tracks: PropTypes.arrayOf(PropTypes.object).isRequired,
type: PropTypes.string.isRequired,
year: PropTypes.string.isRequired,
};
export default AlbumInfo;
<file_sep>import React, { PureComponent } from 'react';
import AlbumInfo from '../../components/AlbumInfo/AlbumInfo';
import RatingBar from '../../components/RatingBar/RatingBar';
import classes from './AlbumDetails.css';
import CommentDisplay from '../../components/CommentDisplay/CommentDisplay';
class AlbumDetails extends PureComponent {
state = {
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
albumName: 'Ordinary Human Currupt Love',
description: 'In My Secret Life. I saw you this morning. A Thousand Kisses Deep. for Sandy. That Don\'t Make It Junk. I fought against the bottle, Here It Is. Here is your crown. Love Itself. for L.W. *) The light came through the window, By The Rivers Dark. By the rivers dark. <NAME>. You Have Loved Enough.',
genres: 'soft rock',
musician: '<NAME>',
numbersOfRatings: '138',
rating: '9.0',
tracks: [
{
id: '1',
name: 'In My Secret Life',
duration: '4:55',
},
{
id: '2',
name: 'A Thousand Kisses Deep',
duration: '6:29',
},
{
id: '3',
name: 'That Don\'t Make It Junk',
duration: '4:28',
},
{
id: '4',
name: 'Here It Is',
duration: '4:18',
},
{
id: '5',
name: 'Love Itself',
duration: '5:26',
},
{
id: '6',
name: 'By the Rivers Dark',
duration: '5:20',
},
{
id: '7',
name: '<NAME>',
duration: '5:25',
},
{
id: '8',
name: 'You Have Loved Enough',
duration: '5:41',
},
{
id: '9',
name: '<NAME>',
duration: '6:04',
},
{
id: '10',
name: 'The Land of Plenty',
duration: '4:35',
},
],
type: 'album',
year: '2001',
}
render() {
const {
albumCoverSrc,
albumName,
description,
genres,
musician,
numbersOfRatings,
rating,
tracks,
type,
year,
} = this.state;
return (
<div className={classes.albumDetails}>
<div className={classes.albumDetails__content}>
<AlbumInfo
albumCoverSrc={albumCoverSrc}
albumName={albumName}
description={description}
genres={genres}
musician={musician}
numbersOfRatings={numbersOfRatings}
rating={rating}
tracks={tracks}
type={type}
year={year}
/>
<RatingBar
tracks={tracks}
/>
<CommentDisplay />
</div>
</div>
);
}
}
export default AlbumDetails;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import NoBorderButton from '../NoBorderButton/NoBorderButton';
import classes from './SmallTitleBar.css';
const SmallTitleBar = (props) => {
const {
title,
} = props;
return (
<div className={classes.smallTitleBar}>
<p className={classes.smallTitleBar__title}>
{title}
</p>
<NoBorderButton>
show more
</NoBorderButton>
</div>
);
};
SmallTitleBar.propTypes = {
title: PropTypes.string.isRequired,
};
export default SmallTitleBar;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classes from './NoBorderButton.css';
const NoBorderButton = (props) => {
const {
children,
onClick,
} = props;
return (
<button
className={classes.noBorderButton}
type="button"
onClick={onClick}
>
{ children }
</button>
);
};
NoBorderButton.propTypes = {
children: PropTypes.node.isRequired,
onClick: PropTypes.func.isRequired,
};
export default NoBorderButton;
<file_sep>import * as actionTypes from '../actions/actionTypes';
import updateObject from '../utility';
const user = {
name: 'WangErMa',
email: '<EMAIL>',
labels: [
'intersting',
'sad song',
'one pick',
'english',
'traditional',
'want to buy',
'LP',
'jazz',
'acid jazz',
'post rock',
'punk',
'dont like',
'80\'s',
'aisan',
'rap',
'pop',
'art pop',
'male singer',
'dead',
'shit',
],
albums: [
{
id: '1',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 5,
rating: '9.0',
labels: [
'LP',
],
},
{
id: '2',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b1963f60a9e325d3f0287/1:1/w_160/lemon%20twigs_go%20to%20school.jpg',
ranking: '01',
albumName: 'Go to School',
musician: 'The Lemon Twigs',
userRate: 4,
rating: '7.4',
labels: [
'LP',
],
},
{
id: '3',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ecd008a8eb536b9b12888/1:1/w_320/maymind.jpg',
ranking: '01',
albumName: 'Cheap Storage',
musician: 'Maymind',
userRate: 4,
rating: '8.3',
labels: [
'interesting',
'LP',
],
},
{
id: '4',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b254b8a8eb536b9b126be/1:1/w_320/Punishment%20in%20Flesh_Innumerable%20Forms.jpg',
ranking: '01',
albumName: 'Punishment in Flesh',
musician: 'Innumerable Forms',
userRate: 2,
rating: '2.9',
labels: [
'LP',
],
},
{
id: '5',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7735baf60a9e325d3f01d5/1:1/w_320/blood%20orange_negro%20swan.jpg',
ranking: '01',
albumName: '<NAME>',
musician: 'Blood Orange',
userRate: 3,
rating: '4.5',
labels: [
'LP',
],
},
{
id: '6',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7737b6f60a9e325d3f01d7/1:1/w_320/Anna%20Meredith_Anno.jpg',
ranking: '01',
albumName: 'Anno',
musician: '<NAME>',
userRate: 4,
rating: '9.1',
labels: [
'LP',
],
},
{
id: '7',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b731d5e61613f18abb1b3c3/1:1/w_320/Donchristian_Where%20there\'s%20smoke.jpg',
ranking: '01',
albumName: 'Where There’s Smoke',
musician: 'DonChristian',
userRate: 3,
rating: '5.7',
labels: [
'LP',
],
},
{
id: '8',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ecea9f66e723ab75eacf9/1:1/w_320/skinless.jpg',
ranking: '01',
albumName: 'Marauder',
musician: 'Interpol',
userRate: 4,
rating: '8.2',
labels: [
'interesting',
'LP',
],
},
{
id: '9',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ecea9f66e723ab75eacf9/1:1/w_320/skinless.jpg',
ranking: '01',
albumName: 'Skinless X-1',
musician: 'Fire-Toolz',
userRate: 1,
rating: '7.5',
labels: [
'interesting',
'LP',
],
},
{
id: '10',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ec49ba78458227bd780cd/1:1/w_320/parts.jpg',
ranking: '01',
albumName: 'Parts',
musician: 'Ohmme',
userRate: 3,
rating: '8.2',
labels: [
'interesting',
'LP',
],
},
{
id: '11',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b247cbec1b01e6732b3a9/1:1/w_320/VA_Kompakt%20Total%2018.jpg',
ranking: '01',
albumName: 'Total 18',
musician: 'Various Artists',
userRate: 4,
rating: '8.7',
labels: [
'LP',
],
},
{
id: '12',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7af96a8a8eb536b9b12686/1:1/w_320/The%20Hermit%20And%20The%20Recluse_Orpheus%20Vs%20The%20Sirens.jpg',
ranking: '01',
albumName: 'Orpheus vs. the Sirens',
musician: 'Hermit and the Recluse',
userRate: 4,
rating: '4.4',
labels: [
'LP',
],
},
{
id: '13',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b1adfb1f53320b62b998a/1:1/w_320/gabriel%20kahane_book%20of%20travelers.jpg',
ranking: '01',
albumName: 'Book of Travelers',
musician: '<NAME>',
userRate: 2,
rating: '6.7',
labels: [
'LP',
],
},
{
id: '14',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b1c58a78458227bd77ee1/1:1/w_320/Tra%CC%88den_st.jpg',
ranking: '01',
albumName: 'Träden',
musician: 'Träden',
userRate: 1,
rating: '2.2',
labels: [
'LP',
],
},
{
id: '15',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7732f167a8ff3026124467/1:1/w_320/djrum_portrait%20with%20firewood.jpg',
ranking: '01',
albumName: 'Portrait With Firewood',
musician: 'Djrum',
userRate: 5,
rating: '9.5',
labels: [
'LP',
],
},
{
id: '16',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b17a3494ed0265fa9d947/1:1/w_320/lori%20scacco_desire%20loop.jpg',
ranking: '01',
albumName: '<NAME>',
musician: '<NAME>',
userRate: 2,
rating: '3.3',
labels: [
'LP',
],
},
{
id: '17',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b77198cb1f53320b62b980a/1:1/w_320/ariana%20grande_Sweetener.jpg',
ranking: '01',
albumName: 'Sweetener',
musician: '<NAME>',
userRate: 4,
rating: '4.7',
labels: [
'interesting',
'LP',
],
},
{
id: '18',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b771c3ea78458227bd77dbb/1:1/w_320/Amine%CC%81_ONEPOINTFIVE.jpg',
ranking: '01',
albumName: 'ONEPOINTFIVE',
musician: 'Aminé',
userRate: 4,
rating: '8.5',
labels: [
'LP',
],
},
{
id: '19',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b76d4984aea202eae1ac64e/1:1/w_320/our%20garden%20needs%20its%20flowers_jess%20sah%20bi%20peter%20one.jpg',
ranking: '01',
albumName: 'Our Garden Needs Its Flowers',
musician: '<NAME>',
userRate: 3,
rating: '7.2',
labels: [
'LP',
],
},
{
id: '20',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b731f5179bedf15f0a107c6/1:1/w_320/prodigy_the%20fat%20of%20the%20land.jpg',
ranking: '01',
albumName: 'The Fat Of the Land',
musician: 'The Prodigy',
userRate: 3,
rating: '6.9',
labels: [
'LP',
],
},
],
};
const initialState = {
loginStatus: true,
user,
comments: null,
};
const updateUser = (state, action) => {
const valueToChange = {
loginStatus: action.loginStatus,
user: action.user,
};
return updateObject(state, valueToChange);
};
const updateComment = (state, action) => {
const valueToChange = {
comments: action.comments,
};
return updateObject(state, valueToChange);
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.LOG_IN:
case actionTypes.LOG_OUT:
return updateUser(state, action);
case actionTypes.POST_COMMENT:
case actionTypes.PUT_COMMENT:
case actionTypes.GET_COMMENT:
case actionTypes.DELETE_COMMENT:
return updateComment(state, action);
default:
return state;
}
};
export default reducer;
<file_sep>import React, { PureComponent } from 'react';
import SingleItem from '../../components/SingleItem/SingleItem';
import classes from './ArtistDetails.css';
class ArtistDetails extends PureComponent {
state = {
artistPhotoSrc: 'https://upload.wikimedia.org/wikipedia/commons/b/b4/Leonard_Cohen%2C_1988_01.jpg',
name: '<NAME>',
birthName: '<NAME>',
birth: '21/09/1934 ~ 07/11/2016',
genres: 'folk/soft rock',
intro: '<NAME> CC GOQ (September 21, 1934 – November 7, 2016) was a Canadian singer-songwriter, poet and novelist. His work explored religion, politics, isolation, sexuality and personal relationships.[2] Cohen was inducted into the Canadian Music Hall of Fame, the Canadian Songwriters Hall of Fame, and the Rock and Roll Hall of Fame. He was invested as a Companion of the Order of Canada, the nation\'s highest civilian honour. In 2011, Cohen received one of the Prince of Asturias Awards for literature and the ninth Glenn Gould Prize.',
albums,
}
render() {
const {
artistPhotoSrc,
name,
birthName,
birth,
genres,
intro,
albums,
} = this.state;
const discographyDisplay = albums.map(album => (
<SingleItem
key={album.id}
albumCoverSrc={album.albumCoverSrc}
albumName={album.albumName}
musician={album.musician}
year={album.year}
genres={album.genres}
rating={album.rating}
/>
));
return (
<div className={classes.artistDetails}>
<div className={classes.artistDetails__details}>
<img
src={artistPhotoSrc}
alt={name}
/>
<div className={classes.artistDetails__details__text}>
<p className={classes.artistDetails__details__text_name}>
{name}
</p>
<p>
Birth Name:
{birthName}
</p>
<p>
Birth:
{birth}
</p>
<p>
Genres:
{genres}
</p>
<div className={classes.artistDetails__details_intro}>
<p>
Intro:
</p>
<p>
{intro}
</p>
</div>
</div>
</div>
<div className={classes.artistDetails__discography}>
<p className={classes.artistDetails__discography_title}>
discography
</p>
<div className={classes.artistDetails__discography_albums}>
{discographyDisplay}
</div>
</div>
</div>
);
}
}
export default ArtistDetails;
const albums = [
{
id: '1',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
year: '2001',
genres: 'soft rock',
rating: '9.0',
},
{
id: '2',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
year: '2001',
genres: 'soft rock',
rating: '9.0',
},
{
id: '3',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
year: '2001',
genres: 'soft rock',
rating: '9.0',
},
{
id: '4',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
year: '2001',
genres: 'soft rock',
rating: '9.0',
},
{
id: '5',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
year: '2001',
genres: 'soft rock',
rating: '9.0',
},
{
id: '6',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
year: '2001',
genres: 'soft rock',
rating: '9.0',
},
];
<file_sep># taste-label
This program is based on React.js. This is a website where you can rate every single song of one album.
### Setup
1. `<EMAIL>:eveshi/taste-label.git`
2. Then, run `npm install`.
3. Run `cd client` and `npm start` for the client. Then check https://localhost:3000.
### Preview
- for computer:
<div align="center">
<img src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/com_home.png">
</div>
<div align='center'>
<img src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/com_sign.png">
</div>
<div align='center'>
<img src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/com_album_comment.png">
</div>
<div align='center'>
<img src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/com_user.png">
</div>
<div align='center'>
<img src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/com_rates.png">
</div>
- for mobile:
<div align="center">
<img width="250" src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/mobile_home.png">
<img width="250" style="margin-left:20px" src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/mobile_sign.png">
<img width="250" style="margin-left:20px" src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/mobile_album.png">
</div>
<div align="center">
<img width="250" src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/mobile_rate.png">
<img width="250" style="margin-left:20px" src="https://raw.githubusercontent.com/eveshi/taste-label/master/README_IMAGE/mobile_rates.png">
</div>
<file_sep>import axios from 'axios';
import * as actionTypes from './actionTypes';
const LOG_IN_REQUEST = () => ({ type: actionTypes.LOG_IN });
const LOG_IN_FAILURE = error => ({
type: actionTypes.LOG_IN,
error,
});
const LOG_IN_SUCCESS = user => ({
type: actionTypes.LOG_IN,
loginStatus: true,
user,
});
export const LOG_IN = userInfo => (dispatch) => {
dispatch(LOG_IN_REQUEST);
try {
axios.get('/login', {
userInfo,
}).then(user => user.json())
.then(user => dispatch(LOG_IN_SUCCESS(user)));
} catch (error) {
dispatch(LOG_IN_FAILURE(error));
}
};
export const LOG_OUT = () => ({
type: actionTypes.LOG_OUT,
loginStatus: false,
user: null,
});
<file_sep>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import RateStar from '../RateStar/RateStar';
import Button from '../Button/Button';
import Input from '../Input/Input';
import LabelItem from '../LabelItem/LabelItem';
import Textarea from '../Textarea/Textarea';
import classes from './RatingBar.css';
class RatingBar extends PureComponent {
state = {
showMore: false,
label: '',
labelList: [
'jazz',
'pop',
'joy',
],
comment: '',
inputLength: 0,
}
showMoreHandler = () => {
const { showMore } = this.state;
this.setState({
showMore: !showMore,
});
}
quickSave = () => {
console.log('yes');
}
labelInput = (event) => {
const { key } = event;
const {
label,
labelList,
} = this.state;
const list = [...labelList];
if (key === 'Enter') {
list.push(label);
this.setState({
label: '',
labelList: list,
});
}
}
labelChangeHandler = (event) => {
const { value } = event.target;
this.setState({
label: value,
});
}
labelDelete = (index) => {
const { labelList } = this.state;
const list = [...labelList];
list.splice(index, 1);
this.setState({
labelList: list,
});
}
commentChangeHandler = (event) => {
const { value } = event.target;
const inputLength = value.length;
this.setState({
comment: value,
inputLength,
});
}
render() {
const {
showMore,
label,
labelList,
comment,
inputLength,
} = this.state;
const {
showMoreHandler,
quickSave,
labelInput,
labelChangeHandler,
labelDelete,
commentChangeHandler,
} = this;
const {
tracks,
} = this.props;
const labelTracks = tracks.map(track => (
<div
key={track.id}
className={classes.ratingBar__more__track_single}
>
<div className={classes.ratingBar__more__track_single_text}>
<p>
{track.id}
.
</p>
<p>
{track.name}
</p>
</div>
<RateStar />
</div>
));
const labels = labelList.map(((item, index) => (
<LabelItem
key={item}
labelItem={item}
onClick={() => labelDelete(index)}
/>
)));
return (
<div className={classes.ratingBar}>
<div className={classes.ratingBar__rateNow}>
<div className={classes.ratingBar__rateNow__text}>
<p>
Rate Now
</p>
</div>
<RateStar />
</div>
{showMore
? (
<React.Fragment>
<div className={classes.ratingBar__more}>
<Input
maxLength="20"
value={label}
placeholder="Enter label here..."
onKeyPress={event => labelInput(event)}
onChange={event => labelChangeHandler(event)}
/>
<div className={classes.ratingBar__more__labels}>
{labels}
</div>
<Textarea
maxLength="10000"
value={comment}
placeholder="Write your comment..."
inputLength={inputLength}
onChange={event => commentChangeHandler(event)}
/>
<div className={classes.ratingBar__more__track}>
{labelTracks}
</div>
</div>
<div className={classes.ratingBar__button}>
<Button onClick={quickSave}>
save all
</Button>
<Button onClick={showMoreHandler}>
write less
</Button>
</div>
</React.Fragment>
)
: (
<div className={classes.ratingBar__button}>
<Button onClick={quickSave}>
quick save
</Button>
<Button onClick={showMoreHandler}>
write more
</Button>
</div>
)}
</div>
);
}
}
RatingBar.propTypes = {
tracks: PropTypes.arrayOf(PropTypes.object).isRequired,
};
export default RatingBar;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Star from '../../assets/icon/star';
import classes from './RateStar.css';
const RateStar = (props) => {
const { onClick } = props;
return (
<div className={classes.rateStar}>
<input
name="rate"
className={classes.rateStar__input}
type="radio"
id="5"
/>
<label
htmlFor="5"
className={classes.rateStar__label}
onClick={onClick}
>
<Star />
</label>
<input
name="rate"
className={classes.rateStar__input}
type="radio"
id="4"
/>
<label
htmlFor="4"
className={classes.rateStar__label}
onClick={onClick}
>
<Star />
</label>
<input
name="rate"
className={classes.rateStar__input}
type="radio"
id="3"
/>
<label
htmlFor="3"
className={classes.rateStar__label}
onClick={onClick}
>
<Star />
</label>
<input
name="rate"
className={classes.rateStar__input}
type="radio"
id="2"
/>
<label
htmlFor="2"
className={classes.rateStar__label}
onClick={onClick}
>
<Star />
</label>
<input
name="rate"
className={classes.rateStar__input}
type="radio"
id="1"
/>
<label
htmlFor="1"
className={classes.rateStar__label}
onClick={onClick}
>
<Star />
</label>
</div>
);
};
RateStar.propTypes = {
onClick: PropTypes.func.isRequired,
};
export default RateStar;
<file_sep>import React, { PureComponent } from 'react';
import Intro from './Intro/Intro';
import ChartRow from './ChartRow/ChartRow';
import classes from './Home.css';
class Charts extends PureComponent {
state = {
list1,
list2,
list3,
}
render() {
const { list1, list2, list3 } = this.state;
return (
<div className={classes.home}>
<Intro />
<ChartRow
list={list1}
chartName="Latest Album"
/>
<ChartRow
list={list2}
chartName="New Best Album"
/>
<ChartRow
list={list3}
chartName="New Best Singles"
/>
</div>
);
}
}
export default Charts;
const list1 = [
{
id: '1',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 5,
year: 2011,
genres: 'folk/rock',
rating: '9.0',
},
{
id: '2',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b1963f60a9e325d3f0287/1:1/w_160/lemon%20twigs_go%20to%20school.jpg',
ranking: '01',
albumName: 'Go to School',
musician: '<NAME>',
userRate: 4,
year: 2005,
genres: 'rap',
rating: '7.4',
},
{
id: '3',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ecd008a8eb536b9b12888/1:1/w_320/maymind.jpg',
ranking: '01',
albumName: 'Cheap Storage',
musician: 'Maymind',
userRate: 4,
year: 1988,
genres: 'country',
rating: '8.3',
},
{
id: '4',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b254b8a8eb536b9b126be/1:1/w_320/Punishment%20in%20Flesh_Innumerable%20Forms.jpg',
ranking: '01',
albumName: 'Punishment in Flesh',
musician: 'Innumerable Forms',
userRate: 2,
year: 2002,
genres: 'rock/pop',
rating: '2.9',
},
{
id: '5',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7735baf60a9e325d3f01d5/1:1/w_320/blood%20orange_negro%20swan.jpg',
ranking: '01',
albumName: '<NAME>',
musician: 'Blood Orange',
userRate: 3,
year: 1967,
genres: 'R&B',
rating: '4.5',
},
{
id: '6',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7737b6f60a9e325d3f01d7/1:1/w_320/Anna%20Meredith_Anno.jpg',
ranking: '01',
albumName: 'Anno',
musician: '<NAME>',
userRate: 4,
year: 1988,
genres: 'soul',
rating: '9.1',
},
];
const list2 = [
{
id: '7',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b731d5e61613f18abb1b3c3/1:1/w_320/Donchristian_Where%20there\'s%20smoke.jpg',
ranking: '01',
albumName: 'Where There’s Smoke',
musician: 'DonChristian',
userRate: 3,
year: 2017,
genres: 'rap',
rating: '5.7',
},
{
id: '8',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ecea9f66e723ab75eacf9/1:1/w_320/skinless.jpg',
ranking: '01',
albumName: 'Marauder',
musician: 'Interpol',
userRate: 4,
year: 2018,
genres: 'post rock',
rating: '8.2',
},
{
id: '9',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ecea9f66e723ab75eacf9/1:1/w_320/skinless.jpg',
ranking: '01',
albumName: 'Skinless X-1',
musician: 'Fire-Toolz',
userRate: 1,
year: 2018,
genres: 'folk',
rating: '7.5',
},
{
id: '10',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7ec49ba78458227bd780cd/1:1/w_320/parts.jpg',
ranking: '01',
albumName: 'Parts',
musician: 'Ohmme',
userRate: 3,
year: 2016,
genres: 'jazz',
rating: '8.2',
},
{
id: '11',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b247cbec1b01e6732b3a9/1:1/w_320/VA_Kompakt%20Total%2018.jpg',
ranking: '01',
albumName: 'Total 18',
musician: 'Various Artists',
userRate: 4,
year: 2003,
genres: 'pop',
rating: '8.7',
},
{
id: '12',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7af96a8a8eb536b9b12686/1:1/w_320/The%20Hermit%20And%20The%20Recluse_Orpheus%20Vs%20The%20Sirens.jpg',
ranking: '01',
albumName: 'Orpheus vs. the Sirens',
musician: 'Hermit and the Recluse',
userRate: 4,
year: 2004,
genres: 'art pop',
rating: '4.4',
},
];
const list3 = [
{
id: '13',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b1adfb1f53320b62b998a/1:1/w_320/gabriel%20kahane_book%20of%20travelers.jpg',
ranking: '01',
albumName: 'Book of Travelers',
musician: '<NAME>',
userRate: 2,
year: 1988,
genres: 'dream pop',
rating: '6.7',
},
{
id: '14',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b1c58a78458227bd77ee1/1:1/w_320/Tra%CC%88den_st.jpg',
ranking: '01',
albumName: 'Träden',
musician: 'Träden',
userRate: 1,
year: 2011,
genres: 'alternative',
rating: '2.2',
},
{
id: '15',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7732f167a8ff3026124467/1:1/w_320/djrum_portrait%20with%20firewood.jpg',
ranking: '01',
albumName: 'Portrait With Firewood',
musician: 'Djrum',
userRate: 5,
year: 2000,
genres: 'asian tranditional',
rating: '9.5',
},
{
id: '16',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b7b17a3494ed0265fa9d947/1:1/w_320/lori%20scacco_desire%20loop.jpg',
ranking: '01',
albumName: 'Desire Loop',
musician: '<NAME>',
userRate: 2,
year: 2016,
genres: 'country',
rating: '3.3',
},
{
id: '17',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b77198cb1f53320b62b980a/1:1/w_320/ariana%20grande_Sweetener.jpg',
ranking: '01',
albumName: 'Sweetener',
musician: '<NAME>',
userRate: 4,
year: 2003,
genres: 'acid jazz',
rating: '4.7',
},
{
id: '18',
albumCoverSrc: 'https://media.pitchfork.com/photos/5b771c3ea78458227bd77dbb/1:1/w_320/Amine%CC%81_ONEPOINTFIVE.jpg',
ranking: '01',
albumName: 'ONEPOINTFIVE',
musician: 'Aminé',
userRate: 4,
year: 2001,
genres: 'pop',
rating: '8.5',
},
];
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Input from '../Input/Input';
import Button from '../Button/Button';
import NoBorderButton from '../NoBorderButton/NoBorderButton';
import classes from './SignInBox.css';
const SignInBox = (props) => {
const {
email,
emailChangeHandler,
isEmailValid,
password,
passwordChangeHandler,
isPasswordValid,
submitTrigger,
submitDisabled,
onClick,
} = props;
let emailValidationClass = classes.signInBox__input;
let passwordValidationClass = classes.signInBox__input;
if (isEmailValid === false) {
emailValidationClass = classes.signInBox__emailNotValid;
}
if (isPasswordValid === false) {
passwordValidationClass = classes.signInBox__passwordNotValid;
}
return (
<div className={classes.signInBox}>
<div className={emailValidationClass}>
<p>
email:
</p>
<Input
maxLength="30"
value={email}
placeholder="..."
onChange={emailChangeHandler}
/>
</div>
<div className={passwordValidationClass}>
<p>
password:
</p>
<Input
maxLength="30"
type="password"
value={password}
placeholder="..."
onChange={passwordChangeHandler}
/>
</div>
<div className={classes.signInBox__button}>
<Button
disabled={submitDisabled}
onClick={onClick}
>
Sign In
</Button>
<div className={classes.signInBox__button_forgetPassword}>
<NoBorderButton onClick={submitTrigger}>
forget password
</NoBorderButton>
</div>
</div>
</div>
);
};
SignInBox.propTypes = {
email: PropTypes.string.isRequired,
isEmailValid: PropTypes.bool.isRequired,
emailChangeHandler: PropTypes.func.isRequired,
password: PropTypes.string.isRequired,
isPasswordValid: PropTypes.bool.isRequired,
passwordChangeHandler: PropTypes.func.isRequired,
submitTrigger: PropTypes.func.isRequired,
submitDisabled: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
};
export default SignInBox;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import ToolBar from '../ToolBar/ToolBar';
import Footer from '../Footer/Footer';
import classes from './Layouts.css';
const Layouts = (props) => {
const { children } = props;
return (
<div className={classes.layouts}>
<ToolBar />
{children}
<Footer />
</div>
);
};
Layouts.propTypes = {
children: PropTypes.node.isRequired,
};
export default Layouts;
<file_sep>import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import UserLabels from './UserLabels/UserLabels';
import UserRates from './UserRates/UserRates';
import NoBorderButton from '../../components/NoBorderButton/NoBorderButton';
import classes from './UserDetails.css';
class UserDetails extends PureComponent {
state = {
name: 'eve',
email: '<EMAIL>',
labels: [],
albums,
}
componentWillMount() {
const {
user,
} = this.props;
this.setState({
name: user.name,
email: user.email,
labels: user.labels,
albums: user.albums,
});
}
render() {
const {
name,
email,
labels,
albums,
} = this.state;
return (
<div className={classes.userDetails}>
<div className={classes.userDetails__title}>
<p className={classes.userDetails__title_name}>
{name}
</p>
<p className={classes.userDetails__title_email}>
{email}
</p>
<NoBorderButton>
change password
</NoBorderButton>
</div>
<UserLabels labels={labels} />
<UserRates albums={albums} />
</div>
);
}
}
const mapStateToProps = state => ({
user: state.user,
comments: state.comments,
});
export default connect(mapStateToProps)(UserDetails);
const user = {
name: '',
email: '',
labels: [],
albums: [],
};
UserDetails.propTypes = {
user: PropTypes.instanceOf(user).isRequired,
};
const albums = [
{
id: '1',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: 'Leonard Cohen',
userRate: 3,
rating: '9.0',
},
{
id: '2',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '3',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '4',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '5',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
{
id: '6',
albumCoverSrc: 'https://www.leonardcohenfiles.com/tns-cover.jpg',
ranking: '01',
albumName: 'Ten New Songs',
musician: '<NAME>',
userRate: 3,
rating: '9.0',
},
];
<file_sep>import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import * as actions from '../../store/actions/index';
import SignInBox from '../../components/SignInBox/SignInBox';
import SignUpBox from '../../components/SignUpBox/SignUpBox';
import classes from './UserSign.css';
import Button from '../../components/Button/Button';
class UserSign extends PureComponent {
state = {
signInEmail: '',
isSignInEmailValid: true,
signInPassword: '',
isSignInPasswordValid: true,
signUpEmail: '',
isSignUpEmailValid: true,
signUpPassword: '',
isSignUpPasswordValid: true,
signUpUsername: '',
isSignUpUsernameValid: true,
signUpRepeatPassword: '',
isSignUpRepeatPasswordValid: true,
signInButtonStatus: classes.button_active,
signUpButtonStatus: classes.button_notActive,
showSignIn: null,
showSignUp: classes.notShow,
signInSubmitDisabled: 'disabled',
signUpSubmitDisabled: 'disabled',
};
signInEmailChangeHandler = (event) => {
const { value } = event.target;
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
if (!value.match(pattern)) {
this.setState({
signInEmail: value,
isSignInEmailValid: false,
});
}
if (value.match(pattern)) {
this.setState({
signInEmail: value,
isSignInEmailValid: true,
});
}
}
signInPasswordChangeHandler = (event) => {
const { value } = event.target;
const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm;
if (!value.match(pattern)) {
this.setState({
signInPassword: value,
isSignInPasswordValid: false,
});
}
if (value.match(pattern)) {
this.setState({
signInPassword: value,
isSignInPasswordValid: true,
});
}
}
signUpEmailChangeHandler = (event) => {
const { value } = event.target;
const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
if (!value.match(pattern)) {
this.setState({
signUpEmail: value,
isSignUpEmailValid: false,
});
}
if (value.match(pattern)) {
this.setState({
signUpEmail: value,
isSignUpEmailValid: true,
});
}
}
signUpPasswordChangeHandler = (event) => {
const { value } = event.target;
const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm;
if (!value.match(pattern)) {
this.setState({
signUpPassword: value,
isSignUpPasswordValid: false,
});
}
if (value.match(pattern)) {
this.setState({
signUpPassword: value,
isSignUpPasswordValid: true,
});
}
}
signUpRepeatPasswordChangeHandler = (event) => {
const { value } = event.target;
const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm;
if (!value.match(pattern)) {
this.setState({
signUpRepeatPassword: value,
isSignUpRepeatPasswordValid: false,
});
}
if (value.match(pattern)) {
this.setState({
signUpRepeatPassword: value,
isSignUpRepeatPasswordValid: true,
});
}
}
signUpUsernameChangeHandler = (event) => {
const { value } = event.target;
const pattern = /^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{2,29}$/igm;
if (!value.match(pattern)) {
this.setState({
signUpUsername: value,
isSignUpUsernameValid: false,
});
}
if (value.match(pattern)) {
this.setState({
signUpUsername: value,
isSignUpUsernameValid: true,
});
}
}
showSignInHandler = () => {
this.setState({
signInButtonStatus: classes.button_active,
signUpButtonStatus: classes.button_notActive,
showSignIn: null,
showSignUp: classes.notShow,
});
}
showSignUpHandler = () => {
this.setState({
signInButtonStatus: classes.button_notActive,
signUpButtonStatus: classes.button_active,
showSignIn: classes.notShow,
showSignUp: null,
});
}
signinSubmit = () => {
const {
signInEmail,
signInPassword,
} = this.state;
const userInfo = {
signInEmail,
signInPassword,
};
const { login } = this.props;
login(userInfo);
}
render() {
const {
signInEmail,
isSignInEmailValid,
signInPassword,
isSignInPasswordValid,
signUpEmail,
isSignUpEmailValid,
signUpPassword,
isSignUpPasswordValid,
signUpUsername,
isSignUpUsernameValid,
signUpRepeatPassword,
isSignUpRepeatPasswordValid,
signInButtonStatus,
signUpButtonStatus,
showSignIn,
showSignUp,
signInSubmitDisabled,
signUpSubmitDisabled,
} = this.state;
const {
signInEmailChangeHandler,
signInPasswordChangeHandler,
signUpEmailChangeHandler,
signUpPasswordChangeHandler,
signUpUsernameChangeHandler,
signUpRepeatPasswordChangeHandler,
showSignInHandler,
showSignUpHandler,
signInSubmit,
} = this;
return (
<div className={classes.userSign}>
<div className={classes.box}>
<div className={classes.box__title}>
<div className={signUpButtonStatus}>
<Button onClick={showSignUpHandler}>
Sign Up
</Button>
</div>
<div className={signInButtonStatus}>
<Button onClick={showSignInHandler}>
Sign In
</Button>
</div>
</div>
<div className={showSignIn}>
<SignInBox
email={signInEmail}
isEmailValid={isSignInEmailValid}
emailChangeHandler={event => signInEmailChangeHandler(event)}
password={<PASSWORD>}
isPasswordValid={isSignInPasswordValid}
passwordChangeHandler={event => signInPasswordChangeHandler(event)}
submitDisabled={signInSubmitDisabled}
onClick={signInSubmit}
/>
</div>
<div className={showSignUp}>
<SignUpBox
email={signUpEmail}
isEmailValid={isSignUpEmailValid}
emailChangeHandler={event => signUpEmailChangeHandler(event)}
username={signUpUsername}
isUsernameValid={isSignUpUsernameValid}
usernameChangeHandler={event => signUpUsernameChangeHandler(event)}
password={<PASSWORD>}
isPasswordValid={<PASSWORD>}
passwordChangeHandler={event => signUpPasswordChangeHandler(event)}
repeatPassword={<PASSWORD>Up<PASSWORD>}
isRepeatPasswordValid={isSignUpRepeatPasswordValid}
repeatPasswordChangeHandler={event => signUpRepeatPasswordChangeHandler(event)}
submitDisabled={signUpSubmitDisabled}
/>
</div>
</div>
</div>
);
}
}
UserSign.propTypes = {
login: PropTypes.func.isRequired,
};
const mapActionToProps = dispatch => ({
login: userInfo => dispatch(actions.LOG_IN(userInfo)),
});
export default connect(null, mapActionToProps)(UserSign);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Search from '../../assets/icon/search';
import classes from './SearchBox.css';
const SearchBox = (props) => {
const {
onChange,
onClick,
placeholder,
showSearchBox,
value,
} = props;
return (
<div className={classes.searchBox}>
<input
className={
showSearchBox
? classes.searchBox__input
: classes.searchBox__input_hidden
}
type="text"
placeholder={placeholder}
value={value}
onChange={onChange}
/>
<button
className={
showSearchBox
? classes.searchBox__button_left
: classes.searchBox__button_right
}
type="button"
onClick={onClick}
>
<Search />
</button>
</div>
);
};
SearchBox.propTypes = {
onChange: PropTypes.func.isRequired,
onClick: PropTypes.func.isRequired,
placeholder: PropTypes.string.isRequired,
showSearchBox: PropTypes.bool.isRequired,
value: PropTypes.string.isRequired,
};
export default SearchBox;
<file_sep>export {
LOG_IN,
LOG_OUT,
} from './user';
export {
POST_COMMENT,
PUT_COMMENT,
GET_COMMENT,
DELETE_COMMENT,
} from './comments';
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import SingleItem from '../../../components/SingleItem/SingleItem';
import classes from './ChartRow.css';
const ChartRow = (props) => {
const {
list,
chartName,
} = props;
const itemList = list.map(item => (
<SingleItem
key={item.id}
albumCoverSrc={item.albumCoverSrc}
albumName={item.albumName}
musician={item.musician}
year={item.year}
genres={item.genres}
rating={item.rating}
/>
));
return (
<div className={classes.chartRow}>
<div className={classes.chartRow__header}>
<p>
{chartName}
</p>
</div>
<div className={classes.chartRow__items}>
{itemList}
</div>
</div>
);
};
ChartRow.propTypes = {
list: PropTypes.arrayOf(PropTypes.object).isRequired,
chartName: PropTypes.string.isRequired,
};
export default ChartRow;
| 7b98f297c78b43114dc584708b75f3abd97cdd85 | [
"JavaScript",
"Markdown"
] | 25 | JavaScript | eveshi/taste-label | b0ebd4eadb3b9550144c0685ca710d4cd21476e7 | c8967eafc7ed3dfd077aa4153e405a502cd833c4 | |
refs/heads/master | <repo_name>ed-fruty/php-environment<file_sep>/src/Runtime.php
<?php
namespace Fruty\Environment;
/**
* Class Runtime
* @package Fruty\Environment
*/
class Runtime
{
/**
* @return int
*/
public function getProcessPid()
{
return getmypid();
}
/**
* @return int
*/
public function getProcessGid()
{
return getmygid();
}
/**
* @return int
*/
public function getProcessUid()
{
return getmygid();
}
/**
* @return int
*/
public function getProcessInode()
{
return getmyinode();
}
/**
* @return string
*/
public function getProcessOwner()
{
return get_current_user();
}
/**
* @return string
*/
public function getFullOS()
{
return $this->getUName();
}
/**
* @return string
*/
public function getOsName()
{
return $this->getUName('s');
}
/**
* @param null $mode
* @return string
*/
public function getUName($mode = null)
{
return php_uname($mode);
}
/**
* @return bool
*/
public function isWindows()
{
return (strtoupper(substr($this->getOsName(), 0, 3)) === 'WIN');
}
/**
* @return bool
*/
public function isLinux()
{
return (strtoupper(substr($this->getOsName(), 0, 3)) === 'LIN');
}
/**
* @return bool
*/
public function isUnix()
{
$names = array(
'CYG',
'DAR',
'FRE',
'HP-',
'IRI',
'LIN',
'NET',
'OPE',
'SUN',
'UNI'
);
return in_array($this->getOsName(), $names) !== false;
}
/**
* @return bool
*/
public function isHHVM()
{
return defined('HHVM_VERSION');
}
/**
* @return bool
*/
public function isPHP()
{
return ! $this->isHHVM();
}
/**
* @return bool
* @param string $extension
*/
public function hasExtension($extension)
{
return extension_loaded($extension);
}
/**
* @return string
*/
public function getVersion()
{
if ($this->isHHVM()) {
return HHVM_VERSION;
} else {
return PHP_VERSION;
}
}
/**
* @return bool
*/
public function isCli()
{
return substr(strtolower(php_sapi_name()), 0, 3) == 'cli';
}
/**
* @return bool
*/
public function isWeb()
{
return !$this->isCli();
}
/**
* @return string
*/
public function getPwd()
{
return getcwd();
}
}<file_sep>/README.md
# PHP-Environment
PHP Environment Wrapper to load environment variables [supported json, php, ini, xml, yml and serialized data formats]
Why ed-fruty/php-environment?
-----------------------------
**You should never store sensitive credentials in your code**. Storing
[configuration in the environment](http://www.12factor.net/config) is one of
the tenets of a [twelve-factor app](http://www.12factor.net/). Anything that is
likely to change between deployment environments – such as database credentials
or credentials for 3rd party services – should be extracted from the
code into environment variables.
Basically, an environment file is an easy way to load custom configuration
variables that your application needs without having to modify .htaccess
files or Apache/nginx virtual hosts. This means you won't have to edit
any files outside the project, and all the environment variables are
always set no matter how you run your project - Apache, Nginx, CLI, and
even PHP 5.4's built-in webserver. This way is easier than all the other
ways you know of to set environment variables, and you're going to love
it.
* NO editing virtual hosts in Apache or Nginx
* NO adding `php_value` flags to .htaccess files
* EASY portability and sharing of required ENV values
* COMPATIBLE with PHP's built-in web server and CLI runner
Installation with Composer
--------------------------
```shell
composer require ed-fruty/php-environment
```
Usage
-----
An environment file is generally kept out of version control since it can contain
sensitive API keys and passwords. You can create the example file (`env.json.example`)
with all the required environment variables defined except for the sensitive
ones, which are either user-supplied for their own development environments or
are communicated elsewhere to project collaborators. The project collaborators
then independently copy an environment file to a local `env.json` and ensure
all the settings are correct for their local environment, filling in the secret
keys or providing their own values when necessary. In this usage, the `env.json`
file should be added to the project's `.gitignore` file so that it will never
be committed by collaborators. This usage ensures that no sensitive passwords
or API keys will ever be in the version control history so there is less risk
of a security breach, and production values will never have to be shared with
all project collaborators.
Add your application configuration to your environment file anywhere, but basically put it in the root of your
project. **Make sure an environment file is added to your `.gitignore` so it is not
checked-in the code**
Simple exmaple
--------------
Create a file `env.json` with the same content
```json
{
"database" : {
"connection" : {
"host" : "localhost",
"username" : "root",
"password" : "<PASSWORD>",
"port" : "3310"
}
}
}
```
Now you need to load environment configuration in your code.
Here we go!
```php
use Fruty\Environment\Env;
Env::instance()->load(__DIR__, 'env');
```
All done!
`env` argument is the environment filename.
`__DIR__` is the path where file is located. Default file extension is `json`,
but you can use others (see below).
Note. Maybe instead of `__DIR__` you need to set path, where you put your envrionment file.
Now you can use
```php
echo Env::instance()->get('databse.connection.host'); // Will print 'localhost'
var_dump(Env::instance()->get('database.connection'));
/*
* object(stdClass)#3 (4) {
* ["host"]=>
* string(9) "localhost"
* ["username"]=>
* string(4) "root"
* ["password"]=>
* string(15) "<PASSWORD>"
* ["port"]=>
* string(4) "3310"
* }
*/
```
You can access to your envrionment variables with the different ways. Next examples are alternatives to each other.
```php
$result = Env::instance('database');
$result = $_ENV['database']; // global php array, has limits (see below)
$result = getenv('database'); // standart php function, has limits (see below)
$result = env_get('database');
$result = envGet('database');
```
As you can se, we use package helper functions `env_get` and `envGet`. They are short alternatives for `Env::instance()->get()`.
Get all environment variables
-----------------------------
```php
$env = Env::instance()->get();
```
Default Values
--------------
To get some value or set or set defaults, put default values as the second argument
```php
$databaseUser = env_get('database.connection.username', 'myDbUser');
```
This example shows, `$databaseUser` value will be value from environment file, or 'myDbUser' by defaults if it not exists
in the environment file
Also you can use (but not recommended) somethig like this:
```php
echo Env::instance()->get('database')->connection->host; // Will print 'localhost'
echo $_ENV['database']->connection->host; // will print 'localhost'
```
Limits for $_ENV and getenv()
---------
```php
$_ENV['database.connection'];
getenv('database.connection');
```
will not work. For `$_ENV` and `getenv` function only first level of definition will be work (before dot '.').
And `getenv` function has one surprice. Php allow us to save by `putenv` only scalar values, so such code:
```php
$result = getenv('database');
```
Is not an object. I will be string with json_encoded values
Array keys not works ?
------------
Note, associative array will be object instance of stdClass
```php
echo env_get('services')['database']; // Wrong
echo env_get('services')->database; // Right
```
Auto-file detecting
-------------------
For example, many companies has such envrionment way. Every developer set `APP_ENV` value to his local machine
and environment filename loads with the same name.
For example my local `APP_ENV` value is `dev-fruty`, so next script will load variables from `dev-fruty.json` file.
```php
Env::instance()->load(__DIR__, null);
```
Thats all.
How to add APP_ENV to your local machine?
[Windows users](http://www.computerhope.com/issues/ch000549.htm)
[Ubuntu](https://help.ubuntu.com/community/EnvironmentVariables)
[Mac](http://apple.stackexchange.com/questions/106778/how-do-i-set-environment-variables-on-os-x)
Envrionment file not exists?
----------------------------
By default, if envrionment file not exists, `env_get('key')` will return null, or default value if it setted.
You can set
```php
Env::instance()->fileNotFoundException(true);
```
And `InvalidArgumentException` will throws if envrionment file not exists.
Required variables
------------------
Your can set not only that must be exists envronment file, also you can set requred variables definitions.
```php
Env::instance()->required([
'appName',
'cache',
'database.connection.charset',
]);
```
Now if one of this params not exists in your envrioment file you will get `RuntimeException`.
Envriornment readers
--------------------
Early in examples we use only `json` format, but you can use such supported formats:
- JSON
- XMl
- INI
- PHP Array
- Yml
- Serialize
What you need to use it? put reader name as third argument, when loading your environment
```php
Env::instance()->load(__DIR__, 'env', 'ini');
Env::instance()->load(__DIR__, null, 'xml'); // for auto detecting your envrionment filename
```
JSON Reader example
-------------------
1. Create file `env.json` with the same content
```json
{
"database" : {
"connection" : {
"host" : "localhost",
"username" : "root",
"password" : "<PASSWORD>",
"port" : "3310"
}
}
}
```
2. Load envrionment file
```php
Env::isntance()->load(__DIR__, 'env', 'json');
```
3. Use it.
```php
echo Env::instance('database.connection.host'); // will print 'localhost'
```
Ini Reader example
-------------------
1. Create file `env.ini` with the same content
```ini
appName=My Application Name
;commentedVariable=Value
[database_connection]
host=localhost
username=root
password=<PASSWORD>
port=3306
```
2. Load envrionment file
```php
Env::isntance()->load(__DIR__, 'env', 'ini');
```
3. Use it.
```php
var_dump(env_get('database_connection'));
/* class stdClass#7 (4) {
* public $host =>
* string(9) "localhost"
* public $username =>
* string(4) "root"
* public $password =>
* string(16) "<PASSWORD>"
* public $port =>
* string(4) "3306"
*/ }
echo env_get('commentedVariable'); // NULL
echo env_get('appName') // string(19) "My Application Name"
```
PHP Array Reader example
-------------------
1. Create file `env.php` with the same content
```php
<?php
return [
'appName' => 'My Application Name',
'services' => [
'database' => [
'connection_default' => [
'host' => 'localhost',
'username' => 'root',
'password' => '<PASSWORD>'
]
]
]
];
```
2. Load envrionment file
```php
Env::isntance()->load(__DIR__, 'env', 'php');
```
3. Use it.
```php
var_dump(env_get('services.database.connection_default'));
/* class stdClass#9 (3) {
* public $host =>
* string(9) "localhost"
* public $username =>
* string(4) "root"
* public $password =>
* string(12) "<PASSWORD>"
*/ }
```
Xml Reader example
-------------------
1. Create file `env.xml` with the same content
```xml
<?xml version="1.0"?>
<root>
<database>
<connection>
<host>localhost</host>
<database>db_name</database>
<username>custom_user</username>
</connection>
</database>
</root>
```
2. Load envrionment file
```php
Env::isntance()->load(__DIR__, 'env', 'xml');
```
3. Use it.
```php
var_dump(env_get('database.connection'));
/* class stdClass#8 (3) {
* public $host =>
* string(9) "localhost"
* public $database =>
* string(7) "db_name"
* public $username =>
* string(11) "custom_user"
*/ }
```
Serialize Reader example
-------------------
1. Create file `env.serialize` with the same content
```
a:2:{s:7:"appName";s:19:"My Application Name";s:8:"services";a:1:{s:8:"database";a:1:{s:18:"connection_default";a:3:{s:4:"host";s:9:"localhost";s:8:"username";s:4:"root";s:8:"password";s:12:"<PASSWORD>";}}}}
```
2. Load envrionment file
```php
Env::isntance()->load(__DIR__, 'env', 'serialize');
```
3. Use it.
```php
var_dump(env_get('services.database.connection_default'));
/* class stdClass#9 (3) {
* public $host =>
* string(9) "localhost"
* public $username =>
* string(4) "root"
* public $password =>
* string(12) "<PASSWORD>"
*/ }
```
Yaml Reader example
-------------------
For using yml reader you need to install `Symfony Yaml` component firstly. So do:
```php
composer require symfony/yaml
```
Next, create file `env.yml` or `env.yaml` (in our example it will be `env.yaml`) with the same content
```yaml
database:
host: localhost
username: root
```
Load envrionment file
```php
Env::isntance()->load(__DIR__, 'env', 'yaml');
```
Now use it.
```php
var_dump(env_get('database'));
/* class stdClass#7 (2) {
* public $host =>
* string(9) "localhost"
* public $username =>
* string(4) "root"
*/ }
echo env_get('database.host'); // will print 'localhost'
```<file_sep>/src/Readers/XmlReader.php
<?php
namespace Fruty\Environment\Readers;
use Fruty\Environment\EnvReaderInterface;
use SimpleXMLElement;
/**
* Class XmlReader
* @package Fruty\Environment\Readers
*/
class XmlReader implements EnvReaderInterface
{
/**
* @param string $file
* @return \stdClass
* @throws \RuntimeException
*/
public function run($file)
{
return json_decode(json_encode((new SimpleXMLElement($file, 0, true))));
}
}<file_sep>/helper.php
<?php
if (! function_exists('envGet')) {
function envGet($key = null, $default = null)
{
return \Fruty\Environment\Env::instance()->get($key, $default);
}
}
if (! function_exists('env_get')) {
function env_get($key = null, $default = null)
{
return \Fruty\Environment\Env::instance()->get($key, $default);
}
}<file_sep>/src/EnvReaderInterface.php
<?php
namespace Fruty\Environment;
/**
* Interface EnvReaderInterface
* @package Fruty\Environment
*/
interface EnvReaderInterface
{
/**
* @param string $file
* @return \stdClass
* @throws \RuntimeException
*/
public function run($file);
}<file_sep>/src/Readers/YmlReader.php
<?php
namespace Fruty\Environment\Readers;
use Fruty\Environment\EnvReaderInterface;
use RuntimeException;
use Symfony\Component\Yaml\Yaml;
/**
* Class YmlReader
* @package Fruty\Environment\Readers
*/
class YmlReader implements EnvReaderInterface
{
/**
* @param string $file
* @return \stdClass
* @throws \RuntimeException
*/
public function run($file)
{
$symfonyYamlClass = 'Symfony\Component\Yaml\Yaml';
if (! class_exists($symfonyYamlClass)) {
throw new RuntimeException("Yaml reader not avaliable, {$symfonyYamlClass} must installed for it. Try to run `composer require symfony/yaml`", 500);
}
return json_decode(json_encode(Yaml::parse(file_get_contents($file))));
}
}<file_sep>/src/Env.php
<?php
namespace Fruty\Environment;
use stdClass;
use InvalidArgumentException;
/**
* Class Env
* @package Fruty\Environment
*/
class Env
{
/**
* @var stdClass
*/
private $storage;
/**
* @var stdClass
*/
private $cache;
/**
* @var EnvReaderInterface
*/
private $reader;
/**
* @var string
*/
private $envFile;
/**
* @var bool
*/
private $fileNotFoundException = false;
/**
* @var array
*/
private $required;
/**
* @var Runtime
*/
private $runtime;
/**
* Get singleton instance of Env class
*
* @return static
*/
public static function instance()
{
static $instance;
if (! $instance) {
$instance = new static();
}
return $instance;
}
/**
* Load environment variables
*
* @param string $path
* @param string $file
* @param string $reader
*/
public function load($path, $file = null, $reader = 'json')
{
$this->initialize();
$file = is_null($file) ? getenv('APP_ENV') : $file;
$envFile = $this->combineEnvFileName($path, $file, $reader);
$this->setReader($reader);
if (is_file($envFile)) {
$this->envFile = $envFile;
$this->loadData();
} elseif ($this->fileNotFoundException) {
throw new InvalidArgumentException("Environment file '{$file}' not found", 500);
}
$this->merge();
$this->checkRequired();
}
/**
* Check required variables
*
* @throws \RuntimeException
*/
private function checkRequired()
{
if ($this->required) {
foreach ($this->required as $el) {
if (! isset($this->storage->$el)) {
throw new \RuntimeException("Environment variable '{$el}' must be defined", 500);
}
}
}
}
/**
* Merge $_ENV with parsed values
*/
private function merge()
{
$this->storage = (object) array_merge($_ENV, $_SERVER, (array) $this->storage);
foreach ($this->storage as $k => $v) {
$_ENV[$k] = $v;
$_SERVER[$k] = $v;
putenv("{$k}=" . json_encode($v));
}
}
/**
* Throw Exception when env file is not found
*
* @param $value
*/
public function fileNotFoundException($value)
{
$this->fileNotFoundException = (bool) $value;
}
/**
* Get env variable value
*
* @access public
* @param string $key
* @param mixed $default
* @return mixed
*/
public function get($key = null, $default = null)
{
if ($key === null) {
return $this->storage;
}
if (! isset($this->cache->$key)) {
$this->cache->$key = $this->getFromStorage($this->storage, $key, $default);
}
return $this->cache->$key;
}
/**
* Set required env variables
*
* @param array $required
*/
public function required(array $required)
{
$this->required = $required;
}
/**
* Get env filename
*
* @return string
*/
public function getEnvFile()
{
return $this->envFile;
}
/**
* @return Runtime
*/
public function runtime()
{
if (! $this->runtime) {
$this->runtime = new Runtime();
}
return $this->runtime;
}
/**
* Get value from storage
*
* @access private
* @param stdClass $storage
* @param string $key
* @param mixed $default
* @return mixed
*/
private function getFromStorage(stdClass $storage, $key, $default = null)
{
if (is_null($key)) return $storage;
if (isset($storage->$key)) return $storage->$key;
foreach (explode('.', $key) as $segment) {
if ((! is_object($storage)) || ! isset($storage->$segment)) {
return $default;
}
$storage = $storage->$segment;
}
return $storage;
}
/**
* Initialize
*/
private function initialize()
{
$this->storage = new stdClass();
$this->cache = new stdClass();
}
/**
* Collect env file name from parts
* @param string $path
* @param string $file
* @param string $reader
* @return string
*/
private function combineEnvFileName($path, $file, $reader)
{
return rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file . "." . $reader;
}
/**
* @param $type
* @return EnvReaderInterface
*/
private function readerFactory($type)
{
$class = $this->getReaderClassName($type);
if (! class_exists($class)) {
throw new \InvalidArgumentException("Reader class {$class} not found", 500);
}
$reader = new $class;
if ($reader instanceof EnvReaderInterface === false) {
throw new \InvalidArgumentException("Reader class {$class} must implement EnvReaderInterface interface", 500);
}
return $reader;
}
/**
* @param $type
* @return string
*/
private function getReaderClassName($type)
{
$name = ucfirst(strtolower($type));
switch ($name) {
case 'Yaml':
$name = 'Yml';
break;
}
return __NAMESPACE__ . "\\Readers\\{$name}Reader";
}
/**
* Set reader
*
* @param string $reader
* @return EnvReaderInterface
*/
private function setReader($reader)
{
$this->reader = $this->readerFactory($reader);
}
/**
* Load data by reader
*/
private function loadData()
{
$this->storage = $this->reader->run($this->envFile);
}
}<file_sep>/src/Readers/IniReader.php
<?php
namespace Fruty\Environment\Readers;
use Fruty\Environment\EnvReaderInterface;
/**
* Class IniReader
* @package Fruty\Environment\Readers
*/
class IniReader implements EnvReaderInterface
{
/**
* @param string $file
* @return \stdClass
* @throws \RuntimeException
*/
public function run($file)
{
return json_decode(json_encode(parse_ini_file($file, true)));
}
} | 1363b0944b9481513d612c267d866a7c2f3b33fa | [
"Markdown",
"PHP"
] | 8 | PHP | ed-fruty/php-environment | c3abd515ef933c8dcc291ab06ff9f80930c72447 | 70b0c74f51d112818d7607e9f6f4009a733d5188 | |
refs/heads/master | <repo_name>bthomp4/481_TTT_Server<file_sep>/TTT_Game.py
# Game class for the tic tac toe game
class Game(object):
# when constructing a Game object there is an optional paramter for player_first
# if player_first is 1, the player makes the first move, the player is "X"
# if player_first is 0 (default), the computer makes the first move, the computer is "X"
def __init__(self, player_first = 0):
# the board 2-d list holds the game board
self.board = [[" ", " ", " "],[" ", " ", " "],[" ", " ", " "]]
# indicates if the marker to be used by the player and computer
self.player_first = player_first
# if move_count gets to 9 without a winner the game is a draw
self.move_count = 0
# set the marker for the player and computer accordingly
if self.player_first:
self.player_marker = "X"
self.comp_marker = "O"
else:
self.player_marker = "O"
self.comp_marker = "X"
# when invoked AI_move claims the first available space for the computer
# returns True to indicate game over
# return False to indicate continue game
def AI_move(self):
for row in range(len(self.board)):
for col in range(len(self.board[row])):
if self.board[row][col] == " ":
return self.place_move(self.comp_marker, (row, col))
# when invoked player_move claims the space indicated by coordinates
# returns True to indicate game over
# returns False to indicate continue game
def player_move(self, coordinates):
return self.place_move(self.player_marker, coordinates)
# when invoked place_move changes the board to the indicated marker at the indicated coordinates
# return True to indicate game over
# return False to indicate continue game
def place_move(self, marker, coordinates):
self.board[coordinates[0]][coordinates[1]] = marker
return self.check_board(coordinates)
# when invoked print_board prints the information stored in board as a formated tic tac toe board
def print_board(self):
'''
count = 0;
for line in self.board:
for pos in range(len(line)):
print(line[pos], end='')
if pos == 2:
print()
else:
print("|", end='')
if count < 2:
print("_|_|_")
else:
print(" | |")
count += 1
'''
print(self.board_to_str(), end='')
# when invoked board_to_str converts the board into a string and returns the string object
def board_to_str(self):
ret_str = ""
count = 0;
for line in self.board:
for pos in range(len(line)):
ret_str += line[pos]
if pos == 2:
ret_str += "\n"
else:
ret_str += "|"
if count < 2:
ret_str += "_|_|_\n"
else:
ret_str += " | | \n"
count += 1
return ret_str
# when invoked check_coords checks to see if the coordinates are valid for the board
# returns True if the coordinates are valid
# returns False if the coordinates are not valid
def check_coords(self, coordinates):
return self.board[coordinates[0]][coordinates[1]] == " "
# when invoked check_board checks the board to see if there is a winner or stalemate
# checks possible states based on the most recent move
# if there is a winner an appropriate message is printed
# return 1 if there is a winner
# return -1 if there is a stalemate
# return 0 if there is not a winner
def check_board(self, coordinates):
# increment the move count
self.move_count += 1
# flag to indicate win condition
win_flag = 0
# check the row of the most recent move
prev_pos = self.board[coordinates[0]][0]
for i in range(len(self.board[coordinates[0]])-1):
curr_pos = self.board[coordinates[0]][i+1]
if curr_pos != prev_pos:
win_flag = 0
break
else:
win_flag = 1
prev_pos = curr_pos
# check to see if the entire row matched
if win_flag:
# there was a winner
self.print_winner(curr_pos)
return 1
# the row did not have a winner check the column
prev_pos = self.board[0][coordinates[1]]
for i in range(len(self.board[coordinates[1]])-1):
curr_pos = self.board[i+1][coordinates[1]]
if curr_pos != prev_pos:
win_flag = 0
break
else:
win_flag = 1
prev_pos = curr_pos
# check to seee if the entire column matched
if win_flag:
# there was a winner
self.print_winner(curr_pos)
return 1
# the column did not have a winner check to see if the coordinates match a diagonal
if coordinates == (0,0) or coordinates == (1,1) or coordinates == (2,2):
# check to seee if the entire diagonal matched
if self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:
# there was a winner
self.print_winner(curr_pos)
return 1
elif coordinates == (2,0) or coordinates == (1,1) or coordinates == (0,2):
# check to seee if the entire diagonal matched
if self.board[2][0] == self.board[1][1] and self.board[1][1] == self.board[0][2]:
# there was a winner
self.print_winner(curr_pos)
return 1
# there was not a winner check for a draw
for row in self.board:
for col in row:
if col == " ":
# there is still a blank space
return 0
# a blank space was not found there was a draw
print("Stalemate! It could have been worse!")
return -1
def print_winner(self, marker):
# check to see if the winning marker belongs to the computer or player
if self.player_marker == marker:
# the player won
print("Congrats! You won!")
else:
# the computer won
print("You lost! Better luck next time!")
'''
# main to test the class
def main():
print("Lets play Tic Tac Toe!")
input_flag = 1
while (input_flag):
player_first = input("Would you like to go first? Y/n: ")
if isinstance(player_first, str):
player_first.upper()
if player_first == "Y" or player_first == "N":
input_flag = 0
else:
print("Please make a valid selection!")
else:
print("Please make a valid selection!")
if player_first == "Y":
game = Game(1)
moves = 0
else:
game = Game()
game.AI_move()
moves = 1
game_flag = 1
while(game_flag):
game.print_board()
input_flag = 1
while (input_flag):
coor_raw = input("Enter the coordinates for your move seperated by a space (e.g. \"0 2\"): ")
try:
coordinates_raw = coor_raw.split()
coordinates = (int(coordinates_raw[0]), int(coordinates_raw[1]))
if coordinates[0] >= 0 and coordinates[0] <= 2 and coordinates[1] >= 0 and coordinates[1] <= 2:
input_flag = 0
else:
# invalid input
print("Please enter valid coordinates between 0 and 2!")
except TypeError:
print("TypeError: Please enter valid coordinates between 0 and 2!")
if game.player_move(coordinates):
game_flag = 0
moves += 1
if moves == 9:
break
if game.AI_move():
game_flag = 0
moves += 1
if moves == 9:
game_flag = 0
game.print_board()
main()
'''
<file_sep>/TTT_Server.py
# the following code is from "Computer Networking a Top-Down Approach"
# by <NAME> Ross
# this code will be modified for the project's funstionality
'''
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('',serverPort))
print("The server is ready to recieve")
while True:
message, clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.decode().upper()
serverSocket.sendto(modifiedMessage.encode(), clientAddress)
'''
from socket import *
from TTT_Game import Game
import signal
import sys
server_port = 12000
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(('', server_port))
client_dict = dict()
get_coor_str = 'CRDR,Please enter the coordinates for your move sperated by a space (e.g. \"0 2\"): '
print('The server is ready to recieve')
invalid_coor_str = 'INVC,Those coordinates are invalid!\nPlease enter valid coordinates: '
discnt_client_str = 'DCNT,See you again soon!'
discnt_server_str = 'DCNT,Server Disconnected!'
win_str = 'EOG,Congrats! You won!'
loss_str = 'EOG,Sorry you lost! Better luck next time!'
stale_str = 'EOG,Stalemate! Try harder next time!'
err_str = 'ERR,Error message not recieved correctly!'
bad_connect_str = 'BCNT,You are an unregistered client!'
def signal_handler(signal, frame):
print('You pressed Ctrl+C')
# send a disconnect message to all clients
for key in client_dict:
response = discnt_server_str
server_socket.sendto(response.encode(), key)
server_socket.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
while True:
message, current_address = server_socket.recvfrom(2048)
# decode the message
dec_msg = message.decode().split(',')
''' debug print message id'''
print(dec_msg[0])
if current_address not in client_dict:
if dec_msg[0] == 'INIT':
# the message corresponds to a new connect
if dec_msg[1] == '1':
# the player wants to start
game = Game(1)
else:
# the computer starts
game = Game()
# have the computer make the first move
game.AI_move()
client_dict[current_address] = game
response = get_coor_str
board_flag = 1
else:
# the message came from an un-registered client and it was not a new connect message
response = bad_connect_str
board_flag = 0
else:
board_flag = 1
# check the message type
if dec_msg[0] == 'MOVE':
# the message corresponds to a player move
# check to see if the move is valid
coor_raw = dec_msg[1].split()
coordinates = (int(coor_raw[0]), int(coor_raw[1]))
if client_dict[current_address].check_coords(coordinates):
# the coordinates are valid place the move on the board
game_over = client_dict[current_address].player_move(coordinates)
# check to see if the game is over
if game_over:
# the game is over check to see if win or stalemate
if game_over > 0:
# the client won
response = win_str
else:
# there was a stalemate
response = stale_str
else:
# the game is not over yet have the AI make a move
game_over = client_dict[current_address].AI_move()
if game_over:
# the game is over check to see if win or stalemate
if game_over > 0:
# the server won
response = loss_str
else:
# there was a stalemate
response = stale_str
else:
# the game is not over prompt for a new coordinate
response = get_coor_str
else:
# the coordinates are not valid
response = invalid_coor_str
elif dec_msg[0] == 'DCNT':
# The client is discontinuing the game
# remove the client from the client_dict
client_dict.pop(current_address)
response = discnt_client_str
board_flag = 0
else:
# the message does not take the correct form
response = err_str
# the response has been calculated
# check to see if the client is still connected
if board_flag:
# append the game board to the message
response = response + ',' + client_dict[current_address].board_to_str()
# send the response back to the client
server_socket.sendto(response.encode(), current_address)
<file_sep>/TTT_Client.py
# the following code is from "Computer Networking a Top-Down Approach"
# by Kurose and Ross
# this code will be modified for the project's functionality
'''
from socket import *
serverName = '10.0.2.15'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = raw_input('Input lowecase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
clientSocket.close()
'''
from socket import *
import argparse
import signal
import sys
server_port = 12000
client_socket = socket(AF_INET, SOCK_DGRAM)
parser = argparse.ArgumentParser(description='Play Tic Tac Toe with a remote server!')
parser.add_argument('-c', help='indicates the client will go first', action='store_true')
parser.add_argument('-s', dest='server_name', help='specifies the IP of the server, this is required', required=True)
args = parser.parse_args()
game_flag = 1
init_user_str = 'INIT,1'
init_server_str = 'INIT,0'
move_str = 'MOVE'
disconnect_str = 'DCNT'
if args.c:
# the user wants to go first
message = init_user_str
else:
# the server will go first
message = init_server_str
def signal_handler(signal, frame):
print('You pressed Ctrl+C')
message = disconnect_str
client_socket.sendto(message.encode(), (args.server_name, server_port))
client_socket.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# send the message to initilize the game
client_socket.sendto(message.encode(), (args.server_name, server_port))
error_flag = 0
while game_flag:
prev_msg = message
response, server_address = client_socket.recvfrom(2048)
# decode the response
dec_rsp = response.decode().split(',')
# check the response type
if dec_rsp[0] == 'CRDR' or dec_rsp[0] == 'INVC':
# the response indicates the server wants coordinates from the user
# print the current board
print(dec_rsp[2])
# get the coordinates using the prompt string provided by the server
input_flag = 1
while input_flag:
coor_str_raw = input(dec_rsp[1])
coordinates = coor_str_raw.split()
if len(coordinates) < 2:
print("Please use a space!")
elif coordinates[0].isdigit and coordinates[1].isdigit():
# both coordinates are numbers
# check to see if the numbers fall into the correct range
if int(coordinates[0]) >= 0 and int(coordinates[0]) < 3 and int(coordinates[1]) >= 0 and int(coordinates[1]) < 3:
# the coordinates are valid for the range of the board
# send the coordinates in the next message
message = move_str + ',' + coor_str_raw
input_flag = 0
# check to see if the input was not valid
if input_flag:
print("Please enter valid coordinates!")
elif dec_rsp[0] == 'EOG':
# the game is over
# print the current board
print(dec_rsp[2])
# print the end of game message
print(dec_rsp[1])
# send a disconnect message
message = disconnect_str
elif dec_rsp[0] == 'DCNT':
# the server is disconecting
# print the server's disconnect message
print(dec_rsp[1])
game_flag = 0
''' debug print '''
# print('disconnect')
elif dec_rsp[0] == 'ERR':
# the server did not recieve the message correctly
# check to see if there is already an active error message
if error_flag:
# the previous message also failed exit the program
print("Error sending message to server!")
message = disconnect_str
game_flag = 0
error_flag = 2
else:
# this is the first error
# attempt to resend the previous message
message = prev_msg
error_flag = 1
# check to see if the server did not disconnect
if not dec_rsp[0] == 'DCNT':
# send the message
client_socket.sendto(message.encode(), (args.server_name, server_port))
print('Thank you for playing!')
client_socket.close()
| c2cecfa2436f8e7a82b25f01b2ea725de12e2ff2 | [
"Python"
] | 3 | Python | bthomp4/481_TTT_Server | effcc95b86dbbadc5b93af044fa348071b4d6e47 | 6a727ecf416f8b372cb76ea8aff10ba8bd199826 | |
refs/heads/main | <file_sep>//
// RecordTableViewCell.swift
// 1_Test_TableView_CollectionView
//
// Created by 1 on 2020/10/27.
//
import UIKit
class RecordTableViewCell: UITableViewCell {
static var nib: UINib {
return UINib(nibName: "RecordTableViewCell", bundle: Bundle(for: self))
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// RecordTableViewController.swift
// 1_Test_TableView_CollectionView
//
// Created by 1 on 2020/10/27.
//
import UIKit
class RecordTableViewController: UITableViewController {
var recordListInTableView: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(RecordTableViewCell.nib, forCellReuseIdentifier: "RecordTableViewCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recordListInTableView.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tablecell = tableView.dequeueReusableCell(withIdentifier: "RecordTableViewCell", for: indexPath) as! RecordTableViewCell
tablecell.textLabel?.text = recordListInTableView[indexPath.row]
return tablecell
}
}
<file_sep>//
// ViewController.swift
// Test_Collection
//
// Created by 1 on 2020/10/28.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource {
var mycollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
makeMyCollectionView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
mycollectionView.collectionViewLayout.invalidateLayout()
}
func makeMyCollectionView() {
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
// section與 section 之間的距離 (如果只有一個section, 可以想像成 frame)
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
//cell的寬、高
layout.itemSize = CGSize(width: (self.view.frame.size.width - 30) / 2, height: 120)
// 滑動方向為「垂直」的話即「上下」的間距;滑動方向為「平行」則為「左右」的間距
layout.minimumLineSpacing = CGFloat(integerLiteral: 10)
// 滑動方向為「垂直」的話即「左右」的間距;滑動方向為「平行」則為「上下」的間距
layout.minimumInteritemSpacing = CGFloat(integerLiteral: 10)
//滑動方向預設為垂直。注意若設為垂直,則cell的加入方式為由左至右,滿了才會換行;若是水平則由上往下,滿了才會換列
//layout.scrollDirection = UICollectionView.ScrollDirection.vertical
self.mycollectionView = UICollectionView(frame: CGRect(x: 0, y: 10, width: self.view.frame.width, height: self.view.frame.size.height), collectionViewLayout: layout)
self.mycollectionView.dataSource = self
self.mycollectionView.delegate = self
self.mycollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
self.mycollectionView.backgroundColor = UIColor.white
self.view.addSubview(mycollectionView)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.orange :UIColor.brown
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("row: \(indexPath.row)")
}
}
<file_sep>//
// ViewController.swift
// 1_Test_TableView_CollectionView
//
// Created by 1 on 2020/10/27.
//
import UIKit
class ViewController: UIViewController {
//拳型
let rps:[String] = ["paper", "rock", "scissors"]
var winAndLose:[String] = []
// 紀錄陣列
var recordListRps: [String] = []
// 猜拳圖片
@IBOutlet weak var com: UIImageView!
@IBOutlet weak var own: UIImageView!
// 結果
@IBOutlet weak var resultLabel: UILabel!
// 開始猜拳
@IBAction func mora(_ sender: UIButton) {
// 隨機亂數 取出list
let comIndex = Int(arc4random_uniform(UInt32(rps.count)))
let ownIndex = Int(arc4random_uniform(UInt32(rps.count)))
// 顯示圖片
com.image = UIImage(named: rps[comIndex])
own.image = UIImage(named: rps[ownIndex])
checkWinner(ownIndex: ownIndex, comIndex: comIndex)
print(winAndLose)
print(recordListRps)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//判斷
func checkWinner(ownIndex :Int, comIndex: Int){
// 勝負
let checkWinner = (ownIndex, comIndex)
switch checkWinner {
case let (x, y) where x == y:
recordListRps.append("我方:" + rps[ownIndex] + " 電腦:" + rps [comIndex] + " / 結果:平手")
winAndLose.append("平手")
return resultLabel.text! = "平手"
case (0,1):
recordListRps.append("我方:" + rps[ownIndex] + " / 電腦:" + rps [comIndex] + " / 結果:我方勝利")
winAndLose.append("贏")
return resultLabel.text! = "我方勝利"
case (0,2):
recordListRps.append("我方:" + rps[ownIndex] + " / 電腦:" + rps [comIndex] + " / 結果:電腦勝利")
winAndLose.append("輸")
return resultLabel.text! = "電腦勝利"
case (1,0):
recordListRps.append("我方:" + rps[ownIndex] + " / 電腦:" + rps [comIndex] + " / 結果:電腦勝利")
winAndLose.append("輸")
return resultLabel.text! = "電腦勝利"
case (1,2):
recordListRps.append("我方:" + rps[ownIndex] + " / 電腦:" + rps [comIndex] + " / 結果:我方勝利")
winAndLose.append("贏")
return resultLabel.text! = "我方勝利"
case (2,0):
recordListRps.append("我方:" + rps[ownIndex] + " / 電腦:" + rps [comIndex] + " / 結果:我方勝利")
winAndLose.append("贏")
return resultLabel.text! = "我方勝利"
case (2,1):
recordListRps.append("我方:" + rps[ownIndex] + " / 電腦:" + rps [comIndex] + " / 結果:電腦勝利")
winAndLose.append("輸")
return resultLabel.text! = "電腦勝利"
case (_, _):
return
}
}
// 下一頁資訊
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue_rps_to_table" {
let table_VC = segue.destination as! RecordTableViewController
if recordListRps != [] {
table_VC.recordListInTableView = recordListRps
} else {
table_VC.recordListInTableView = ["比賽尚未開始"]
}
}
if segue.identifier == "segue_rps_to_collection"{
let cellection_VC = segue.destination as! CollectionViewController
cellection_VC.imageWinAndLose = winAndLose
}
}
}
<file_sep>//
// CollectionViewCell.swift
// 1_Test_TableView_CollectionView
//
// Created by 1 on 2020/10/28.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
static var nib: UINib {
return UINib(nibName: "CollectionViewCell", bundle: Bundle(for: self))
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 78386e9c8e769812ad25cc3dd5620b67115ff806 | [
"Swift"
] | 5 | Swift | liamwongw/IOS | 20516f028370f19c9917b7d8d770b4c1fbd4b534 | 72b685b089f6a7012c737703dc1b92cd96e5ebd3 | |
refs/heads/master | <file_sep>#ifndef KDTREE_HPP_
#define KDTREE_HPP_
#include <algorithm>
#include <cfloat>
#include <vector>
#include "Point.hpp"
template <size_t D>
class KDTree {
private:
class KDTreeNode {
public:
/* Constructors */
KDTreeNode() : KDTreeNode{0, 0} {}
KDTreeNode(size_t axis) : KDTreeNode{axis, 0} {}
KDTreeNode(size_t axis, double value)
: KDTreeNode{{}, axis, value, nullptr, nullptr} {}
KDTreeNode(size_t axis, Point<D> point)
: KDTreeNode{point, axis, point[axis], nullptr, nullptr} {}
KDTreeNode(const Point<D>& point, size_t axis, double value,
KDTreeNode* left, KDTreeNode* right)
: point_{point},
axis_{axis},
value_{value},
left_{left},
right_{right} {}
/**
* Deep destructor
*/
~KDTreeNode() {
if (left_ != nullptr) delete left_;
if (right_ != nullptr) delete right_;
}
bool isLeaf() const { return left_ == nullptr && right_ == nullptr; }
Point<D> point_;
size_t axis_;
double value_;
KDTreeNode* left_;
KDTreeNode* right_;
};
public:
KDTreeNode* root;
KDTree(std::vector<Point<D>> points) : root{createTree(points, 0)} {}
~KDTree() {
if (root != nullptr) delete root;
}
void deleteNode(KDTreeNode* node) {
if (node != nullptr) delete node;
}
KDTreeNode* createTree(std::vector<Point<D>> points, size_t depth) {
size_t axis = depth % D;
std::sort(points.begin(), points.end(),
[axis](const Point<D>& a, const Point<D>& b) {
return a[axis] < b[axis];
});
if (points.size() == 1) {
return new KDTreeNode{axis, points[0]};
} else if (points.size() < 1) {
return nullptr;
}
size_t middleIndex = points.size() / 2; // For indexing points
int midInc = middleIndex; // For adding to iterator
KDTreeNode* node = new KDTreeNode{axis, points[middleIndex]};
node->left_ =
createTree({points.begin(), points.begin() + midInc}, depth + 1);
node->right_ =
createTree({points.begin() + midInc, points.end()}, depth + 1);
return node;
}
Point<D> nns(const Point<D>& point) {
double infinity = DBL_MAX;
Point<D> nearestNeighbor{};
nnsRecurse(point, root, infinity, nearestNeighbor);
return nearestNeighbor;
}
void nnsRecurse(const Point<D>& point, KDTreeNode* node, double& radius,
Point<D>& nearestNeighbor) {
if (node == nullptr) return;
if (node->isLeaf()) {
double pointsDistance = distance(point, node->point_);
if (radius > pointsDistance) {
radius = pointsDistance;
nearestNeighbor = node->point_;
}
return;
}
if (point[node->axis_] < node->value_) {
nnsRecurse(point, node->left_, radius, nearestNeighbor);
if (radius == DBL_MAX || point[node->axis_] + radius >= node->value_) {
nnsRecurse(point, node->right_, radius, nearestNeighbor);
}
} else {
nnsRecurse(point, node->right_, radius, nearestNeighbor);
if (radius == DBL_MAX || point[node->axis_] - radius < node->value_) {
nnsRecurse(point, node->left_, radius, nearestNeighbor);
}
}
}
};
#endif // KDTREE_HPP_
<file_sep>CXX ?= g++
CXXFLAGS := -g -O3 -std=c++14 -Wall -Wextra -pedantic
LDFLAGS :=
all: main.o NearestNeighbor.o
$(CXX) $(LDFLAGS) main.o NearestNeighbor.o -o main.exe
main.o: main.cpp KDTree.hpp Point.hpp
$(CXX) $(CXXFLAGS) -c main.cpp
NearestNeighbor.o: NearestNeighbor.cpp NearestNeighbor.hpp KDTree.hpp Point.hpp
$(CXX) $(CXXFLAGS) -c NearestNeighbor.cpp
clean:
-rm *.o main.exe
<file_sep>#include "NearestNeighbor.hpp"
#include <chrono>
#include <fstream>
#include <iostream>
#include <stdexcept>
#define DIMENSION 3
#define NUM_POINTS 3e6
void run_tests() {
std::cout << "# of points: " << NUM_POINTS << std::endl;
auto cloud = generate_point_cloud<DIMENSION>(NUM_POINTS, {-100.0, 100.0});
auto point = random_point<DIMENSION>({-100.0, 100.0});
std::cout << "---------- Brute Force Method ---------- " << std::endl;
auto v = makeDecorator(brute_force<DIMENSION>)(point, cloud, 1);
std::cout << "Closest points to " << point << std::endl;
for (auto e : v) {
std::cout << e << std::endl;
std::cout << "Distance: " << distance(point, e) << std::endl;
}
std::cout << "---------- KD-Tree Method ---------- " << std::endl;
std::cout << "> Constructing tree..." << std::endl;
auto kdTree = makeDecorator(initialize_kd_tree<DIMENSION>)(cloud);
std::cout << "> Running NNS algorithm..." << std::endl;
auto nearestNeighbor = makeDecorator(kd_tree_nns<DIMENSION>)(point, kdTree);
std::cout << "Closest point to " << point << std::endl;
std::cout << nearestNeighbor << std::endl;
std::cout << "Distance: " << distance(point, nearestNeighbor) << std::endl;
std::ofstream file{"results.csv"};
if (!file.is_open()) throw std::runtime_error{"Unable to open file"};
file << "Points,Construction Time (ns),NNS Time (ns)" << std::endl;
file << std::fixed;
for (int i = 0; i < 8; i++) {
std::cout << "10^" << i << " points" << std::endl;
cloud = generate_point_cloud<DIMENSION>(pow(10, i), {-100.0, 100.0});
point = random_point<DIMENSION>({-100.0, 100.0});
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
initialize_kd_tree<DIMENSION>(cloud);
end = std::chrono::system_clock::now();
std::chrono::nanoseconds kd_time = end - start;
start = std::chrono::system_clock::now();
kd_tree_nns<DIMENSION>(point, kdTree);
end = std::chrono::system_clock::now();
std::chrono::nanoseconds nns_time = end - start;
file << static_cast<int>(pow(10, i)) << "," << kd_time.count() << ","
<< nns_time.count() << std::endl;
}
}
<file_sep># cs375-final-project
CS 375 Final Project - Nearest Neighbor
<file_sep>#include <vector>
#include "KDTree.hpp"
#include "NearestNeighbor.hpp"
#include "Point.hpp"
int main() {
run_tests();
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.2 FATAL_ERROR)
project(NearestNeighbor)
set(CMAKE_BUILD_TYPE Release)
## C++11 support
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
## Increase warning levels
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
endif()
add_executable(main.exe main.cpp NearestNeighbor.cpp)
target_compile_features(main.exe PRIVATE
cxx_aggregate_default_initializers
cxx_lambdas
cxx_nullptr
cxx_auto_type
cxx_generalized_initializers
cxx_range_for
cxx_uniform_initialization
cxx_delegating_constructors)
<file_sep>#ifndef NEARESTNEIGHBOR_HPP_
#define NEARESTNEIGHBOR_HPP_
#include <algorithm>
#include <chrono>
#include <functional>
#include <random>
#include <utility>
#include <vector>
#include "KDTree.hpp"
static std::random_device rand_dev;
template <typename>
struct Decorator;
void run_tests();
/*
* For creating a single point.
* Not used in generate_point_cloud because of efficiency
*/
template <size_t D>
Point<D> random_point(const std::pair<double, double>& range) {
std::default_random_engine e1(rand_dev());
std::uniform_real_distribution<double> uniform_dist{range.first,
range.second};
std::array<double, D> components;
for (size_t j = 0; j < D; j++) {
components[j] = uniform_dist(e1);
}
return Point<D>{components};
}
template <size_t D>
std::vector<Point<D>> generate_point_cloud(
size_t number, const std::pair<double, double>& range) {
std::default_random_engine e1(rand_dev());
std::uniform_real_distribution<double> uniform_dist{range.first,
range.second};
std::vector<Point<D>> ret;
for (size_t i = 0; i < number; i++) {
std::array<double, D> components;
for (size_t j = 0; j < D; j++) {
components[j] = uniform_dist(e1);
}
ret.emplace_back(components);
}
return ret;
}
template <size_t D>
std::vector<Point<D>> brute_force(const Point<D>& point,
std::vector<Point<D>> neighbors, size_t num) {
std::vector<Point<D>> nearest;
for (size_t i = 0; i < num; i++) {
auto neighbor =
std::min_element(neighbors.begin(), neighbors.end(),
[point](const Point<D>& lhs, const Point<D>& rhs) {
return distance(point, lhs) < distance(point, rhs);
});
nearest.push_back(*neighbor);
neighbors.erase(neighbor);
}
return nearest;
}
template <size_t D>
Point<D> kd_tree_nns(const Point<D>& point, KDTree<D>& kdTree) {
return kdTree.nns(point);
}
template <size_t D>
KDTree<D> initialize_kd_tree(const std::vector<Point<D>>& neighbors) {
return KDTree<D>{neighbors};
}
template <size_t D>
Point<D> kd_nearest_neighbor(const Point<D>& point, const KDTree<D>& kdTree) {
Point<D> nearestNeighbor = kd_tree_nns(point, kdTree);
return nearestNeighbor;
}
/* http://stackoverflow.com/questions/30679445/python-like-c-decorators */
template <typename R, typename... Args>
struct Decorator<R(Args...)> {
Decorator(std::function<R(Args...)> f) : f_(f) {}
R operator()(Args... args) {
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
R ret = f_(args...);
end = std::chrono::system_clock::now();
std::chrono::nanoseconds elapsed_nanos =
std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
std::cout << "Execution took " << elapsed_nanos.count() << "ns"
<< std::endl;
return ret;
}
std::function<R(Args...)> f_;
};
template <typename R, typename... Args>
Decorator<R(Args...)> makeDecorator(R (*f)(Args...)) {
return Decorator<R(Args...)>(std::function<R(Args...)>(f));
}
#endif // NEARESTNEIGHBOR_HPP_
| 9cf592b5bc876b87d7bd12228869d8543fd2a38b | [
"Markdown",
"CMake",
"Makefile",
"C++"
] | 7 | C++ | rukumar333/cs375-final-project | b825ef2c2f29ab9d6c8499f5b95eaf7749de050d | 962a973c54b09ff041b7c163f6488c2fbfe22749 | |
refs/heads/master | <file_sep><?php
namespace Mebel\Model;
class Transaction
{
public $id;
public $type;
public $description;
public $material;
public $quantity;
public $sum;
public $tarif;
public $isWholesale;
public $isIncome;
public function exchangeArray($data)
{
$this->id = (!is_null($data['id'])) ? $data['id'] : null;
$this->type = (!is_null($data['type'])) ? $data['type'] : null;
$this->description = (!is_null($data['description'])) ? $data['description'] : null;
$this->material = (!is_null($data['material'])) ? $data['material'] : null;
$this->quantity = (!is_null($data['quantity'])) ? $data['quantity'] : null;
$this->sum = (!empty($data['sum'])) ? $data['sum'] : 0;
$this->tarif = (!empty($data['tarif'])) ? $data['tarif'] : 0;
$this->isWholesale = (!is_null($data['isWholesale'])) ? $data['isWholesale'] : null;
$this->isIncome = (!is_null($data['isIncome'])) ? $data['isIncome'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}<file_sep><?php
namespace Mebel\Model;
class Worker
{
public $id;
public $fio;
public $description;
public $phone;
public $address;
public function exchangeArray($data)
{
$this->id = (!is_null($data['id'])) ? $data['id'] : null;
$this->fio = (!is_null($data['fio'])) ? $data['fio'] : null;
$this->description = (!is_null($data['description'])) ? $data['description'] : null;
$this->phone = (!is_null($data['phone'])) ? $data['phone'] : null;
$this->address = (!is_null($data['address'])) ? $data['address'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}<file_sep>CREATE TABLE `material` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`type` VARCHAR(50) NOT NULL,
`name` VARCHAR(255) DEFAULT NULL,
`description` TEXT,
`wholesale` FLOAT NOT NULL DEFAULT 0,
`retail` FLOAT NOT NULL DEFAULT 0,
`count` INT(11) NOT NULL DEFAULT 0,
`image` VARCHAR(255) DEFAULT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8<file_sep><?php
namespace Mebel\Model;
class Rate
{
public $id;
public $description;
public $payment;
public $amount;
public $metrik;
public function exchangeArray($data)
{
$this->id = (!is_null($data['id'])) ? $data['id'] : null;
$this->description = (!is_null($data['description'])) ? $data['description'] : null;
$this->payment = (!is_null($data['payment'])) ? $data['payment'] : 0;
$this->amount = (!is_null($data['amount'])) ? $data['amount'] : 0;
$this->metrik = (!is_null($data['metrik'])) ? $data['metrik'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}<file_sep><?php
namespace Mebel\Controller;
use Mebel\Form\WorkerForm;
use Mebel\Model\Worker;
use Mebel\Model\WorkerTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
class WorkerController extends AbstractActionController
{
protected $workerTable;
public function indexAction()
{
if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
$view = new ViewModel(array(
'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
));
return $view;
}
public function ajaxAction(){
$request = $this->getRequest();
$current = $request->getPost('current', 1); ;
$rowCount = $request->getPost('rowCount', 10);
$sort = $request->getPost('sort');
$sortField = key($sort);
$sortType = $sort[$sortField];
$searchPhrase = $request->getPost('searchPhrase');
$offset = intval($rowCount) * (intval($current)-1);
$workers= $this->getWorkerTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase);
$count= $this->getWorkerTable()->getCount();
return new JsonModel(array(
'current' => intval($current),
'rowCount' => intval($rowCount),
'rows' => $workers->toArray(),
"total"=> $count,
));
}
public function deleteAction()
{
$id = (int)$this->params()->fromRoute('id');
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Удалить') {
$id = (int)$request->getPost('id');
$this->getWorkerTable()->deleteWorker($id);
}
return $this->redirect()->toRoute('worker');
}
$worker = $this->getWorkerTable()->getWorker($id);
$view = new ViewModel([
'id' => $worker->id,
'title' => 'Өшіру '.$worker->fio,
'description' => $worker->fio,
'url' => $this->url()->fromRoute('worker',['action' => 'delete', 'id' => $worker->id])
]
);
$view->setTemplate('mebel/admin/delete.phtml');
return $view;
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if($id){
$worker = $this->getWorkerTable()->getWorker($id);
}
else
$worker = new Worker();
$form = new WorkerForm();
$form->bind($worker);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getWorkerTable()->saveWorker($worker);
$this->flashMessenger()->addSuccessMessage('Сәтті сақталды');
if(empty($id))
$id = $this->getWorkerTable()->insertedWorker();
$this->redirect()->toRoute('worker', ['action' => 'edit', 'id' => $id]);
}else {
$this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
$form->highlightErrorElements();
}
}
$view = new ViewModel([
'form' => $form,
'id' => $id,
]);
return $view;
}
/**
* @return WorkerTable
*/
public function getWorkerTable()
{
if (!$this->workerTable) {
$sm = $this->getServiceLocator();
$this->workerTable = $sm->get('WorkerTable');
}
return $this->workerTable;
}
}<file_sep>function load_prices() {
clear();
if ($('select[name=material]').val() > 0) {
$.ajax({
url: '/material/' + $('input[name=type]').val() + '/one/' + $('select[name=material]').val(),
type: 'POST',
dataType: 'json',
async: true,
data: {},
success: function (data) {
if (data) {
if ($('input[name=isIncome]').val() == 0) {
if ($('input[name=quantity]').val() > parseInt(data.count)) {
alert('Количество не может быть больше остатка материала!');
$('input[name=quantity]').val(data.count);
$('input[name=quantity]').attr('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);')
}
if ($('input[name=isWholesale]').is(":checked")) {
$('input[name=tarif]').val(data.wholesale);
} else {
$('input[name=tarif]').val(data.retail);
}
}
if ($('input[name=quantity]').val() > 0) {
$('input[name=sum]').val($('input[name=tarif]').val() * $('input[name=quantity]').val());
} else {
$('input[name=sum]').val(0);
}
}
},
error: function (data) {
clear();
console.log(data);
}
});
} else {
clear();
}
}
function clear() {
if ($('input[name=isIncome]').val() == 0) {
$('input[name=tarif]').val(0);
}
$('input[name=sum]').val(0);
}
$(document).ready(function() {
$("select[name=material]").select2({
placeholder: "Материал таңдаңыз",
allowClear: true,
language: "ru"
});
});
<file_sep>$(function () {
handleaction();
var timestamp = Date.parse($('input[name=workdate]').val())
if (isNaN(timestamp) == true) {
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
$('input[name=workdate]').attr("value", today);
}
$("select[name='rate[]']").multiselect({
buttonWidth: '100%',
onChange: add_workdones
});
});
function load_rate(rateId) {
if (rateId > 0) {
$.ajax({
url: '/rate/one/' + rateId,
type: 'POST',
dataType: 'json',
async: true,
data: {},
success: function (data) {
if (data) {
$("input[name='workdones["+rateId+"][rate]']").val(rateId);
$("input[name='workdones["+rateId+"][metrik]']").val(data.metrik);
$("input[name='workdones["+rateId+"][rateamount]']").val(parseFloat(data.amount));
$("input[name='workdones["+rateId+"][ratepayment]']").val(parseFloat(data.payment));
$amount = $("input[name='workdones["+rateId+"][amount]']").val();
$payment = data.payment * ($amount / data.amount);
$("input[name='[workdones"+rateId+"][payment]']").val($payment);
}
},
error: function (data) {
console.log(data);
}
});
}
}
function recaluculate(){
$('input[name=total]').val(0);
$("input[name$='[payment]']").each(function() {
var total = $('input[name=total]').val();
$('input[name=total]').val(Number($( this ).val()) + Number(total));
});
}
function add_workdones(option, checked, select) {
/*alert('Changed option ' + $(option).text() + '.');
var currentCount = $('#workdonesDiv> fieldset').length;*/
recaluculate();
$('#panel' + option.val()).remove();
$('#panel0').remove();
if (checked === true) {
var template = $('#workdonesDiv> span').data('template');
template = template.replace(/__workdones_count__/g, option.val());
$('#workdonesDiv').append(template);
$('.title' + option.val()).html('<b>' + $(option).text() + '</b>');
$("input[name='workdones["+$(option).val()+"][name]']").val($(option).text());
handleaction();
load_rate( option.val());
}
return false;
}
function handleaction(){
$("input[name$='[amount]']").tooltip({ placement: "left",trigger: "hover"});
$("input[name$='[payment]']").tooltip({ placement: "left",trigger: "hover"});
$("input[name$='[amount]']").change(function(){
$amount = $(this).val();
$rateamount = $(this).siblings("input[name$='[rateamount]']").val();
$ratepayment = $(this).siblings("input[name$='[ratepayment]']").val();
$payment = $ratepayment * ($amount / $rateamount);
$(this).siblings("input[name$='[payment]']").val($payment);
recaluculate();
});
}
<file_sep><?php
namespace Mebel\Form;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory;
class MaterialForm extends Form
{
protected $adapter;
public function __construct($type, $transactionCount)
{
parent::__construct('material');
$inputFilter = new InputFilter();
$factory = new Factory();
$this->add([
'name' => 'id',
'type' => 'Hidden',
]);
$this->add([
'name' => 'type',
'type' => 'Hidden',
'attributes' => [
'value' => $type,
],
'haystack' => ['ldsp','dvp','pvh','stol', 'mdf'],
]);
$inputFilter->add($factory->createInput([
'name' => 'type',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
new \Zend\Validator\InArray(
['haystack' => ['ldsp', 'dvp', 'pvh', 'stol', 'mdf']]
),
],
]));
$this->add([
'name' => 'image',
'required' => false,
'type' => 'File',
'attributes' => [],
'options' => [
'label' => 'Фото',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$this->add([
'name' => 'name',
'required' => true,
'type' => 'Text',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Наименование',
'required' => 'true'
],
'options' => [
'label' => 'Наименование',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'name',
'required' => false,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
]));
$this->add([
'name' => 'description',
'required' => true,
'type' => 'Textarea',
'attributes' => [
'class' => 'form-control',
'style' => 'width:100%',
'rows' => '3',
'placeholder' => 'Описание',
],
'options' => [
'label' => 'Описание',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'description',
'required' => false,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
]));
if($type!='pvh') {
$this->add([
'name' => 'wholesale',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Оптовая цена',
'required' => 'true',
'min' => '0',
'step' => '1'
],
'options' => [
'label' => 'Оптовая цена',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
}
$this->add([
'name' => 'retail',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Рознечная цена',
'min' => '0',
'step' => '1'
],
'options' => [
'label' => 'Рознечная цена',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$countParams = [
'name' => 'count',
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => $type!='pvh'?'Количество(Остаток на складе)':'Метр(на складе)',
'min' => '0',
'step' => '1'
],
'options' => [
'label' => $type!='pvh'?'Количество':'Метр',
'label_attributes' => ['class' => 'control-label col-md-2']
],
];
if($transactionCount==0) {
$countParams['required'] = true;
}
$this->add($countParams);
$inputFilter->add($factory->createInput([
'name' => 'count',
'required' => $transactionCount==0?true:false,
]));
/* $this->add([
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf'
));*/
$this->add([
'name' => 'submit',
'type' => 'Submit',
'attributes' => [
'value' => 'Сақтау',
'id' => 'submitbutton',
'class' => 'btn btn-success pull-right'
],
]);
$this->setInputFilter($inputFilter);
}
public function highlightErrorElements()
{
foreach ($this->getElements() as $element) {
if ($element->getMessages()) {
$element->setAttribute('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);');
$element->setLabelAttributes([
'class' => 'control-label col-md-2',
'style' => 'color:#a94442']);
}
}
}
}<file_sep>CREATE TABLE `account` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`password` VARCHAR(255) NOT NULL,
`fio` VARCHAR(255) NOT NULL,
`phone` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`address` TEXT,
`role` VARCHAR(255) NOT NULL DEFAULT 'user',
PRIMARY KEY (`id`)
)
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARSET = utf8;
INSERT INTO account (ID, PASSWORD, FIO, PHONE, EMAIL, ROLE)
VALUES (1, 'admin', 'Admin', '<PASSWORD>', 'admin', 'admin');
<file_sep><?php
namespace Mebel\Model;
class Work
{
public $id;
public $worker;
public $total;
public $workdate;
public $workdones;
public function exchangeArray($data)
{
$this->id = (!is_null($data['id'])) ? $data['id'] : null;
$this->worker = (!is_null($data['worker'])) ? $data['worker'] : null;
$this->total = (!is_null($data['total'])) ? $data['total'] : 0;
$this->workdate = (!is_null($data['workdate'])) ? $data['workdate'] : null;
$this->workdones = (isset($data['workdones'])) ? $data['workdones'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
/**
* @return mixed
*/
public function getWorkdones()
{
return $this->workdones;
}
/**
* @param mixed $workdones
*/
public function setWorkdones($workdones)
{
$this->workdones = $workdones;
}
}<file_sep><?php
namespace Mebel\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class WorkerTable
{
protected $tableGateway;
public static $tableName = 'worker';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function fetchPage($rowCount, $offset, $orderby, $searchPhrase)
{
$sql = new Sql($this->tableGateway->adapter);
$select = $sql->select();
$select->from($this->tableGateway->table);
$select->columns(['*']);
if ($rowCount < 0)
$select->offset(0);
else
$select->limit($rowCount)->offset($offset);
$select->order($orderby);
$select->order('date desc');
if ($searchPhrase) {
$select->where->NEST->like('fio', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('phone', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('address', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('date', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->UNNEST;
}
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet;
}
public function getCount()
{
$resultSet = $this->tableGateway->select();
return $resultSet->count();
}
public function getWorker($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveWorker(Worker $worker)
{
$data = array(
'fio' => $worker->fio,
'description' => $worker->description,
'phone' => $worker->phone,
'address' => $worker->address,
);
$id = (int)$worker->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getWorker($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Worker_id does not exist');
}
}
}
public function deleteWorker($id)
{
$this->tableGateway->delete(array('id' => (int)$id));
}
public function insertedWorker()
{
return $this->tableGateway->lastInsertValue;
}
}<file_sep><?php
namespace Mebel\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
class WorkdoneTable
{
protected $tableGateway;
public static $tableName = 'workdone';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function getWorkdoneByWorkId($workId)
{
$workId = (int) $workId;
$rowset = $this->tableGateway->select(['work' => $workId]);
return $rowset;
}
public function getCount()
{
$resultSet = $this->tableGateway->select();
return $resultSet->count();
}
public function getWorkdone($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveWorkdone(Workdone $workdone)
{
$data = array(
'work' => $workdone->work,
'payment' => $workdone->payment,
'rateamount' => $workdone->rateamount,
'ratepayment' => $workdone->ratepayment,
'amount' => $workdone->amount,
'name' => $workdone->name,
'metrik' => $workdone->metrik,
);
$id = (int)$workdone->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getWorkdone($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Workdone_id does not exist');
}
}
}
public function deleteWorkdone($id)
{
$this->tableGateway->delete(array('id' => (int)$id));
}
public function insertedWorkdone()
{
return $this->tableGateway->lastInsertValue;
}
}<file_sep><?php
namespace Mebel\Form;
use Mebel\Model\Workdone;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
class WorkdoneFieldset extends Fieldset implements InputFilterProviderInterface
{
public static $span = "<span data-template='
<div class=\"panel panel-default\" id=\"panel__workdones_count__\">
<div class=\"panel-heading\">
<h4 class=\"panel-title\">
<a data-toggle=\"collapse\" data-target=\"#rate__workdones_count__\"
href=\"#rate__workdones_count__\" class=\"collapsed title__workdones_count__\">
</a>
</h4>
</div>
<div id=\"rate__workdones_count__\" class=\"panel-collapse collapse in\">
<div class=\"panel-body\">
<fieldset>
<input type=\"hidden\" name=\"workdones[__workdones_count__][id]\" value=\"\">
<input type=\"hidden\" name=\"workdones[__workdones_count__][work]\" value=\"\">
<input type=\"hidden\" name=\"workdones[__workdones_count__][rate]\" value=\"\">
<input type=\"hidden\" name=\"workdones[__workdones_count__][name]\" value=\"\">
<input data-toggle=\"tooltip\" title=\"Жұмыс көлемі\" type=\"number\" name=\"workdones[__workdones_count__][amount]\" class=\"form-control\"
placeholder=\"Жұмыс көлемі\" min=\"0\" step=\"1\"value=\"\">
<input data-toggle=\"tooltip\" title=\"Жұмыс төлемі(тенге)\" type=\"number\" name=\"workdones[__workdones_count__][payment]\" class=\"form-control\"
placeholder=\"Жұмыс төлемі(тенге)\" min=\"0\" step=\"1\" readonly=\"readonly\" value=\"\">
<input type=\"hidden\" name=\"workdones[__workdones_count__][ratepayment]\" value=\"\">
<input type=\"hidden\" name=\"workdones[__workdones_count__][rateamount]\" value=\"\">
<input type=\"hidden\" name=\"workdones[__workdones_count__][metrik]\" value=\"\">
</fieldset>
</div>
</div>
</div>
'></span>";
public function __construct()
{
parent::__construct('workdones');
$this
->setHydrator(new ClassMethodsHydrator(false))
->setObject(new Workdone());
$this->add([
'name' => 'id',
'type' => 'Hidden',
]);
$this->add([
'name' => 'work',
'type' => 'Hidden',
]);
$this->add([
'name' => 'rate',
'type' => 'Hidden',
]);
$this->add([
'name' => 'name',
'type' => 'Hidden',
]);
$this->add([
'name' => 'payment',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Жұмыс төлемі(тенге)',
'min' => '0',
'step' => '0.01',
'readonly' => 'readonly'
],
'options' => [
'label' => 'Жұмыс төлемі(тенге)',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$this->add([
'name' => 'amount',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Жұмыс көлемі',
'min' => '0',
'step' => '0.01',
],
'options' => [
'label' => 'Жұмыс көлемі',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$this->add([
'name' => 'ratepayment',
'type' => 'Hidden',
]);
$this->add([
'name' => 'rateamount',
'type' => 'Hidden',
]);
$this->add([
'name' => 'metrik',
'type' => 'Hidden',
]);
/* $this->add([
'name' => 'ratepayment',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'тарифтік толем',
'min' => '0',
'step' => '0.01',
'readonly' => 'readonly'
],
'options' => [
'label' => 'Тарифтік жұмыс төлемі(тенге)',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$this->add([
'name' => 'rateamount',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'тарифтік көлемі',
'min' => '0',
'step' => '0.01',
'readonly' => 'readonly'
],
'options' => [
'label' => 'Тарифтік жұмыс көлемі',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$this->add([
'name' => 'metrik',
'required' => true,
'type' => 'Text',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Измерение(метр/штук)',
'required' => 'true',
'readonly' => 'readonly'
],
'options' => [
'label' => 'Измерение(метр/штук)',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);*/
}
/**
* @return array
*/
public function getInputFilterSpecification()
{
return [
[
'name' => 'name',
'required' => true,
],
[
'name' => 'rateamount',
'required' => true,
],
[
'name' => 'ratepayment',
'required' => true,
],
[
'name' => 'amount',
'required' => true,
],
[
'name' => 'payment',
'required' => true,
],
[
'name' => 'metrik',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
]
];
}
}<file_sep>CREATE TABLE `worker` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fio` VARCHAR(255) NOT NULL,
`description` TEXT,
`phone` VARCHAR(255) NULL,
`address` TEXT,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;
<file_sep><?php
namespace Mebel\Form;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory;
class TransactionForm extends Form
{
protected $adapter;
public function __construct(AdapterInterface $dbAdapter, $type, $config)
{
$this->adapter =$dbAdapter;
parent::__construct('transaction');
$inputFilter = new InputFilter();
$factory = new Factory();
$this->add([
'name' => 'id',
'type' => 'Hidden',
]);
$this->add([
'name' => 'type',
'type' => 'Hidden',
'attributes' => [
'value' => $type,
],
'haystack' => ['ldsp','dvp','pvh','stol'],
]);
$inputFilter->add($factory->createInput([
'name' => 'type',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
new \Zend\Validator\InArray(
['haystack' => ['ldsp', 'dvp', 'pvh', 'stol', 'mdf']]
),
],
]));
$this->add([
'name' => 'isIncome',
'type' => 'Hidden',
]);
$inputFilter->add($factory->createInput([
'name' => 'isIncome',
'required' => true,
]));
$this->add([
'name' => 'description',
'required' => true,
'type' => 'Textarea',
'attributes' => [
'class' => 'form-control',
'style' => 'width:100%',
'rows' => '3',
'placeholder' => 'Описание',
],
'options' => [
'label' => 'Описание',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'description',
'required' => false,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
]));
$this->add(array(
'name' => 'material',
'type' => 'Select',
'attributes' => array(
'class' => 'form-control',
'required' => 'required',
'onchange' => 'load_prices();'
),
'options' => array(
'label' => 'Материал ('.$config['menu'][$type].')',
'label_attributes' => ['class' => 'control-label col-md-2'],
'empty_option' => 'Материал таңдаңыз',
'value_options' => $this->getMaterial($type),
),
));
$inputFilter->add($factory->createInput([
'name' => 'material',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
]));
$this->add([
'name' => 'quantity',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Саны',
'required' => 'true',
'min' => '0',
'step' => '1',
'onchange' => 'load_prices();'
],
'options' => [
'label' => 'Саны',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'quantity',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
]));
$this->add([
'name' => 'sum',
'required' => true,
'type' => 'Number',
'attributes' => [
'readonly' => 'true',
'class' => 'form-control',
'placeholder' => 'Сумма',
'min' => '0',
'step' => '1'
],
'options' => [
'label' => 'Сумма',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'sum',
'required' => false,
]));
$this->add([
'name' => 'tarif',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Тариф',
'min' => '0',
'step' => '1',
'onchange' => 'load_prices();'
],
'options' => [
'label' => 'Тариф',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'tarif',
'required' => false,
]));
$this->add([
'name' => 'isWholesale',
'type' => 'Checkbox',
'attributes' => [
'value' => 0,
'onchange' => 'load_prices();'
],
'options' => [
'label' => 'Оптовая продажа',
'label_attributes' => ['class' => 'control-label col-md-2'],
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 0
],
]);
/* $this->add([
'name' => 'isIncome',
'type' => 'Checkbox',
'attributes' => [
'value' => 0
],
'options' => [
'label' => 'Кіріс',
'label_attributes' => ['class' => 'control-label col-md-2'],
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 0
],
]);*/
/* $this->add([
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf'
));*/
$this->add([
'name' => 'confirm',
'type' => 'Submit',
'attributes' => [
'value' => 'Потвердить',
'id' => 'submitbutton',
'class' => 'btn btn-success pull-right'
],
]);
$this->add([
'name' => 'save',
'type' => 'Submit',
'attributes' => [
'value' => 'Сохранить',
'id' => 'submitbutton',
'class' => 'btn btn-primary pull-right'
],
]);
$this->add([
'name' => 'edit',
'type' => 'Submit',
'attributes' => [
'value' => 'Редактировать',
'id' => 'submitbutton',
'class' => 'btn btn-warning pull-right',
'style' => 'margin-right:10px'
],
]);
$this->setInputFilter($inputFilter);
}
public function getMaterial($type)
{
$dbAdapter = $this->adapter;
$sql = "SELECT id, name, count FROM material WHERE type='".$type."' ORDER BY id ASC";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = [];
foreach ($result as $res) {
$selectData[$res['id']] = $res['name'].'(складта '.$res['count'].' қалды)';
}
return $selectData;
}
public function highlightErrorElements()
{
foreach ($this->getElements() as $element) {
if ($element->getMessages()) {
$element->setAttribute('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);');
$element->setLabelAttributes([
'class' => 'control-label col-md-2',
'style' => 'color:#a94442']);
}
}
}
}<file_sep>CREATE TABLE `workdone` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`work` INT(10) UNSIGNED NOT NULL,
`name` TEXT,
`ratepayment` FLOAT NOT NULL,
`rateamount` FLOAT NOT NULL,
`payment` FLOAT NOT NULL DEFAULT 0,
`amount` FLOAT NOT NULL DEFAULT 0,
`metrik` VARCHAR(255) NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `FK1_work` (`work`),
CONSTRAINT `FK1_work` FOREIGN KEY (`work`) REFERENCES `work` (`id`)
ON UPDATE CASCADE
ON DELETE CASCADE
)
ENGINE = InnoDB;
<file_sep><?php
return array(
'menu' => [
'all' => 'Все материалы',
'ldsp' => 'ЛДСП',
'mdf' => 'МДФ акрель',
'dvp' => 'ДВП',
'pvh' => 'ПВХ',
'stol' => 'Столешница',
],
'sale' => [
0 => 'Рознечная продажа',
1 => 'Оптовая продажа',
],
'come' => [
0 => 'Шығыс',
1 => 'Кіріс',
],
'controllers' => array(
'invokables' => array(
'Mebel\Controller\Admin' => 'Mebel\Controller\AdminController',
'Mebel\Controller\Material' => 'Mebel\Controller\MaterialController',
'Mebel\Controller\Transaction' => 'Mebel\Controller\TransactionController',
'Mebel\Controller\Worker' => 'Mebel\Controller\WorkerController',
'Mebel\Controller\Rate' => 'Mebel\Controller\RateController',
'Mebel\Controller\Work' => 'Mebel\Controller\WorkController',
)
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'segment',
'options' => array(
'route' => '/[:action]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Admin',
'action' => 'index',
),
),
),
'material' => array(
'type' => 'segment',
'options' => array(
'route' => '/material[/:type][/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Material',
'action' => 'index',
),
),
),
'transaction' => array(
'type' => 'segment',
'options' => array(
'route' => '/transaction[/:type][/:action][/:id][?direction=:direction]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Transaction',
'action' => 'index',
),
),
),
'worker' => array(
'type' => 'segment',
'options' => array(
'route' => '/worker[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Worker',
'action' => 'index',
),
),
),
'rate' => array(
'type' => 'segment',
'options' => array(
'route' => '/rate[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Rate',
'action' => 'index',
),
),
),
'work' => array(
'type' => 'segment',
'options' => array(
'route' => '/work[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Work',
'action' => 'index',
),
),
),
'report' => array(
'type' => 'segment',
'options' => array(
'route' => '/report[/:action]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Report',
'action' => 'index',
),
),
),
'login' => array(
'type' => 'Literal',
'options' => array(
'route' => '/login',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Admin',
'action' => 'login',
),
),
),
'authenticate' => array(
'type' => 'Literal',
'options' => array(
'route' => '/authenticate',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Admin',
'action' => 'authenticate',
),
),
),
'logout' => array(
'type' => 'Literal',
'options' => array(
'route' => '/logout',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mebel\Controller\Admin',
'action' => 'logout',
),
),
),
'admin' => array(
'type' => 'segment',
'options' => array(
'route' => '/admin/setting/[:action][/:id][?[page=:page]]',
'defaults' => array(
'controller' => 'Mebel\Controller\Admin',
'action' => 'admin',
),
),
),
),
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'aliases' => array(
'translator' => 'MvcTranslator',
'Zend\Authentication\AuthenticationService' => 'AuthService',
),
),
'translator' => array(
'locale' => 'ru_RU',
'available' => array(
'kz_KZ' => 'Kazakh',
'ru_RU' => 'Russian',
),
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
'strategies' => array(
'ViewJsonStrategy'
),
),
// Placeholder for console routes
'console' => array(
'router' => array(
'routes' => array(
'sendmail' => [
'options' => [
'route' => 'sendmail',
'defaults' => [
'controller' => 'Mebel\Admin\Console',
'action' => 'sendMail',
],
],
],
),
),
),
);<file_sep>CREATE TABLE `work` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`worker` INT(10) UNSIGNED NOT NULL,
`total` FLOAT NOT NULL DEFAULT 0,
`workdate` DATE NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `FK1_worker` (`worker`),
CONSTRAINT `FK1_worker` FOREIGN KEY (`worker`) REFERENCES `worker` (`id`)
ON UPDATE CASCADE
ON DELETE CASCADE
)
ENGINE = InnoDB;
<file_sep><?php
namespace Mebel\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class TransactionTable
{
protected $tableGateway;
public static $tableName = 'transaction';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function countByMaterial($material)
{
return $this->tableGateway->select(['material' => $material])->count();
}
public function fetchPage($rowCount, $offset, $orderby, $searchPhrase, $type, $direction)
{
$sql = new Sql($this->tableGateway->adapter);
$select = $sql->select();
$select->from($this->tableGateway->table);
$select->columns([
'*',
new Expression("CASE isWholesale WHEN 0 THEN 'рознечная' WHEN 1 THEN 'оптовая' END as saleStr"),
new Expression("CASE isIncome WHEN 0 THEN 'шығыс' WHEN 1 THEN 'кіріс' END as comeStr"),
new Expression('material.name as materialStr'),
new Expression("DATE_FORMAT(transaction.date, '%Y-%m-%d') as dateStr"),
new Expression("DATE_FORMAT(transaction.date,'%H:%i:%s') as timeStr"),
]);
$select->join('material', 'material.id = transaction.material', ['name'], Select::JOIN_LEFT);
if ($rowCount < 0)
$select->offset(0);
else
$select->limit($rowCount)->offset($offset);
$select->order($orderby);
$select->order('date desc');
if ($searchPhrase) {
$select->where->NEST->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('quantity', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('sum', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('tarif', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('date', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->UNNEST;
}
if($type != 'all') {
$select->where->equalTo('transaction.type', $type);
}
if($direction == 'income') {
$select->where->equalTo('isIncome', 1);
}
if($direction == 'outcome') {
$select->where->equalTo('isIncome', 0);
}
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet;
}
public function getCount($type)
{
if($type!='all') {
$resultSet = $this->tableGateway->select(function (Select $select) use($type) {
$select->where->like('type', $type);
});
} else {
$resultSet = $this->tableGateway->select();
}
return $resultSet->count();
}
public function getTransaction($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveTransaction(Transaction $transaction)
{
$data = array(
'type' => $transaction->type,
'description' => $transaction->description,
'material' => $transaction->material,
'quantity' => $transaction->quantity,
'sum' => $transaction->sum,
'tarif' => $transaction->tarif,
'isWholesale' => $transaction->isWholesale === null?0:$transaction->isWholesale,
'isIncome' => $transaction->isIncome === null?0:$transaction->isIncome,
);
$id = (int)$transaction->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getTransaction($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Transaction_id does not exist');
}
}
}
public function deleteTransaction($id)
{
$this->tableGateway->delete(array('id' => (int)$id));
}
public function insertedTransaction()
{
return $this->tableGateway->lastInsertValue;
}
}<file_sep><?php
namespace Mebel\Model;
class Workdone
{
public $id;
public $work;
public $rate;
public $payment;
public $amount;
public $ratepayment;
public $rateamount;
public $name;
public $metrik;
public function exchangeArray($data)
{
$this->id = (!is_null($data['id'])) ? $data['id'] : null;
$this->work = (!is_null($data['work'])) ? $data['work'] : null;
$this->rate = (!empty($data['rate'])) ? $data['rate'] : 0;
$this->payment = (!is_null($data['payment'])) ? $data['payment'] : 0;
$this->amount = (!is_null($data['amount'])) ? $data['amount'] : 0;
$this->ratepayment = (!is_null($data['payment'])) ? $data['payment'] : null;
$this->rateamount = (!is_null($data['amount'])) ? $data['amount'] : null;
$this->name = (!is_null($data['name'])) ? $data['name'] : null;
$this->metrik = (!is_null($data['metrik'])) ? $data['metrik'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getWork()
{
return $this->work;
}
/**
* @param mixed $work
*/
public function setWork($work)
{
$this->work = $work;
}
/**
* @return mixed
*/
public function getRate()
{
return $this->rate;
}
/**
* @param mixed $rate
*/
public function setRate($rate)
{
$this->rate = $rate;
}
/**
* @return mixed
*/
public function getPayment()
{
return $this->payment;
}
/**
* @param mixed $payment
*/
public function setPayment($payment)
{
$this->payment = $payment;
}
/**
* @return mixed
*/
public function getAmount()
{
return $this->amount;
}
/**
* @param mixed $amount
*/
public function setAmount($amount)
{
$this->amount = $amount;
}
/**
* @return mixed
*/
public function getRatepayment()
{
return $this->ratepayment;
}
/**
* @param mixed $ratepayment
*/
public function setRatepayment($ratepayment)
{
$this->ratepayment = $ratepayment;
}
/**
* @return mixed
*/
public function getRateamount()
{
return $this->rateamount;
}
/**
* @param mixed $rateamount
*/
public function setRateamount($rateamount)
{
$this->rateamount = $rateamount;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getMetrik()
{
return $this->metrik;
}
/**
* @param mixed $metrik
*/
public function setMetrik($metrik)
{
$this->metrik = $metrik;
}
}<file_sep><?php
namespace Mebel;
use Mebel\Model\Material;
use Mebel\Model\MaterialTable;
use Mebel\Model\Rate;
use Mebel\Model\RateTable;
use Mebel\Model\Transaction;
use Mebel\Model\TransactionTable;
use Mebel\Model\User;
use Mebel\Model\UserTable;
use Mebel\Model\AuthStorage;
use Mebel\Model\Work;
use Mebel\Model\Workdone;
use Mebel\Model\WorkdoneTable;
use Mebel\Model\Worker;
use Mebel\Model\WorkerTable;
use Mebel\Model\WorkTable;
use Mebel\View\Helper\Config;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$this->initAcl($e);
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkAcl'));
}
public function initAcl(MvcEvent $e)
{
$acl = new Acl();
$acl->addRole(new Role('nobody'))
->addRole(new Role('admin'));
$acl->addResource(new Resource('home'))
->addResource(new Resource('material'))
->addResource(new Resource('transaction'))
->addResource(new Resource('worker'))
->addResource(new Resource('rate'))
->addResource(new Resource('work'))
->addResource(new Resource('login'))
->addResource(new Resource('logout'))
->addResource(new Resource('authenticate'));
$acl->allow('nobody', 'home')->allow('nobody', 'login')->allow('nobody', 'authenticate')
->allow('admin', 'home')->allow('admin', 'authenticate')->allow('admin', 'logout')->allow('admin', 'material')->allow('admin', 'transaction')->allow('admin', 'worker')->allow('admin', 'rate')->allow('admin', 'work');
$e->getViewModel()->acl = $acl;
}
public function checkAcl(MvcEvent $e)
{
$route = $e->getRouteMatch()->getMatchedRouteName();
$authStorage = new AuthStorage();
$userRole = $authStorage->getRole();
if (!$e->getViewModel()->acl->isAllowed($userRole, $route) ) {
$response = $e->getResponse();
//location to page or what ever
$response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/login');
$response->setStatusCode(301);
}
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// Autoload all classes from namespace 'Blog' from '/module/Blog/src/Blog'
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
)
)
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getViewHelperConfig(){
return [
'factories' => [
'config' => function($sm){
$config = $sm->getServiceLocator()->get('config');
return new Config($config);
},
],
];
}
public function getServiceConfig()
{
return array(
'factories'=> [
'Mebel\Model\AuthStorage' => function ($sm) {
return new AuthStorage(UserTable::$tableName);
},
'AuthService' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, UserTable::$tableName,'email','<PASSWORD>');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
$authService->setStorage($sm->get('Mebel\Model\AuthStorage'));
return $authService;
},
'UserTable' => function($sm) {
$tableGateway = $sm->get('UserTableGateway');
$table = new UserTable($tableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway(UserTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
'MaterialTable' => function($sm) {
$tableGateway = $sm->get('MaterialTableGateway');
$table = new MaterialTable($tableGateway);
return $table;
},
'MaterialTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Material());
return new TableGateway(MaterialTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
'TransactionTable' => function($sm) {
$tableGateway = $sm->get('TransactionTableGateway');
$table = new TransactionTable($tableGateway);
return $table;
},
'TransactionTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Transaction());
return new TableGateway(TransactionTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
'WorkerTable' => function($sm) {
$tableGateway = $sm->get('WorkerTableGateway');
$table = new WorkerTable($tableGateway);
return $table;
},
'WorkerTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Worker());
return new TableGateway(WorkerTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
'RateTable' => function($sm) {
$tableGateway = $sm->get('RateTableGateway');
$table = new RateTable($tableGateway);
return $table;
},
'RateTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Rate());
return new TableGateway(RateTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
'WorkTable' => function($sm) {
$tableGateway = $sm->get('WorkTableGateway');
$table = new WorkTable($tableGateway);
return $table;
},
'WorkTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Work());
return new TableGateway(WorkTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
'WorkdoneTable' => function($sm) {
$tableGateway = $sm->get('WorkdoneTableGateway');
$table = new WorkdoneTable($tableGateway);
return $table;
},
'WorkdoneTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Workdone());
return new TableGateway(WorkdoneTable::$tableName, $dbAdapter, null, $resultSetPrototype);
},
],
);
}
}<file_sep><?php
namespace Mebel\Controller;
use Mebel\Form\TransactionForm;
use Mebel\Model\MaterialTable;
use Mebel\Model\Transaction;
use Mebel\Model\TransactionTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
class TransactionController extends AbstractActionController
{
protected $transactionTable;
protected $materialTable;
public function indexAction()
{
if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
$type = $this->params()->fromRoute('type');
if(empty($type))
$this->redirect()->toRoute('transaction', ['type' => 'all']);
$direction = $this->params()->fromQuery('direction');
$config = $this->getServiceLocator()->get('config');
$view = new ViewModel(array(
'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
'type' => $type,
'direction' => $direction,
'config' => $config,
));
return $view;
}
public function ajaxAction(){
$type = $this->params()->fromRoute('type');
$direction = $this->params()->fromQuery('direction');
$request = $this->getRequest();
$current = $request->getPost('current', 1); ;
$rowCount = $request->getPost('rowCount', 10);
$sort = $request->getPost('sort');
$sortField = key($sort);
$sortType = $sort[$sortField];
$searchPhrase = $request->getPost('searchPhrase');
$offset = intval($rowCount) * (intval($current)-1);
$transactions= $this->getTransactionTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase, $type, $direction);
$count= $this->getTransactionTable()->getCount($type);
return new JsonModel(array(
'current' => intval($current),
'rowCount' => intval($rowCount),
'rows' => $transactions->toArray(),
"total"=> $count,
));
}
/*
public function deleteAction()
{
$id = (int)$this->params()->fromRoute('id');
$type = $this->params()->fromRoute('type');
$direction = $this->params()->fromQuery('direction');
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Удалить') {
$id = (int)$request->getPost('id');
$this->getTransactionTable()->deleteTransaction($id);
}
return $this->redirect()->toRoute('transaction', ['type' => $type]);
}
$transaction = $this->getTransactionTable()->getTransaction($id);
$view = new ViewModel([
'id' => $transaction->id,
'title' => 'Өшіру '.$transaction->type,
'description' => $transaction->description,
'type' => $transaction->type,
'url' => $this->url()->fromRoute('transaction',['action' => 'delete', 'type' => $transaction->type , 'direction' => $transaction->direction, 'id' => $transaction->id])
]
);
$view->setTemplate('mebel/admin/delete.phtml');
return $view;
}
*/
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$type = $this->params()->fromRoute('type');
$direction = $this->params()->fromQuery('direction');
if(empty($type))
$this->redirect()->toRoute('transaction', ['type' => 'all']);
if($id){
$transaction = $this->getTransactionTable()->getTransaction($id);
}
else
$transaction = new Transaction();
$save = false;
$message = '';
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$config = $this->getServiceLocator()->get('config');
$form = new TransactionForm($dbAdapter, $type, $config);
$form->bind($transaction);
if(!empty($id)) {
foreach ($form->getElements() as $element) {
$element->setAttribute('readonly', 'readonly');
}
}
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$material = null;
if($transaction->material){
$material = $this->getMaterialTable()->getMaterial($transaction->material);
if ($transaction->quantity <= 0) {
$message = 'Количество не может быть ранво нулю!';
}
if ($transaction->quantity > $material->count && $transaction->isIncome == 0) {
$message = 'Количество не может быть больше остатка материала!';
}
} else {
$message = 'Материал в базе отсутствует';
}
if($transaction->isIncome == 0) {
if ($transaction->isWholesale == 1) {
$transaction->tarif = $material->wholesale;;
}
if ($transaction->isWholesale == 0) {
$transaction->tarif = $material->retail;
}
}
$transaction->sum= $transaction->tarif * $transaction->quantity;
$confirmBtn = $request->getPost('confirm');
if(!empty($confirmBtn)) {
$save = true;
foreach ($form->getElements() as $element) {
$element->setAttribute('readonly', 'readonly');
}
}
$saveBtn = $request->getPost('save');
if (empty($message) && !empty($saveBtn) && empty($id)) {
$result = false;
if($transaction->isIncome == 1) {
$result = $this->getMaterialTable()->incomeMaterial($material, $transaction->quantity);
}
if($transaction->isIncome == 0) {
$result = $this->getMaterialTable()->outcomeMaterial($material, $transaction->quantity);
}
if($result){
$this->getTransactionTable()->saveTransaction($transaction);
$this->flashMessenger()->addSuccessMessage('Сәтті сақталды');
$this->redirect()->toRoute('transaction', ['action' => 'edit', 'type' => $type, 'direction' => $direction, 'id' => $this->getTransactionTable()->insertedTransaction()]);
}
}
}else {
$this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
$form->highlightErrorElements();
}
}
$view = new ViewModel([
'save' => $save,
'form' => $form,
'id' => $id,
'type' => $type,
'direction' => $direction,
'config' => $config,
'message' => $message,
]);
return $view;
}
/**
* @return TransactionTable
*/
public function getTransactionTable()
{
if (!$this->transactionTable) {
$sm = $this->getServiceLocator();
$this->transactionTable = $sm->get('TransactionTable');
}
return $this->transactionTable;
}
/**
* @return MaterialTable
*/
public function getMaterialTable()
{
if (!$this->materialTable) {
$sm = $this->getServiceLocator();
$this->materialTable = $sm->get('MaterialTable');
}
return $this->materialTable;
}
}<file_sep><?php
namespace Mebel\Controller;
use Mebel\Form\MaterialForm;
use Mebel\Model\Material;
use Mebel\Model\MaterialTable;
use Mebel\Model\TransactionTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
class MaterialController extends AbstractActionController
{
protected $materialTable;
protected $transactionTable;
public function indexAction()
{
if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
$type = $this->params()->fromRoute('type');
if(empty($type))
$this->redirect()->toRoute('material', ['type' => 'all']);
$config = $this->getServiceLocator()->get('config');
$view = new ViewModel(array(
'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
'type' => $type,
'config' => $config,
));
return $view;
}
public function ajaxAction(){
$type = $this->params()->fromRoute('type');
$request = $this->getRequest();
$current = $request->getPost('current', 1); ;
$rowCount = $request->getPost('rowCount', 10);
$sort = $request->getPost('sort');
$sortField = key($sort);
$sortType = $sort[$sortField];
$searchPhrase = $request->getPost('searchPhrase');
$offset = intval($rowCount) * (intval($current)-1);
$materials= $this->getMaterialTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase, $type);
$count= $this->getMaterialTable()->getCount($type);
return new JsonModel(array(
'current' => intval($current),
'rowCount' => intval($rowCount),
'rows' => $materials->toArray(),
"total"=> $count,
));
}
public function oneAction(){
$id = (int)$this->params()->fromRoute('id');
$material= $this->getMaterialTable()->getMaterial($id);
return new JsonModel($material->getArrayCopy());
}
public function deleteAction()
{
$id = (int)$this->params()->fromRoute('id');
$type = $this->params()->fromRoute('type');
$transactionCount = $this->getTransactionTable()->countByMaterial($id);
$request = $this->getRequest();
if ($request->isPost()) {
if($transactionCount<=0) {
$del = $request->getPost('del', 'No');
if ($del == 'Удалить') {
$id = (int)$request->getPost('id');
$this->getMaterialTable()->deleteMaterial($id);
}
}
return $this->redirect()->toRoute('material', ['type' => $type]);
}
$material = $this->getMaterialTable()->getMaterial($id);
$view = new ViewModel([
'id' => $material->id,
'title' => 'Өшіру '.$material->type.($transactionCount>0?'<span style="color: red"> Бүл материалда кіріс шығыстар бар, егер өшіргіңіз келсе алдымен кіріс шығысты өшіріңіз</span>':''),
'description' => $material->name,
'type' => $material->type,
'delete' => $transactionCount,
'url' => $this->url()->fromRoute('material',['action' => 'delete', 'type' => $material->type, 'id' => $material->id])
]
);
$view->setTemplate('mebel/admin/delete.phtml');
return $view;
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$type = $this->params()->fromRoute('type');
if(empty($type))
$this->redirect()->toRoute('material', ['type' => 'all']);
$transactionCount = 0;
$message = '';
if($id){
$material = $this->getMaterialTable()->getMaterial($id);
$transactionCount = $this->getTransactionTable()->countByMaterial($material->id);
}
else
$material = new Material();
$form = new MaterialForm($type, $transactionCount);
$form->bind($material);
if($transactionCount > 0){
$form->get('count')->setAttribute('disabled', 'disabled');
$form->get('name')->setAttribute('disabled', 'disabled');
}
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$materialCount = $this->getMaterialTable()->countByMaterialName($material->name);
if($materialCount > 0) {
$message = 'Материал с таким именем уже существеут!!!';
} else {
$this->getMaterialTable()->saveMaterial($material, $transactionCount);
$this->flashMessenger()->addSuccessMessage('Сәтті сақталды');
if(empty($id))
$id = $this->getMaterialTable()->insertedMaterial();
$this->redirect()->toRoute('material', ['type' => $type, 'action' => 'edit', 'id' => $id]);
}
}else {
$this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
$form->highlightErrorElements();
}
}
$config = $this->getServiceLocator()->get('config');
$view = new ViewModel([
'form' => $form,
'id' => $id,
'type' => $type,
'config' => $config,
'message' => $message,
'photo' => empty($material->image)?'empty.png':$material->image,
]);
return $view;
}
public function photoAction()
{
$id = (int)$this->params()->fromRoute('id', 0);
$type = $this->params()->fromRoute('type');
if(empty($type))
$this->redirect()->toRoute('material', ['type' => 'all']);
if($id== 0) {
return $this->redirect()->toRoute('material', [
'action' => 'index',
'type' => $type
]);
}
$request = $this->getRequest();
if ($request->isPost()) {
$adapter = new \Zend\File\Transfer\Adapter\Http();
$fullpath = getcwd() . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'photo' . DIRECTORY_SEPARATOR;
$filename = $fullpath.$id . '.jpg';
$adapter->addFilter('Rename', array('target' => $filename, 'overwrite' => true));
$adapter->receive();
$this->getMaterialTable()->saveImage($id, $id . '.jpg');
$this->createThumbs($filename, $fullpath.$id . '-400.jpg', 400);
$this->createThumbs($filename, $fullpath.$id . '-150.jpg', 150);
return new JsonModel([]);
}
$material = $this->getMaterialTable()->getMaterial($id);
$config = $this->getServiceLocator()->get('config');
$view = new ViewModel([
'material' => $material,
'config' => $config,
]);
return $view;
}
function createThumbs($pathToImage, $pathToThumbImage, $thumbWidth)
{
$info = pathinfo($pathToImage);
// continue only if this is a JPEG image
if (strtolower($info['extension']) == 'jpg') {
//echo "Creating thumbnail for {$pathToThumbImage} <br />";
// load image and get image size
$img = imagecreatefromjpeg($pathToImage);
$width = imagesx($img);
$height = imagesy($img);
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor($height * ($thumbWidth / $width));
// create a new temporary image
$tmp_img = imagecreatetruecolor($new_width, $new_height);
// copy and resize old image into new image
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// save thumbnail into a file
imagejpeg($tmp_img, $pathToThumbImage);
}
}
/**
* @return MaterialTable
*/
public function getMaterialTable()
{
if (!$this->materialTable) {
$sm = $this->getServiceLocator();
$this->materialTable = $sm->get('MaterialTable');
}
return $this->materialTable;
}
/**
* @return TransactionTable
*/
public function getTransactionTable()
{
if (!$this->transactionTable) {
$sm = $this->getServiceLocator();
$this->transactionTable = $sm->get('TransactionTable');
}
return $this->transactionTable;
}
}<file_sep><?php
namespace Mebel\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Predicate\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class MaterialTable
{
protected $tableGateway;
public static $tableName = 'material';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function fetchPage($rowCount, $offset, $orderby, $searchPhrase, $type)
{
$sql = new Sql($this->tableGateway->adapter);
$select = $sql->select();
$select->from($this->tableGateway->table);
$select->columns(['*']);
if ($rowCount < 0)
$select->offset(0);
else
$select->limit($rowCount)->offset($offset);
$select->order('name asc');
if ($searchPhrase) {
$select->where->NEST->like('name', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('wholesale', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('retail', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('count', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('date', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->UNNEST;
}
if($type!='all') {
$select->where->equalTo('type', $type);
}
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet;
}
public function getCount($type)
{
if($type!='all') {
$resultSet = $this->tableGateway->select(function (Select $select) use($type) {
$select->where->like('type', $type);
});
} else {
$resultSet = $this->tableGateway->select();
}
return $resultSet->count();
}
/**
* @param $id
* @return Material
* @throws \Exception
*/
public function getMaterial($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function countByMaterialName($materialName)
{
return $this->tableGateway->select( function (Select $select) use ($materialName) {
$where = new Where();
$where->addPredicate(new Expression("TRIM(LOWER(name)) = TRIM(LOWER(?)) ", $materialName));
$select->where($where);
$select->columns(['id']);
})->count();
}
public function saveMaterial(Material $material, $transactionCount)
{
$data = array(
'type' => $material->type,
'description' => $material->description,
'wholesale' => $material->wholesale,
'retail' => $material->retail,
'image' => $material->image,
);
if ($transactionCount ==0) {
$data['count'] =$material->count;
$data['name'] =$material->name;
}
$id = (int)$material->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getMaterial($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Material_id does not exist');
}
}
}
public function incomeMaterial($material, $income)
{
$count = $material->count + $income;
if($count<0)
return false;
$data = array(
'count' =>$count,
);
$id = (int)$material->id;
$this->tableGateway->update($data, array('id' => $id));
return true;
}
public function outcomeMaterial($material, $outcome)
{
$count = $material->count - $outcome;
if($count<0)
return false;
$data = array(
'count' =>$count,
);
$id = (int)$material->id;
$this->tableGateway->update($data, array('id' => $id));
return true;
}
public function saveImage($id, $image)
{
$data = array(
'image' => $image,
);
$this->tableGateway->update($data, array('id' => intval($id)));
}
public function deleteMaterial($id)
{
$this->tableGateway->delete(array('id' => (int)$id));
}
public function insertedMaterial()
{
return $this->tableGateway->lastInsertValue;
}
}<file_sep><?php
namespace Mebel\Controller;
use Mebel\Form\LoginForm;
use Mebel\Model\SettingTable;
use Mebel\Model\UserTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AdminController extends AbstractActionController
{
protected $form;
protected $storage;
protected $authservice;
protected $settingTable;
protected $userTable;
public function getAuthService()
{
if (!$this->authservice) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
public function getSessionStorage()
{
if (!$this->storage) {
$this->storage = $this->getServiceLocator()->get('Mebel\Model\AuthStorage');
}
return $this->storage;
}
public function getForm()
{
if (!$this->form) {
$this->form = new LoginForm();
}
return $this->form;
}
public function loginAction()
{
//if already login, redirect to success page
if ($this->getAuthService()->hasIdentity()) {
$this->redirect()->toRoute('food', ['type' => 'pizza']);
}
$form = $this->getForm();
$view = new ViewModel([
'form' => $form,
'messages' => $this->flashmessenger()->getMessages()
]);
$view->setTerminal(true);
return $view;
}
public function authenticateAction()
{
$form = $this->getForm();
$request = $this->getRequest();
if ($request->isPost()) {
// fwrite(STDOUT, "test stop");
$form->setData($request->getPost());
if ($form->isValid()) {
//check authentication...
$this->getAuthService()->getAdapter()
->setIdentity($request->getPost('email'))
->setCredential($request->getPost('password'))
->setCredentialTreatment('MD5(?)');
$result = $this->getAuthService()->authenticate();
foreach ($result->getMessages() as $message) {
//save message temporary into flashmessenger
$this->flashmessenger()->addMessage($message);
}
if ($result->isValid()) {
$resultRow = $this->getAuthService()->getAdapter()->getResultRowObject();
{
$this->getAuthService()->setStorage($this->getSessionStorage());
$this->getAuthService()->getStorage()->write([
'id' => $resultRow->id,
'fio' => $resultRow->fio,
'email' => $resultRow->email,
'phone' => $resultRow->phone,
'role' => $resultRow->role,
'address' => $resultRow->address,
]);
return $this->redirect()->toRoute('transaction', ['type' => 'all']);
}
}
}
}
return $this->redirect()->toRoute('login');
}
public function menuAction()
{
if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
$config = $this->getServiceLocator()->get('config');
$menuArray = $config['menu'];
$setting= $this->getSettingTable()->getSettingByName('menu');
$request = $this->getRequest();
if ($request->isPost()) {
$menus = $request->getPost('menu', []);
$setting->value = implode(';', $menus);
$this->getSettingTable()->saveSetting($setting);
}
$view = new ViewModel([
'menu' => $menuArray,
'menustr' => $setting->value,
]);
return $view;
}
public function passwordAction()
{
/*var_dump(md5('admin')); 21232f297a57a5a743894a0e4a801fc3 */
$id = (int)$this->getAuthService()->getStorage()->read()['id'];
$user = $this->getUserTable()->getUser($id);
$error = '';
$success = '';
$request = $this->getRequest();
if ($request->isPost()) {
$password = $request->getPost('password');
$newpassword = $request->getPost('newpassword');
$repassword = $request->getPost('repassword');
if(md5($password)!= $user->password) {
$error = 'Не правельно ввели текущий пароль!!!';
goto metka;
}
if($newpassword!= $repassword) {
$error = 'Пароль который ввели не совпадают!!!';
goto metka;
}
if(strlen($newpassword)<6) {
$error = 'Длина пароля должна быть не меньше шести символов!!!';
goto metka;
}
if(empty($newpassword)) {
$error = 'Нельзя установить пустой пароль!!!';
goto metka;
}
if (empty($error)) {
$newpasswordHash = md5($newpassword);
$this->getUserTable()->changePassword($id, $newpasswordHash);
$success = 'Ваш пароль успешно обнавлен';
}
}
metka:
$view = new ViewModel([
'id' => $user->id,
'title' => 'Сменить пароль пользователя '.$user->email.', '.$user->fio,
'success' => $success,
'error' => $error,
]
);
return $view;
}
public function indexAction()
{
if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
return $this->redirect()->toRoute('material');
}
public function logoutAction()
{
$this->getSessionStorage()->forgetMe();
$this->getAuthService()->clearIdentity();
//$this->flashmessenger()->addMessage("Вы вышли из системы");
return $this->redirect()->toRoute('login');
}
/**
* @return UserTable
*/
public function getUserTable()
{
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('UserTable');
}
return $this->userTable;
}
/**
* @return SettingTable
*/
public function getSettingTable()
{
if (!$this->settingTable) {
$sm = $this->getServiceLocator();
$this->settingTable = $sm->get('SettingTable');
}
return $this->settingTable;
}
}<file_sep><?php
namespace Mebel\Controller;
use Mebel\Form\RateForm;
use Mebel\Model\Rate;
use Mebel\Model\RateTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
class RateController extends AbstractActionController
{
protected $rateTable;
public function indexAction()
{
if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
$view = new ViewModel(array(
'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
));
return $view;
}
public function ajaxAction(){
$request = $this->getRequest();
$current = $request->getPost('current', 1); ;
$rowCount = $request->getPost('rowCount', 10);
$sort = $request->getPost('sort');
$sortField = key($sort);
$sortType = $sort[$sortField];
$searchPhrase = $request->getPost('searchPhrase');
$offset = intval($rowCount) * (intval($current)-1);
$rates= $this->getRateTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase);
$count= $this->getRateTable()->getCount();
return new JsonModel(array(
'current' => intval($current),
'rowCount' => intval($rowCount),
'rows' => $rates->toArray(),
"total"=> $count,
));
}
public function oneAction(){
$id = (int)$this->params()->fromRoute('id');
$rate= $this->getRateTable()->getRate($id);
return new JsonModel($rate->getArrayCopy());
}
public function deleteAction()
{
$id = (int)$this->params()->fromRoute('id');
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Удалить') {
$id = (int)$request->getPost('id');
$this->getRateTable()->deleteRate($id);
}
return $this->redirect()->toRoute('rate');
}
$rate = $this->getRateTable()->getRate($id);
$view = new ViewModel([
'id' => $rate->id,
'title' => 'Тарифті өшіру '.$rate->description,
'description' => $rate->payment.'/'.$rate->amount,
'url' => $this->url()->fromRoute('rate',['action' => 'delete', 'id' => $rate->id])
]
);
$view->setTemplate('mebel/admin/delete.phtml');
return $view;
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if($id){
$rate = $this->getRateTable()->getRate($id);
}
else
$rate = new Rate();
$form = new RateForm();
$form->bind($rate);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getRateTable()->saveRate($rate);
$this->flashMessenger()->addSuccessMessage('Сәтті сақталды');
if(empty($id))
$id = $this->getRateTable()->insertedRate();
$this->redirect()->toRoute('rate', ['action' => 'edit', 'id' => $id]);
}else {
$this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
$form->highlightErrorElements();
}
}
$view = new ViewModel([
'form' => $form,
'id' => $id,
]);
return $view;
}
/**
* @return RateTable
*/
public function getRateTable()
{
if (!$this->rateTable) {
$sm = $this->getServiceLocator();
$this->rateTable = $sm->get('RateTable');
}
return $this->rateTable;
}
}<file_sep><?php
namespace Mebel\Form;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\Factory;
use Zend\InputFilter\InputFilter;
class WorkForm extends Form
{
protected $adapter;
public function __construct(AdapterInterface $dbAdapter, $count)
{
$this->adapter =$dbAdapter;
parent::__construct('work');
$inputFilter = new InputFilter();
$factory = new Factory();
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'rate',
'type' => 'Select',
'attributes' => array(
'class' => 'form-control',
'required' => 'required',
'multiple' => 'multiple'
),
'options' => array(
'label' => 'Тариф',
'label_attributes' => ['class' => 'control-label col-md-2'],
'value_options' => $this->getRate(),
),
));
$this->add(array(
'name' => 'worker',
'type' => 'Select',
'attributes' => array(
'class' => 'form-control',
'required' => 'required',
),
'options' => array(
'label' => 'Жұмысшы',
'label_attributes' => ['class' => 'control-label col-md-2'],
'empty_option' => 'Жұмысшы таңдаңыз',
'value_options' => $this->getWorker(),
),
));
$inputFilter->add($factory->createInput([
'name' => 'worker',
'required' => true,
]));
$this->add([
'name' => 'total',
'required' => true,
'type' => 'Number',
'attributes' => [
'class' => 'form-control',
'placeholder' => 'Жалпы төленетін сома(тенге)',
'min' => '0',
'step' => '0.01',
'required' => 'required',
'readonly' => 'readonly'
],
'options' => [
'label' => 'Жалпы төленетін сома(тенге)',
'label_attributes' => ['class' => 'control-label col-md-2']
],
]);
$inputFilter->add($factory->createInput([
'name' => 'total',
'required' => true,
]));
$this->add([
'name' => 'workdate',
'type' => 'Date',
'attributes' => [
'class' => 'form-control',
],
'options' => [
'label' => 'Дата выполнения работы',
'label_attributes' => ['class' => 'control-label col-md-2'],
],
]);
$inputFilter->add($factory->createInput([
'name' => 'workdate',
'required' => true
]));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'workdones',
'options' => array(
'count' => $count,
'should_create_template' => true,
'allow_add' => true,
'template_placeholder' => '__workdones_count__',
'target_element' => array(
'type' => 'Mebel\Form\WorkdoneFieldset',
),
),
));
/* $this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf'
));*/
$this->add([
'name' => 'submit',
'type' => 'Submit',
'attributes' => [
'value' => 'Сақтау',
'id' => 'submitbutton',
'class' => 'btn btn-success pull-right'
],
]);
$this->setInputFilter($inputFilter);
}
public function highlightErrorElements()
{
foreach ($this->getElements() as $element) {
if ($element->getMessages()) {
$element->setAttribute('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);');
$element->setLabelAttributes(array(
'class' => 'control-label col-xs-2',
'style' => 'color:#a94442'));
}
}
}
public function getWorker()
{
$dbAdapter = $this->adapter;
$sql = "SELECT id, fio FROM worker ORDER BY fio ASC";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = [];
foreach ($result as $res) {
$selectData[$res['id']] = $res['fio'];
}
return $selectData;
}
public function getRate()
{
$dbAdapter = $this->adapter;
$sql = "SELECT id, description, payment, amount, metrik FROM rate ORDER BY id ASC";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = [];
foreach ($result as $res) {
$selectData[$res['id']] = $res['description'].', төлемі '.$res['payment'].' тенге / '.$res['amount'].' '.$res['metrik'];
}
return $selectData;
}
}<file_sep><?php
namespace Mebel\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
class RateTable
{
protected $tableGateway;
public static $tableName = 'rate';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function fetchPage($rowCount, $offset, $orderby, $searchPhrase)
{
$sql = new Sql($this->tableGateway->adapter);
$select = $sql->select();
$select->from($this->tableGateway->table);
$select->columns(['*']);
if ($rowCount < 0)
$select->offset(0);
else
$select->limit($rowCount)->offset($offset);
$select->order($orderby);
$select->order('date desc');
if ($searchPhrase) {
$select->where->NEST->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('payment', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('amount', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('metrik', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->UNNEST;
}
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet;
}
public function getCount()
{
$resultSet = $this->tableGateway->select();
return $resultSet->count();
}
public function getRate($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveRate(Rate $rate)
{
$data = array(
'description' => $rate->description,
'payment' => $rate->payment,
'amount' => $rate->amount,
'metrik' => $rate->metrik,
);
$id = (int)$rate->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getRate($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Rate_id does not exist');
}
}
}
public function deleteRate($id)
{
$this->tableGateway->delete(array('id' => (int)$id));
}
public function insertedRate()
{
return $this->tableGateway->lastInsertValue;
}
}<file_sep><?php
namespace Mebel\Model;
class Material
{
public $id;
public $type;
public $name;
public $description;
public $wholesale;
public $retail;
public $count;
public $image;
public $date;
public function exchangeArray($data)
{
$this->id = (!is_null($data['id'])) ? $data['id'] : null;
$this->type = (!is_null($data['type'])) ? $data['type'] : null;
$this->name = (!is_null($data['name'])) ? $data['name'] : null;
$this->description = (!is_null($data['description'])) ? $data['description'] : null;
$this->wholesale = (!is_null($data['wholesale'])) ? $data['wholesale'] : 0;
$this->retail = (!is_null($data['retail'])) ? $data['retail'] : 0;
$this->count = (!is_null($data['count'])) ? $data['count'] : 0;
$this->image = (!empty($data['image'])) ? $data['image'] : null;
$this->date = (!empty($data['date'])) ? $data['date'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}<file_sep>CREATE TABLE `rate` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`description` TEXT,
`payment` FLOAT NOT NULL DEFAULT 0,
`amount` FLOAT NOT NULL DEFAULT 1,
`metrik` VARCHAR(255) NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;
<file_sep>CREATE TABLE `transaction` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`type` VARCHAR(50) NOT NULL,
`description` TEXT,
`material` INT(10) UNSIGNED NOT NULL,
`quantity` INT(11) NOT NULL DEFAULT 0,
`sum` FLOAT NOT NULL DEFAULT 0,
`tarif` FLOAT NOT NULL DEFAULT 0,
`isWholesale` INT(11) NOT NULL DEFAULT 0,
`isIncome` INT(11) NOT NULL DEFAULT 0,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `FK1_material` (`material`),
CONSTRAINT `FK1_material` FOREIGN KEY (`material`) REFERENCES `material` (`id`)
)
ENGINE = InnoDB;
<file_sep><?php
namespace Mebel\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
class WorkTable
{
protected $tableGateway;
public static $tableName = 'work';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function fetchPage($rowCount, $offset, $orderby, $searchPhrase)
{
$sql = new Sql($this->tableGateway->adapter);
$select = $sql->select();
$select->from($this->tableGateway->table);
$select->columns(['*']);
$select->join('worker', 'work.worker = worker.id', ['fio'], Select::JOIN_LEFT);
if ($rowCount < 0)
$select->offset(0);
else
$select->limit($rowCount)->offset($offset);
$select->order($orderby);
$select->order('date desc');
if ($searchPhrase) {
$select->where->NEST
->OR->like('total', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->OR->like('fio', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
->UNNEST;
}
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet;
}
public function getCount()
{
$resultSet = $this->tableGateway->select();
return $resultSet->count();
}
/**
* @param $id
* @return Work
* @throws \Exception
*/
public function getWork($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveWork(Work $work)
{
$data = array(
'worker' => $work->worker,
'total' => $work->total,
'workdate' => $work->workdate,
);
$id = (int)$work->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getWork($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Work_id does not exist');
}
}
}
public function deleteWork($id)
{
$this->tableGateway->delete(array('id' => (int)$id));
}
public function insertedWork()
{
return $this->tableGateway->lastInsertValue;
}
} | 94df7f413848b6f8e1741476d4f6bf5a3b0e994e | [
"JavaScript",
"SQL",
"PHP"
] | 32 | PHP | yerganat/meb | 16aa893dcf66678abc499d3301793df97709d484 | a6d2ad890c76f4ad903a7892f132212f12888e87 | |
refs/heads/master | <repo_name>hopsor/pumarex<file_sep>/README.md
# Pumarex
A movie theater web application built with **Phoenix Framework 1.3** and **Elm 0.18**.
Don't take it seriously. It's just an exercise for me to learn Elm and try the
new features included in Phoenix Framework 1.3
## TODO list
- [x] Room management.
- [x] Room list.
- [x] Room creation.
- [x] Screening management
- [x] Screening list.
- [x] Screening creation.
- [x] Box office.
- [x] User authentication.
## Development setup
To start your Phoenix server:
* Install dependencies with `mix deps.get`
* Create and migrate your database with `mix ecto.create && mix ecto.migrate`
* Install Node.js dependencies with `cd assets && npm install`
* Install Elm dependencies with `cd assets/elm && elm-package install`
* Start Phoenix endpoint with `mix phx.server`
Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
<file_sep>/assets/js/app.js
import '../css/application.scss';
import Elm from './main';
const elmDiv = document.getElementById('app')
if (elmDiv) {
const initialSessionData = localStorage.getItem('sessionData');
const sessionData = initialSessionData ? JSON.parse(initialSessionData) : null;
const loggedIn = initialSessionData ? true : false;
const elmFlags = {
sessionData: sessionData,
loggedIn: loggedIn,
websocketUrl: window.websocketUrl
};
const app = Elm.Main.embed(elmDiv, elmFlags);
app.ports.storeSessionData.subscribe((sessionData) => {
localStorage.setItem('sessionData', JSON.stringify(sessionData));
});
app.ports.destroySessionData.subscribe(() => {
localStorage.removeItem('sessionData');
});
}
| 1ec29130658332ea8ff5d8e0691847bdc5872358 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | hopsor/pumarex | ac266e6f4775aac6a05f4fd999738e177aa4da9b | ab90be0add7aff356ca2595340121ff4a63e9a97 | |
refs/heads/master | <repo_name>NewbergFTC/Bulletproof-2016-2017<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/lib/Sensors.java
package us.newberg.bulletproof.lib;
import com.elvishew.xlog.XLog;
import com.qualcomm.hardware.hitechnic.HiTechnicNxtLightSensor;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class Sensors
{
public static HiTechnicNxtLightSensor LightSensor;
public static void Init(HardwareMap hardware)
{
LightSensor = (HiTechnicNxtLightSensor) hardware.lightSensor.get("Lightsensor");
XLog.tag("Sensors").d("Sensors initialized");
}
}
<file_sep>/STYLE.md
# 6712 BulletProof Java Style Guide
###### Revision 0 (WIP)
- [Introduction](#introduction)
- [File Basics](#file-basics)
- [Source File Basics](#source-file-basics)
- [Formatting](#formatting)
## Introduction
The purpose of this style guide is to provide a standard of code that is consistant and easy to read. This guide will insure that your code is professional-looking and readable on the many devices and screen sizes we work with.
---
## File Basics
- File name: The source file name will match the case-sensitive name of the top-level class it contains.
- File encoding: UTF-8
- Whitespace characters: Spaces, not tabs, will be used for indentation and general whitespace.
- Column Width: The max column width is 120 characters. All lines must be line-wrapped if they exceed this number.
---
### Source File Basics
- Package statement: The package statement will not be line-wrapped.
- Import statements: Import statements will not be line-wrapped.
- Imports will be ordered as follows:
1. All standard library imports
2. All other third party imports
3. All project imports
4. All static imports
- One or two blank lines will follow each block.
- There are no other blank lines between imports.
- Within each block, imports will be in an alphabetical order.
- Class declaration: Each top-level class resides in its own source file.
- Class member ordering: Class members will be ordered in _some logical order_.
- Method names: When a class has multiple methods with the same name, and/or multiple constructors, they will appear sequentially.
---
### Formatting
- Braces: Braces are always used with `` if ``, `` else ``, `` while ``, `` for ``, `` do `` statements, even if the body contains one line, or is empty.
- Line breaks <!-- TODO(Garrison): Examples -->
- Line break before the opening brace
- Line break after the opening brace
- Line break before closing brace
- Line break after the closing brace
<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/opmodes/StraightOpMode.java
package us.newberg.bulletproof.opmodes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import us.newberg.bulletproof.Direction;
/**
* FTC team 6712 Bulletproof
*/
@Autonomous(name = "Straight", group = "Common")
public class StraightOpMode extends BulletproofOpMode
{
@Override
protected void Run() throws InterruptedException
{
_driveTrain.Drive(Direction.NORTH, 0.8f, 39, 10000, this);
}
}
<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/opmodes/RedShootMoveSideOpMode.java
package us.newberg.bulletproof.opmodes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import us.newberg.bulletproof.Direction;
import us.newberg.bulletproof.modules.Flipper;
import us.newberg.bulletproof.lib.Motors;
/**
* FTC team 6712 Bulletproof
*/
@Autonomous(name = "Red Shoot Move Side", group = "Red")
public class RedShootMoveSideOpMode extends BulletproofOpMode
{
@Override
protected void Run() throws InterruptedException
{
_flipper.AutoMoveBlocking(this);
Motors.Collector.setPower(-1.0f);
sleep(3000);
Motors.Collector.setPower(0);
_flipper.AutoMoveBlocking(this);
_driveTrain.Drive(Direction.NORTH_EAST, 0.5f, 3.7f * 12.0f, 5000, this);
sleep(500);
_driveTrain.Drive(-0.5f, -0.5f);
sleep(500);
_driveTrain.StopAll();
sleep(500);
_driveTrain.Drive(Direction.NORTH, 1.0f, 2.0f * 12.0f, 10000, this);
}
}
<file_sep>/Makefile
.PHONY: build install start pullLogs
all: build install start
build:
@printf '\e[34mBuilding...\n'
@./gradlew :Bulletproof:build
install:
@printf '\e[34mInstalling...\n'
@adb push ./Bulletproof/build/outputs/apk/Bulletproof-debug.apk /data/local/tmp/com.qualcomm.ftcrobotcontroller
@adb shell pm install -r "/data/local/tmp/com.qualcomm.ftcrobotcontroller"
start:
@printf '\e[34mStarting...\n'
@adb shell am start -n "com.qualcomm.ftcrobotcontroller/org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
@sl
pullLogs:
@adb pull /sdcard/bullet ./logs<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/modules/Flipper.java
package us.newberg.bulletproof.modules;
import com.elvishew.xlog.XLog;
import com.qualcomm.robotcore.hardware.DcMotor;
import us.newberg.bulletproof.lib.Motors;
import us.newberg.bulletproof.opmodes.BulletproofOpMode;
import us.or.k12.newberg.newbergcommon.WatchDog;
/**
* FTC team 6712 Bulletproof
*/
public class Flipper
{
public static final String TAG = "Flipper";
public static final float GEAR_RATIO = 20.0f / 3.0f; // 6 2/3
public static final float HALF_GEAR_RATIO = GEAR_RATIO / 2; // One flick
public enum State
{
NOTHING,
MANUAL,
AUTO
}
private Flipper.State _state;
private FlipperHelper _helper;
private DcMotor _flipperMotor;
private WatchDog _watchDog;
public Flipper(DcMotor motor)
{
_helper = new FlipperHelper(this);
_flipperMotor = motor;
_watchDog = new WatchDog();
}
public void AutoMoveBlocking(BulletproofOpMode caller) throws InterruptedException
{
XLog.tag(TAG).d("Auto-move Blocking Start");
_helper.SetTask(HelperTask.STOP);
_watchDog.Watch(_helper, 15000);
StartAutoMove();
while (GetState() == Flipper.State.AUTO)
{
caller.sleep(1);
caller.Update();
}
_watchDog.Stop();
XLog.tag(TAG).d("Auto-move Blocking Stop");
}
public void StartAutoMove()
{
XLog.tag(TAG).d("Auto-move Start");
final float targetTicks = (float) _flipperMotor.getCurrentPosition() + ((float)Motors.TICKS_PER_ROTATION * HALF_GEAR_RATIO * 1.7f);
_state = State.AUTO;
new Thread(new Runnable()
{
@Override
public void run()
{
while (_flipperMotor.getCurrentPosition() < targetTicks)
{
SetPower(1.0f);
_state = State.AUTO;
}
SetPower(0.0f);
_state = State.NOTHING;
XLog.tag(TAG).d("Auto-move Stop");
}
}).start();
}
public void SetPower(double power)
{
XLog.tag(TAG).d("Set power to " + String.valueOf(power));
_flipperMotor.setPower(power);
}
public Flipper.State GetState()
{
return _state;
}
private enum HelperTask
{
NONE,
COMPLETE,
STOP,
}
private class FlipperHelper implements Runnable
{
private Flipper _flipper;
private HelperTask _task;
private FlipperHelper(Flipper target)
{
_flipper = target;
_task = HelperTask.NONE;
}
private void SetTask(HelperTask task)
{
_task = task;
}
public HelperTask GetTask()
{
return _task;
}
private void StopAll()
{
_flipper.SetPower(0);
}
@Override
public void run()
{
switch (_task)
{
default:
case NONE:
break;
case STOP:
StopAll();
SetTask(HelperTask.COMPLETE);
break;
}
}
}
}
<file_sep>/settings.gradle
include ':FtcRobotController'
include ':Bulletproof'
include ':NewbergCommon'
include ':opencv-java'
<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/Direction.java
package us.newberg.bulletproof;
/**
* FTC team 6712 Bulletproof
*/
public enum Direction
{
NORTH,
NORTH_EAST,
EAST,
SOUTH_EAST,
SOUTH,
SOUTH_WEST,
WEST,
NORTH_WEST
}
<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/modules/Collector.java
package us.newberg.bulletproof.modules;
import com.elvishew.xlog.XLog;
import com.qualcomm.robotcore.hardware.DcMotor;
import us.newberg.bulletproof.opmodes.BulletproofOpMode;
import us.or.k12.newberg.newbergcommon.WatchDog;
public class Collector
{
public static final String TAG = "Collector";
public static double MAIN_POWER = 1.0;
public static double STOP_POWER = 0.0;
private DcMotor _motor;
private WatchDog _watchDog;
public Collector(DcMotor motor)
{
_motor = motor;
Stop();
XLog.tag(TAG).d("Initialized");
}
public void StartPull()
{
_motor.setPower(MAIN_POWER);
XLog.tag(TAG).d("Pulling");
}
public void StartPush()
{
_motor.setPower(-MAIN_POWER);
XLog.tag(TAG).d("Pushing");
}
public void Stop()
{
_motor.setPower(STOP_POWER);
XLog.tag(TAG).d("Stop");
}
}
<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/lib/Motors.java
package us.newberg.bulletproof.lib;
/**
* FTC team 6712 Bulletproof
*/
import com.elvishew.xlog.XLog;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class Motors
{
public static final double WHEEL_CIRCUMFRENCE = Math.PI * 4; // inches
public static final double TICKS_PER_ROTATION = 1120; // ticks
public static final double TICKS_TO_DEG = 360 / TICKS_PER_ROTATION; // deg / ticks
public static final double DEG_TO_TICKS = TICKS_PER_ROTATION / 360; // ticks / deg
public static final double TICKS_TO_INCHES = TICKS_PER_ROTATION / WHEEL_CIRCUMFRENCE; // ticks / in
public static final double INCHES_TO_TICKS = WHEEL_CIRCUMFRENCE / TICKS_PER_ROTATION; // in / ticks
public static final double WHEEL_DISTANCE_CORRECTION = 1.414213526373095; // sqrt(2)
public static DcMotor FrontLeft;
public static DcMotor FrontRight;
public static DcMotor BackLeft;
public static DcMotor BackRight;
public static DcMotor Collector;
public static DcMotor Flipper;
public static void Init(HardwareMap hardwareMap)
{
FrontLeft = hardwareMap.dcMotor.get("frontLeft");
FrontRight = hardwareMap.dcMotor.get("frontRight");
BackLeft = hardwareMap.dcMotor.get("backLeft");
BackRight = hardwareMap.dcMotor.get("backRight");
Collector = hardwareMap.dcMotor.get("collector");
Flipper = hardwareMap.dcMotor.get("flipper");
FrontLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
FrontRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
BackLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
BackRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
XLog.tag("Motors").d("Motors initialized");
}
}
<file_sep>/Bulletproof/src/main/java/us/newberg/bulletproof/modules/ButtonPusher.java
package us.newberg.bulletproof.modules;
import com.elvishew.xlog.XLog;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.Telemetry;
/**
* FTC team 6712 Bulletproof
*/
public class ButtonPusher
{
public static final String TAG = "ButtonPusher";
public static float LEFT_DEPLOY_POS = 1f;
public static float LEFT_CLOSE_POS = 0f;
public static float RIGHT_DEPLOY_POS = 1f;
public static float RIGHT_CLOSE_POS = 0f;
private enum State
{
DEPLOYED,
CLOSED
}
private Servo _servoLeft;
private Servo _servoRight;
private State _stateLeft;
private State _stateRight;
public ButtonPusher(Servo left, Servo right)
{
_servoLeft = left;
_servoRight = right;
_servoLeft.setPosition(LEFT_CLOSE_POS);
_servoRight.setPosition(RIGHT_CLOSE_POS);
_stateLeft = State.CLOSED;
_stateRight = State.CLOSED;
XLog.tag(TAG).d("Initialized");
}
public void DeployLeft()
{
_servoLeft.setPosition(LEFT_DEPLOY_POS);
_stateLeft = State.DEPLOYED;
XLog.tag(TAG).d("Deploy Left");
}
public void DeployRight()
{
_servoRight.setPosition(RIGHT_DEPLOY_POS);
_stateRight = State.DEPLOYED;
XLog.tag(TAG).d("Deploy Right");
}
public void CloseLeft()
{
_servoLeft.setPosition(LEFT_CLOSE_POS);
_stateLeft = State.CLOSED;
XLog.tag(TAG).d("Close Left");
}
public void CloseRight()
{
_servoRight.setPosition(RIGHT_CLOSE_POS);
_stateRight = State.CLOSED;
XLog.tag(TAG).d("Close Right");
}
public void ToggleLeft()
{
if (_stateLeft == State.CLOSED)
{
DeployLeft();
}
else
{
CloseLeft();
}
}
public void ToggleRight()
{
if (_stateRight == State.CLOSED)
{
DeployRight();
}
else
{
CloseRight();
}
}
}
<file_sep>/README.md
# FTC Team 6712 Bulletproof
## 2016-2017 FTC Season
---
| ec4ac0e284aa59442f449024f33c87cad7d22f7c | [
"Markdown",
"Java",
"Makefile",
"Gradle"
] | 12 | Java | NewbergFTC/Bulletproof-2016-2017 | 6db9e558f5b4f5551dc6d93355bf47602d6d36cb | 8aa16bd8efca7a5dc99a64b54dd756b7ed1aeda6 | |
refs/heads/master | <repo_name>binaychap/jersey-exercise<file_sep>/README.md
# jersey-exercise
<file_sep>/src/main/java/com/binay/ActivityResource.java
package com.binay;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.binay.model.Activity;
import com.binay.model.User;
import com.binay.repository.ActivityRepository;
import com.binay.repository.ActivityRepositoryStub;
@Path("activities") // http:localhost:8080/exercise-services/webapi/activities
public class ActivityResource {
private ActivityRepository activityRepository = new ActivityRepositoryStub();
@POST
@Path("activity")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Activity createActivity(Activity activity) {
System.out.println(activity.getDescription());
System.out.println(activity.getDuration());
activityRepository.create(activity);
return activity;
}
@POST
@Path("activity")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Activity createActivityParams(MultivaluedMap<String, String> formParams) {
Activity activity = new Activity();
activity.setDescription(formParams.getFirst("description"));
activity.setDuration(Integer.parseInt(formParams.getFirst("duration")));
activityRepository.create(activity);
return activity;
}
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Activity> getAllActivities() {
return activityRepository.findAllActivities();
}
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("{activityId}")
public Response getAllActivity(@PathParam("activityId") String activityId) {
if (activityId == null || activityId.length() < 4) {
return Response.status(Status.BAD_REQUEST).build();
}
Activity activity = activityRepository.findAllActivity(activityId);
if (activity == null) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok().entity(activity).build();
}
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("{activityId}/user")
public User getAllActivityUser(@PathParam("activityId") String activityId) {
return activityRepository.findAllActivity(activityId).getUser();
}
}
| 262e443b295f515b19feaa42f18a954415cda67c | [
"Markdown",
"Java"
] | 2 | Markdown | binaychap/jersey-exercise | 6103b25e0c4e7faec3c14edc16c8ec4eb48450a0 | 0417cae0a555587498cbed37dea7bb33d013300a | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Epam.Task6.BACKUP_SYSTEM
{
public partial class BACKUPSYSTEM : Form
{
private string pathforwatch;
private string subpath = @"BACKUP";
private DirectoryInfo dirInfo;
private FileSystemWatcher fileWatcher;
public BACKUPSYSTEM()
{
this.InitializeComponent();
this.dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
if (!this.dirInfo.Exists)
{
this.dirInfo.Create();
}
this.dirInfo.CreateSubdirectory(this.subpath);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, true);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = false;
this.fileWatcher.EnableRaisingEvents = true;
}
private void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = true;
this.fileWatcher.EnableRaisingEvents = false;
}
private void Button2_Click(object sender, EventArgs e)
{
this.folderBrowserDialog1.ShowDialog();
this.pathforwatch = this.folderBrowserDialog1.SelectedPath;
if (!this.pathforwatch.Equals(string.Empty))
{
radioButton1.Enabled = true;
radioButton2.Enabled = true;
dateTimePicker1.Enabled = true;
this.fileWatcher = new FileSystemWatcher(this.pathforwatch);
this.fileWatcher.Changed += new FileSystemEventHandler(this.Savechanges);
this.fileWatcher.Created += new FileSystemEventHandler(this.Savechanges);
this.fileWatcher.Deleted += new FileSystemEventHandler(this.Savechanges);
this.fileWatcher.Renamed += new RenamedEventHandler(this.Savechanges);
this.fileWatcher.EnableRaisingEvents = true;
}
}
private void Savechanges(object sender, FileSystemEventArgs fileSystemEventArgs)
{
DirectoryCopy(this.pathforwatch, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.subpath, DateTime.Now.ToString("dd.MMMM.yyyy.HH.mm.ss")), true);
}
private void Button1_Click(object sender, EventArgs e)
{
int twoday = 172800;
DateTimePicker d = dateTimePicker1;
this.dirInfo = new DirectoryInfo(this.pathforwatch);
TimeSpan onesec = new TimeSpan(0, 0, 0, 1);
for (int i = 0; i < twoday; i++)
{
this.dateTimePicker1 = d;
if (Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.subpath, dateTimePicker1.Text)))
{
foreach (FileInfo f in this.dirInfo.GetFiles())
{
f.Delete();
}
foreach (DirectoryInfo dir in this.dirInfo.GetDirectories())
{
dir.Delete(true);
}
DirectoryCopy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.subpath, dateTimePicker1.Text), this.pathforwatch, true);
break;
}
if (i == twoday - 1)
{
MessageBox.Show("at that time and 2 days ago there were no changes");
}
}
}
private void BACKUPSYSTEM_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.USER
{
public class USER
{
private string lastName;
private string firstName;
private string patronymic;
private DateTime dateofBirth;
private int age;
public USER(string lastName, string firstName, string patronymic, DateTime dateofBirth, int age)
{
if ((int)(DateTime.Now.Year - dateofBirth.Year) != age)
{
throw new Exception("such age cannot with such date of birth");
}
this.lastName = lastName;
this.firstName = firstName;
this.patronymic = patronymic;
this.dateofBirth = dateofBirth;
this.age = age;
}
public string Getfullinf()
{
StringBuilder sb = new StringBuilder();
sb.Append(this.lastName).Append(" ");
sb.Append(this.firstName).Append(" ");
sb.Append(this.patronymic).Append(" ");
sb.Append(this.dateofBirth.ToString("dd.MM.yyyy")).Append(" ");
sb.Append(this.age).Append(" ");
return sb.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task5.NUMBER_ARRAY_SUM
{
public static class Program
{
public static int NUMBERARRAYSUM(this int[] array)
{
int sum = 0;
foreach (var item in array)
{
sum += item;
}
return sum;
}
public static void Main(string[] args)
{
int[] array = { 15, 7, -5, 6, 4 };
int sum;
Console.WriteLine("enter an array");
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("apply our widening method and output a sum");
sum = NUMBERARRAYSUM(array);
Console.WriteLine(sum);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2.NON_NEGATIVE_SUM
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[10];
Random ran = new Random();
int sum = 0;
Console.WriteLine("Random array");
for (int i = 0; i < array.Length; i++)
{
array[i] = ran.Next(-100, 100);
Console.WriteLine(array[i]);
if (array[i] > 0)
{
sum += array[i];
}
}
Console.WriteLine($"sum of non-negative elements = {sum}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2.NO_POSITIVE
{
class Program
{
static void Main(string[] args)
{
int[,,] array = new int[3,3,3];
Random ran = new Random();
for (int i = 0; i < array.GetUpperBound(0)+1; i++)
{
for (int j = 0; j < array.GetUpperBound(1)+1; j++)
{
for (int z = 0; z < array.GetUpperBound(2)+1; z++)
{
array[i,j,z] = ran.Next(-100, 100);
Console.Write($"array element before conversion = {array[i, j, z]} ");
if (array[i, j, z] > 0)
{
array[i, j, z] = 0;
}
Console.WriteLine($" after = {array[i, j, z]}");
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.CUSTOMSORTDEMO
{
public class Program
{
public delegate int Comparison<T>(T first, T second);
public static void Sort<T>(T[] a, Comparison<T> compare)
{
for (int i = 0; i < a.Length; i++)
{
for (int j = i + 1; j < a.Length; j++)
{
if (compare(a[i], a[j]) > 0)
{
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
public static int Comparestring(string first, string second)
{
if (first.Length == second.Length)
{
for (int i = 0; i < first.Length; i++)
{
if ((int)first[i] > (int)second[i])
{
return 1;
}
if ((int)first[i] < (int)second[i])
{
return -1;
}
}
return 0;
}
if (first.Length > second.Length)
{
return 1;
}
else
{
return -1;
}
}
public static void Main(string[] args)
{
string[] array = { "vova", "ekaterina", "vafelnica", "kica", "ribalovIvan" };
Console.WriteLine("enter an unsorted array");
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("apply our method and output an array");
Sort(array, Comparestring);
foreach (var item in array)
{
Console.WriteLine(item);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2.AVERAGE_STRING_LENGTH
{
class Program
{
static void Main(string[] args)
{
string[] str_array;
int sum = 0;
Console.WriteLine("enter the string");
StringBuilder sb = new StringBuilder(Console.ReadLine());
for (int i = 0; i < sb.Length; i++)
{
if (Char.IsPunctuation(sb[i]))
{
sb.Remove(i, 1);
i--;
}
}
str_array = sb.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < str_array.Length; i++)
{
sum += str_array[i].Length;
}
Console.WriteLine($"average word length = {(double)sum / str_array.Length}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.DAL.Interface;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.DAL
{
public class UserDao : IUserDao
{
private static string path = System.IO.Path.GetTempPath() + "users.txt";
public void Add(User user)
{
int k = 0;
StreamWriter output = new StreamWriter(path, true);
output.Close();
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
for (int i = 0; i < str.Length; i++)
{
if (str[0].Equals('1') & i == 0)
{
k++;
}
if (i == str.Length - 1)
{
break;
}
if (str[i].Equals((char)13) & str[i + 1].Equals((char)10))
{
k++;
}
}
input.Close();
output = new StreamWriter(path, true);
user.Id = k;
output.WriteLine(user.ToString());
output.Close();
}
public void Delete(int id)
{
StreamWriter output = new StreamWriter(path, true);
output.Close();
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
input.Close();
int k = 0;
int firstchar = -1;
for (int i = 0; i < str.Length; i++)
{
if (i == str.Length - 1)
{
break;
}
if (str[i].Equals((char)13) & str[i + 1].Equals((char)10))
{
if (id == 0)
{
str = str.Remove(0, i);
str = str.Insert(0, "delete");
break;
}
k++;
if (firstchar >= 0)
{
str = str.Remove(firstchar, i - firstchar);
str = str.Insert(firstchar, "\r" + "\n" + "delete");
break;
}
if (k == id)
{
firstchar = i;
}
}
}
output = new StreamWriter(path, false);
output.Write(str);
output.Close();
}
public string GetAll()
{
StreamWriter output = new StreamWriter(path, true);
output.Close();
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
input.Close();
return str;
}
public string ShowAwards(int id)
{
string pathusersandawards = System.IO.Path.GetTempPath() + "usersandawards.txt";
StreamWriter output = new StreamWriter(pathusersandawards, true);
output.Close();
StreamReader input = new StreamReader(pathusersandawards);
string str = input.ReadToEnd();
string idfromfile = string.Empty;
input.Close();
string awards = string.Empty;
AwardDao awarddao = new AwardDao();
for (int i = 0; i < str.Length; i++)
{
if ((str[0] + string.Empty).Equals(id.ToString()) & i == 0)
{
awards = awarddao.GetById(int.Parse(str[i + 2] + string.Empty)) + " ";
}
if (i == str.Length - 2)
{
break;
}
if (str[i].Equals((char)13) & str[i + 1].Equals((char)10))
{
idfromfile = str[i + 2] + string.Empty;
if (idfromfile.Equals(id.ToString()))
{
awards += awarddao.GetById(int.Parse(str[i + 4] + string.Empty)) + " ";
}
}
}
return awards;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.VECTOR_GRAPHICS_EDITOR
{
public class Program
{
public static void Main(string[] args)
{
LINE line;
CIRCUMFERENCE circumference;
double radiusforcircumference;
double radius2forcircumference;
RECTANGLE rectangle;
double asideforrectangle;
double bsideforrectangle;
ROUND.ROUND round;
double radiusforround;
RING.RING ring;
double radiusforring;
double outerradiusforring;
Random rnd = new Random();
Console.WriteLine("create a line with an random parameter \"x\" and \"y\"");
line = new LINE(rnd.NextDouble(), rnd.NextDouble());
Console.WriteLine("the object we created has the following parameters");
Console.WriteLine(line.ToString());
Console.WriteLine($"x = {line.X}");
Console.WriteLine($"y = {line.Y}" + Environment.NewLine);
Console.WriteLine("create a circumference with an random parameter \"x\" and \"y\"");
Console.WriteLine("enter a first radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out radiusforcircumference) & radiusforcircumference >= 0)
{
Console.WriteLine("enter a second radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out radius2forcircumference) & radius2forcircumference >= 0)
{
circumference = new CIRCUMFERENCE(radiusforcircumference, rnd.NextDouble(), rnd.NextDouble(), radius2forcircumference);
Console.WriteLine("the object we created has the following parameters");
Console.WriteLine(circumference.ToString());
Console.WriteLine($"first radius = {circumference.Radius}");
Console.WriteLine($"second radius= {circumference.Radiustwo}");
Console.WriteLine($"x = {circumference.X}");
Console.WriteLine($"y = {circumference.Y}" + Environment.NewLine);
}
else
{
Console.WriteLine("error in second entering radius" + Environment.NewLine);
}
}
else
{
Console.WriteLine("error in first entering radius" + Environment.NewLine);
}
Console.WriteLine("create a rectangle with an random parameter\"x\" and \"y\"");
Console.WriteLine("enter a first side \"a\" more than 0");
if (double.TryParse(Console.ReadLine(), out asideforrectangle) & asideforrectangle > 0)
{
Console.WriteLine("enter a second side \"b\" more than 0");
if (double.TryParse(Console.ReadLine(), out bsideforrectangle) & bsideforrectangle > 0)
{
rectangle = new RECTANGLE(asideforrectangle, bsideforrectangle, rnd.NextDouble(), rnd.NextDouble());
Console.WriteLine("the object we created has the following parameters");
Console.WriteLine(rectangle.ToString());
Console.WriteLine($"first side \"a\" = {rectangle.A}");
Console.WriteLine($"second side \"b\"= {rectangle.B}");
Console.WriteLine($"x = {rectangle.X}");
Console.WriteLine($"y = {rectangle.Y}" + Environment.NewLine);
}
else
{
Console.WriteLine("error in second entering side \"b\"" + Environment.NewLine);
}
}
else
{
Console.WriteLine("error in first entering side \"a\"" + Environment.NewLine);
}
Console.WriteLine("create a round with an random parameter \"x\" and \"y\"");
if (double.TryParse(Console.ReadLine(), out radiusforround) & radiusforround >= 0)
{
Console.WriteLine("enter a radius more than or equal to 0");
round = new ROUND.ROUND(radiusforround, rnd.NextDouble(), rnd.NextDouble());
Console.WriteLine("the object we created has the following parameters");
Console.WriteLine(round.ToString());
Console.WriteLine($"radius = {round.Radius}");
Console.WriteLine($"x = {round.X}");
Console.WriteLine($"y = {round.Y}" + Environment.NewLine);
}
else
{
Console.WriteLine("error in entering radius" + Environment.NewLine);
}
Console.WriteLine("create a ring with an random parameter \"x\" and \"y\"");
Console.WriteLine("enter a radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out radiusforring) & radiusforring >= 0)
{
Console.WriteLine("enter a outer radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out outerradiusforring) & outerradiusforring >= 0)
{
if (outerradiusforring > radiusforring)
{
ring = new RING.RING(radiusforring, rnd.NextDouble(), rnd.NextDouble(), outerradiusforring);
Console.WriteLine("the object we created has the following parameters");
Console.WriteLine(ring.ToString());
Console.WriteLine($"radius = {ring.Radius}");
Console.WriteLine($"outer radius = {ring.Outer_radius}");
Console.WriteLine($"x = {ring.X}");
Console.WriteLine($"y = {ring.Y}");
}
else
{
Console.WriteLine("outer radius cannot be less or equal to radius");
}
}
else
{
Console.WriteLine("error in outer entering radius");
}
}
else
{
Console.WriteLine("error in entering radius");
}
}
}
}
<file_sep>function deleteChars(){
var str = document.getElementById("text1").value;
var spl;
var letters = ["?", "!", ":", ";", ",", ".", " ", "\t"];
for(let i = 1; i<str.length; i++)
{
for(let j = 0; j<letters.length; j++)
{
if(str[i] == letters[j])
{
str = str.replace(str[i], " ");
}
}
}
spl = str.split(" ");
for(var i=0;i<spl.length;i++)
{
for(var j=0;j<spl[i].length;j++)
{
var current_char = spl[i].charAt(j);
for(var z=j;z<spl[i].length-1;z++)
{
if(current_char==spl[i].charAt(z+1))
{
str = str.split(current_char).join("");
}
}
}
}
document.getElementById("text2").value = str;
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.BLL.Interface
{
public interface IAwardLogic
{
void AddAward(Award award);
string GetAll();
void AddAwardForUser(int idaward, int iduser);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task4.DYNAMIC_ARRAY
{
public class DYNAMICARRAY<T> : IEnumerable<object>, IEnumerable
{
private object[] obj;
public DYNAMICARRAY()
{
this.obj = new object[8];
this.Capacity = this.obj.Length;
}
public DYNAMICARRAY(int n)
{
this.obj = new object[n];
this.Capacity = this.obj.Length;
}
public DYNAMICARRAY(IEnumerable<T> n)
{
this.obj = new object[n.Count()];
for (int i = 0; i < n.Count(); i++)
{
this.obj[i] = n.ElementAt(i);
}
this.Capacity = this.obj.Length;
}
public int Capacity { get; private set; }
public int Length { get; private set; }
public void Add(T obj)
{
if (this.Length != this.obj.Length)
{
this.obj[this.Length] = obj;
}
else
{
int length = this.obj.Length;
object[] objcopy = this.obj;
this.obj = new object[length * 2];
this.Capacity = this.obj.Length;
for (int i = 0; i < objcopy.Length; i++)
{
this.obj[i] = objcopy[i];
}
this.obj[this.Length] = obj;
}
this.СountLength();
}
public void AddRange(IEnumerable<T> n)
{
for (int i = this.obj.Length - 1; i > 0; i--)
{
if (this.obj[i] != null)
{
object[] objcopy = this.obj;
this.obj = new object[i + n.Count() + 1];
for (int j = 0; j <= i; j++)
{
this.obj[j] = objcopy[j];
}
for (int j = 0; j < n.Count(); j++)
{
this.obj[i + j + 1] = n.ElementAt(j);
}
break;
}
}
}
public bool Remove(int index)
{
if (index < this.obj.Length)
{
this.obj[index] = default(T);
this.СountLength();
return true;
}
else
{
return false;
}
}
public bool Insert(int index, T obj)
{
if (index <= this.obj.Length - 1)
{
if (this.obj[index] == null)
{
this.obj[index] = obj;
this.СountLength();
return true;
}
else
{
object[] objcopy = this.obj;
this.obj = new object[this.obj.Length * 2];
this.Capacity = this.obj.Length;
int newelement = 0;
for (int i = 0; i < objcopy.Length; i++)
{
if (i != index)
{
this.obj[i] = objcopy[i - newelement];
}
else
{
this.obj[i] = obj;
newelement++;
}
}
this.СountLength();
return true;
}
}
else
{
throw new System.ArgumentOutOfRangeException("argument outside array border");
}
}
public object Indexer(int index)
{
if (index <= this.obj.Length)
{
return this.obj[index];
}
else
{
throw new System.ArgumentOutOfRangeException("argument outside array border");
}
}
public IEnumerator<object> GetEnumerator()
{
return ((IEnumerable<object>)this.obj).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<object>)this.obj).GetEnumerator();
}
private void СountLength()
{
int k = 0;
for (int i = 0; i < this.Capacity; i++)
{
if (!(this.obj[i] == null))
{
k++;
}
}
this.Length = k;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.GAME
{
public abstract class ENEMY : MOVINGOBJECT
{
private Random rnd;
public ENEMY(int x, int y, int speed)
: base(x, y, speed)
{
}
public new int X { get; set; }
public new int Y { get; set; }
public new int Speed { get; set; }
public void ArtificialIntelligence(BARRIER barrier)
{
while (true)
{
try
{
this.rnd = new Random();
this.Move(this.rnd.Next(-1, 1), this.rnd.Next(-1, 1), barrier);
}
catch
{
Console.WriteLine("there can not move");
}
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task5.TOINTORNOTTOINT
{
public static class Program
{
public static bool TOINTORNOTTOINT(this string str)
{
if (str[0].Equals('-'))
{
str = str.Remove(0, 1);
}
var pointcounter = str.Where(i => i == '.');
if (str[0].Equals('.') | str[str.Length - 1].Equals('.') | pointcounter.Count() >= 2)
{
return false;
}
var ecounter = str.Where(i => i == 'e' | i == 'E');
if (str[0].Equals('e') | str[str.Length - 1].Equals('e') | str[0].Equals('E') | str[str.Length - 1].Equals('E') | ecounter.Count() >= 2)
{
return false;
}
for (int i = 1; i < str.Length; i++)
{
if (str[i].Equals('e') | str[i].Equals('E'))
{
if (str[i - 1].Equals('.') | str[i + 1].Equals('.'))
{
return false;
}
str = str.Remove(i, 1);
if (str[i].Equals('+'))
{
str = str.Remove(i, 1);
if (i == str.Length)
{
return false;
}
}
}
}
bool result = str.All(char.IsDigit) | str.Any(i => i == '.');
return result;
}
public static void Main(string[] args)
{
Console.WriteLine("enter a string to check for a number using a dot and not a comma for example 3.14E+06");
string str = Console.ReadLine();
Console.WriteLine("is string digit? " + str.TOINTORNOTTOINT());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.BLL;
using Epam.Task7.USERS.BLL.Interface;
using Epam.Task7.USERS.Common;
using Epam.Task7.USERS.DAL;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.ConsolePL
{
public class Program
{
public static void Main(string[] args)
{
var award = new Award
{
Title = "oscar"
};
string input;
var userLogic = DependencyResolver.UserLogic;
var awardlogic = DependencyResolver.Awardlogic;
while (true)
{
Console.WriteLine("write \"addu\" or \"delu\" or \"showu\" to add or delete or show a user");
Console.WriteLine("write \"adda\" or \"showa\" to add or show a award/s");
Console.WriteLine("write \"addau\" or \"showau\" to add award to user or show a user awards");
input = Console.ReadLine();
if (input.Equals("addu"))
{
AddUser(userLogic);
}
else if (input.Equals("delu"))
{
DeleteUser(userLogic);
}
else if (input.Equals("showu"))
{
Console.WriteLine("Id | Name | Date Of Birth | Age");
Console.WriteLine(userLogic.GetAll());
}
else if (input.Equals("adda"))
{
AddAward(awardlogic);
}
else if (input.Equals("showa"))
{
Console.WriteLine("current awards");
Console.WriteLine(awardlogic.GetAll());
}
else if (input.Equals("addau"))
{
AddAwardForUser(awardlogic);
}
else if (input.Equals("showau"))
{
ShowUserAwards(userLogic);
}
else
{
Console.WriteLine("error in the entered string, enter \"add\" or \"del\"");
}
}
}
private static void AddUser(IUserLogic userlogic)
{
string name;
int age;
Console.WriteLine("Enter a name");
name = Console.ReadLine();
Console.WriteLine("Enter a age more 4");
if (!(int.TryParse(Console.ReadLine(), out age) & age > 4))
{
Console.WriteLine("date entry error");
return;
}
Console.WriteLine("the date will be selected current");
var user = new User
{
Name = name,
DateOfBirth = DateTime.Now,
Age = age,
};
userlogic.Add(user);
}
private static void DeleteUser(IUserLogic userlogic)
{
int id;
Console.WriteLine("enter the ID of the user you want to delete");
if (!int.TryParse(Console.ReadLine(), out id))
{
Console.WriteLine("id entry error");
}
userlogic.Delete(id);
}
private static void AddAward(IAwardLogic awardlogic)
{
string name;
Console.WriteLine("Enter a name of award");
name = Console.ReadLine();
var award = new Award
{
Title = name
};
awardlogic.AddAward(award);
}
private static void AddAwardForUser(IAwardLogic awardlogic)
{
int iduser;
int idaward;
Console.WriteLine("enter the user ID to which you want to add a award");
if (!int.TryParse(Console.ReadLine(), out iduser))
{
Console.WriteLine("date entry user ID");
return;
}
Console.WriteLine("enter the award ID to which you want to add");
if (!int.TryParse(Console.ReadLine(), out idaward))
{
Console.WriteLine("date entry award ID");
return;
}
awardlogic.AddAwardForUser(iduser, idaward);
}
private static void ShowUserAwards(IUserLogic userlogic)
{
int id;
Console.WriteLine("enter the ID of the user you want to show awards");
if (!int.TryParse(Console.ReadLine(), out id))
{
Console.WriteLine("id entry error");
}
Console.WriteLine("This user has the following awards.");
Console.WriteLine(userlogic.ShowAwards(id));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FONT_ADJUSTMENT
{
class Program
{
[Flags]
enum text_formatting : byte
{
none = 0,
bold = 1,
italic = 2,
underline = 4,
}
static text_formatting curecurrent_text_status = text_formatting.none;
public static void current_state()
{
Console.Write("label parameters: ");
Console.Write(curecurrent_text_status + Environment.NewLine);
Console.WriteLine("1: " + text_formatting.bold + Environment.NewLine + "2: " + text_formatting.italic + Environment.NewLine + "3: " + text_formatting.underline);
}
public static void change_state(int n)
{
n = Convert.ToInt32(Math.Pow(2, n - 1));
if (curecurrent_text_status.HasFlag((text_formatting)n))
{
curecurrent_text_status &= ~(text_formatting)n;
}
else
{
curecurrent_text_status |= (text_formatting)n;
}
}
static void Main(string[] args)
{
int n;
while (true)
{
current_state();
Console.WriteLine("enter the number of the label which you want to add or delete");
if (Int32.TryParse(Console.ReadLine(), out n) & n <= 3 & n > 0)
{
change_state(n);
}
else
{
Console.WriteLine("error in entering number of label");
}
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.BLL.Interface;
using Epam.Task7.USERS.DAL.Interface;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.BLL
{
public class AwardLogic : IAwardLogic
{
private readonly IAwardDao awarddao;
public AwardLogic(IAwardDao awardDao)
{
this.awarddao = awardDao;
}
public void AddAward(Award award)
{
this.awarddao.AddAward(award);
}
public string GetAll()
{
return this.awarddao.GetAll();
}
public void AddAwardForUser(int idaward, int iduser)
{
this.awarddao.AddAwardForUser(idaward, iduser);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.EMPLOYEE
{
public class EMPLOYEE : USER.USER
{
private int workexperience;
private string position;
public EMPLOYEE(string lastName, string firstName, string patronymic, DateTime dateofBirth, int age, int workexperience, string position)
: base(lastName, firstName, patronymic, dateofBirth, age)
{
if (workexperience < 0)
{
throw new Exception("experience can not be negative");
}
this.workexperience = workexperience;
this.position = position;
}
public new string Getfullinf()
{
StringBuilder sb = new StringBuilder();
sb.Append(base.Getfullinf());
sb.Append(this.workexperience).Append(" ");
sb.Append(this.position);
return sb.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.ROUND
{
public class ROUND
{
private double radius;
private double x;
private double y;
private double circlelength;
private double areacircle;
public ROUND(double radius, double x, double y)
{
if (radius < 0)
{
throw new Exception("Radius should be positive");
}
this.radius = radius;
this.x = x;
this.y = y;
this.Circle_Length();
this.Area_Circle();
}
public double Circle_length
{
get
{
return this.circlelength;
}
}
public double Area_circle
{
get
{
return this.areacircle;
}
}
public double Radius
{
get
{
return this.radius;
}
}
public double X
{
get
{
return this.x;
}
}
public double Y
{
get
{
return this.y;
}
}
private void Circle_Length()
{
this.circlelength = 2 * Math.PI * this.radius;
}
private void Area_Circle()
{
this.areacircle = Math.PI * Math.Pow(this.radius, 2);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Epam.Task8.REGULAREXPRESSIONS.NUMBERVALIDATOR
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("enter a number");
string text = Console.ReadLine();
string regstrusual = @"^[-]?[0-9]*\.?,?[0-9]+$";
string regstrscience = @"-?[\d.]+(?:e-?\d+)?";
var regexusual = new Regex(regstrusual, RegexOptions.IgnoreCase);
var regexuscience = new Regex(regstrscience, RegexOptions.IgnoreCase);
if (regexusual.IsMatch(text))
{
Console.WriteLine("this number is in usual notation.");
}
else if (regexuscience.IsMatch(text))
{
Console.WriteLine("this number is in scientific notation.");
}
else
{
Console.WriteLine("this is not number");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task4.LOST
{
public class Program
{
public static void Main(string[] args)
{
int n;
bool chek = false;
List<int> people = new List<int>();
while (true)
{
Console.WriteLine("enter a number more than 0");
if (int.TryParse(Console.ReadLine(), out n) & n > 0)
{
break;
}
else
{
Console.WriteLine("error in entering number");
}
}
for (int i = 1; i <= n; i++)
{
people.Add(i);
Console.Write(people[i - 1] + " ");
}
Console.WriteLine();
while (people.Count > 1)
{
for (int i = 0; i < people.Count; i++)
{
if (chek)
{
people.RemoveAt(i);
i--;
}
chek = !chek;
}
for (int j = 0; j < people.Count; j++)
{
Console.Write(people[j] + " ");
}
Console.WriteLine();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.EMPLOYEE
{
public class Program
{
public static void Main(string[] args)
{
EMPLOYEE employee;
string lastName;
string firstName;
string patronymic;
DateTime dateofBirth;
int age;
int workexperience;
string position;
Console.WriteLine("enter a last Name");
lastName = Console.ReadLine();
Console.WriteLine("enter a first Name");
firstName = Console.ReadLine();
Console.WriteLine("enter a patronymic");
patronymic = Console.ReadLine();
Console.WriteLine("enter a work position");
position = Console.ReadLine();
while (true)
{
Console.WriteLine("enter date as in example 21.05.2015");
if (DateTime.TryParse(Console.ReadLine(), out dateofBirth))
{
Console.WriteLine("enter a age");
if (int.TryParse(Console.ReadLine(), out age))
{
if ((int)(DateTime.Now.Year - dateofBirth.Year) == age)
{
break;
}
else
{
Console.WriteLine("such age cannot with such date of birth");
}
}
else
{
Console.WriteLine("error in entering age");
}
}
else
{
Console.WriteLine("error in entering date");
}
}
while (true)
{
Console.WriteLine("enter a work experience");
if (int.TryParse(Console.ReadLine(), out workexperience) & workexperience > 0)
{
break;
}
else
{
Console.WriteLine("error in entering work experience");
}
}
employee = new EMPLOYEE(lastName, firstName, patronymic, dateofBirth, age, workexperience, position);
Console.WriteLine(employee.Getfullinf());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task5.ISEEKYOU
{
public class Program
{
public delegate bool Sumelement(int element);
public static int Sumnonegativeelement(int[] array)
{
int sum = 0;
foreach (var item in array)
{
if (item >= 0)
{
sum += item;
}
}
return sum;
}
public static int Sumnonegativeelement(int[] array, Sumelement compare)
{
int sum = 0;
foreach (var item in array)
{
if (compare(item))
{
sum += item;
}
}
return sum;
}
public static bool Nonegativeelement(int element)
{
if (element >= 0)
{
return true;
}
else
{
return false;
}
}
public static void Main(string[] args)
{
int step = 100;
List<long> time = new List<long>();
Stopwatch sw = new Stopwatch();
Random rnd = new Random();
int[] array = new int[500];
for (int i = 0; i < array.Length; i++)
{
array[i] = rnd.Next(-100, 100);
}
for (int i = 0; i < step; i++)
{
sw.Start();
Sumnonegativeelement(array);
time.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Time method 1 = " + time.Average());
time.Clear();
for (int i = 0; i < step; i++)
{
sw.Start();
Sumnonegativeelement(array, Nonegativeelement);
time.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Time method 2 = " + time.Average());
time.Clear();
for (int i = 0; i < step; i++)
{
sw.Start();
var result = Sumnonegativeelement(
array,
delegate(int element)
{
if (element >= 0)
{
return true;
}
else
{
return false;
}
});
time.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Time method 3 = " + time.Average());
time.Clear();
for (int i = 0; i < step; i++)
{
sw.Start();
Sumnonegativeelement(array, element => element > -1);
time.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Time method 4 = " + time.Average());
time.Clear();
for (int i = 0; i < step; i++)
{
sw.Start();
int result = array.Where(j => j > -1).Sum();
time.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Time method 5 = " + time.Average());
time.Clear();
}
}
}
<file_sep>function mathCalc() {
var pattern = /-?\d+(\.\d+)?|[\/\+\-\=\*]{1}/g;
var numb = document.getElementById("text1").value;
var arr = numb.match(pattern);
var result;
if (+arr[0] !== "NaN") {
result = +arr[0];
}
for (let i = 0; i < arr.length; i++) {
switch (arr[i]) {
case '+':
result += +arr[i + 1];
break;
case '*':
result *= arr[i + 1];
break;
case '/':
result /= arr[i + 1];
break;
case '=':
document.getElementById('text2').value = result.toFixed(2);
break;
}
if (arr[i] < 0 && arr[i - 1] != '*' && arr[i - 1] != '/' && arr[i - 1] != null) {
result += +arr[i];
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.VECTOR_GRAPHICS_EDITOR
{
public class RECTANGLE
{
private double a;
private double b;
private double x;
private double y;
public RECTANGLE(double a, double b, double x, double y)
{
if (a <= 0)
{
throw new Exception("Side \"a\" should be positive");
}
if (b <= 0)
{
throw new Exception("Side \"b\" should be positive");
}
this.a = a;
this.b = b;
this.x = x;
this.y = y;
}
public double X
{
get
{
return this.x;
}
}
public double Y
{
get
{
return this.y;
}
}
public double A
{
get
{
return this.a;
}
}
public double B
{
get
{
return this.b;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.GAME
{
public abstract class TERRITORY
{
public TERRITORY()
{
this.X = 25;
this.Y = 25;
}
public int X { get; }
public int Y { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2.CHAR_DOUBLER
{
class Program
{
static void Main(string[] args)
{
bool chek_doubl = false;
Console.WriteLine("Enter the first line:");
StringBuilder sb = new StringBuilder(Console.ReadLine());
Console.WriteLine("Enter the second line:");
StringBuilder sb1 = new StringBuilder(Console.ReadLine());
for (int i = 0; i < sb1.Length; i++)
{
chek_doubl = false;
for (int j = 0; j < sb.Length; j++)
{
if (sb1[i].ToString().ToUpper().Equals(sb[j].ToString().ToUpper()))
{
sb.Insert(j, sb1[i]);
j++;
chek_doubl = true;
}
}
if (chek_doubl)
{
sb1.Replace(sb1[i].ToString(), "");
i = -1;
}
}
Console.WriteLine(sb.ToString());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.GAME
{
public class PLAYER : MOVINGOBJECT
{
public PLAYER(int x, int y, int speed, int effecttime)
: base(x, y, speed)
{
this.Effecttime = effecttime;
}
public new int X { get; set; }
public new int Y { get; set; }
public new int Speed { get; set; }
public int Effecttime { get; set; }
public void Changeeffecttime(int speed, int effecttime)
{
if (this.Speed + speed > 0 & this.Effecttime + effecttime > 0)
{
this.Speed += speed;
this.Effecttime += effecttime;
}
}
public void Move(int x, int y, BARRIER barrier, BONUS bonus)
{
if (!(barrier.X == this.X + x) & !(barrier.Y == this.Y + y))
{
if (x >= base.X & x <= 0)
{
throw new Exception("player can not be located abroad, error x");
}
if (y >= base.Y & y <= 0)
{
throw new Exception("player can not be located abroad, error y");
}
this.X = x;
this.Y = y;
}
if (bonus.X == this.X + x & bonus.Y == this.Y + y)
{
this.Speed += bonus.Speedincrease;
this.Effecttime += bonus.Effecttime;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task4.DYNAMIC_ARRAY
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("create an instance of DYNAMICARRAY with a size of 1");
DYNAMICARRAY<object> array = new DYNAMICARRAY<object>(1);
Console.WriteLine("test \"add\" add objects of different types larger than the size of the array");
array.Add("somestring");
array.Add(15);
array.Add(true);
Console.WriteLine(array.Remove(2));
Console.WriteLine(array.Remove(1));
Console.WriteLine(array.Insert(0, "newstring"));
Console.WriteLine(array.Insert(5, 44444));
Console.WriteLine(array.Length);
Console.WriteLine(array.Capacity);
var testindexer = array.Indexer(4);
foreach (var item in array)
{
Console.WriteLine(item);
}
DYNAMICARRAY<object> array1 = new DYNAMICARRAY<object>(array);
array.AddRange(array1);
int sdfsd = 5;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2._2D_ARRAY
{
class Program
{
static void Main(string[] args)
{
int[,] array = new int[5, 5];
Random ran = new Random();
int sum = 0;
Console.WriteLine("Random array");
for (int i = 0; i < array.GetUpperBound(0)+1; i++)
{
for (int j = 0; j < array.GetUpperBound(1)+1; j++)
{
array[i, j] = ran.Next(-100, 100);
Console.Write(array[i, j] + " ");
if ((i + j) % 2 == 0)
{
sum += array[i, j];
}
}
Console.Write(Environment.NewLine);
}
Console.WriteLine($"the sum of the position numbers of the array in both even dimensions = {sum}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task1._1
{
class Program
{
public static void SEQUENCE(int n)
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++)
{
if (i != n)
{
Console.Write(i + ", ");
}
else
{
Console.WriteLine(i);
}
}
}
static void Main(string[] args)
{
Console.WriteLine("enter a number more than 0");
while (true)
{
try
{
int n = int.Parse(Console.ReadLine());
if (n > 0)
{
SEQUENCE(n);
break;
}
else
{
throw new Exception("Not this, enter a number more than 0");
}
}
catch
{
Console.WriteLine("Not this, enter a number more than 0");
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.RING
{
public class RING : ROUND.ROUND
{
private double outerradius;
private double arearing;
private double ringlength;
public RING(double radius, double x, double y, double outerradius)
: base(radius, x, y)
{
if (outerradius < 0)
{
throw new Exception("Insideradius should be positive");
}
if (radius >= outerradius)
{
throw new Exception("Insideradius should be more radius");
}
this.outerradius = outerradius;
this.Area_Ring();
this.Ring_Length();
}
public double Outer_radius
{
get
{
return this.outerradius;
}
}
public double Ring_length
{
get
{
return this.ringlength;
}
}
public double Area_ring
{
get
{
return this.arearing;
}
}
private void Area_Ring()
{
this.arearing = Math.PI * (Math.Pow(this.outerradius, 2) - Math.Pow(this.Radius, 2));
}
private void Ring_Length()
{
this.ringlength = (2 * Math.PI * this.outerradius) + this.Circle_length;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Epam.Task8.REGULAREXPRESSIONS.HTMLREPLACER
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("enter a string with HTML tegs");
string text = Console.ReadLine();
string regstr = @"<[^>]*>";
var regex = new Regex(regstr, RegexOptions.IgnoreCase);
Console.WriteLine("The result of the replacement:" + regex.Replace(text, "_"));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.RING
{
public class Program
{
public static void Main(string[] args)
{
double radius;
double outerradius;
double x;
double y;
RING ring;
while (true)
{
Console.WriteLine("enter a radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out radius) & radius >= 0)
{
Console.WriteLine("enter a outer radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out outerradius) & outerradius >= 0)
{
if (outerradius > radius)
{
break;
}
else
{
Console.WriteLine("outer radius cannot be less or equal to radius");
}
}
else
{
Console.WriteLine("error in outer entering radius");
}
}
else
{
Console.WriteLine("error in entering radius");
}
}
while (true)
{
Console.WriteLine("enter x coordinate");
if (double.TryParse(Console.ReadLine(), out x))
{
break;
}
else
{
Console.WriteLine("error in entering x");
}
}
while (true)
{
Console.WriteLine("enter y coordinate");
if (double.TryParse(Console.ReadLine(), out y))
{
break;
}
else
{
Console.WriteLine("error in entering y");
}
}
ring = new RING(radius, x, y, outerradius);
Console.WriteLine($"Ring length = {ring.Ring_length}");
Console.WriteLine($"Area ring = {ring.Area_ring}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.MY_STRING
{
public class Program
{
public static void Main(string[] args)
{
MYSTRING str = new MYSTRING("hello");
char chr;
char chrtwo;
int index;
int indextwo;
string[] array;
Console.WriteLine("create an instance of the MYSTRING class with the \"hello\" parameter");
Console.WriteLine("enter the words with which to compare it");
Console.WriteLine(str.Mycompare(Console.ReadLine()));
Console.WriteLine("enter the words that you want to add to our class");
Console.WriteLine(str.Myconcat(Console.ReadLine()));
Console.WriteLine("enter the character the number of the first entry of which you want to see if such a character in \"hello\" is not displayed on the screen -1");
if (char.TryParse(Console.ReadLine(), out chr))
{
Console.WriteLine(str.Myindexof(chr));
}
else
{
Console.WriteLine("character is incorrect");
}
Console.WriteLine("enter the character the number of the last entry of which you want to see if such a character in \"hello\" is not displayed on the screen -1");
if (char.TryParse(Console.ReadLine(), out chr))
{
Console.WriteLine(str.Mylastindexof(chr));
}
else
{
Console.WriteLine("character is incorrect");
}
Console.WriteLine("enter the number of the character you want to remove from \"hello\"");
if (int.TryParse(Console.ReadLine(), out index))
{
Console.WriteLine(str.Myremove(index));
}
else
{
Console.WriteLine("number is incorrect");
}
Console.WriteLine("enter the number of character from which you want to remove from \"hello\"");
if (int.TryParse(Console.ReadLine(), out index) & index >= 0)
{
Console.WriteLine("enter the number of character to which you want to remove from \"hello\"");
if (int.TryParse(Console.ReadLine(), out indextwo) & indextwo > index)
{
Console.WriteLine(str.Myremove(index, indextwo));
}
else
{
Console.WriteLine("number is incorrect");
}
}
else
{
Console.WriteLine("number is incorrect");
}
Console.WriteLine("create an instance of the MYSTRING class with the \"say hello to my little friend\" parameter");
str = new MYSTRING("say hello to my little friend");
Console.WriteLine("enter the character you want to share the phrase \"say hello to my little friend\"");
if (char.TryParse(Console.ReadLine(), out chr))
{
array = str.Mysplit(chr);
foreach (var item in array)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("character is incorrect");
}
Console.WriteLine("create an instance of the MYSTRING class with the \" hello world \" parameter");
str = new MYSTRING(" hello world ");
Console.WriteLine("use the trim function without parameters");
Console.WriteLine(str.Mytrim());
Console.WriteLine("create an instance of the MYSTRING class with the \"hello world\" parameter");
str = new MYSTRING("hello world");
Console.WriteLine("enter the first character that you do not want to see on the edges of \"hello world\"");
if (char.TryParse(Console.ReadLine(), out chr))
{
Console.WriteLine("enter the second character that you do not want to see on the edges of \"hello world\"");
if (char.TryParse(Console.ReadLine(), out chrtwo))
{
Console.WriteLine(str.Mytrim(chr, chrtwo));
}
else
{
Console.WriteLine("character is incorrect");
}
}
else
{
Console.WriteLine("character is incorrect");
}
Console.WriteLine("create an instance of the MYSTRING class with the \"hello world\" parameter");
Console.WriteLine("enter the number from which you want to cut the string \"hello world\"");
if (int.TryParse(Console.ReadLine(), out index) & index >= 0)
{
Console.WriteLine(str.Mysubstring(index));
}
else
{
Console.WriteLine("number is incorrect");
}
Console.WriteLine("enter the number of the character from which you want to insert the string in \"hello world\"");
if (int.TryParse(Console.ReadLine(), out index) & index >= 0)
{
Console.WriteLine("enter the string you want to insert in \"hello world\"");
Console.WriteLine(str.Myinsert(index, Console.ReadLine()));
}
else
{
Console.WriteLine("number is incorrect");
}
}
}
}
<file_sep>var list1 = document.getElementById("left");
var list2 = document.getElementById("right");
function one_move(name)
{
var my_element = document.getElementById(name);
var my_index = my_element.selectedIndex;
if(name=="left")
{
if(my_index==-1)
{
alert("element isn't choosen!!!!!")
}
else
{
var newElement = my_element[my_index].cloneNode(true);
list1.removeChild(my_element[my_index]);
list2.append(newElement);
}
}
if(name=="right")
{
if(my_index==-1)
{
alert("element isn't choosen!!!!!")
}
else
{
var newElement = my_element[my_index].cloneNode(true);
list2.removeChild(my_element[my_index]);
list1.append(newElement);
}
}
}
function all_move(name)
{
my_element = document.getElementById(name);
if(name == "left")
{
while(my_element.length > 0)
{
var newElement = my_element[0].cloneNode(true);
list1.removeChild(my_element[0]);
list2.append(newElement);
}
}
else if(name == "right")
{
while(my_element.length > 0)
{
var newElement = my_element[0].cloneNode(true);
list2.removeChild(my_element[0]);
list1.append(newElement);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.TRIANGLE
{
public class Program
{
public static void Main(string[] args)
{
TRIANGLE triangle;
double a;
double b;
double c;
while (true)
{
Console.WriteLine("enter the first side of the triangle");
if (double.TryParse(Console.ReadLine(), out a) & a >= 0)
{
Console.WriteLine("enter the second side of the triangle");
if (double.TryParse(Console.ReadLine(), out b) & b >= 0)
{
Console.WriteLine("enter the third side of the triangle");
if (double.TryParse(Console.ReadLine(), out c) & c >= 0)
{
if (a + b > c & a + c > b & b + c > a)
{
triangle = new TRIANGLE(a, b, c);
Console.WriteLine($" triangle area = {triangle.CalcArea()}");
Console.WriteLine($" triangle perimeter = {triangle.CalcPerimeter()}");
break;
}
else
{
Console.WriteLine("such a triangle does not exist");
}
}
else
{
Console.WriteLine("error in entering third side");
}
}
else
{
Console.WriteLine("error in entering second side");
}
}
else
{
Console.WriteLine("error in entering first side");
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2.ARRAY_PROCESSING
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[10];
Random ran = new Random();
int variable;
for (int i = 0; i < array.Length; i++)
{
array[i] = ran.Next(0,100);
}
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (array[i] > array[j])
{
variable = array[i];
array[i] = array[j];
array[j] = variable;
}
}
}
Console.WriteLine("random sorted array");
foreach (int i in array)
{
Console.WriteLine(i);
}
Console.WriteLine($"minimal array element = {array[0]}");
Console.WriteLine($"minimal array element = { array[9]}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.DAL.Interface
{
public interface IAwardDao
{
void AddAward(Award award);
string GetAll();
void AddAwardForUser(int idaward, int iduser);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.MY_STRING
{
public class MYSTRING
{
private char[] chr;
public MYSTRING(string str)
{
this.chr = new char[str.Length];
for (int i = 0; i < str.Length; i++)
{
this.chr[i] = str[i];
}
}
public bool Mycompare(string str)
{
if (this.chr.Length == str.Length)
{
for (int i = 0; i < str.Length; i++)
{
if (this.chr[i] != str[i])
{
return false;
}
}
return true;
}
else
{
return false;
}
}
public string Myconcat(string str)
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
sb.Append(this.chr[i]);
}
sb.Append(str);
return sb.ToString();
}
public int Myindexof(char chr)
{
for (int i = 0; i < this.chr.Length; i++)
{
if (this.chr[i] == chr)
{
return i;
}
}
return -1;
}
public int Mylastindexof(char chr)
{
for (int i = this.chr.Length - 1; i >= 0; i--)
{
if (this.chr[i] == chr)
{
return i;
}
}
return -1;
}
public string Myremove(int index)
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
if (i != index)
{
sb.Append(this.chr[i]);
}
}
return sb.ToString();
}
public string Myremove(int firstindex, int lastindex)
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
if (i < firstindex | i >= lastindex)
{
sb.Append(this.chr[i]);
}
}
return sb.ToString();
}
public string[] Mysplit(char chr)
{
string[] array;
int index = 0;
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
if (this.chr[i] == chr)
{
index++;
}
}
array = new string[index + 1];
index = 0;
for (int i = 0; i < this.chr.Length; i++)
{
if (this.chr[i] != chr)
{
sb.Append(this.chr[i]);
}
else
{
array[index] = sb.ToString();
sb.Remove(0, sb.Length);
index++;
}
}
array[index] = sb.ToString();
return array;
}
public string Mytrim()
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
if (!(this.chr[i] == ' ' & i == 0) & !(this.chr[i] == ' ' & i == this.chr.Length - 1))
{
sb.Append(this.chr[i]);
}
}
return sb.ToString();
}
public string Mytrim(char one, char two)
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
if (!(((this.chr[i] == one) | (this.chr[i] == two)) & ((i == 0) | (i == this.chr.Length - 1))))
{
sb.Append(this.chr[i]);
}
}
return sb.ToString();
}
public string Mysubstring(int index)
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
if (i >= index)
{
sb.Append(this.chr[i]);
}
}
return sb.ToString();
}
public string Myinsert(int index, string str)
{
StringBuilder sb = new StringBuilder(string.Empty);
for (int i = 0; i < this.chr.Length; i++)
{
sb.Append(this.chr[i]);
if (i == index - 1)
{
sb.Append(str);
}
}
return sb.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task5.CUSTOM_SORT
{
public class Program
{
public delegate int Comparison<T>(T first, T second);
public static void Sort<T>(T[] a, Comparison<T> compare)
{
for (int i = 0; i < a.Length; i++)
{
for (int j = i + 1; j < a.Length; j++)
{
if (compare(a[i], a[j]) > 0)
{
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
public static int Compareint(int first, int second)
{
if (first > second)
{
return 1;
}
if (first == second)
{
return 0;
}
return -1;
}
public static void Main(string[] args)
{
int[] array = { 15, 7, -5, 6, 4 };
Console.WriteLine("enter an unsorted array");
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("apply our method and output an array");
Sort(array, Compareint);
foreach (var item in array)
{
Console.WriteLine(item);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Epam.Task5.SORTING_UNIT
{
public class SORTINGUNIT
{
public delegate string SortFinished();
public delegate int Comparison<T>(T first, T second);
public event SortFinished Already;
public Thread Th { get; private set; }
public void Sort<T>(T[] a, Comparison<T> compare)
{
if (compare == null)
{
throw new ArgumentNullException();
}
for (int i = 0; i < a.Length; i++)
{
for (int j = i + 1; j < a.Length; j++)
{
if (compare(a[i], a[j]) > 0)
{
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
this.Already?.Invoke();
}
public int Compareint(int first, int second)
{
if (first > second)
{
return 1;
}
if (first == second)
{
return 0;
}
return -1;
}
public void Sortflow<T>(T[] a, Comparison<T> compare)
{
ThreadStart thstart = new ThreadStart(() => this.Sort(a, compare));
this.Th = new Thread(thstart);
this.Th.Start();
}
public string Conclusion()
{
Console.WriteLine("array is ready");
return "array is ready";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task4.WORD_FREQUENCY
{
public class Program
{
public static void Main(string[] args)
{
string str;
string[] strarray;
char[] separator = { ' ', '.' };
int k = 0;
List<string> words = new List<string>();
Console.WriteLine("enter text in English");
str = Console.ReadLine().ToLower();
strarray = str.Split(separator);
foreach (var item in strarray)
{
if (!item.Equals(string.Empty))
{
words.Add(item);
}
}
for (int i = 0; i < words.Count; i++)
{
for (int j = i; j < words.Count; j++)
{
if (words[i].Equals(words[j]))
{
k++;
}
if (k > 1 & words[i].Equals(words[j]))
{
words.RemoveAt(j);
j--;
}
}
Console.WriteLine(words[i] + " = " + k);
k = 0;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task2.RECTANGLE
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
while (true)
{
Console.WriteLine("enter a width more than 0 using the number");
if (Int32.TryParse(Console.ReadLine(), out a) & a>0)
{
break;
}
else
{
Console.WriteLine("error in entering width");
}
}
while (true)
{
Console.WriteLine("enter a length more than 0 using the number");
if (Int32.TryParse(Console.ReadLine(), out b) & b > 0)
{
break;
}
else
{
Console.WriteLine("error in entering length");
}
}
Console.WriteLine($"rectangle area = {a * b}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.BLL.Interface;
using Epam.Task7.USERS.DAL;
using Epam.Task7.USERS.DAL.Interface;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.BLL
{
public class UserLogic : IUserLogic
{
private readonly IUserDao userdao;
public UserLogic(IUserDao userDao)
{
this.userdao = userDao;
}
public void Add(User user)
{
this.userdao.Add(user);
}
public void Delete(int id)
{
this.userdao.Delete(id);
}
public string GetAll()
{
return this.userdao.GetAll();
}
public string ShowAwards(int id)
{
return this.userdao.ShowAwards(id);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.ROUND
{
public class Program
{
public static void Main(string[] args)
{
double radius;
double x;
double y;
ROUND сircle;
while (true)
{
Console.WriteLine("enter a radius more than or equal to 0");
if (double.TryParse(Console.ReadLine(), out radius) & radius >= 0)
{
break;
}
else
{
Console.WriteLine("error in entering radius");
}
}
while (true)
{
Console.WriteLine("enter x coordinate");
if (double.TryParse(Console.ReadLine(), out x))
{
break;
}
else
{
Console.WriteLine("error in entering x");
}
}
while (true)
{
Console.WriteLine("enter y coordinate");
if (double.TryParse(Console.ReadLine(), out y))
{
break;
}
else
{
Console.WriteLine("error in entering y");
}
}
сircle = new ROUND(radius, x, y);
Console.WriteLine($"Circle length = {сircle.Circle_length}");
Console.WriteLine($"Area circle = {сircle.Area_circle}");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.GAME
{
public abstract class BONUS : TERRITORY
{
public BONUS(int x, int y, int speedincrease)
{
if (x >= base.X & x <= 0)
{
throw new Exception("bonus can not be located abroad, error x");
}
if (y >= base.Y & y <= 0)
{
throw new Exception("bonus can not be located abroad, error y");
}
if (speedincrease > 0)
{
throw new Exception("speed bonus can not be negative");
}
if (this.Effecttime > 0)
{
throw new Exception("time bonus can not be negative");
}
this.X = x;
this.Y = y;
this.Speedincrease = speedincrease;
}
public new int X { get; set; }
public new int Y { get; set; }
public int Speedincrease { get; set; }
public int Effecttime { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Epam.Task8.REGULAREXPRESSIONS.EMAILFINDER
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("enter a string with email addresses");
string text = Console.ReadLine();
string regstr = @"\b[\w\.-]+@[\w\.-]+\.\w{2,6}\b";
var regex = new Regex(regstr);
var match = regex.Matches(text);
if (match.Count > 0)
{
Console.WriteLine("managed to find the following addresses");
foreach (var item in match)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("email addresses not found");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task1._2
{
class Program
{
public static void SIMPLE(int n)
{
for (int i = 2; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
Console.WriteLine("the number is not simple");
return;
}
}
Console.WriteLine("the number is simple");
}
static void Main(string[] args)
{
Console.WriteLine("enter a number more than 0");
while (true)
{
try
{
int n = int.Parse(Console.ReadLine());
if (n > 0)
{
SIMPLE(n);
break;
}
else
{
throw new Exception("Not this, enter a number more than 0");
}
}
catch
{
Console.WriteLine("Not this, enter a number more than 0");
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Epam.Task8.REGULAREXPRESSIONS.TIMECOUNTER
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("enter a string with time");
string text = Console.ReadLine();
string regstr = @"\s+([01]?[0-9]|2[0-3]):[0-5][0-9]";
var regex = new Regex(regstr, RegexOptions.IgnoreCase);
Console.WriteLine($"time met in the text {regex.Matches(text).Count} times");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Epam.Task8.REGULAREXPRESSIONS.DATEEXISTANCE
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("enter a string with date");
string text = Console.ReadLine();
string regstr = "(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-](19|20)[0-9]{2}";
var regex = new Regex(regstr, RegexOptions.IgnoreCase);
Console.WriteLine("in a string there is a date. " + regex.IsMatch(text));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.TRIANGLE
{
public class TRIANGLE
{
private double a;
private double b;
private double c;
public TRIANGLE(double a, double b, double c)
{
if (a <= 0 || b <= 0 || c <= 0)
{
throw new Exception("the side of the triangle cannot be less than or equal to 0");
}
if (a + b <= c || a + c <= b || b + c <= a)
{
throw new Exception("the sum of the two sides cannot be more or equal than the other");
}
this.a = a;
this.b = b;
this.c = c;
}
public double CalcPerimeter()
{
return this.a + this.b + this.c;
}
public double CalcArea()
{
double p = (this.a + this.b + this.c) / 2;
return Math.Sqrt(p * (p - this.a) * (p - this.b) * (p - this.c));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.GAME
{
public abstract class MOVINGOBJECT : TERRITORY
{
public MOVINGOBJECT(int x, int y, int speed)
{
if (x >= base.X & x <= 0)
{
throw new Exception("object can not be located abroad, error x");
}
if (y >= base.Y & y <= 0)
{
throw new Exception("object can not be located abroad, error y");
}
if (speed > 0)
{
throw new Exception("object can not be negative");
}
this.X = x;
this.Y = y;
this.Speed = speed;
}
public new int X { get; set; }
public new int Y { get; set; }
public int Speed { get; set; }
public void Move(int x, int y, BARRIER barrier)
{
if (!(barrier.X == this.X + x) & !(barrier.Y == this.Y + y))
{
if (x >= base.X & x <= 0)
{
throw new Exception("object can not be located abroad, error x");
}
if (y >= base.Y & y <= 0)
{
throw new Exception("object can not be located abroad, error y");
}
this.X = x;
this.Y = y;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Epam.Task5.SORTING_UNIT
{
public class Program
{
public static void Main(string[] args)
{
SORTINGUNIT ty = new SORTINGUNIT();
int[] array = { 15, 7, -5, 6, 4 };
Console.WriteLine("enter an unsorted array");
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("apply our method and output an array");
ty.Already += ty.Conclusion;
ty.Sortflow(array, ty.Compareint);
while (true)
{
if (!ty.Th.IsAlive)
{
break;
}
Console.WriteLine("wait another flow...");
}
foreach (var item in array)
{
Console.WriteLine(item);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.VECTOR_GRAPHICS_EDITOR
{
public class CIRCUMFERENCE : ROUND.ROUND
{
private double radiustwo;
public CIRCUMFERENCE(double radius, double x, double y, double radiustwo)
: base(radius, x, y)
{
if (radiustwo < 0)
{
throw new Exception("radius two should be positive");
}
this.radiustwo = radiustwo;
}
public double Radiustwo
{
get
{
return this.radiustwo;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Task3.GAME
{
public abstract class BARRIER : TERRITORY
{
public BARRIER(int x, int y, string color)
{
if (x >= base.X & x <= 0)
{
throw new Exception("barrier can not be located abroad, error x");
}
if (y >= base.Y & y <= 0)
{
throw new Exception("barrier can not be located abroad, error y");
}
this.X = x;
this.Y = y;
this.Color = color;
}
public new int X { get; set; }
public new int Y { get; set; }
public string Color { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.BLL.Interface
{
public interface IUserLogic
{
void Add(User user);
void Delete(int id);
string GetAll();
string ShowAwards(int id);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.DAL.Interface
{
public interface IUserDao
{
void Add(User user);
void Delete(int id);
string GetAll();
string ShowAwards(int id);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Epam.Task7.USERS.DAL.Interface;
using Epam.Task7.USERS.Entities;
namespace Epam.Task7.USERS.DAL
{
public class AwardDao : IAwardDao
{
private static string path = System.IO.Path.GetTempPath() + "awards.txt";
private static string pathusersandawards = System.IO.Path.GetTempPath() + "usersandawards.txt";
public void AddAward(Award award)
{
int k = 0;
StreamWriter output = new StreamWriter(path, true);
output.Close();
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
for (int i = 0; i < str.Length; i++)
{
if (str[0].Equals('1') & i == 0)
{
k++;
}
if (i == str.Length - 1)
{
break;
}
if (str[i].Equals((char)13) & str[i + 1].Equals((char)10))
{
k++;
}
}
input.Close();
output = new StreamWriter(path, true);
award.Id = k;
output.WriteLine(award.ToString());
output.Close();
}
public void Delete(int id)
{
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
input.Close();
int k = 0;
int firstchar = -1;
for (int i = 0; i < str.Length; i++)
{
if (i == str.Length - 1)
{
break;
}
if (str[i].Equals((char)13) & str[i + 1].Equals((char)10))
{
if (id == 0)
{
str = str.Remove(0, i);
str = str.Insert(0, "delete");
break;
}
k++;
if (firstchar >= 0)
{
str = str.Remove(firstchar, i - firstchar);
str = str.Insert(firstchar, "\r" + "\n" + "delete");
break;
}
if (k == id)
{
firstchar = i;
}
}
}
StreamWriter output = new StreamWriter(path, false);
output.Write(str);
output.Close();
}
public string GetAll()
{
StreamWriter output = new StreamWriter(path, true);
output.Close();
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
input.Close();
return str;
}
public void AddAwardForUser(int iduser, int idaward)
{
StreamWriter output = new StreamWriter(pathusersandawards, true);
output.WriteLine(iduser + " " + idaward);
output.Close();
}
public string GetById(int id)
{
StreamWriter output = new StreamWriter(path, true);
output.Close();
StreamReader input = new StreamReader(path);
string str = input.ReadToEnd();
string[] delid;
input.Close();
for (int i = 0; i < str.Length; i++)
{
if ((str[0] + string.Empty).Equals(id.ToString()) & i == 0)
{
for (int j = 0; j < str.Length; j++)
{
if (str[j].Equals((char)13) & str[j + 1].Equals((char)10))
{
str = str.Remove(j, str.Length - j);
delid = str.Split(' ');
str = delid[1];
return str;
}
}
}
if (i == str.Length - 2)
{
break;
}
string idfromfile = str[i + 2] + string.Empty;
if (str[i].Equals((char)13) & str[i + 1].Equals((char)10))
{
if (idfromfile.Equals(id.ToString()))
{
for (int j = i + 2; j < str.Length; j++)
{
if (str[j].Equals((char)13) & str[j + 1].Equals((char)10))
{
str = str.Remove(j, str.Length - j);
delid = str.Split(' ');
str = delid[delid.Length - 1];
return str;
}
}
}
}
}
return null;
}
public void AddImage(int id)
{
Directory.CreateDirectory(System.IO.Path.GetTempPath() + "imageaward\\");
}
}
}
| 3255674a1ff54697fa7e2ca2dc5042a1e97dd7a9 | [
"JavaScript",
"C#"
] | 59 | C# | SergeyKormilicyn/XT-2018Q4 | aa8f3b55554bf66574c2f0727b298496fee3fa5e | 7b9257a649388cc0a1274622792588cb34ca9162 | |
refs/heads/master | <repo_name>yyyAndroid/Sproject<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/ui/activity/BaseActivity.java
package com.abe.dwwd.sporjectone.ui.activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
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 com.abe.dwwd.sporjectone.utils.LogUtils;
import java.util.HashMap;
import java.util.Map;
import butterknife.ButterKnife;
/**
* Created by Administrator on 2017/1/16.
*/
public class BaseActivity extends AppCompatActivity {
/**
* group:android.permission-group.CONTACTS//联系人
* permission:android.permission.WRITE_CONTACTS//写写联系人
* permission:android.permission.GET_ACCOUNTS//得到账号
* permission:android.permission.READ_CONTACTS//读联系人
* <p>
* group:android.permission-group.PHONE
* permission:android.permission.READ_CALL_LOG
* permission:android.permission.READ_PHONE_STATE
* permission:android.permission.CALL_PHONE
* permission:android.permission.WRITE_CALL_LOG
* permission:android.permission.USE_SIP
* permission:android.permission.PROCESS_OUTGOING_CALLS
* permission:com.android.voicemail.permission.ADD_VOICEMAIL
* <p>
* group:android.permission-group.CALENDAR
* permission:android.permission.READ_CALENDAR
* permission:android.permission.WRITE_CALENDAR
* <p>
* group:android.permission-group.CAMERA
* permission:android.permission.CAMERA
* <p>
* group:android.permission-group.SENSORS
* permission:android.permission.BODY_SENSORS
* <p>
* group:android.permission-group.LOCATION
* permission:android.permission.ACCESS_FINE_LOCATION
* permission:android.permission.ACCESS_COARSE_LOCATION
* <p>
* group:android.permission-group.STORAGE
* permission:android.permission.READ_EXTERNAL_STORAGE
* permission:android.permission.WRITE_EXTERNAL_STORAGE
* <p>
* group:android.permission-group.MICROPHONE
* permission:android.permission.RECORD_AUDIO
* <p>
* group:android.permission-group.SMS
* permission:android.permission.READ_SMS
* permission:android.permission.RECEIVE_WAP_PUSH
* permission:android.permission.RECEIVE_MMS
* permission:android.permission.RECEIVE_SMS
* permission:android.permission.SEND_SMS
* permission:android.permission.READ_CELL_BROADCASTS
*
* @param savedInstanceState
* @param persistentState
*/
private static final String TAG = "BaseActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* 检查权限并申请
*/
private Map<Integer, String> requestCodes;
protected boolean checkAppPermission(final String permission, final int requestCode, String message) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermission(permission, requestCode);
}
}).show();
} else {
//申请权限
requestPermission(permission, requestCode);
}
return false;
}
return true;
}
/**
* 申请权限
*/
private void requestPermission(String permission, int requestCode) {
if (requestCodes == null) {
requestCodes = new HashMap();
}
if (!requestCodes.containsKey(requestCode)) {
requestCodes.put(requestCode, permission);
}
//申请权限
ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCodes.containsKey(requestCode)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionCallback(true, requestCode, requestCodes.get(requestCode));
} else {
permissionCallback(false, requestCode, requestCodes.get(requestCode));
}
requestCodes.remove(requestCode);
}
}
/**
* 权限返回状态
*
* @param successed
* @param requestCode
*/
protected void permissionCallback(boolean successed, int requestCode, String permission) {
LogUtils.d("permission:" + permission + " requestCode:" + requestCode + " success:" + successed);
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportDBOperator.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
*/
public class ExportDBOperator extends ExportOperate{
@Override
public ExportFileApi newFile() {
return new ExportDBFile();
}
public void export(String data){
ExportDBFile file = new ExportDBFile();
file.export(data);
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportTextOperator.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
*/
public class ExportTextOperator {
}
<file_sep>/README.md
# Sproject
####动画百分比柱状图
<img src="https://github.com/yyyAndroid/Sproject/blob/master/gif/GIF.gif" width = "320" height = "640" align=center />
####ViewPage效果
<img src="https://github.com/yyyAndroid/Sproject/blob/master/gif/GIF2.gif" width = "320" height = "640" align=center />
#####下拉刷新
<img src="https://github.com/yyyAndroid/Sproject/blob/master/gif/GIF3.gif" width = "320" height = "640" align=center />
```
//支持ListView ScrolView RecyclerView
<com.abe.dwwd.sporjectone.view.refresh.RefreshLayout
android:id="@+id/refresh_layout"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</com.abe.dwwd.sporjectone.view.refresh.RefreshLayout>
```
#####签到dialog
<img src="https://github.com/yyyAndroid/Sproject/blob/master/gif/GIF4.gif" width = "320" height = "640" align=center />
<file_sep>/app/src/androidTest/java/com/abe/dwwd/sporjectone/until/CalculatorTest.java
package com.abe.dwwd.sporjectone.until;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Administrator on 2017/2/16.
*/
public class CalculatorTest {
private Calculator mCalculator;
@Before
public void setUp() throws Exception {
mCalculator = new Calculator();
}
@Test
public void sum() throws Exception {
assertEquals(6d,mCalculator.sum(1d,5d),0);
}
@Test
public void substract() throws Exception {
assertEquals(1d,mCalculator.substract(5d,4d),0);
}
@Test
public void divide() throws Exception {
assertEquals(4d,mCalculator.divide(20d,5d),0);
}
@Test
public void multiply() throws Exception {
assertEquals(10d,mCalculator.multiply(2d,5d),0);
}
}<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/view/CustomDrawText.java
package com.abe.dwwd.sporjectone.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by Administrator on 2017/1/6.
* 绘制文字方法
* //第一类 只能在指定文本极限位置(基线x默认在字符串左侧,基线y默认在字符串下方)
*
* public void drawText(String text,float x,float y,Paint paint);
* public void drawText(String text,int start,int end,float x,float y,Paint paint);
* public void drawText(CharSequence text,int start,int end,float x,float y,Paint paint);
* public void drawText(char[] text,int index,int count,float x,float y,Paint paint);
*
* //第二类 可以分别指定每个文字的位置
* public void drawPostText(String text,float[] pos,Paint paint)
* public void drawPostText(char[] text,int index,int count,float[] pos,Paint);
*
* //第三类 指定一个路径,根据路径绘制文字
* public drawTextOnPath(String text,Path path,float hOffsef,float voffset,Paint paint);
* public drawTextOnPath(char[] text,int index,int count,Path path,float hOffset,float vOffset,Paint paint);
*
*
* Paint文本相关常用的方法
* setColor,setARGB,setAlpha
* setTextSize
* setTypeface
* setStyle FILL,STROKE,FILL_AND_STROKE
* setTestAlign 左对齐(LEFT),居中(CENTER),右对齐(RIGHT)
* measureText 测量文字大小(注意,请在设置完文本各项参数后条用)
*
*/
public class CustomDrawText extends View {
public CustomDrawText(Context context) {
super(context);
}
public CustomDrawText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomDrawText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setStyle(Paint.Style.FILL);
// textPaint.setTypeface(Typeface.SERIF);
textPaint.setTextSize(50);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
String str = "HELL";
// 第一类方法:参数分别为 (文本,基线x,基线y,画笔)
// canvas.drawText(str,200,500,textPaint);
//第二类方法:
/* canvas.drawPosText(str,new float[]{
100,100,
200,200,
300,300,
400,400
},textPaint);*/
//第三类(drawTextOnPath)
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportFileOperator.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
*/
public class ExportFileOperator extends ExportOperate{
@Override
public ExportFileApi newFile() {
return new ExportTextFile();
}
public void export(String data) {
ExportTextFile file = new ExportTextFile();
file.export(data);
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/bean/Course.java
package com.abe.dwwd.sporjectone.bean;
/**
* Created by Administrator on 2017/2/28.
*/
public class Course {
private double math;
private double english;
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportOperate.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
*/
public abstract class ExportOperate {
public abstract ExportFileApi newFile();
/**
* 导出数据
* @param data
*/
public void export(String data){
ExportFileApi file = newFile();
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/CustomView/CustomImageCharacterView.java
package com.abe.dwwd.sporjectone.CustomView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.PictureDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Administrator on 2017/1/3.
* 绘制图片 使用Picture是要关闭硬件加速
* drawPicture(矢量图)
* drawBitmap(位图)
* public int getWidth()//获取宽度
* public int getHeight()//获取高度
* public Canvas beginRecordin(int width,int height)//开始录制返回一个Canvas,在
* Canvas中素有的绘制都会存储在Picture
* public void endRecoding()//结束录制
* public void draw(Canvas canvas)将Picture中内容会知道Canvas中
* public static Picture createFromStream(InputStream stream)//通过输入流常见一个Picture
* public static Picture writeToStream(OutputStream stream)//将Picture中内容写出到
*/
public class CustomImageCharacterView extends View {
//1.创建Picture
private Picture mPicture = new Picture();
private static final String TAG = "CustomImageCharacterVie";
private static final String TAG_NAME = "图片文字控件";
private Context mContext;
public CustomImageCharacterView(Context context) {
this(context, null);
Log.e(TAG, TAG_NAME + "this(context, null);");
}
public CustomImageCharacterView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
Log.e(TAG, TAG_NAME + "this(context, null,0);");
}
public CustomImageCharacterView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
Log.e(TAG, TAG_NAME + "super(context, attrs,defStyleAttr);");
recording();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.e(TAG, TAG_NAME + "mPicture.getHeight():" + mPicture.getHeight() + " mPicture.getWidth():" + mPicture.getWidth());
// drawPictureMethod(canvas);
drawBitmapMethod(canvas);
}
/**
* 注注:需要关闭硬件加速
* 注注:需要关闭硬件加速
* 注注:需要关闭硬件加速
* 注注:需要关闭硬件加速
* 注注:需要关闭硬件加速
* 注注:需要关闭硬件加速
* 注注:需要关闭硬件加速
* @param canvas
*/
private void drawPictureMethod(Canvas canvas) {
//第一种使用方式 对Canvas有影响,绘制完成后会影响
mPicture.draw(canvas);
//第二种使用方式 对Canvas操作无影响
canvas.drawPicture(mPicture, new RectF(0, 0, mPicture.getWidth(), 200));
//第三种使用方式
PictureDrawable drawable = new PictureDrawable(mPicture);
drawable.setBounds(0, 0, 250, mPicture.getHeight());
drawable.draw(canvas);
Log.e(TAG, TAG_NAME + "onDraw(Canvas canvas)");
}
/**
* 在Canvas中绘制图片
* @param canvas
*/
private void drawBitmapMethod(Canvas canvas){
//第一种
// canvas.drawBitmap(getBitmap(),new Matrix(),new Paint());
//第二种
canvas.drawBitmap(getBitmap(),200,500,new Paint());
//第三种
canvas.drawBitmap(getBitmap(),new Rect(0,0,getBitmap().getWidth()/2,getBitmap().getHeight()/2),
new RectF(0,0,200,100),null);
}
private Bitmap getBitmap(){
//资源文件 raw
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), android.R.mipmap.sym_def_app_icon);
//assets 资源文件
/* Bitmap bitmap1 = null;
try {
InputStream is = mContext.getAssets().open("bitmap.png");
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
//内存卡读取文件
Bitmap bitmap2 = BitmapFactory.decodeFile("/sdcard/bitmap.png");*/
return bitmap;
}
//2.录制内容方法
private void recording() {
//开始录制
Canvas canvas = mPicture.beginRecording(300, 300);
//创建一个画笔
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL);
//在Canvas中的具体操作
canvas.translate(250, 250);
//绘制一个圆
canvas.drawCircle(0, 0, 100, paint);
mPicture.endRecording();//结束录制
}
}
<file_sep>/text/rxjava_read.md
##Rxjava到底是什么?
Rxjava在Github主页上的自我介绍是:一个在Java VM上使用__可观测的序列__ 来组成异步的,基于事件的程序库
然而,对于初学者来说,这太难看懂了,因为它是一个 总结,而初学者需要一个引言。
###RxJva好在哪里
换句话说,【同样是异步,为什么人们用它,而不用现成的 AsyncTask、Handler//xxx】
一个词:简洁
RxJava的观察者模式
RxJava有四个基本概念:Observable(可观察者,既被观察者)、Observer(观察者)、subscribe(订阅)、事件。Observable和Observer通过subscribe()
方法实现订阅关系,从而Observable可以在需要的时候发出事件来通知Observer
与传统观察者模式不同RxJava的事件毁掉方法除了普通事件onNext() (相当于onClick()/onEvent())之外,还定义了两个特殊的事件:
onCompleted()和onError();
onComplete():事件队列完结。RxJava不仅把每个事件丹徒处理,还会把它看做一个队列。RxJava规定,当不在有新的onNext()发出时,需要出发onCompleted()
方法作为标志
onError():事件队列异常。事件处理过程中出现异常时,onError()会被出发,同时队列会自动终止,不允许再有事件发出
在一个正确运行的事件序列中,onComlplete()和onError()有且只有一个,并且是事件序列中的最后一个。需要注意的是,onCompleted()和onError()二者也是互相
排斥的,既在队列中调用了其中一个,就不应该在调用另一个。
2.基本实现
RxJava的基本实现由3点:
1).创建Observer
Observer既观察者,它决定事件触发的时候将有怎样的操作的行为。RxJava中的Observer接口的实现方式:
除了Observer接口之外,RxJava还内置了一个实现Observer的抽象类:Subscriber.Subscriber对Observer接口进行了一些扩展
,但他们的基本使用方式是完全一样的
不仅基本使用方式一样,实质上,在RxJava的subscriber过程中,Observer也是会先被转换成一个Subscriber再使用。所以如果你
只想使用基本功能,选择Observer和Subscriber是完全一样的。它们的区别对于使用者来说主要有两点:
1). onStart():这是Subscriber增加的方法。它会在subscribe刚开始,而时间还未发送之前被调用,可以用于做一些准备工作,例如数据的清零和重置。这是一个
可选择的方法,默认情况下它的实现为空。需要注意的是,如果对准备工作的线程有要求(例如弹出一个显示进度的对话框,这必须在主线程),onStart()就不适用了,
因为它总是在subscribe所发生的线程被调用,而不能指定线程。要在指定的线程来做准备工作,可以使用doOnSubscribe()方法,具体可以在后面的稳重看到。
2.)unSubscribe():这是subscriber所实现的另一个接口Subscription的方法,用于取消订阅。
在这个方法调用后,Subscriber将不在接受时间。一般在这个方法钱,可以使用isUnsubscribe()先判断一下状态、unsubscibe()这个方法很重要,
因为在subscribe()之后,Observable会持有Subscriber的引用,这个引用如果不能及时被释放,将有内存泄漏的的风险。所以最好保持一个原则:
要在不在使用的时候尽快的合适的地方(例如onPauser() onStop()等方法中)电泳unSubscribe()来解除引用关系,以避免内存泄漏的发生。
2.创建Observable
Observable既被观察者,它决定什么时候触发事件以及触发怎样的事件。RxJava使用create()方法来创建一个Observable,
并为它定义事件触发规则:
3.Subscribe(订阅)
1).创建了Observable()和Observer()之后,再用subscriber()方法将他们链接起来,整条链子就可以工作了。代码形式很简单:
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportExceOperator.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
*/
public class ExportExceOperator {
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/MainActivity.java
package com.abe.dwwd.sporjectone;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.abe.dwwd.sporjectone.rxjava.RxJavaSecondActivity;
import com.abe.dwwd.sporjectone.rxjava.RxJavaVaryActivity;
import com.abe.dwwd.sporjectone.ui.activity.BaseActivity;
import com.abe.dwwd.sporjectone.ui.activity.ChartActivity;
import com.abe.dwwd.sporjectone.ui.activity.MoveActivity;
import com.abe.dwwd.sporjectone.ui.activity.OkHttpActivity;
import com.abe.dwwd.sporjectone.ui.activity.PathPainterActivity;
import com.abe.dwwd.sporjectone.ui.activity.PullToRefreshActivity;
import com.abe.dwwd.sporjectone.ui.activity.SearchViewActivity;
import com.abe.dwwd.sporjectone.ui.activity.VLayoutActivity;
import com.abe.dwwd.sporjectone.ui.activity.ViewPageActivity;
import com.abe.dwwd.sporjectone.view.SignInDialog;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends BaseActivity {
Button btChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btChart = (Button) findViewById(R.id.bt_chart);
}
public void clickChart(View view){
if (btChart == null){
Toast.makeText(this, "bt为空", Toast.LENGTH_SHORT).show();
}
startActivity(new Intent(this, ChartActivity.class));
}
public void clickOkHttp(View view){
startActivity(new Intent(this, OkHttpActivity.class));
}
public void clickViewpage(View view){
startActivity(new Intent(this, ViewPageActivity.class));
}
public void clickMove(View view){
startActivity(new Intent(this, MoveActivity.class));
}
public void clickRefresh(View view){
startActivity(new Intent(this, PullToRefreshActivity.class));
}
public void clickSignDialog(View view){
SignInDialog signInDialog = new SignInDialog(this,null);
signInDialog.show();
}
public void clickRx(View view){
startActivity(new Intent(this, RxJavaSecondActivity.class));
}
public void clickRxVary(View view){
startActivity(new Intent(this, RxJavaVaryActivity.class));
}
public void clickVLayout(View view){
startActivity(new Intent(this, VLayoutActivity.class));
}
public void clickSearch(View view){
startActivity(new Intent(this, SearchViewActivity.class));
}
public void clickPathMeasure(View view){
startActivity(new Intent(this, PathPainterActivity.class));
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportExceFile.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
*/
public class ExportExceFile implements ExportFileApi {
@Override
public void export(String data) {
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/facetory/ExportDBFile.java
package com.abe.dwwd.sporjectone.facetory;
/**
* Created by Administrator on 2017/2/15.
* 数据库文件
*/
public class ExportDBFile implements ExportFileApi{
@Override
public void export(String data) {
System.out.println("导出到数据库文件");
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/ui/activity/OkHttpActivity.java
package com.abe.dwwd.sporjectone.ui.activity;
import android.os.Bundle;
import android.view.View;
import com.abe.dwwd.sporjectone.R;
public class OkHttpActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok_http);
}
public void clickRequest(View view){
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
repositories {
flatDir {
dirs 'libs/aar'
}
mavenCentral()
jcenter()
maven {
url "http://mvn.gt.igexin.com/nexus/content/repositories/releases/"
}
maven { url "https://jitpack.io" }
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.abe.dwwd.sporjectone"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
// View注入框架
compile 'com.jakewharton:butterknife:+'
compile 'com.orhanobut:logger:+'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.squareup.okhttp:okhttp:+'
compile 'com.squareup.okio:okio:+'
compile 'com.android.support:design:25.1.0'
//RxJava
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.0.1'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
compile('com.alibaba.android:vlayout:1.0.2@aar') {
transitive = true
}
//可选,用于生成application类
/* compile('com.tencent.tinker:tinker-android-anno:1.7.1')
//tinker的核心库
compile('com.tencent.tinker:tinker-android-lib:1.7.1')*/
// compile 'cn.pedant.sweetalert:library:1.3'
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/view/SignInDialog.java
package com.abe.dwwd.sporjectone.view;
import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import com.abe.dwwd.sporjectone.R;
/**
* Created by yanyangy on 2017/2/23.
* 签到dialog
*/
public class SignInDialog extends Dialog {
ImageView ivBack;//返回
ImageView ivHeader;//头像
String headerUrl;
View view;
public SignInDialog(Context context, String headerUrl) {
super(context, R.style.sign_in_dialog);
this.headerUrl = headerUrl;
init();
}
private void init(){
view = LayoutInflater.from(getContext()).inflate(R.layout.view_sign_in, null);
ivBack = (ImageView) view.findViewById(R.id.sign_in_back);
ivHeader = (ImageView) view.findViewById(R.id.sign_in_header);
setContentView(view);
configurationWindow();
}
/**
* 配置windows
*/
private void configurationWindow() {
this.setCanceledOnTouchOutside(false);
Window select_window = getWindow();
select_window.setGravity(Gravity.TOP);
WindowManager.LayoutParams lp = select_window.getAttributes();
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
select_window.setAttributes(lp);
}
@Override
public void show() {
super.show();
}
@Override
public void dismiss() {
super.dismiss();
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/ui/activity/PullToRefreshActivity.java
package com.abe.dwwd.sporjectone.ui.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import com.abe.dwwd.sporjectone.R;
import com.abe.dwwd.sporjectone.view.refresh.OnRefreshListener;
import com.abe.dwwd.sporjectone.view.refresh.RefreshLayout;
import butterknife.BindView;
public class PullToRefreshActivity extends BaseActivity {
RefreshLayout refreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_reflsh);
refreshLayout = (RefreshLayout) findViewById(R.id.refresh_layout);
refreshLayout.setEnabled(true);
refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
Toast.makeText(PullToRefreshActivity.this, "下拉刷新", Toast.LENGTH_SHORT).show();
refreshLayout.postDelayed(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
}
},3000);
}
});
}
}
<file_sep>/app/src/main/java/com/abe/dwwd/sporjectone/rxjava/RxJavaActivity.java
package com.abe.dwwd.sporjectone.rxjava;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.abe.dwwd.sporjectone.R;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.ActionN;
public class RxJavaActivity extends AppCompatActivity {
private static final String TAG = "RxJavaActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_java);
}
/**
* 创建 Observer观察者
*/
Observer<String> observer = new Observer<String>() {
@Override
public void onCompleted() {
Log.d(TAG, TAG + " onCompleted()");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, TAG + " onError()" + e);
}
@Override
public void onNext(String s) {
Log.d(TAG, TAG + " s:" + s);
}
};
/**
* RxJava还内置了一个实现Observer的抽象类:Subscriber.Subscriber对Observer接口进行了一些扩展,但他们的基本使用方式是完全一样的:
*/
Subscriber<String> subscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
Log.d(TAG, TAG + " onCompleted");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, TAG + " onError():" + e);
}
@Override
public void onNext(String s) {
Log.d(TAG, TAG + " onNext():" + s);
}
};
/**
* 这里传入了一个OnSubscribe对象作为参数。OnSubscribe会被存储在返回的Observable对象中,它的作用相当于一个计划表,当
* Observable被订阅的时候,OnSubscriber的call()方法 会自动被调用,时间序列就会依照设定一次触发(对于上面的代码,就是观察者Subscriber将会
* 被调用三次onNext()和一次 onComplete()。这样,有被观察者调用了观察者的回调方法,就实现了由被观察者向观察者的事件传递,既观察者模式。
*/
Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("Hello");
subscriber.onNext("Hi");
subscriber.onNext("abe");
subscriber.onCompleted();
}
});
/**
* create()方法是RxJava最基本的创造事件序列的方法。基于这个方法,RxJava还提供了一些方法用来快捷创建事件队列,例如:
* <p>
* just(T...):将传入的参数一次发送出来。
*/
Observable observable2 = Observable.just("Hello", "hi", "abe");
/*将会一次调用:
onNext("Hello");
onNext("Hi");
noNext("abe");
onCompleted();
*/
/**
* from(T[]) / from(Iterable<? extend T>); 将传入的数组或Iterable拆分成具体对象后,依次发送出来。
*/
String[] words = {"Hello", "Hi", "abe"};
Observable observable3 = Observable.from(words);
/*
讲一次调用:
onNext("Hello");
onNext("Hi");
onNext("abe");
onCompleted();
*/
//上面just(T...)的例子,都和之前的create(OnSubscribe)的例子是等价的
/**
* 除了subscribe(Observer)和subscriber(Subscriber),subscribe()还支持不完整定义的回调,
* RxJava会自动根据定义创建出Subscriber。形式如下:
*/
Action1<String> onNextAction = new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG," onNext "+s);
}
};
Action1<String> onErrorAction = new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG,"error :"+s);
}
};
Action0 onCompleteAction = new Action0() {
@Override
public void call() {
Log.d(TAG," onCompleteAction ");
}
};
/**
* Subscribe(订阅)
*/
public void init() {
//observable.subscribe(subscriber);
//或者
//observable.subscribe(observer);
//自动创建 Subscriber,并使用onNextAction 来定义 onNext();
observable.subscribe(onNextAction);
//自动创建 Subscriber, 并使用onNextAction和 onErrorAction()来定义 onNext()和onError();
observable.subscribe(onNextAction,onErrorAction);
//自动创建 Subscriber,并使用onNextAction 和 onErrorAction() 和 onCompleteAction() 来定义 onNext()和onError和 onComplete();
observable.subscribe(onNextAction,onErrorAction,onCompleteAction);
}
//简单的RxJava例子
public void clickBt(View view){
String[] names = new String[]{"",""};
Observable.from(names).subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG,s);
}
});
}
/**
* 3.线程控制 -- Scheduler (一)
* 在不指定线程的情况下,RxJava遵循的是线程不变原则,既:在哪一个线程调用Subscriber(),就在哪个线程生产事件;在哪个线程消费事件。如果需要切换线程,
* 就系要用到Scheduler(调度器)
*
* 1).Schedule的API(一)
* 在RxJava中,Scheduler -- 调度器,相当于相当于线程控制器,RxJava通过它来指定每一段代码应该运行在什么样的线程。RxJava已经内置了
* 几个Scheduler,它们已近适合大多数的使用场景:
*
* 1.Schedulers.immediate():直接在当前线程运行,相当于不指定线程。这是模式的Scheduler
* 2.Schedulers.newThread():总是启用新线程,并在新县城执行操作
* 3.Schedulers.io():I/O操作(读写文件、读写数据库、网络信息交互等)所使用的Scheduler。行为模式和newThread()差不多,
* 区别在于io()的内部实现的是一个无数量限制的线程池,可以重用空闲的线程,因此多数情况下io()比newThread()更有效。
* 不要把计算工作放在io()中,可以避免创建不必要的线程。
* 4.Schedulers.computation():计算所使用的Scheduler。这个计算值得是CPU密集型计算,既不会被i/o等操作限制性能的操作,例如图形计算
* 。这个Scheduler使用的固定的线程池,大小为CPU核数。不要把i/o操作放在computation()中,否则i/o操作的等待会时间会浪费CPU资源
* 5.另外,Android还有一个专用的AndroidSchedulers.mainThread(),它指定的操作将在Android主线程中运行。
*
*/
}
| 8b1031ff252da5ef1148924f0119f7c1df14f334 | [
"Markdown",
"Java",
"Gradle"
] | 20 | Java | yyyAndroid/Sproject | 03ad499463db63ad36cbc1c20f85b337e42ecea5 | dba3c8e756aa8db15f2a2cfc338696fb5b853eca | |
refs/heads/master | <repo_name>Mastergalen/Zugy-Laravel-eCommerce-Store<file_sep>/app/Listeners/NotifyDriversOfOrder.php
<?php
namespace App\Listeners;
use App\Events\OrderWasPlaced;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Pushbullet\Pushbullet;
class NotifyDriversOfOrder
{
/**
* @var Pushbullet
*/
private $pb;
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
$this->pb = new Pushbullet(config('services.pushbullet.token'));
}
/**
* Handle the event.
*
* @param OrderWasPlaced $event
* @return void
*/
public function handle(OrderWasPlaced $event)
{
$orderUrl = action('Admin\OrderController@show', $event->order->id);
$channel = config('site.pushbullet.channels.orders');
$this->pb->channel($channel)->pushLink(
"A new order has been placed on Zugy",
$orderUrl,
("Total: {$event->order->total} Euro")
);
}
}
<file_sep>/app/Zugy/Repos/DbRepository.php
<?php
namespace Zugy\Repos;
abstract class DbRepository
{
public function find($id) {
return $this->model->findOrFail($id);
}
public function all() {
return $this->model->all();
}
public function paginate($perPage) {
return $this->model->paginate($perPage);
}
public function with($model) {
return $this->model->with($model);
}
public function orderBy($table, $direction)
{
return $this->model->orderBy($table, $direction);
}
}<file_sep>/tests/AddressTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AddressTest extends TestCase
{
use DatabaseTransactions;
private $user;
protected function setUp()
{
parent::setUp();
$this->user = factory(App\User::class)->create();
$this->actingAs($this->user);
//Add item to cart to bypass checkout middleware, which requires a non-empty cart
$product = factory(App\Product::class)->create();
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => 1, //Qty 1
])->seeJson(['status' => 'success']);
}
/**
* Test adding a simple address
*/
public function testCreateAddress()
{
$service = new App\Services\CreateOrUpdateAddress();
$address = factory(App\Address::class)->make([
'country' => 'ITA'
]);
$service->delivery($address->toArray());
$database = $address->toArray();
unset($database['country']);
$this->seeInDatabase('addresses', $database);
}
/**
* Test trying to add a delivery outside delivery area
*/
public function testCreateAddressOutsideDeliveryArea()
{
$service = new App\Services\CreateOrUpdateAddress();
$address = factory(App\Address::class)->make([
'country' => 'ITA',
'postcode' => 12345, //Outside delivery area
]);
$service->delivery($address->toArray());
$database = $address->toArray();
unset($database['country']);
$this->dontSeeInDatabase('addresses', $database);
}
/**
* Test user filling out address form with a billing address that is different from the delivery address
*/
public function testCreateDeliveryAddressWithDifferentBillingAddress() {
$this->visit('en/checkout/address')->see('Delivery Address');
$deliveryAddress = factory(App\Address::class)->make([
'country' => 'ITA'
]);
$billingAddress = factory(App\Address::class)->make([
'country' => 'ITA'
]);
$this->type($deliveryAddress->name, 'delivery[name]')
->type($deliveryAddress->line_1, 'delivery[line_1]')
->type($deliveryAddress->postcode, 'delivery[postcode]')
->type($deliveryAddress->city, 'delivery[city]')
->type($deliveryAddress->delivery_instructions, 'delivery[delivery_instructions]')
->type($deliveryAddress->phone, 'delivery[phone]')
->uncheck('delivery[billing_same]')
->type($billingAddress->name, 'billing[name]')
->type($billingAddress->line_1, 'billing[line_1]')
->type($billingAddress->postcode, 'billing[postcode]')
->type($billingAddress->city, 'billing[city]')
->press('Proceed')
;
\Log::debug($deliveryAddress);
\Log::debug($billingAddress);
$databaseDeliveryAddress = $deliveryAddress->toArray();
unset($databaseDeliveryAddress['country']);
$databaseDeliveryAddress['isShippingPrimary'] = 1;
$databaseDeliveryAddress['isBillingPrimary'] = 0;
$databaseBillingAddress = $billingAddress->toArray();
unset($databaseBillingAddress['country']);
unset($databaseBillingAddress['delivery_instructions']);
unset($databaseBillingAddress['phone']);
$databaseBillingAddress['isShippingPrimary'] = 0;
$databaseBillingAddress['isBillingPrimary'] = 1;
$this->seeInDatabase('addresses', $databaseDeliveryAddress);
$this->seeInDatabase('addresses', $databaseBillingAddress);
}
}
<file_sep>/app/Http/Controllers/OrderController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Zugy\Repos\Order\OrderRepository;
class OrderController extends Controller
{
/**
* @var OrderRepository
*/
private $orderRepo;
/**
* OrderController constructor.
*/
public function __construct(OrderRepository $orderRepository)
{
$this->orderRepo = $orderRepository;
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$order = $this->orderRepo->find($id);
$order->vat;
return view('pages.order.show')->with(compact('order'));
}
}
<file_sep>/app/Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Order extends Model
{
use SoftDeletes;
protected $table = 'orders';
protected $with = ['items', 'coupon'];
protected $appends = ['total'];
protected $dates = ['order_placed', 'order_completed', 'delivery_time'];
protected $statuses = [
0 => 'New order',
1 => 'Being processed',
2 => 'Out for delivery',
3 => 'Delivered',
4 => 'Cancelled',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function items()
{
return $this->hasMany('App\OrderItem');
}
public function payment()
{
return $this->hasOne('App\Payment');
}
public function coupon()
{
return $this->belongsTo('App\Coupon');
}
public function activity()
{
return $this->hasMany('App\ActivityLog', 'content_id')->where('content_type', '=', 'Order');
}
public function getVatAttribute()
{
$totalVat = 0;
//Calculate VAT for items
foreach($this->items()->get() as $item) {
$net = $item->final_price / ((100 + $item->tax) / 100);
$totalVat += round($item->final_price - $net, 2);
}
//Calculate VAT for shipping
$fee = $this->attributes['shipping_fee'];
$shippingTax = config('site.shippingTax');
$net = $fee / ((100 + $shippingTax) / 100);
$vatShipping = round($fee - $net, 2);
$totalVat += $vatShipping;
return $totalVat;
}
public function getTotalAttribute()
{
return $this->items()->sum('final_price');
}
public function getGrandTotalAttribute()
{
return $this->getTotalAttribute() + $this->attributes['shipping_fee'] - $this->attributes['coupon_deduction'];
}
public function scopeUnprocessed($query) {
return $query->where('order_status', '=', 0);
}
public function scopeIncomplete($query) {
return $query->whereIn('order_status', [0, 1, 2]);
}
public function scopeUncancelled($query) {
return $query->where('order_status', '!=', 4);
}
public function getActivityDescriptionForEvent($eventName)
{
return $eventName;
}
}
<file_sep>/resources/lang/it/your-account.php
<?php
return [
'title' => 'Il tuo account',
'orders' => 'Ordini',
'orders.desc' => 'Controlla, rintraccia o cancella un ordine',
'orders.dispatch-to' => 'Invia a',
'payment.manage' => 'Gestisci i tuoi metodi di pagamento',
'settings.title' => 'Impostazioni',
'settings.email' => 'Cambia l\'indirizzo email o la password',
];<file_sep>/app/Zugy/Cart/CartServiceProvider.php
<?php
namespace Zugy\Cart;
use Illuminate\Support\ServiceProvider;
class CartServiceProvider extends ServiceProvider
{
public function register()
{
$this->app['zugyCart'] = $this->app->share(function($app)
{
$session = $app['session'];
$events = $app['events'];
return new Cart($session, $events);
});
}
}<file_sep>/app/Zugy/AlgoliaEloquentTrait/ZugyModelHelper.php
<?php
namespace Zugy\AlgoliaEloquentTrait;
use AlgoliaSearch\Laravel\ModelHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
class ZugyModelHelper extends ModelHelper
{
public function getFinalIndexName(Model $model, $indexName)
{
$appEnv = App::environment('testing') ? 'local' : App::environment();
$env_suffix = property_exists($model, 'perEnvironment') && $model::$perEnvironment === true ? '_' . $appEnv : '';
return $indexName.$env_suffix;
}
}<file_sep>/app/Zugy/Repos/Order/OrderRepository.php
<?php
namespace Zugy\Repos\Order;
interface OrderRepository {
/**
* Fetch incomplete orders
* @return mixed
*/
public function incomplete();
}<file_sep>/app/Http/Controllers/API/OrderController.php
<?php
namespace App\Http\Controllers\Api;
use App\Events\OrderStatusChanged;
use App\Http\Controllers\Controller;
use App\Order;
use Zugy\Repos\Order\OrderRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
class OrderController extends Controller
{
/**
* @var OrderRepository
*/
protected $orderRepository;
/**
* OrderController constructor.
*/
public function __construct(OrderRepository $orderRepository)
{
$this->orderRepository = $orderRepository;
}
public function update(Request $request, $orderId)
{
$order = Order::findOrFail($orderId);
if(Gate::denies('adminUpdate', $order)) {
abort(403);
}
$validator = Validator::make($request->all(), [
'order_status' => 'integer',
]);
if($validator->fails()) {
return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
}
if($order->order_status == $request->input('order_status')) {
return response()->json(['status' => 'error', 'message' => trans('order.api.error.status-same')], 422);
}
if($request->input('order_status') == 3) {//Set status to delivered, update payment to "paid"
$order->payment()->update(['status' => 1, 'paid' => \Carbon::now()]);
$order->order_completed = \Carbon::now();
}
$order->order_status = $request->input('order_status');
$order->save();
\Event::fire(new OrderStatusChanged($order));
return ['status' => 'success', 'message' => trans('order.api.update.success')];
}
public function show(Request $request, $orderId) {
$order = Order::findOrFail($orderId);
if(Gate::denies('show', $order)) {
abort(403);
}
return $order;
}
public function index(Request $request) {
if(Gate::denies('index', new Order())) {
abort(403);
}
return $this->orderRepository->orderBy('order_placed', 'desc')->paginate(30);
}
}<file_sep>/app/Zugy/Facades/PaymentGateway.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class PaymentGateway extends Facade
{
protected static function getFacadeAccessor() { return 'paymentGateway'; }
}<file_sep>/app/Zugy/Checkout/Checkout.php
<?php
namespace Zugy\Checkout;
use App\Address;
use App\Coupon;
use App\Exceptions\Coupons\CouponExpiredException;
use App\Exceptions\Coupons\CouponNotStartedException;
use App\Exceptions\Coupons\CouponOrderMinimumException;
use App\Exceptions\Coupons\CouponUsedException;
use App\PaymentMethod;
use App\User;
use Carbon\Carbon;
use Zugy\Facades\Cart;
class Checkout
{
protected $sessionKey = 'checkout';
protected $session;
public function __construct($session) {
$this->session = $session;
}
public function setShippingAddress(Address $address) {
$this->session->put($this->sessionKey . '.address.shipping', $address);
}
public function setBillingAddress(Address $address) {
$this->session->put($this->sessionKey . '.address.billing', $address);
}
public function setPaymentMethod(PaymentMethod $paymentMethod) {
$this->session->put($this->sessionKey . '.payment', $paymentMethod);
}
public function getShippingAddress(User $user = null) {
if($user !== null) {
return $user->addresses()->where('isShippingPrimary', '=', 1)->first();
}
$content = ($this->session->has($this->sessionKey . '.address.shipping')) ? $this->session->get($this->sessionKey . '.address.shipping') : null;
if($content === null && auth()->check()) {
$content = auth()->user()->addresses()->where('isShippingPrimary', '=', 1)->first();
}
return $content;
}
public function forgetShippingAddress() {
$this->session->forget($this->sessionKey . 'address.shipping');
}
public function getBillingAddress(User $user = null) {
if($user !== null) {
return $user->addresses()->where('isBillingPrimary', '=', 1)->first();
}
$content = ($this->session->has($this->sessionKey . '.address.billing')) ? $this->session->get($this->sessionKey . '.address.billing') : null;
if($content === null && auth()->check()) {
$content = auth()->user()->addresses()->where('isBillingPrimary', '=', 1)->first();
}
return $content;
}
public function forgetBillingAddress() {
$this->session->forget($this->sessionKey . 'address.billing');
}
public function getPaymentMethod() {
$content = ($this->session->has($this->sessionKey . '.payment')) ? $this->session->get($this->sessionKey . '.payment') : null;
if($content === null && auth()->check()) {
$content = auth()->user()->payment_methods()->default()->get()->first();
}
return $content;
}
public function setCoupon(Coupon $coupon)
{
self::validateCoupon($coupon);
$this->session->put($this->sessionKey . '.coupon', $coupon);
}
public function hasCoupon()
{
return $this->session->has($this->sessionKey . '.coupon');
}
public function validateCoupon(Coupon $coupon) {
//Check coupon has started
if($coupon->starts != null && Carbon::now() < $coupon->starts) {
throw new CouponNotStartedException();
}
//Check coupon is still valid
if($coupon->expires != null && Carbon::now() > $coupon->expires) {
throw new CouponExpiredException();
}
//Check uses
if($coupon->max_uses != null && $coupon->uses >= $coupon->max_uses) {
throw new CouponUsedException();
}
//Check minimum order total
if($coupon->minimumTotal != null && Cart::total() < $coupon->minimumTotal) {
throw new CouponOrderMinimumException();
}
return true;
}
public function getCoupon()
{
return ($this->session->has($this->sessionKey . '.coupon')) ? $this->session->get($this->sessionKey . '.coupon') : null;
}
public function forgetCoupon()
{
$this->session->forget($this->sessionKey . '.coupon');
}
public function setDeliveryDate($date) {
$this->session->put($this->sessionKey . '.delivery.date', $date);
}
public function setDeliveryTime($time) {
$this->session->put($this->sessionKey . '.delivery.time', $time);
}
public function getDeliveryDate() {
return $this->session->get($this->sessionKey . '.delivery.date');
}
public function getDeliveryTime() {
return $this->session->get($this->sessionKey . '.delivery.time');
}
/**
* Forget entire shopping cart settings
*/
public function forget() {
$this->session->forget($this->sessionKey);
\Cart::destroy();
}
}<file_sep>/app/Payment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Payment Status:
* 0 | Unpaid
* 1 | Paid
* 2 | Refunded
* 3 | Payment on delivery
*/
class Payment extends Model
{
protected $table = 'order_payments';
protected $fillable = ['status'];
protected $casts = [
'metadata' => 'json',
];
public function getFormatted()
{
switch($this->attributes['method']) {
case 'stripe':
return [
'method' => 'card',
'card' => [
'brand' => $this->metadata['source']['brand'],
'last4' => $this->metadata['source']['last4']
],
];
case 'paypal':
return [
'method' => 'paypal'
];
case 'cash':
return [
'method' => 'cash'
];
default:
throw new \Exception('Payment method does not exist:' . $this->attributes['method']);
break;
}
}
}
<file_sep>/resources/assets/js/setup.js
/*
* Add CSRF token to ajax request headers
*/
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="_token"]').attr('content'));
}
});
//Pjax default timeout increase
$.pjax.defaults.timeout = 4000;
$(document).on('ready pjax:success', function() {
$('[data-toggle="popover"]').popover();
});
/**
* Fetch GET variables from URL
* @param qs
* @returns {{}}
*/
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
<file_sep>/app/Policies/AddressPolicy.php
<?php
namespace App\Policies;
use App\Address;
use App\User;
class AddressPolicy extends BasePolicy
{
public function update(User $user, Address $address)
{
return $user->id === $address->user_id || $this->isAdmin($user);
}
public function show(User $user, Address $address)
{
return $user->id === $address->user_id || $this->isAdmin($user);
}
}<file_sep>/app/Exceptions/EmptyCartException.php
<?php
namespace App\Exceptions;
class EmptyCartException extends \Exception
{
public function __construct($message = "Cart cannot be empty")
{
parent::__construct($message);
}
}<file_sep>/app/ProductImage.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\FileNotFoundException;
class ProductImage extends Model
{
protected $table = 'product_images';
protected $appends = ['url'];
public function getURLAttribute() {
if(config('filesystems.default') == 's3') {
return "https://s3." . config('services.aws.region') . ".amazonaws.com/" . config('services.aws.bucket') . "/" . $this->attributes['location'];
} else {
return url('uploads/' . $this->attributes['location']);
}
}
public function product() {
return $this->belongsTo('App\Product');
}
/**
* Override parent delete
* Updates product references and deletes disk storage
* @throws FileNotFoundException
*/
public function delete() {
//Update parent product if has thumbnail set to the image to be deleted
$products = $this->product()->get();
foreach($products as $p) {
if($p->thumbnail_id == $this->attributes['id']) {
$p->thumbnail_id = null;
$p->save();
}
}
try {
Storage::disk(config('filesystems.default'))->delete($this->attributes['location']);
} catch(FileNotFoundException $e) {
//Carry on
}
parent::delete();
}
}
<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use App\Services\AuthenticateUser;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
if($this->app->environment('local')) {
$this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider');
$this->app->register('Barryvdh\Debugbar\ServiceProvider');
AliasLoader::getInstance()->alias('Debugbar', 'Barryvdh\Debugbar\Facade'); //Register alias
$this->app->register('Fitztrev\QueryTracer\Providers\QueryTracerServiceProvider');
}
$this->app->bind(AuthenticateUser::class, function() {
return new AuthenticateUser();
});
$this->app->bind('\AlgoliaSearch\Laravel\ModelHelper', 'Zugy\AlgoliaEloquentTrait\ZugyModelHelper');
$this->app->bind('Zugy\Repos\Order\OrderRepository', 'Zugy\Repos\Order\DbOrderRepository');
$this->app->bind('Zugy\Repos\Category\CategoryRepository', 'Zugy\Repos\Category\DbCategoryRepository');
$this->app->bind('Zugy\Repos\Product\ProductRepository', 'Zugy\Repos\Product\DbProductRepository');
}
}
<file_sep>/resources/lang/en/postcode.php
<?php
return [
'check.success' => 'We deliver to you!',
'browse-store' => 'Browse the store',
'check.error.title' => 'We currently do not deliver to your area. Sorry!',
'check.error.desc' => 'You can still browse our store, however.',
'api.error.postcode.invalid' => 'The postcode was invalid.',
];<file_sep>/resources/lang/en/status.php
<?php
return [
'payment.0' => 'Unpaid',
'payment.1' => 'Paid',
'payment.2' => 'Refunded',
'payment.3' => 'Payment on delivery',
];<file_sep>/app/Http/Middleware/ShopClosed.php
<?php
namespace App\Http\Middleware;
use Carbon\Carbon;
use Closure;
class ShopClosed
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$reopeningTime = Carbon::create(2017, 9, 28, 4, 0, 0); //4 am Wednesday
if(Carbon::now() < $reopeningTime) {
$request->session()->put('error', "Sorry, we are closed for a short summer break! We will be back open soon!");
}
return $next($request);
}
}
<file_sep>/app/Exceptions/Coupons/CouponUsedException.php
<?php
namespace App\Exceptions\Coupons;
class CouponUsedException extends \Exception
{
}<file_sep>/app/Listeners/LogSuccessfulLogin.php
<?php
namespace App\Listeners;
use Carbon\Carbon;
use Illuminate\Auth\Events\Login;
class LogSuccessfulLogin
{
/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event)
{
\Log::info('User logged in', [
'id' => auth()->user()->id,
'ip' => $_SERVER['REMOTE_ADDR']
]);
auth()->user()->last_login = Carbon::now();
auth()->user()->last_login_ip = $_SERVER['REMOTE_ADDR'];
auth()->user()->save();
}
}
<file_sep>/database/seeds/CategoriesSeeder.php
<?php
use Illuminate\Database\Seeder;
class CategoriesSeeder extends Seeder
{
public function run() {
DB::table('categories')->insert([
['id' => 1, 'parent_id' => null],
['id' => 2, 'parent_id' => null],
['id' => 3, 'parent_id' => 1],
['id' => 4, 'parent_id' => 1],
['id' => 5, 'parent_id' => 3],
['id' => 6, 'parent_id' => 3],
['id' => 7, 'parent_id' => 1],
['id' => 8, 'parent_id' => 3],
['id' => 9, 'parent_id' => 3],
['id' => 10, 'parent_id' => 1], // Special
['id' => 11, 'parent_id' => 3],
['id' => 12, 'parent_id' => null], //Mixers
['id' => 13, 'parent_id' => 12], //Soda
['id' => 14, 'parent_id' => 12], //Juice
['id' => 15, 'parent_id' => 12], //Energy drinks
['id' => 16, 'parent_id' => null], //Deals
['id' => 17, 'parent_id' => 16], //Packs
['id' => 18, 'parent_id' => 7], //Craft Beer
['id' => 19, 'parent_id' => null], // Other products
['id' => 20, 'parent_id' => 1],
['id' => 22, 'parent_id' => null], //Summer sales
]);
DB::table('category_translations')->insert([
['category_id' => 1, 'locale' => 'en', 'name' => 'Alcohol', 'slug' => 'alcohol'],
['category_id' => 1, 'locale' => 'it', 'name' => 'Alcol', 'slug' => 'alcol'],
['category_id' => 2, 'locale' => 'en', 'name' => 'Food', 'slug' => 'food'],
['category_id' => 2, 'locale' => 'it', 'name' => 'Cibo', 'slug' => 'cibo'],
['category_id' => 3, 'locale' => 'en', 'name' => 'Spirits', 'slug' => 'spirits'],
['category_id' => 3, 'locale' => 'it', 'name' => 'Superalcolici', 'slug' => 'superalcolici'],
['category_id' => 4, 'locale' => 'en', 'name' => 'Wine & champagne', 'slug' => 'wine-and-champagne'],
['category_id' => 4, 'locale' => 'it', 'name' => 'Vino e champagne', 'slug' => 'vino-e-champagne'],
['category_id' => 5, 'locale' => 'en', 'name' => 'Vodka', 'slug' => 'vodka'],
['category_id' => 5, 'locale' => 'it', 'name' => 'Vodka', 'slug' => 'vodka'],
['category_id' => 6, 'locale' => 'en', 'name' => 'Rum', 'slug' => 'rum'],
['category_id' => 6, 'locale' => 'it', 'name' => 'Rum', 'slug' => 'rum'],
['category_id' => 7, 'locale' => 'en', 'name' => 'Beer', 'slug' => 'beer'],
['category_id' => 7, 'locale' => 'it', 'name' => 'Birra', 'slug' => 'birra'],
['category_id' => 8, 'locale' => 'en', 'name' => 'Tequila', 'slug' => 'tequila'],
['category_id' => 8, 'locale' => 'it', 'name' => 'Tequila', 'slug' => 'tequila'],
['category_id' => 9, 'locale' => 'en', 'name' => 'Whiskey', 'slug' => 'whiskey'],
['category_id' => 9, 'locale' => 'it', 'name' => 'Whisky', 'slug' => 'whisky'],
['category_id' => 10, 'locale' => 'en', 'name' => 'Other Spirits', 'slug' => 'other-spirits'],
['category_id' => 10, 'locale' => 'it', 'name' => 'Altri liquori', 'slug' => 'altri-liquori'],
['category_id' => 11, 'locale' => 'en', 'name' => 'Gin', 'slug' => 'gin'],
['category_id' => 11, 'locale' => 'it', 'name' => 'Gin', 'slug' => 'gin'],
['category_id' => 12, 'locale' => 'en', 'name' => 'Mixers', 'slug' => 'mixers'],
['category_id' => 12, 'locale' => 'it', 'name' => 'Mixers', 'slug' => 'mixers'],
['category_id' => 13, 'locale' => 'en', 'name' => 'Soda', 'slug' => 'soda'],
['category_id' => 13, 'locale' => 'it', 'name' => 'Soda', 'slug' => 'soda'],
['category_id' => 14, 'locale' => 'en', 'name' => 'Juice', 'slug' => 'juice'],
['category_id' => 14, 'locale' => 'it', 'name' => 'Succhi', 'slug' => 'succhi'],
['category_id' => 15, 'locale' => 'en', 'name' => 'Energy Drinks', 'slug' => 'energy-drinks'],
['category_id' => 15, 'locale' => 'it', 'name' => 'Bevande energetiche', 'slug' => 'bevande-energetiche'],
['category_id' => 16, 'locale' => 'en', 'name' => 'Deals', 'slug' => 'deals'],
['category_id' => 16, 'locale' => 'it', 'name' => 'Offerte', 'slug' => 'offerte'],
['category_id' => 17, 'locale' => 'en', 'name' => 'Packs', 'slug' => 'packs'],
['category_id' => 17, 'locale' => 'it', 'name' => 'Packs', 'slug' => 'packs'],
['category_id' => 18, 'locale' => 'en', 'name' => 'Craft Beer', 'slug' => 'craft-beer'],
['category_id' => 18, 'locale' => 'it', 'name' => 'Birra artigianale', 'slug' => 'birra-artigianale'],
['category_id' => 19, 'locale' => 'en', 'name' => 'Other products', 'slug' => 'other-products'],
['category_id' => 19, 'locale' => 'it', 'name' => 'Altri prodotti', 'slug' => 'alti-prodotti'],
['category_id' => 20, 'locale' => 'en', 'name' => 'Premium', 'slug' => 'premium'],
['category_id' => 20, 'locale' => 'it', 'name' => 'Premium', 'slug' => 'premium'],
['category_id' => 22, 'locale' => 'en', 'name' => 'Summer Sales', 'slug' => 'summer-sales'],
['category_id' => 22, 'locale' => 'it', 'name' => 'Summer Sales', 'slug' => 'summer-sales'],
]);
}
}
<file_sep>/resources/lang/en/address.php
<?php
return [
'empty' => 'No address set',
'api.update.success' => 'Updated address successfully',
'api.destroy.success' => 'Address removed successfully',
'api.error.404' => 'Address does not exist',
'api.error.invalid' => 'Address was invalid',
];<file_sep>/app/Zugy/PaymentGateway/Gateways/AbstractGateway.php
<?php
namespace Zugy\PaymentGateway\Gateways;
use App\Payment;
use App\PaymentMethod;
abstract class AbstractGateway
{
/**
* Unique identifier for this payment method e.g. 'stripe' or 'paypal'
* @var string
*/
protected $methodName;
/**
* Stores an instance of the PaymentMethod model.
* @var PaymentMethod
*/
protected $paymentMethod;
/**
* AbstractGateway constructor.
* @param PaymentMethod $paymentMethod
*/
public function __construct(PaymentMethod $paymentMethod = null)
{
$this->paymentMethod = $paymentMethod;
}
/**
* Adds or updates the payment method to the currently signed in user
*/
abstract public function addOrUpdateMethod();
/**
* Fetch the PaymentMethod from DB
* @return PaymentMethod | null
*/
public function fetchPaymentMethod() {
return auth()->user()->payment_methods()->where('method', '=', $this->methodName)->first();
}
/**
* Store payment method in DB
* @param array|null $payload
* @return PaymentMethod
*/
public function createPaymentMethod(array $payload = null) {
return auth()->user()->payment_methods()->create([
'method' => $this->methodName,
'payload' => $payload
]);
}
/**
* Update payment method in DB
* @param array|null $payload
* @return PaymentMethod
*/
public function updatePaymentMethod(array $payload = null) {
$this->paymentMethod->payload = $payload;
$this->paymentMethod->save();
return $this->paymentMethod;
}
/**
* Sets the current method to default in DB
* @param bool $setAsDefault
*/
public function setAsDefault($setAsDefault = true) {
//Make other payment methods false for that user first
if($setAsDefault == true) {
$userId = $this->paymentMethod->user_id;
PaymentMethod::where('user_id', '=', $userId)->update(['isDefault' => false]);
}
$this->paymentMethod->isDefault = $setAsDefault;
$this->paymentMethod->save();
}
/**
* Charge the payment method
* @param PaymentMethod $paymentMethod
* @param String $amount E.g. '15.99'
* @return Payment
*/
abstract public function charge($amount);
/**
* Retrieve printable information on the payment method
* @param PaymentMethod $paymentMethod
* @return array
*/
abstract public function getFormatted();
}<file_sep>/app/Http/routes.php
<?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 controller to call when that URI is requested.
|
*/
use Illuminate\Support\Facades\Route;
Route::group([
'prefix' => (app()->environment('testing') ? 'en' : Localization::setLocale()),
'middleware' => ['web', 'localeSessionRedirect', 'localizationRedirect' ]
], function() {
Route::get('/', function () {
return view('pages.home');
});
});
Route::group([
'prefix' => (app()->environment('testing') ? 'en' : Localization::setLocale()),
'middleware' => [ 'web', 'localize', 'localeSessionRedirect', 'setLocale'] // Route translate middleware
],
function() {
/*
* Account
*/
Route::group(['middleware' => 'auth'], function () {
Route::get(Localization::transRoute('routes.account.index'), ['as' => 'your-account', 'uses' => 'AccountController@getHome']);
Route::get(Localization::transRoute('routes.account.settings'), ['as' => 'your-account', 'uses' => 'AccountController@getSettings']);
Route::get(Localization::transRoute('routes.account.orders'), ['uses' => 'AccountController@getOrders']);
});
Route::get(Localization::transRoute('routes.product'), ['uses' => 'ProductController@show']);
Route::get(Localization::transRoute('routes.search'), ['uses' => 'ProductController@search']);
/*
* Shop
*/
Route::get(Localization::transRoute('routes.shop.index'), ['uses' => 'ShopController@index', 'as' => 'shop']);
Route::get(Localization::transRoute('routes.shop.category'), ['uses' => 'ShopController@category']);
/*
* Checkout
*/
Route::get(Localization::transRoute('routes.checkout.landing'), ['uses' => 'CheckoutController@getCheckout']);
Route::get(Localization::transRoute('routes.checkout.address'), ['uses' => 'CheckoutController@getCheckoutAddress']);
Route::post(Localization::transRoute('routes.checkout.address'), ['uses' => 'CheckoutController@postCheckoutAddress']);
Route::get(Localization::transRoute('routes.checkout.payment'), ['uses' => 'CheckoutController@getCheckoutPayment']);
Route::post(Localization::transRoute('routes.checkout.payment'), ['uses' => 'CheckoutController@postCheckoutPayment']);
Route::get(Localization::transRoute('routes.checkout.review'), ['uses' => 'CheckoutController@getCheckoutReview']);
Route::post(Localization::transRoute('routes.checkout.review'), ['uses' => 'CheckoutController@postCheckoutReview']);
Route::get(Localization::transRoute('routes.checkout.confirmation'), ['uses' => 'CheckoutController@getCheckoutConfirmation']);
Route::get(Localization::transRoute('routes.checkout.gatewayReturn'), ['uses' => 'CheckoutController@getGatewayReturn']);
Route::get(Localization::transRoute('routes.order.show'), ['uses' => 'OrderController@show']);
/* Cart */
Route::get(Localization::transRoute('routes.cart'), ['uses' => 'PageController@getCart']);
Route::get(Localization::transRoute('routes.about-us'), function () {
return view('pages.about-us');
});
Route::get(Localization::transRoute('routes.contact'), function () {
return view('pages.contact');
});
Route::get(Localization::transRoute('routes.terms-and-conditions'), function() {
return view('pages.terms-and-conditions.index');
});
Route::get(Localization::transRoute('routes.privacy-policy'), function() {
return view('pages.privacy-policy.index');
});
Route::group(['prefix' => 'auth'], function () {
Route::get('login', ['as' => 'login', 'uses' => 'Auth\AuthController@getLogin']);
Route::post('login', ['uses' => 'Auth\AuthController@postLogin']);
Route::get('register', ['uses' => 'Auth\AuthController@getRegister']);
Route::post('register', ['uses' => 'Auth\AuthController@postRegister']);
/*
* Password reset
*/
Route::get('password/email', ['uses' => 'Auth\PasswordController@getEmail']);
Route::post('password/email', ['uses' => 'Auth\PasswordController@postEmail']);
Route::get('password/reset/{token}', ['uses' => 'Auth\PasswordController@getReset']);
Route::post('password/reset', ['uses' => 'Auth\PasswordController@postReset']);
Route::post('password/change', ['uses' => 'Auth\PasswordController@postPasswordChange']);
});
});
/*
* No localisation needed
*/
Route::group(['prefix' => 'auth', 'middleware' => ['web']], function () {
Route::get('login/facebook', 'Auth\AuthController@facebookLogin');
Route::get('login/google', 'Auth\AuthController@googleLogin');
Route::get('logout', ['as' => 'logout', 'uses' => 'Auth\AuthController@getLogout']);
Route::post('adminLogin', ['uses' => 'Auth\AuthController@postAdminLogin']);
});
/* API */
Route::group(['prefix' => 'api', 'middleware' => ['api']], function () {
Route::group(['prefix' => 'v1'], function () {
//No auth required
Route::patch('cart', 'API\CartController@bulkUpdate');
Route::resource('cart', 'API\CartController', ['except' => [
'update',
'show'
]]);
Route::get('postcode/check/{postcode}', ['uses' => 'API\PostcodeController@checkPostcode']);
//Auth required
Route::group(['middleware' => ['auth']], function () {
Route::resource('address', 'API\AddressController');
Route::resource('order', 'API\OrderController');
Route::post('coupon/apply', 'API\CouponController@apply');
});
Route::group(['prefix' => 'shop'], function() {
Route::get('statistics', 'API\ShopStatisticsController@getStatistics');
});
});
});
Route::group(['prefix' => 'admin', 'middleware' => ['web', 'auth', 'admin', 'setLocale']], function () {
Route::get('', ['uses' => 'Admin\DashboardController@getDashboard']);
Route::resource('catalogue', 'Admin\CatalogueController');
Route::resource('customer', 'Admin\CustomerController');
Route::resource('order', 'Admin\OrderController');
Route::post('image/upload', 'Admin\ImageController@upload');
Route::delete('image/{id}', 'Admin\ImageController@destroy');
});
Route::group(['middleware' => ['web']], function () {
Route::get('test', function() {
});
});
<file_sep>/resources/lang/en/ageSplash.php
<?php
return [
'prompt' => 'Please verify your age to enter.',
'over' => 'Over :age',
'under' => 'Under :age',
'sorry.title' => 'Over 18s only, sorry!',
'sorry.desc' => 'Sorry, we only sell alcohol and deliver within an hour to those who are over the age of 18 only.',
'sorry.party' => 'We will, however, be there with you to celebrate your 18th birthday!'
];<file_sep>/resources/lang/it/payment.php
<?php
return [
'card-number' => 'Numero',
'cardholder-name' => '<NAME>',
'payment-method' => 'Metodo di pagamento',
];<file_sep>/app/Zugy/Cart/Cart.php
<?php
namespace Zugy\Cart;
use Gloudemans\Shoppingcart\Cart as BaseCart;
use App\Product;
use Zugy\Facades\Checkout;
class Cart extends BaseCart
{
/**
* Get shipping costs
* @return int|mixed
*/
public function shipping() {
if($this->total() < config('site.minimumFreeShipping')) {
return config('site.shippingFee');
} else {
return 0;
}
}
public function totalBeforeVat()
{
return $this->grandTotal() - $this->vat();
}
public function grandTotal() {
$grandTotal = $this->shipping() + $this->total() - $this->couponDeduction();
if($grandTotal < 0) {
throw new \RuntimeException("Total cannot be negative");
}
return $grandTotal;
}
public function couponDeduction()
{
$coupon = Checkout::getCoupon();
if($coupon === null) {
return 0;
}
if($coupon->percentageDiscount != null) {
return round($this->total() * ($coupon->percentageDiscount / 100), 2);
}
if($coupon->flatDiscount != null) {
if($coupon->flatDiscount > $this->total()) {
return $this->total();
}
return $coupon->flatDiscount;
}
throw new \RuntimeException("Coupon type not set");
}
/**
* Calculate VAT, including shipping fees
* @return float
*/
public function vat() {
return $this->vatItems() + $this->vatShipping();
}
/**
* Sum up VAT for items in cart
* @return float
*/
public function vatItems()
{
$totalVAT = 0;
$productIDs = [];
$cartProducts = [];
foreach($this->content() as $row) {
$productIDs[] = $row->id;
$cartProducts[$row->id] = ['subtotal' => $row->subtotal];
}
$products = Product::with(['tax_class' => function($query) {
$query->select('id', 'tax_rate');
}])->select('id', 'tax_class_id')->whereIn('id', $productIDs)->get();
foreach($products as $p) {
$net = $cartProducts[$p->id]['subtotal'] / ((100 + $p->tax_class->tax_rate) / 100);
$vat = $cartProducts[$p->id]['subtotal'] - $net;
$totalVAT += round($vat, 2);
}
$coupon = Checkout::getCoupon();
if($coupon != null && $coupon->percentageDiscount != null) {
$totalVAT = round($totalVAT * ($coupon->percentageDiscount / 100), 2);
} elseif($coupon != null && $coupon->flatDiscount != null) {
$overallPercentageVat = $totalVAT / $this->total();
$totalVAT = round(($this->total() - $this->couponDeduction()) * $overallPercentageVat, 2);
}
return $totalVAT;
}
public function vatShipping()
{
$fee = $this->shipping();
$tax = config('site.shippingTax');
$net = $fee / ((100 + $tax) / 100);
$vatShipping = round($fee - $net, 2);
return $vatShipping;
}
}<file_sep>/resources/lang/it/cart.php
<?php
return [
'shopping-cart' => 'Carrello',
'free-shipping-reminder' => 'Ordina più di 20€ e <b>la consegna diventa gratis</b>!',
'mini-cart-empty' => 'Il tuo carrello è vuoto',
'empty-cart-msg' => 'Non hai nulla nel carrello. Visita il <a href=":storeUrl">negozio</a> per riempirlo!',
'api.error.out-of-stock' => 'Impossibile aggiungere al carrello. Abbiamo solo :quantity lasciati in azione.',
];<file_sep>/database/seeds/ProductSeeder.php
<?php
use App\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Storage;
class ProductSeeder extends Seeder
{
public function run() {
$product = Product::create([
'stock_quantity' => 10,
'price' => 12.99,
'compare_price' => 19.99,
'weight' => 0.50,
'tax_class_id' => 1,
'en' => [
'title' => 'Absolut Vodka',
'slug' => 'absolut-vodka',
'description' => 'Absolut Vodka is a Swedish vodka made exclusively from natural ingredients, and unlike some other vodkas, it doesn\'t contain any added sugar. In fact Absolut is as clean as vodka can be. Still, it has a certain taste: Rich, full-bodied and complex, yet smooth and mellow with a distinct character of grain, followed by a hint of dried fruit.',
'meta_description' => 'Buy Absolut Vokda online from Zugy today.',
],
'it' => [
'title' => 'Absolut Vodka',
'slug' => 'absolut-vodka',
'description' => 'Absolut una marca svedese di vodka, della V&S Group, prodotta a hus, Scania nel sud della Svezia.',
'meta_description' => 'Acquista online da Absolut vokda Zugy oggi.',
]
]);
$product->categories()->attach(5); //Vodka category
$product->attributes()->attach(1, ['value' => 0.350]); //Volume
$product->attributes()->attach(2, ['value' => 40.0]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/absolut-vodka/absolut-vodka.jpeg');
Storage::disk(env('FILE_DISC'))->put('demo/absolut-vodka/absolut-vodka.jpeg', $img);
$product->images()->create([
'location' => 'demo/absolut-vodka/absolut-vodka.jpeg'
]);
####
$product = Product::create([
'stock_quantity' => 10,
'price' => 15.00,
'compare_price' => 16.36,
'weight' => 0.50,
'tax_class_id' => 1,
'en' => [
'title' => 'Bacardi 70cl',
'slug' => 'bacardi',
'description' => "<p>Bacardi's original, the Superior is a highly versatile white Rum which has been around since 1862.</p><p>Aged in oak barrels, look out for the smooth taste and the almond and tropical fruit aroma.</p>",
'meta_description' => '',
],
'it' => [
'title' => 'Bacardi 70cl',
'slug' => 'bacardi',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(6); //Rum category
$product->attributes()->attach(1, ['value' => 0.700]); //Volume
$product->attributes()->attach(2, ['value' => 37.5]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/bacardi/bacardi.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/bacardi/bacardi.jpg', $img);
$product->images()->create([
'location' => 'demo/bacardi/bacardi.jpg'
]);
####
$product = Product::create([
'stock_quantity' => 10,
'price' => 15.00,
'compare_price' => 16.57,
'weight' => 0.80,
'tax_class_id' => 1,
'en' => [
'title' => 'Havana Club 70cl',
'slug' => 'havana',
'description' => "",
'meta_description' => '',
],
'it' => [
'title' => 'Havana Club 70cl',
'slug' => 'havana',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(6); //Rum category
$product->attributes()->attach(1, ['value' => 0.700]); //Volume
$product->attributes()->attach(2, ['value' => 40.0]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/havana/havana.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/havana/havana.jpg', $img);
$product->images()->create([
'location' => 'demo/havana/havana.jpg'
]);
####
$product = Product::create([
'stock_quantity' => 10,
'price' => 3.00,
'compare_price' => null,
'weight' => 0.60,
'tax_class_id' => 1,
'en' => [
'title' => 'Heineken',
'slug' => 'heineken',
'description' => "",
'meta_description' => '',
],
'it' => [
'title' => 'Heineken',
'slug' => 'heineken',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(7); //Beer category
$product->attributes()->attach(1, ['value' => 0.660]); //Volume
$product->attributes()->attach(2, ['value' => 5]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/heineken/heineken.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/heineken/heineken.jpg', $img);
$product->images()->create([
'location' => 'demo/heineken/heineken.jpg'
]);
###
$product = Product::create([
'stock_quantity' => 10,
'price' => 2.50,
'compare_price' => null,
'weight' => 0.60,
'tax_class_id' => 1,
'en' => [
'title' => 'Peroni',
'slug' => 'peroni',
'description' => "",
'meta_description' => '',
],
'it' => [
'title' => 'Peroni',
'slug' => 'peroni',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(7); //Beer category
$product->attributes()->attach(1, ['value' => 0.660]); //Volume
$product->attributes()->attach(2, ['value' => 5.1]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/peroni/peroni.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/peroni/peroni.jpg', $img);
$product->images()->create([
'location' => 'demo/peroni/peroni.jpg'
]);
###
$product = Product::create([
'stock_quantity' => 10,
'price' => 28.00,
'compare_price' => 37.15,
'weight' => 0.60,
'tax_class_id' => 1,
'en' => [
'title' => 'Sauza Silver Tequila 100cl',
'slug' => 'sauza-silver',
'description' => "",
'meta_description' => '',
],
'it' => [
'title' => 'Sauza Silver Tequila 100cl',
'slug' => 'sauza-silver',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(8); //Tequila category
$product->attributes()->attach(1, ['value' => 1.0]); //Volume
$product->attributes()->attach(2, ['value' => 40.0]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/sauza-tequila/sauza-tequila.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/sauza-tequila/sauza-tequila.jpg', $img);
$product->images()->create([
'location' => 'demo/sauza-tequila/sauza-tequila.jpg'
]);
###
$product = Product::create([
'stock_quantity' => 10,
'price' => 90.00,
'compare_price' => 128.10,
'weight' => 0.60,
'tax_class_id' => 1,
'en' => [
'title' => 'Veuve Clicquot Champagne',
'slug' => 'veuve-clicquot',
'description' => "Veuve Clicquot",
'meta_description' => '',
],
'it' => [
'title' => 'Peroni',
'slug' => 'veuve-clicquot',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(4); //Wine & champagne category
$product->attributes()->attach(1, ['value' => 0.750]); //Volume
$product->attributes()->attach(2, ['value' => 12]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/veuve-clicquot/veuve-clicquot.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/veuve-clicquot/veuve-clicquot.jpg', $img);
$product->images()->create([
'location' => 'demo/veuve-clicquot/veuve-clicquot.jpg'
]);
###
$product = Product::create([
'stock_quantity' => 10,
'price' => 90.00,
'compare_price' => 128.10,
'weight' => 0.60,
'tax_class_id' => 1,
'en' => [
'title' => 'Moet And Chandon Brut Imperial Non Vintage Champagne',
'slug' => 'moet-chandon-imperial',
'description' => "",
'meta_description' => '',
],
'it' => [
'title' => 'Moet And Chandon Brut Imperial Champagne',
'slug' => 'moet-chandon-imperial',
'description' => '',
'meta_description' => '',
]
]);
$product->categories()->attach(4); //Wine & champagne category
$product->attributes()->attach(1, ['value' => 0.750]); //Volume
$product->attributes()->attach(2, ['value' => 12]); //% Vol
$img = Storage::disk('public')->get('img/demo/products/moet-chandon-imperial/moet-chandon-imperial.jpg');
Storage::disk(env('FILE_DISC'))->put('demo/moet-chandon-imperial/moet-chandon-imperial.jpg', $img);
$product->images()->create([
'location' => 'demo/moet-chandon-imperial/moet-chandon-imperial.jpg'
]);
}
}<file_sep>/resources/lang/it/opening-times.php
<?php
return [
'title-delivery-time' => 'Orari di consegna',
'when' => 'Ogni giorno dall\'una di pomeriggio fino alle 2 di notte',
'closed' => 'Al momento non consegnamo.',
'times' => 'I nostri orari di consegna sono:',
'delivery-time' => 'Puoi ordinare adesso e selezionare un orario di consegna piú comodo per te, magari stasera ( ͡ᵔ ͜ʖ ͡ᵔ )',
'prompt-select' => 'Seleziona un orario per la consegna',
'asap-closed-explanation' => 'Seleziona "ASAP" e ti spediremo l\'ordine appena saremo aperti',
];<file_sep>/resources/lang/it/order.php
<?php
return [
'status.0' => 'Nuovo ordine',
'status.1' => 'Stiamo elaborando',
'status.2' => 'In consegna',
'status.3' => 'Consegnato',
'status.4' => 'Anullato',
'number' => 'Numero ordine',
'date' => 'Data ordine',
'create' => 'Ordine effettuato',
'completed' => 'Ordine completato',
'details' => 'Dettagli',
'summary' => 'Riassunto ordine',
'history' => 'Cronologia ordini',
'api.update.success' => 'Ordine aggiornato',
'api.error.status-same' => 'l\'ordine è già stato impostato',
'email.confirmation.subject' => 'Conferma di ordine Zugy ricevuta [#:id]',
'email.confirmation.paid' => 'Totale Pagato',
'email.delivery.subject' => 'Il tuo ordine [#:id] è in consegna',
'email.delivery.driver' => 'Il nostro Driver è in cammino',
'email.delivery.trouble' => 'Ti contatteremo qualora ci fossero problemi a <b>:phone</b>',
'email.cancelled.subject' => 'Il tuo ordine [#:id] è anullato',
'email.cancelled.questions' => 'Se hai qualche domanda rispetto all\'anullamento rispondi a questa e-mail o chiamaci :phone.',
'email.track.description' => 'Puoi rintracciare il tuo ordine cliccando il tasto sotto',
'email.track' => 'Rintraccia ordine',
'sign-in' => '<a href=":loginUrl">Accedi per vedere</a> più informazione sul tuo ordine',
'total-before-vat' => 'Totale senza IVA',
'vat' => 'IVA',
'include-vat' => 'Ordine totale include',
'status-changed' => 'Stato modificato in <b>:status</b>',
];<file_sep>/resources/assets/js/order.js
(function( order, $, undefined ) {
var apiEndpoint = '/api/v1/order';
/**
* Check if postcode is in delivery range
* @param orderId
* @param status
*/
order.updateStatus = function(orderId, status) {
$.ajax({
type: 'PATCH',
url: apiEndpoint + '/' + orderId,
data: {
order_status: status
},
success: function(data) {
swal({
title: data.message,
type: 'success',
timer: 1000,
showConfirmButton: false
});
$.pjax.reload('#container');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
swal(err.message, JSON.stringify(err.errors), "error");
}
});
};
}( window.order = window.order || {}, jQuery ));<file_sep>/app/Zugy/Repos/Product/DbProductRepository.php
<?php
namespace Zugy\Repos\Product;
use App\Category;
use App\Language;
use App\Product;
use App\ProductDescription;
use App\ProductTranslation;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Zugy\Repos\Category\CategoryRepository;
use Zugy\Repos\DbRepository;
class DbProductRepository extends DbRepository implements ProductRepository
{
/**
* @var CategoryRepository
*/
protected $categoryRepo;
/**
* @var Product
*/
protected $model;
/**
* DbProductRepository constructor.
* @param $categoryRepo CategoryRepository
*/
public function __construct(Product $model, CategoryRepository $categoryRepo)
{
$this->categoryRepo = $categoryRepo;
$this->model = $model;
}
/**
* Fetch all products
* @param string $sort
* @param string $direction
* @return
*/
public function all($sort = 'sales', $direction = 'desc')
{
$query = $this->productQueryBuilder()->orderBy($sort, $direction);
$orderedProductIds = collect($query->get())->pluck('id');
$orderedProductIdsStr = $orderedProductIds->implode(',');
$products = $this->model->with('translations')
->whereIn('id', $orderedProductIds)
->orderByRaw("FIELD(id, $orderedProductIdsStr)")
->paginate(15);
return $products;
}
/**
* Fetch all products for a category slug
* @param $category_slug
* @param string $sort
* @param string $direction
* @return
*/
public function category($category_slug, $sort = 'sales', $direction = 'desc')
{
$category = $this->categoryRepo->getBySlug($category_slug);
$categoryIds = $this->categoryRepo->children($category->id);
$productIds = collect(
DB::table('products_to_categories')
->whereIn('category_id', $categoryIds)
->get()
)->unique('product_id')->pluck('product_id');
$query = $this->productQueryBuilder()
->orderBy($sort, $direction)
->whereIn('products.id', $productIds); // Category filter;
$orderedProductIds = collect($query->get())->pluck('id');
if($orderedProductIds->isEmpty()) {
return new Paginator([], 15);
}
$orderedProductIdsStr = $orderedProductIds->implode(',');
$products = $this->model->with(['translations', 'images'])
->whereIn('id', $orderedProductIds)
->orderByRaw("FIELD(id, $orderedProductIdsStr)")
->paginate(15);
return $products;
}
/**
* Fetch a product by its slug
* @param $slug
* @return mixed
*/
public function getBySlug($slug)
{
$product = $this->model->with(['images', 'attributes', 'translations'])->whereHas('translations', function($query) use ($slug) {
$query->where('locale', '=', LaravelLocalization::getCurrentLocale())
->where('slug', '=', $slug);
})->first();
return $product;
}
public function search($query)
{
$algoliaResults = \App\Product::search($query, [
'restrictSearchableAttributes' => ['translation_' . \Localization::getCurrentLocale()],
]);
$productIds = [];
foreach($algoliaResults['hits'] as $hit) {
$productIds[] = $hit['objectID'];
}
return $this->model->whereIn('id', $productIds)->paginate(15);
}
/**
* Build joined table so that sales for product can be calculated
* @return mixed
*/
private function productQueryBuilder() {
return DB::table('products')
->leftJoin('order_items', 'products.id', '=', 'order_items.product_id')
->leftJoin('orders', 'orders.id', '=', 'order_items.order_id')
->selectRaw('products.*, SUM(
CASE WHEN orders.order_status = 4 THEN
0
ELSE
order_items.quantity
END) as sales') //Ignore cancelled orders
->groupBy('products.id')
->where('products.stock_quantity', '>', 0); //Hide items that are out of stock
}
}<file_sep>/resources/lang/en/product.php
<?php
return [
'product' => 'Product',
'search-results' => 'Search results for <i>:query</i>',
'count' => '{0} No products|{1} 1 product|[2,Inf] :count products',
'stock' => 'Stock Quantity',
'in-stock' => 'In Stock',
'out-of-stock' => 'Out of stock',
'stock-warning' => 'Only :count left in stock.',
'item-weight' => 'Item weight',
'tabs.details' => 'Details',
'quantity' => 'Quantity',
'price' => 'Price',
'edit' => 'Edit product',
'search.empty' => 'No results matching the query <b>":query"</b>',
'category.empty' => 'No products in this category',
'category.title' => 'Category',
'404' => 'That product does not exist',
'form.name.label' => 'Product Name',
'form.add.label' => 'Add a product',
'filter.search' => 'Searching for <b>:name</b>. :count result(s) found.',
'sort.popular' => 'Most popular',
'sort.price.highest' => 'Highest price',
'sort.price.lowest' => 'Lowest price',
'title.category' => 'Shop for :category',
'title.search' => 'Search results for :query',
'title.shop' => 'Shop for Alcohol'
];<file_sep>/resources/lang/en/errors.php
<?php
return [
'unknown' => 'An unknown error occurred. Please try again',
'stripe.invalid_number' => "The card number is not a valid credit card number.",
'stripe.invalid_expiry_month' => "The card's expiration month is invalid.",
'stripe.invalid_expiry_year' => "The card's expiration year is invalid.",
'stripe.invalid_cvc' => "The card's security code is invalid.",
'stripe.incorrect_number' => "The card number is incorrect.",
'stripe.expired_card' => "The card has expired.",
'stripe.incorrect_cvc' => "The card's security code is incorrect.",
'stripe.incorrect_zip' => "The card's zip code failed validation.",
'stripe.card_declined' => "The card was declined.",
'stripe.missing' => "There is no card on a customer that is being charged.",
'stripe.processing_error' => "An error occurred while processing the card.",
'404.message' => 'Page not found',
'404.description' => 'We were unable to find the page you were looking for, sorry!',
'500.message' => 'An internal error occurred',
'500.description' => 'An error occurred, this error has been reported to us and we will fix it as soon as we can - sorry!',
];<file_sep>/config/services.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, Mandrill, and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'aws' => [
'region' => env('AWS_REGION'),
'bucket' => env('AWS_BUCKET')
],
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => '',
'secret' => '',
'region' => 'us-east-1',
],
'stripe' => [
'secret' => env('STRIPE_SECRET'),
'public' => env('STRIPE_PUBLIC'),
],
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_SECRET'),
'redirect' => env('APP_URL') . '/auth/login/google',
],
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_SECRET'),
'redirect' => env('APP_URL') . '/auth/login/facebook',
],
'rollbar' => [
'access_token' => env('ROLLBAR_ACCESS_TOKEN'),
'post_client_item' => env('ROLLBAR_POST_CLIENT_ITEM'),
'level' => 'error',
],
'paypal' => [
'username' => env('PAYPAL_USERNAME'),
'password' => env('PAYPAL_PASSWORD'),
'signature' => env('PAYPAL_SIGNATURE'),
'testMode' => env('PAYPAL_TESTMODE') == "true",
],
'pushbullet' => [
'token' => env('PUSHBULLET_TOKEN'),
'channels' => [
'order' => env('PUSHBULLET_ORDER_CHANNEL'),
]
]
];
<file_sep>/app/Exceptions/TooManyOrdersException.php
<?php
namespace App\Exceptions;
class TooManyOrdersException extends \Exception
{
}<file_sep>/config/site.php
<?php
return [
"name" => 'Zugy',
'address' => 'Azalia Naviglio Grande 36, 20141 Milan, Italy',
'phone' => '(+39) 320 8908315',
'maxImageSize' => 10000000, //10MB
/*
* Cart
*/
'minimumFreeShipping' => 20, //Minimum order value in Euros for free shipping
'shippingFee' => 3, //Cart fee
'shippingTax' => 22,
/*
* Email
*/
'email' => [
'support' => '<EMAIL>',
'logo_path' => env('APP_URL') . '/img/zugy-logo-dark.png', //Full URL to logo
],
/*
* Pushbullet
*/
'pushbullet' => [
'channels' => [
'orders' => env('PUSHBULLET_ORDER_CHANNEL'),
],
],
];<file_sep>/app/OAuthAuthorisations.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OAuthAuthorisations extends Model
{
protected $table = 'users_to_oauth_authorisations';
protected $fillable = ['network', 'network_user_id', 'user_id'];
public function user() {
$this->belongsTo('App\User');
}
}
<file_sep>/app/Zugy/Helpers/Maps/Maps.php
<?php
namespace Zugy\Helpers\Maps;
class Maps
{
protected $apiUrl = 'http://maps.google.com/maps?&q=';
public function getGoogleMapsUrl($line_1, $line_2 = null, $city, $postcode) {
$address = [$line_1];
if($line_2) $address[] = $line_2;
$address[] = $city;
$address[] = $postcode;
return $this->apiUrl . urlencode(implode(', ', $address));
}
}<file_sep>/app/Zugy/PaymentGateway/Gateways/PayPal.php
<?php
namespace Zugy\PaymentGateway\Gateways;
use App\Payment;
use App\PaymentMethod;
use Omnipay\Omnipay;
use Carbon\Carbon;
use Zugy\PaymentGateway\Exceptions\PaymentFailedException;
class PayPal extends AbstractGateway
{
protected $methodName = 'paypal';
protected $gateway;
/**
* PayPal constructor.
* @param string $methodName
*/
public function __construct(PaymentMethod $paymentMethod = null)
{
parent::__construct($paymentMethod);
$this->gateway = Omnipay::create('PayPal_Express');
$this->gateway->initialize([
'username' => config('services.paypal.username'),
'password' => config('services.paypal.password'),
'signature' => config('services.paypal.signature'),
'testMode' => config('services.paypal.testMode'),
]);
}
public function addOrUpdateMethod()
{
$this->paymentMethod = $this->fetchPaymentMethod();
if($this->paymentMethod === null) {
$this->paymentMethod = $this->createPaymentMethod();
}
$this->setAsDefault(request('defaultPayment') !== null);
return $this->paymentMethod;
}
public function charge($amount)
{
$parameters = [
'cancelUrl' => localize_url('routes.checkout.gatewayReturn'), //TODO Implement cancel URL
'returnUrl' => localize_url('routes.checkout.gatewayReturn'),
'description' => 'Zugy Order',
'cardReference' => 'ZUGY',
'amount' => $amount,
'currency' => 'EUR'
];
if(request()->has('token')) {
$response = $this->gateway->completePurchase($parameters)->send();
$data = $response->getData();
if($data['ACK'] !== 'Success') {
\Log::warning('Payment failed');
throw new PaymentFailedException();
}
$payment = new Payment();
$payment->paid = Carbon::now();
$payment->metadata = [
'id' => $data['PAYMENTINFO_0_TRANSACTIONID'],
'currency' => $data['PAYMENTINFO_0_CURRENCYCODE'],
];
$payment->status = 1; //Mark as paid
$payment->amount = $data['PAYMENTINFO_0_AMT'];
$payment->currency = $data['PAYMENTINFO_0_CURRENCYCODE'];
$payment->method = $this->paymentMethod->method;
\Log::info('Payment success');
return $payment;
}
$response = $this->gateway->purchase($parameters)->send();
return redirect($response->getRedirectUrl()); //Redirect to PayPal
}
public function getFormatted()
{
return [
'method' => $this->methodName,
];
}
}<file_sep>/app/Http/Controllers/API/AddressController.php
<?php
namespace App\Http\Controllers\Api;
use App\Address;
use App\Services\CreateOrUpdateAddress;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Gate;
use Zugy\Facades\Checkout;
class AddressController extends Controller
{
public function index()
{
return auth()->user()->addresses()->get();
}
public function show($id)
{
$address = Address::findOrFail($id);
if(Gate::denies('show', $address)) {
abort(403);
}
return $address;
}
public function update(Request $request, CreateOrUpdateAddress $addressService, $id)
{
$address = Address::findOrFail($id);
if(Gate::denies('update', $address)) {
abort(403);
}
$result = $addressService->delivery($request->all(), $address);
if( ! $result instanceof Address) {
return response()->json(['status' => 'error', 'message' => trans('address.api.error.invalid'), 'errors' => $result->errors()], 422);
}
return ['status' => 'success', 'message' => trans('address.api.update.success')];
}
public function destroy($id)
{
try {
$address = Address::findOrFail($id);
} catch(ModelNotFoundException $e) {
return response()->json(['status' => 'failure', 'message' => trans('address.api.error.404')], 404);
}
//Unset session addresses
if(Checkout::getBillingAddress()->id == $id) Checkout::forgetBillingAddress();
if(Checkout::getShippingAddress()->id == $id) Checkout::forgetShippingAddress();
$address->delete();
return ['status' => 'success', 'message' => trans('address.api.destroy.success')];
}
}<file_sep>/app/Http/Controllers/CheckoutController.php
<?php
namespace App\Http\Controllers;
use App\Address;
use App\Exceptions\OutOfStockException;
use App\Exceptions\TooManyOrdersException;
use App\Order;
use App\Services\CreateOrUpdateAddress;
use App\Services\Order\PlaceOrder;
use App\Services\Payment\PaymentMethodService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cart;
use Checkout;
use Zugy\Facades\PaymentGateway;
use Zugy\PaymentGateway\Exceptions\PaymentFailedException;
class CheckoutController extends Controller
{
public function __construct() {
$this->middleware('checkout', ['except' => ['getCheckout']]);
}
/**
* GET /checkout
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function getCheckout(Request $request)
{
if(Cart::count() === 0) {
return redirect(localize_url('routes.cart'));
}
if(auth()->guest()) {
session()->put('url.intended', localize_url('routes.checkout.address'));
return view('pages.checkout.before');
}
if(Checkout::getShippingAddress() === null) {
return redirect(localize_url('routes.checkout.address'));
}
if(Checkout::getPaymentMethod() === null) {
return redirect(localize_url('routes.checkout.payment'));
}
return redirect(localize_url('routes.checkout.review'));
}
/**
* /checkout/address
*/
public function getCheckoutAddress()
{
$addresses = auth()->user()->addresses()->get();
return view('pages.checkout.address')->with(['addresses' => $addresses]);
}
public function postCheckoutAddress(Request $request, CreateOrUpdateAddress $handler) {
if($request->has('delivery.addressId')) {
$delivery = Address::find($request->input('delivery.addressId'));
Checkout::setShippingAddress($delivery);
return redirect(localize_url('routes.checkout.payment'));
} else {
$delivery = $handler->delivery($request->input('delivery'));
if(! $delivery instanceof Address) {
return redirect()->back()->withErrors($delivery)->withInput();
}
if(!$request->has('delivery.billing_same')) {
$billing = $handler->billing($request->input('billing'));
if(! $billing instanceof Address) {
return redirect()->back()->withErrors($billing)->withInput();
}
} else {
$billing = $delivery;
}
}
Checkout::setShippingAddress($delivery);
Checkout::setBillingAddress($billing);
return redirect(localize_url('routes.checkout.payment'));
}
/**
* GET /checkout/payment
* @return \Illuminate\View\View
*/
public function getCheckoutPayment()
{
$paymentMethods = auth()->user()->payment_methods()->get();
$stripe = $paymentMethods->where('method', 'stripe')->first();
if($stripe !== null) {
$cards = PaymentGateway::set($stripe)->listCards($stripe);
}
if(Checkout::getShippingAddress() === null) {
return redirect(localize_url('routes.checkout.address'))->with('info', trans('checkout.address.prompt'));
}
return view('pages.checkout.payment')->with(compact('cards'));
}
/**
* POST /checkout/payment
* @param Request $request
* @param PaymentMethodService $handler
* @return $this|bool|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
* @throws \Exception
*/
public function postCheckoutPayment(Request $request, PaymentMethodService $paymentHandler)
{
try {
$result = $paymentHandler->setMethod($request);
} catch(\Stripe\Error\InvalidRequest $e) {
return redirect()->back()->withErrors([trans('errors.unknown')]);
} catch(\Stripe\Error\Card $e) {
$errorMsg = trans('errors.stripe.' . $e->getStripeCode());
return redirect()->back()->withErrors([$errorMsg])->withInput();
} catch(Exception $e) {
return redirect()->back()->withErrors([trans('errors.unknown') . $e->getMessage()])->withInput();
}
if($result !== true) return $result;
return redirect(localize_url('routes.checkout.review'));
}
/**
* /checkout/review
* @return \Illuminate\View\View
*/
public function getCheckoutReview()
{
//Fetch delivery address information
$shippingAddress = Checkout::getShippingAddress();
$paymentMethod = Checkout::getPaymentMethod();
if($shippingAddress === null) {
return redirect(localize_url('routes.checkout.address'))->with('info', trans('checkout.address.prompt'));
}
if($paymentMethod === null) {
return redirect(localize_url('routes.checkout.payment'))->with('info', trans('checkout.payment.form.title'));
}
$cart = Cart::content();
//Fetch payment information
$payment = $paymentMethod->getFormatted();
return view('pages.checkout.review')->with([
'cart' => $cart,
'shippingAddress' => $shippingAddress,
'payment' => $payment,
'coupon' => Checkout::getCoupon()
]);
}
/**
* Place the actual order finally
* POST /checkout/review
* @param Request $request
* @param PlaceOrder $service
* @return $this|Order
*/
public function postCheckoutReview(Request $request, PlaceOrder $service)
{
$user = auth()->user();
try {
$result = $service->handler($user);
} catch(OutOfStockException $e) {
return redirect(localize_url('routes.checkout.review'))->withErrors($e->getErrorMessages());
} catch(\Stripe\Error\Card $e) { //Card was rejected
$stripeErrorMsg = trans('errors.stripe.' . $e->getStripeCode());
return redirect(localize_url('routes.checkout.review'))->withErrors([
$stripeErrorMsg,
trans('checkout.payment.form.error.different', ['paymentUrl' => localize_url('routes.checkout.payment')])
]);
} catch(TooManyOrdersException $e) {
return redirect(localize_url('routes.checkout.review'))
->withErrors([trans('checkout.review.error.too-fast')]);
} catch(PaymentFailedException $e) {
return redirect(localize_url('routes.checkout.review'))
->withErrors([trans('checkout.payment.form.error.different', ['paymentUrl' => localize_url('routes.checkout.payment')])]);
} catch(\Exception $e) {
\Log::alert($e);
return redirect()->back()->withErrors([trans('errors.unknown')]);
}
if(!$result instanceof Order) return $result;
return redirect(localize_url('routes.order.show', ['id' => $result->id]))
->with([
'success' => trans('checkout.order.success'),
'orderConfirmation' => true
]);
}
/**
* Redirect back here from payment gateway e.g. PayPal
*/
public function getGatewayReturn(Request $request, PlaceOrder $service)
{
return $this->postCheckoutReview($request, $service);
}
public function getCheckoutConfirmation(Request $request) {
if(!auth()->guest()) {
$order = auth()->user()->orders()->with('items')->find($request->get('order'));
} else {
if(!session()->has('order.id')) {
return redirect(localize_url('routes.cart'));
} else {
$order = Order::with('items')->find(session('order.id'));
}
}
return view('pages.checkout.confirmation')->with(['order' => $order]);
}
}
<file_sep>/app/Zugy/ActivityLogParser/ActivityLogParserServiceProvider.php
<?php
namespace Zugy\ActivityLogParser;
use Illuminate\Support\ServiceProvider;
class ActivityLogParserServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('activityLogParser', function()
{
return new ActivityLogParser();
});
}
}<file_sep>/database/seeds/AttributesSeeder.php
<?php
use App\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
class AttributesSeeder extends Seeder
{
public function run() {
Model::unguard();
Attribute::create([
'id' => 1,
'en' => [
'name' => 'Volume',
'unit' => 'litres'
],
'it' => [
'name' => 'Volume',
'unit' => 'litri'
]
]);
Attribute::create([
'id' => 2,
'en' => [
'name' => 'Alcohol Content',
'unit' => '% Vol'
],
'it' => [
'name' => 'Grado alcolico',
'unit' => '% Vol'
]
]);
}
}<file_sep>/app/Zugy/DeliveryTime/Exceptions/ClosedException.php
<?php
namespace Zugy\DeliveryTime\Exceptions;
class ClosedException extends \Exception
{
}<file_sep>/app/Listeners/LogOrderStatus.php
<?php
namespace App\Listeners;
use App\Events\OrderStatusChanged;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class LogOrderStatus
{
/**
* Handle the event.
*
* @param OrderStatusChanged $event
* @return void
*/
public function handle(OrderStatusChanged $event)
{
\Activity::log([
'contentId' => $event->order->id,
'contentType' => 'Order',
'action' => 'status-change',
'description' => $event->order->order_status,
]);
}
}
<file_sep>/tests/AdminOrdersTest.php
<?php
class AdminOrdersTest extends TestCase
{
protected $admin;
public function setUp()
{
parent::setUp();
$this->admin = factory(App\User::class, 'admin')->make();
}
public function testOrdersIndex()
{
$this->actingAs($this->admin)->visit('admin/order');
}
}<file_sep>/tests/FilePermissionsTest.php
<?php
class FilePermissionsTest extends TestCase
{
public function testProductImageUpload()
{
$path = public_path() . '/uploads';
$this->assertTrue(is_writable($path));
}
public function testBootstrapCache()
{
$path = base_path() . '/bootstrap/cache';
$this->assertTrue(is_writable($path));
}
public function testStorage()
{
$path = storage_path();
$this->assertTrue(is_writable($path));
}
}<file_sep>/resources/lang/it/admin.php
<?php
return [
'incomplete-orders' => 'ordini incompleti',
'revenue-yesterday' => 'entrate ieri',
'revenue-this-month' => 'Ricavi mensili',
'details' => 'Dettagli',
'time' => 'Tempo',
'user' => 'Utente',
'description' => 'Descrizione',
'meta_description' => 'Meta descrizione',
'meta_description.desc' => 'Questa è la descrizione che comparirà sugli elenchi dei motori di ricerca.',
'upload-images' => 'Caricare immagini',
'pricing' => 'Prezzi',
'incl-tax' => 'Tasse incluse',
'compare-price.label' => 'filtra per prezzo',
'tax_class' => 'Tipo di tassa',
'attributes.legend' => 'caratteristiche',
'attributes.desc' => 'Inserisci dettagli prodotto come volume, grado alcolico, etc.',
'organisation' => 'Organizzazione',
'miscellaneous' => 'Misto',
'created_at' => 'Creato il',
'last_login' => 'Ultimo accesso',
'current_basket' => 'Articoli presenti nel carrello',
'dashboard.title' => 'Panello di controllo',
'catalogue.title' => 'Catalogo',
'catalogue.image.thumbnail' => 'Impostare questo come miniatura',
'catalogue.image.delete.confirmation' => 'Sei sicuro di voler eliminare questa immagine?',
'catalogue.product.delete.confirmation' => 'Sicuro di voler cancellare questo prodotto?',
'catalogue.product.delete.success' => 'Prodotto cancellato',
'customers.title' => 'Clienti',
'customers.singular' => 'Cliente',
'customers.name.label' => 'Nome cliente',
'customers.total' => 'Totale ordine',
'customers.address.default' => 'Indirizzo preimpostato',
'customers.revenue.lifetime' => 'Totale netto entrate',
'customers.orders_total' => 'Totale ordini',
'orders.title' => 'Ordini',
'orders.show.title' => 'ordine',
'orders.placed-by' => 'Piazzato per',
'orders.paid' => 'Pagato',
'orders.form.id.label' => 'Identificativo ordine',
'orders.filter.incomplete' => 'Filtro incompleto',
'orders.filter.incomplete.info' => 'Visualizzazioni ordini incomplete',
];<file_sep>/resources/assets/js/search.js
$('.getFullSearch').click(function () {
$('#search-full').addClass('active')
.find('input').focus();
})
$('#search-close').click(function () {
$(this).parent().removeClass('active');
});
$('#search-form').submit(function (e) {
e.preventDefault();
var $field = $(this).find('input').eq(0);
var query = $field.val();
if(query == '') {
return;
}
var searchUrl = $field.data('search-url') + '/' + query;
window.open(searchUrl, "_self");
});<file_sep>/readme.md
# Zugy eCommerce
Laravel project for Zugy eCommerce store.
## Features
* Admin panel for managing products
* Coupons
* Rider push notifications when an order is placed
* Order status tracking
* Payment methods
* Stripe
* Paypal
* Cash
## Docker
To start the Docker environment run
```
docker-compose up -d nginx mysql redis
```
Inside `.env` set `DB_HOST` and `REDIS_HOST`
```
DB_HOST=mysql
REDIS_HOST=redis
```
Connect to a container:
```
docker exec -it workspace bash
```
## Installation
Install composer dependencies:
```
composer install
```
Migrate Database tables
```
php artisan migrate
```
Seed the Database
```
php artisan db:seed
```
## Run tests
```
phpunit
```
## Deployment Checklist
* Verify all API keys are working and are not test keys
* Verify database backups are working
* Product table should be synced with Algolia
* Redis is installed and running
* Following locales should be installed (check with `locale -a`):
* it_IT.utf8
* en_GB.utf8
* Run tests on production
* Ensure that Real Visitor IP is revealed by installing additional modules for Apache or nginx due to Cloudflare
<file_sep>/app/Http/Controllers/ShopController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Zugy\Repos\Category\CategoryRepository;
use Zugy\Repos\Product\ProductRepository;
class ShopController extends Controller
{
/**
* @var ProductRepository
*/
private $productRepo;
/**
* @var CategoryRepository
*/
private $categoryRepo;
/**
* ShopController constructor.
* @param $productRepo ProductRepository
*/
public function __construct(ProductRepository $productRepo, CategoryRepository $categoryRepo)
{
$this->productRepo = $productRepo;
$this->categoryRepo = $categoryRepo;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index(Request $request)
{
if($request->has('sort')) {
$sort = $request->input('sort');
} else {
$sort = 'sales';
}
if($request->has('direction')) {
$direction = $request->input('direction');
} else {
$direction = 'desc';
}
$products = $this->productRepo->all($sort, $direction);
return view('pages.product.product-list')->with(compact('products', 'category'));
}
public function category(Request $request, $category_slug) {
if($request->has('sort')) {
$sort = $request->input('sort');
} else {
$sort = 'sales';
}
if($request->has('direction')) {
$direction = $request->input('direction');
} else {
$direction = 'desc';
}
$category = $this->categoryRepo->getBySlug($category_slug);
$translations = $category->translations()->pluck('slug', 'locale');
foreach($translations as $locale => $slug) {
$translations[$locale] = \Localization::getURLFromRouteNameTranslated($locale, 'routes.shop.category', ['slug' => $slug]);
}
$products = $this->productRepo->category($category_slug, $sort, $direction);
return view('pages.product.product-list')->with(compact('products', 'category', 'translations'));
}
}
<file_sep>/app/Zugy/Charts/ChartsServiceProvider.php
<?php
namespace Zugy\Charts;
use Illuminate\Support\ServiceProvider;
class ChartsServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('charts', function()
{
return new Charts();
});
}
}<file_sep>/app/Http/Controllers/Admin/CatalogueController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Attribute;
use App\Language;
use App\Product;
use App\Services\CreateOrUpdateProduct;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Gate;
use Zugy\Repos\Product\ProductRepository;
class CatalogueController extends Controller
{
protected $productRepo;
/**
* CatalogueController constructor.
* @param $productRepo ProductRepository
*/
public function __construct(ProductRepository $productRepo)
{
$this->productRepo = $productRepo;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index(Request $request)
{
if($request->has('product_name')) {
$products = $this->productRepo->search($request->input('product_name'));
} else {
$products = Product::with('translations')->paginate(30);
}
return view('admin.pages.catalogue.index')->with(['products' => $products]);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
if(Gate::denies('create', new Product())) {
abort(403);
}
$languages = Language::all();
$attributes = Attribute::all();
return view('admin.pages.catalogue.create')->with([
'product' => new Product(),
'languages' => $languages,
'attributes' => $attributes,
'translations' => null,
'category' => null,
]);
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request, CreateOrUpdateProduct $service)
{
if(Gate::denies('create', new Product())) {
return redirect()->back()->withErrors('You do not have permission to create new products');
}
return $service->handler($request);
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$product = \App\Product::with(['translations', 'categories', 'attributes', 'images'])->findOrFail($id);
$languages = Language::all();
$attributes = Attribute::all();
$category = $product->categories()->first();
$translations = $product->translations->keyBy('locale');
$productAttributes = $product->attributes()->get()->keyBy('id');
return view('admin.pages.catalogue.edit')->with([
'product' => $product,
'languages' => $languages,
'attributes' => $attributes,
'productAttributes' => $productAttributes,
'translations' => $translations,
'category' => $category,
]);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(Request $request, CreateOrUpdateProduct $service, $productId)
{
return $service->handler($request, $productId);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy(Request $request, $id)
{
$product = \App\Product::findOrFail($id);
//Delete images
$images = $product->images()->get();
foreach($images as $i) {
$i->delete();
}
\Log::info('Deleting product', ['user' => auth()->user()->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'product' => $product->id]);
//Soft delete product
$product->delete($id);
if($request->ajax()) {
return response()->json(['status' => 'success']);
} else {
return redirect(action('Admin\CatalogueController@index'))->withSuccess(trans('admin.catalogue.product.delete.success'));
}
}
}
<file_sep>/resources/lang/it/pages.php
<?php
return [
'about-us.title' => 'Chi siamo',
'about-us.desc' => '<p>Noi di Zugy operiamo proprio come un normale negozio di liquori al dettaglio ma con una piccola significativa differenza: visiti il nostro sito web invece di andare in un negozio. Qui troverai un\'ampia selezione di bevande; potrai scegliere tra circa 50 tipologie di liquori diversi. Basta scegliere quello che desiderate. Fate il vostro ordine e noi lo consegneremo alla vostra porta. Alla consegna puoi pagare con carta di credito, paypal o in contanti.</p>
<p>La tecnologia ha trasformato molte attività ma non ancora quella degli alcolici che non ha subito trasformazioni negli ultimi cento anni. Zugy sta rivoluzionando il modo con cui le persone degustano le bevande attraverso l\'uso di una moderna tecnologia che caratterizza il nostro modo di operare.</p>',
'about-us.find-out-more' => 'Per saperne di più sui social media',
'about-us.partners' => 'Soci',
'about-us.partners-desc' => '<p>Zugy è orgogliosa di essere partner di <a href="http://securitycourier.it/">Security Courier Express</a> che ti porterà a casa il tuo ordine.</p>
<p>Usiamo solo corrieri in bicicletta, garantendo la consegna senza emissione di CO2 <i class="fa fa-leaf"></i>.</p>',
'about-us.mission-statement.title' => 'Obiettivi',
'about-us.mission-statement.desc' => '<p>In Zugy, il nostro obiettivo è e sarà sempre rendere felici i nostri clienti. Vogliamo regalare ricordi ed emozioni, siano questi una bottiglia per una bella chiacchierata o un party pack per rendere un compleanno il migliore di sempre.</p>
<p>Non importa se sarà una nottata da urlo o una tranquilla serata con gli amici, noi speriamo che sceglierete Zugy per rendere la vostra notte indimenticabile.</p>',
'contact.title' => 'Contatti',
'contact.address' => 'Zugy Srl. <br>Alzaia Navigli Grande 36<br> Milano, 20141 <br> Italia',
'contact.customer-service' => 'Di seguito troverete il numero di telefono relativo al servizio clienti. Saremo felici di rispondere alle vostre domande, commenti o dubbi.',
'contact.email.general' => 'Per richieste generali:',
'contact.email.investors' => 'Per gli investitori:',
'shop.title' => 'Negozio',
'home.title' => 'Home',
'home.meta_description' => 'Zugy è un negozio di liquori online a Milano che consegna nel giro di un\'ora.',
'home.meta-title' => 'Alcool a domicilio Milano',
'home.tagline' => 'La tua birra, vino e liquore preferiti, consegnati direttamente a casa tua.',
'home.marketing.address.title' => 'Imposta l\'indirizzo',
'home.marketing.address.desc' => 'Inserisci il codice postale dove desideri ricevere l\'ordine',
'home.marketing.time.title' => 'Ordina in pochi minuti',
'home.marketing.time.desc' => 'Aggiungi ció che desideri al tuo carrello, paga alla cassa ed é fatto.',
'home.marketing.delivery.title' => 'Consegna a domicilio',
'home.marketing.delivery.desc' => 'Inizieremo subito a preparare il vostro ordine e lo consegneremo a casa vostra. Devi solo presentare un documento d\'identitá ai nostri simpatici fattorini!',
'home.exclusive' => 'Attualmente serviamo solo Milano',
'home.milan' => 'Milano',
'home.expansion' => 'Molti progetti da sviluppare',
'privacy-policy' => 'Informativa sulla privacy',
'team' => 'Team',
'terms-and-conditions' => 'Termini e condizioni',
];
<file_sep>/app/Zugy/DeliveryTime/DeliveryTimeServiceProvider.php
<?php
namespace Zugy\DeliveryTime;
use Illuminate\Support\ServiceProvider;
class DeliveryTimeServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('deliveryTime', function()
{
return new DeliveryTime();
});
}
}<file_sep>/app/Services/CreateOrUpdateProduct.php
<?php
namespace App\Services;
use App\Product;
use App\ProductImage;
use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\LaravelLocalization;
use Illuminate\Support\Facades\Validator;
class CreateOrUpdateProduct
{
public function handler(Request $request, $productId = null)
{
$languages = \Localization::getSupportedLanguagesKeys();
if ($productId === null) { //Create new product
$product = new Product();
} else {
$product = Product::findOrFail($productId);
}
$rules = [
'price' => 'required|numeric|min:0',
'compare_price' => 'numeric|min:0',
'tax_class_id' => 'required|exists:tax_classes,id',
'stock_quantity' => 'required|integer|min:0',
'images' => 'required|integerArray',
'category_id' => 'required|exists:categories,id',
'thumbnail_id' => 'exists:product_images,id',
'attributes.*' => 'max:255',
];
foreach ($languages as $l) {
$rules["meta.{$l}.title"] = "required|max:255";
$rules["meta.{$l}.slug"] = "required|max:255|alpha_dash|unique:product_translations,slug,{$product->translateOrNew($l)['slug']},slug,locale,$l";
$rules["meta.{$l}.description"] = "required|max:65535";
$rules["meta.{$l}.meta_description"] = "required|max:255";
}
$validator = Validator::make($request->all(), $rules);
if($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
$product->stock_quantity = $request->input('stock_quantity');
$product->price = $request->input('price');
$product->compare_price = $request->input('compare_price');
$product->tax_class_id = $request->input('tax_class_id');
if($request->input('thumbnail_id') != "") {
$product->thumbnail_id = $request->input('thumbnail_id');
}
foreach ($languages as $l) {
$product->translateOrNew($l)->title = $request->input("meta.{$l}.title");
$product->translateOrNew($l)->slug = $request->input("meta.{$l}.slug");
$product->translateOrNew($l)->description = $request->input("meta.{$l}.description");
$product->translateOrNew($l)->meta_description = $request->input("meta.{$l}.meta_description");
}
$product->save();
$product->categories()->sync([$request->input('category_id')]);
//TODO Validate if attribute IDs exist
$sync = [];
foreach($request->input('attributes') as $key => $value) {
if(trim($value) == "") continue;
$sync[$key] = ['value' => $value];
}
$product->attributes()->sync($sync);
$product->save();
//Ensure that thumbnail ID gets updated with product ID
$productImages = $request->input('images');
if(!in_array((int) $request->input('thumbnail_id'), $productImages)) {
$productImages[] = (int) $request->input('thumbnail_id');
}
ProductImage::whereIn('id', $productImages)->update(['product_id' => $product->id]);
}
if($productId != null) {
\Log::info('Product updated', ['user' => auth()->user()->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'product' => $product]);
return redirect()->back()->with('success', 'Product updated');
} else {
\Log::info('Product created', ['user' => auth()->user()->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'product' => $product]);
return redirect()->action('Admin\CatalogueController@index')->with('success', 'Product added successfully');
}
}
}
<file_sep>/app/Services/Payment/PaymentMethodService.php
<?php
namespace App\Services\Payment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Zugy\Facades\Checkout;
use Zugy\Facades\PaymentGateway;
class PaymentMethodService
{
public function setMethod(Request $request)
{
$validator = Validator::make($request->all(), [
'method' => 'required',
]);
$validator->sometimes('stripeToken', 'required', function($input) {
return ($input->method == 'stripe') && ($input->cardId === null);
});
$validator->sometimes('cardId', 'required', function($input) {
return ($input->method == 'stripe') && ($input->stripeToken === null);
});
if($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
$paymentMethod = PaymentGateway::set($request->input('method'))->addOrUpdateMethod();
Checkout::setPaymentMethod($paymentMethod);
return true;
}
}<file_sep>/app/Http/Controllers/Auth/PasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' =>
'postPasswordChange'
]);
}
public function redirectPath()
{
return localize_url('routes.account.index');
}
public function getEmailSubject()
{
return trans('auth.reset.email.subject');
}
public function getReset(Request $request, $token = null)
{
return $this->showResetForm($request, $token);
}
public function postPasswordChange(Request $request)
{
$validator = \Validator::make($request->all(), [
'password' => '<PASSWORD>',
]);
$validator->sometimes('current_password', 'required|correct_password', function($input) {
return(auth()->user()->password !== null);
});
if($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
auth()->user()->password = <PASSWORD>($request->input('password'));
auth()->user()->save();
return redirect(localize_url('routes.account.settings'))->withSuccess(trans('auth.form.password.change.success'));
}
}
<file_sep>/app/Zugy/DeliveryTime/DeliveryTime.php
<?php
namespace Zugy\DeliveryTime;
use Carbon\Carbon;
class DeliveryTime
{
/**
* Validate delivery time, throws exceptions if it fails
* @param Carbon $delivery_time
* @throws Exceptions\ClosedException
* @throws Exceptions\PastDeliveryTimeException
*/
public function isValidDeliveryTime(Carbon $delivery_time) {
//Check that delivery time is in future
$cutoff_time = Carbon::now()->addMinutes(30);
if($delivery_time->lt($cutoff_time)) {
throw new Exceptions\PastDeliveryTimeException();
}
if(!$this->isOpen($delivery_time)) {
throw new Exceptions\ClosedException();
}
}
/**
* Check if for given time we are delivering or not
* Open everyday from 1pm to 1am
* @param Carbon $time
* @return bool
*/
public function isOpen(Carbon $time) {
$hour = $time->hour;
switch ($time->dayOfWeek) {
case Carbon::SATURDAY:
case Carbon::SUNDAY:
case Carbon::MONDAY:
return ($hour < 1 || $hour >= 13);
default:
return ($hour < 1 || $hour >= 13);
}
}
/**
* Generate array of days for <select>
* @param $days
* @return array
*/
public function daySelect($days) {
$return = [];
for($i = 0; $i < $days; $i++) {
$currentDay = Carbon::now()->addDays($i);
$dayThreshold = $currentDay->copy();
$dayThreshold->hour = 23;
$dayThreshold->minute = 5;
if($i == 0 && $currentDay->gt($dayThreshold) ) continue; //Don't show day if time is after 23:05
$return[] = $currentDay;
}
return $return;
}
}<file_sep>/app/Zugy/Stock/StockServiceProvider.php
<?php
namespace Zugy\Stock;
use Illuminate\Support\ServiceProvider;
class StockServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('stock', function()
{
return new Stock();
});
}
}<file_sep>/database/migrations/2015_09_13_141415_create_order_payments_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrderPaymentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('order_payments', function (Blueprint $table) {
$table->increments('id');
$table->integer('order_id')->unsigned()->nullable();
$table->foreign('order_id')
->references('id')->on('orders')
->onDelete('cascade');
$table->tinyInteger('status')->unsigned();
$table->decimal('amount', 10, 2);
$table->char('currency', 3);
$table->string('method', 32);
$table->text('metadata');
$table->dateTime('paid')->nullable();
$table->string('billing_name', 64);
$table->string('billing_line_1', 64);
$table->string('billing_line_2', 64)->nullable();
$table->string('billing_city', 32);
$table->string('billing_postcode', 10);
$table->string('billing_state', 32)->nullable();
$table->string('billing_phone', 32);
$table->integer('billing_country_id');
$table->foreign('billing_country_id')
->references('id')->on('countries')
->onDelete('no action');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('order_payments');
}
}
<file_sep>/resources/lang/en/routes.php
<?php
return [
'about-us' => 'about-us',
'account' => [
'index' => 'your-account',
'orders' => 'your-account/orders',
'settings' => 'your-account/settings',
],
'cart' => 'cart',
'checkout' => [
'landing' => 'checkout',
'address' => 'checkout/address',
'payment' => 'checkout/payment',
'review' => 'checkout/review',
'confirmation' => 'checkout/confirmation',
'gatewayReturn' => 'checkout/gatewayReturn',
],
'contact' => 'contact',
'order' => [
'show' => 'order/{id}',
],
'privacy-policy' => 'privacy-policy',
'product' => 'product/{slug}',
'search' => 'search/{query}',
'shop' => [
'index' => 'shop',
'category' => 'shop/category/{slug}',
],
'team' => 'team',
'terms-and-conditions' => 'terms-and-conditions',
];<file_sep>/resources/lang/en/cart.php
<?php
return [
'shopping-cart' => 'Shopping Cart',
'free-shipping-reminder' => 'Order more than 20€ worth and get <b>free shipping</b>!',
'mini-cart-empty' => 'Nothing in your cart yet',
'empty-cart-msg' => 'You don\'t have anything in your cart yet. Visit the <a href=":storeUrl">shop</a> to start filling it up!',
'api.error.out-of-stock' => 'Unable to add to cart. We only have :quantity left in stock.',
];<file_sep>/resources/lang/it/errors.php
<?php
return [
'unknown' => 'Si è verificato un errore sconosciuto. Riprova',
'stripe.invalid_number' => 'Il numero della carta di credito non è valida.',
'stripe.invalid_expiry_month' => 'Mese di scadenza della carta non è valido.',
'stripe.invalid_expiry_year' => 'Anno di scadenza della carta non è valido.',
'stripe.invalid_cvc' => 'Il codice di sicurezza della scheda non è valido.',
'stripe.incorrect_number' => 'Il numero della carta non è corretto.',
'stripe.expired_card' => 'La carta è scaduta.',
'stripe.incorrect_cvc' => 'Il codice di sicurezza della carta non è corretto.',
'stripe.incorrect_zip' => 'Codice postale della scheda non è riuscito ha convalidare.',
'stripe.card_declined' => 'La carta è stata rifiutata.',
'stripe.missing' => 'Non c`è alcuna carta sul cliente che è in carica.',
'stripe.processing_error' => 'Si è verificato un errore durante l\'elaborazione della scheda.',
'404.message' => 'Pagina non trovata',
'404.description' => 'Spiacenti la pagina richiesta non è disponibile.',
'500.message' => 'Si è verificato un errore interno',
'500.description' => 'Si è verificato un errore, questo errore è stato segnalato a noi e noi risolverlo nel più breve tempo possibile - ci dispiace!',
];<file_sep>/resources/lang/en/checkout.php
<?php
return [
'title' => 'Checkout',
'items' => 'Items',
'total' => 'Total',
'subtotal' => 'Subtotal',
'shipping' => 'Shipping',
'address.title' => 'Address',
'address.prompt' => 'Please enter your address',
'address.choose-delivery' => 'Choose a delivery address',
'address.select-delivery' => 'Deliver to this address',
'address.deliver-new' => 'Deliver to a new address',
'address.deliver-new-desc' => 'Add a new delivery address to your address book.',
'address.form.delivery' => 'Delivery Address',
'address.form.billing' => 'Billing Address',
'address.form.name' => 'Full name',
'address.form.line_1' => 'Address Line 1',
'address.form.line_1.desc' => 'House name/number and street, P.O. box, company name, c/o',
'address.form.line_2' => 'Address Line 2',
'address.form.line_2.desc' => 'Apartment, suite, unit, building, floor, etc.',
'address.form.zip' => 'Zip / Postcal Code',
'address.form.town' => 'Town / City',
'address.form.country' => 'Country',
'address.form.instructions' => 'Delivery instructions',
'address.form.instructions.desc' => 'Additional information for our driver',
'address.form.phone' => 'Phone',
'address.form.phone.desc' => 'In case our driver needs to contact you for delivery',
'address.form.default' => 'Use this address as default for future orders',
'address.form.same' => 'Same as delivery address',
'address.form.country.italy' => 'Italy',
'payment.title' => 'Payment',
'payment.form.title' => 'Select payment method',
'payment.form.card' => 'Card',
'payment.form.card.new' => 'Add a new card',
'payment.form.card.show' => '<b>:brand</b> ending in :last4',
'payment.form.card.expires' => 'Expires',
'payment.form.name' => '<NAME>',
'payment.form.cvc' => 'CVC',
'payment.form.expiration' => 'Expiration',
'payment.form.default' => 'Set this as the default payment method',
'payment.form.card.button' => 'Use credit card',
'payment.form.pay-with' => 'Pay with :name',
'payment.form.cash' => 'Cash',
'payment.form.cash.desc' => 'Pay with cash on delivery',
'payment.form.error.different' => 'There was an error processing your payment. Try again or use another payment method. <a href=":paymentUrl?change">Change</a>',
'review.title' => 'Review order',
'review.age-warning' => 'We only sell alcohol to people <b>older than the age of 18</b>, even though the legal drinking age is 16 in Italy. Our drivers will ask you for your photo ID to verify your age at delivery.',
'review.coupon' => 'Coupon',
'review.coupon.desc' => 'Enter a coupon code if you have one',
'review.coupon.placeholder' => 'Enter code',
'review.items' => 'Review items',
'review.place-order' => 'Place order',
'review.accept' => 'By placing your order you agree to :siteName\'s <a href=":privacyPolicyUrl">Privacy Policy</a> and <a href=":termsAndConditionsUrl">Terms and Conditions</a>.',
'review.delivery-time' => 'Delivery time',
'review.delivery-time.label' => 'When do you want your order to be delivered?',
'review.delivery-time.asap' => 'As soon as possible',
'review.delivery-time.slot' => 'Choose a delivery slot',
'review.delivery-time.error.late' => 'It\'s too late to choose this delivery time. Please select a later time',
'review.delivery-time.error.closed' => 'We are closed during this delivery time. Please select a different time',
'review.error.too-fast' => 'You are placing too many orders in a short period of time. Please wait a minute before placing an order again',
'order' => 'Order',
'order.success' => 'Your order has been placed. We will notify you via email when your order is out for delivery.'
];<file_sep>/app/Http/Controllers/API/CouponController.php
<?php
namespace App\Http\Controllers\Api;
use App\Coupon;
use App\Exceptions\Coupons\CouponExpiredException;
use App\Exceptions\Coupons\CouponNotStartedException;
use App\Exceptions\Coupons\CouponOrderMinimumException;
use App\Exceptions\Coupons\CouponUsedException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Zugy\Facades\Checkout;
class CouponController extends Controller
{
/**
* Applies a coupon code to the current
* @param $code
* @return \Illuminate\Http\JsonResponse
*/
public function apply(Request $request) {
$code = "";
if($request->has('coupon')) {
$code = trim($request->input('coupon'));
}
$coupon = Coupon::where('code', '=', $code)->first();
if($coupon == null) {
return response()->json(['status' => 'error', 'message' => trans('coupon.404')], 400);
}
try{
Checkout::setCoupon($coupon);
} catch(CouponUsedException $e) {
return response()->json(['status' => 'error', 'message' => trans('coupon.claimed')], 400);
} catch(CouponExpiredException $e) {
return response()->json(['status' => 'error', 'message' => trans('coupon.expired', ['date' => $coupon->expires->toFormattedDateString()])], 400);
} catch(CouponNotStartedException $e) {
return response()->json(['status' => 'error', 'message' => trans('coupon.notActive', ['date' => $coupon->starts])], 400);
} catch(CouponOrderMinimumException $e) {
return response()->json(['status' => 'error', 'message' => trans('coupon.minimum', ['min' => $coupon->minimumTotal])], 400);
}
return response()->json(['status' => 'success']);
}
}<file_sep>/app/Providers/AuthServiceProvider.php
<?php
namespace App\Providers;
use App\Address;
use App\Order;
use App\Policies\AuthenticationPolicy;
use App\Product;
use App\Policies\AddressPolicy;
use App\Policies\ProductPolicy;
use App\Policies\OrderPolicy;
use App\User;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Product::class => ProductPolicy::class,
Order::class => OrderPolicy::class,
Address::class => AddressPolicy::class,
User::class => AuthenticationPolicy::class
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
}
}<file_sep>/app/Http/Controllers/Admin/DashboardController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Order;
use Zugy\Facades\Charts;
class DashboardController extends Controller
{
public function getDashboard()
{
$orders = new Order();
$revenueYesterday = $orders->uncancelled()->where('order_placed', '>', \Carbon::yesterday())->where('order_placed', '<', \Carbon::today())->get()->sum('grand_total');
$revenueThisMonth = $orders->uncancelled()->where('order_placed', '>', new \Carbon('first day of this month'))->where('order_placed', '<', \Carbon::today())->get()->sum('grand_total');
$chart = [
'30-days' => Charts::revenueByDay()
];
return view('admin.pages.dash')->with([
'orders' => $orders,
'revenueYesterday' => $revenueYesterday,
'revenueThisMonth' => $revenueThisMonth,
'chart' => $chart
]);
}
}<file_sep>/app/PaymentMethod.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zugy\Facades\PaymentGateway;
class PaymentMethod extends Model
{
protected $table = 'users_payment_method';
protected $casts = [
'payload' => 'json',
];
protected $fillable = ['method', 'payload'];
/**
* Get the default payment method
* @param $query
* @return mixed
*/
public function scopeDefault($query) {
return $query->where('isDefault', '=', 1);
}
public function getFormatted()
{
$formattedPayment = PaymentGateway::set($this)->getFormatted();
return $formattedPayment;
}
}
<file_sep>/tests/PostcodeApiTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PostcodeApiTest extends TestCase
{
private $apiEndpoint = '/api/v1/postcode';
public function testPostcodePass()
{
$this->get("{$this->apiEndpoint}/check/20121")
->seeJson([
'delivery' => true,
]);
}
public function testPostcodeFail()
{
$this->get("{$this->apiEndpoint}/check/12345")
->seeJson([
'delivery' => false,
]);
}
}
<file_sep>/tests/StockTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Zugy\Facades\Stock;
class StockTest extends TestCase
{
use DatabaseTransactions;
/**
* Check that stock check passes
*
* @return void
*/
public function testStockPositive()
{
$productA = factory(App\Product::class)->create(['stock_quantity' => 4]);
$productA->translations()->save(factory(App\ProductTranslation::class)->make());
$productB = factory(App\Product::class)->create(['stock_quantity' => 3]);
$productB->translations()->save(factory(App\ProductTranslation::class)->make());
//Add 4 of productA to cart
$this->json('POST', 'api/v1/cart', [
'id' => $productA->id,
'qty' => 4,
])->seeJson(['status' => 'success']);
//Add 2 of productB to cart
$this->json('POST', 'api/v1/cart', [
'id' => $productB->id,
'qty' => 2,
])->seeJson(['status' => 'success']);
$this->assertTrue(Stock::checkCartStock());
}
/**
* Check that stock check throws correct error
*/
public function testStockNegative() {
$this->setExpectedException('App\Exceptions\OutOfStockException');
$productA = factory(App\Product::class)->create(['stock_quantity' => 4]);
$productA->translations()->save(factory(App\ProductTranslation::class)->make());
$productB = factory(App\Product::class)->create(['stock_quantity' => 3]);
$productB->translations()->save(factory(App\ProductTranslation::class)->make());
//Add 4 of productA to cart
$this->json('POST', 'api/v1/cart', [
'id' => $productA->id,
'qty' => 4,
])->seeJson(['status' => 'success']);
//Add 2 of productB to cart
$this->json('POST', 'api/v1/cart', [
'id' => $productB->id,
'qty' => 2,
])->seeJson(['status' => 'success']);
\Log::debug('Updating product stock', [$productA->id]);
$productA->stock_quantity = 3; //Another customer bought 1, only 3 left
$productA->save();
Stock::checkCartStock(); //Should throw OutOfStockException
}
}
<file_sep>/database/migrations/2016_07_06_220419_make_billing_phone_nullable.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class MakeBillingPhoneNullable
* Fixes a bug where if a customer had a billing address different from his delivery address, the billing address
* would not have a phone.
* When inserting a billing address into order_payments, phone was not allowed to be null.
*/
class MakeBillingPhoneNullable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('order_payments', function (Blueprint $table) {
$table->string('billing_phone', 32)->nullable()->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('order_payments', function (Blueprint $table) {
$table->string('billing_phone', 32)->change();
});
}
}
<file_sep>/database/seeds/LanguageSeeder.php
<?php
use Illuminate\Database\Seeder;
/**
* User: <NAME>
* Date: 24.07.2015
* Time: 15:48
*/
class LanguageSeeder extends Seeder
{
public function run() {
DB::table('languages')->insert([
['id' => 1, 'name' => 'English', 'code' => 'en', 'flag' => 'gb'],
['id' => 2, 'name' => 'Italian', 'code' => 'it', 'flag' => 'it']
]);
}
}<file_sep>/app/Services/AuthenticateUser.php
<?php
namespace App\Services;
use App\OAuthAuthorisations;
use App\User;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
class AuthenticateUser
{
public function __construct()
{
//
}
public function requestToken($oauth_provider) {
return Socialite::with($oauth_provider)->redirect();
}
public function facebookLogin(Request $request) {
if(!$request->has('code')) {
return $this->requestToken('facebook');
}
return $this->loginOrCreateUser('facebook', Socialite::driver('facebook')->user());
}
public function googleLogin(Request $request) {
if(!$request->has('code')) {
return $this->requestToken('google');
}
return $this->loginOrCreateUser('google', Socialite::driver('google')->user());
}
public function loginOrCreateUser($oauth_provider, $oauth_user) {
$oauth_authorisation = OAuthAuthorisations::where('network', '=', $oauth_provider)
->where('network_user_id', '=', (string) $oauth_user->id)
->first();
if($oauth_authorisation === null) {
$user = User::where('email', '=', $oauth_user->email)->first();
if($user === null) {
//Create user
$user = $this->createUser($oauth_user->name, $oauth_user->email);
}
OAuthAuthorisations::create([
'network' => $oauth_provider,
'network_user_id' => $oauth_user->id,
'user_id' => $user->id
]);
auth()->loginUsingId($user->id, true);
} else {
auth()->loginUsingId($oauth_authorisation->user_id, true);
}
return redirect()->intended(localize_url('routes.shop.index'))->with('success', trans('auth.login.success'));
}
public function createUser($name, $email) {
$user = User::create([
'name' => $name,
'email' => $email
]);
return $user;
}
}
<file_sep>/app/Attribute.php
<?php
namespace App;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
class Attribute extends Model
{
use Translatable;
public $translatedAttributes = ['name', 'unit'];
}
<file_sep>/resources/lang/en/payment.php
<?php
return [
'card-number' => 'Card Number',
'cardholder-name' => '<NAME>',
'payment-method' => 'Payment method'
];<file_sep>/app/Services/CreateOrUpdateAddress.php
<?php
/**
* User: <NAME>
* Date: 08.09.2015
* Time: 20:50
*/
namespace App\Services;
use App\Address;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use Webpatser\Countries\Countries;
class CreateOrUpdateAddress
{
protected $defaultRules = [
'name' => 'required|string|max:64',
'line_1' => 'required|string|max:64',
'line_2' => 'string|max:64',
'postcode' => 'required|max:5|deliveryPostcode',
'city' => 'required|max:32',
'country' => 'required|size:3|exists:countries,iso_3166_3', //TODO validate is Italy
];
public function delivery(array $deliveryInput, Address $address = null)
{
$deliveryRules = $this->defaultRules;
$deliveryRules['delivery_instructions'] = 'max:1000';
$deliveryRules['phone'] = 'required'; //TODO Validate valid phone
$validator = Validator::make($deliveryInput, $deliveryRules);
if($validator->fails()) {
return $validator;
}
if($address == null) {
$address = new Address($deliveryInput);
} else {
$address->fill($deliveryInput);
}
$address->country_id = Countries::where('iso_3166_3', '=', $deliveryInput['country'])->first()->id;
if(isset($deliveryInput['default'])) {
auth()->user()->addresses()->update(['isShippingPrimary' => false]);
$address->isShippingPrimary = true;
}
if(isset($deliveryInput['billing_same'])) {
auth()->user()->addresses()->update(['isBillingPrimary' => false]);
$address->isBillingPrimary = true;
}
auth()->user()->addresses()->save($address);
return $address;
}
public function billing(array $billingInput, Address $address = null)
{
$billingRules = $this->defaultRules;
$billingRules['postcode'] = 'required|max:5';
$validator = Validator::make($billingInput, $billingRules);
if($validator->fails()) {
return $validator;
}
if($address == null) {
$address = new Address($billingInput);
} else {
$address->fill($billingInput);
}
$address->country_id = Countries::where('iso_3166_3', '=', $billingInput['country'])->first()->id;
if(isset($billingInput['default'])) {
auth()->user()->addresses()->update(['isBillingPrimary' => false]);
$address->isBillingPrimary = true;
}
auth()->user()->addresses()->save($address);
return $address;
}
}<file_sep>/app/Providers/ValidatorServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class ValidatorServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
Validator::extend('integerArray', function($attribute, $value, $parameters)
{
foreach($value as $v) {
if(!is_numeric($v) && !is_int((int)$v)) return false;
}
if(count($value) == 0) return false;
return true;
});
Validator::extend('deliveryPostcode', function($attribute, $value, $parameters)
{
return \Zugy\Validators\PostcodeValidator::isInDeliveryRange($value);
});
Validator::extend('correct_password', function($attribute, $value, $parameters)
{
return auth()->attempt(['id' => auth()->user()->id, 'password' => $value]);
});
Validator::replacer('correct_password', function($message, $attribute, $rule, $parameters)
{
return trans('auth.form.current_password.error');
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep>/resources/lang/en/coupon.php
<?php
return [
'404' => 'The coupon does not exist',
'claimed' => 'This coupon has already been claimed, sorry',
'expired' => 'This coupon expired on :date',
'notActive' => 'This coupon becomes active at :date',
'minimum' => 'You order total needs to be at least :min Euro to use this coupon',
'using' => 'Using coupon code <b>:code</b>',
'flatDiscountDescription' => '-:amount€ off order',
'percentageDiscountDescription' => ':percentage% off'
];<file_sep>/app/Http/Controllers/Admin/CustomerController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
class CustomerController extends Controller
{
public function index(Request $request)
{
if($request->has('name')) {
$customers = User::where('name', 'LIKE', "%{$request->input('name')}%")->paginate(30);
} else {
$customers = User::paginate(30);
}
return view('admin.pages.customer.index-customer')->with(['customers' => $customers]);
}
public function show($id)
{
$customer = User::findOrFail($id);
return view('admin.pages.customer.show-customer')->with(['customer' => $customer]);
}
}<file_sep>/resources/lang/en/email.php
<?php
return [
'thanks' => 'Thank you for using :name.',
'receipt' => 'Here is your receipt.',
'footer.tos' => 'View the :name <a href=":tosUrl">Terms of Service</a>',
'footer.questions' => 'Questions? Email <a href="mailto::email">:email</a>',
];<file_sep>/tests/DeliveryTimeTest.php
<?php
use Carbon\Carbon;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Zugy\Facades\DeliveryTime;
class DeliveryTimeTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
public function testTrueOpeningTimes()
{
for($i = 0; $i < 6; $i++) {
//Any day at 13:00
$this->assertTrue(DeliveryTime::isOpen(Carbon::now()->startOfWeek()->addDay($i)->hour(13)->minute(0)));
//Any day at 18:59
$this->assertTrue(DeliveryTime::isOpen(Carbon::now()->hour(18)->minute(59)));
}
//Monday 00:59
$this->assertTrue(DeliveryTime::isOpen(Carbon::now()->startOfWeek()->hour(0)->minute(59)));
}
public function testFalseOpeningTimes()
{
for($i = 0; $i < 6; $i++) {
//Any day at 02:01
$this->assertFalse(DeliveryTime::isOpen(Carbon::now()->startOfWeek()->addDay($i)->hour(2)->minute(1)));
}
//Tuesday 01:30
$this->assertFalse(DeliveryTime::isOpen(Carbon::now()->startOfWeek()->addDay(1)->hour(1)->minute(30)));
//Friday 01:30
$this->assertFalse(DeliveryTime::isOpen(Carbon::now()->startOfWeek()->addDay(4)->hour(1)->minute(30)));
//Monday 01:01
$this->assertFalse(DeliveryTime::isOpen(Carbon::now()->startOfWeek()->hour(1)->minute(1)));
//Sunday 01:01
$this->assertFalse(DeliveryTime::isOpen(Carbon::now()->endOfWeek()->hour(1)->minute(1)));
}
}
<file_sep>/app/Zugy/Repos/Category/DbCategoryRepository.php
<?php
/**
* User: <NAME>
* Date: 18.09.2015
* Time: 15:07
*/
namespace Zugy\Repos\Category;
use App\CategoryTranslation;
use App\Exceptions\NoTranslationException;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Zugy\Repos\DbRepository;
use App\Category;
class DbCategoryRepository extends DbRepository implements CategoryRepository
{
/**
* @var Category
*/
private $model;
/**
* DbCategoryRepository constructor.
*/
public function __construct(Category $model)
{
$this->model = $model;
}
public function children($categoryId)
{
$categories = $this->model->all();
return $this->recurseChildren($categories, $categoryId);
}
private function recurseChildren($categories, $parentId) {
$children = $categories->where('parent_id', $parentId);
if($children->count() === 0) return [$parentId];
$ids = [$parentId];
foreach($children as $c) {
$ids = array_merge($ids, $this->recurseChildren($categories, $c->id));
}
return $ids;
}
public function getBySlug($slug) {
$category = CategoryTranslation::where('slug', '=', $slug)
->where('locale', '=', LaravelLocalization::getCurrentLocale())->first();
if(is_null($category)) {
throw new NotFoundHttpException();
}
$category = $this->model->find($category->category_id);
return $category;
}
}<file_sep>/tests/AdminCustomersTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AdminCustomersTest extends TestCase
{
use DatabaseTransactions;
public function testViewCustomer()
{
$customer = factory(App\User::class)->create();
$admin = factory(App\User::class, 'admin')->make();
$this->actingAs($admin)->visit('admin/customer/' . $customer['id'])->see($customer['name']);
}
}
<file_sep>/app/Exceptions/NoTranslationException.php
<?php
namespace App\Exceptions;
class NoTranslationException extends \Exception
{
}<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
/**
* Class User
*
* Group ID:
* 0 - Normal user
* 1 - Super admin
* 2 - Admin
* 3 - Driver
*
* @package App
*/
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password', 'settings'];
protected $casts = [
'settings' => 'json'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
protected $adminGroupIds = [1, 2, 3];
/**
* Get the user settings.
*
* @return Settings
*/
public function settings()
{
return new Settings($this);
}
/**
* Define relationship
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function orders()
{
return $this->hasMany('App\Order');
}
public function oauth_authorisations()
{
return $this->hasMany('App\OAuthAuthorisations');
}
/**
* Define relationship
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function addresses()
{
return $this->hasMany('App\Address');
}
/**
* Define relationship
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function payment_methods()
{
return $this->hasMany('App\PaymentMethod');
}
/**
* Define relationship
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function basket()
{
return $this->hasMany('App\Basket');
}
/**
* Define accessor for user language setting
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function getLanguageCodeAttribute()
{
return strtolower(Language::find(auth()->user()->settings()->language)->pluck('code'));
}
public function getIsAdminAttribute()
{
return in_array($this->attributes['group_id'], $this->adminGroupIds);
}
}
<file_sep>/app/ProductTranslation.php
<?php
namespace App;
class ProductTranslation extends \Eloquent
{
public $timestamps = false;
protected $fillable = ['slug', 'title', 'description', 'meta_description'];
}<file_sep>/app/Zugy/Validators/PostcodeValidator.php
<?php
namespace Zugy\Validators;
class PostcodeValidator
{
static public function isInDeliveryRange($postcode) {
return ($postcode >= 20121 && $postcode <= 20162);
}
}<file_sep>/.env.example
APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_URL=http://homestead.app
DB_HOST=localhost
DB_DATABASE=zugy
DB_USERNAME=homestead
DB_PASSWORD=<PASSWORD>
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=sync
MAIL_DRIVER=mailgun
FILE_DISC=local_uploads
####################
# APPLICATION KEYS #
####################
MAILGUN_DOMAIN=
MAILGUN_SECRET=
GOOGLE_CLIENT_ID=
GOOGLE_SECRET=
FACEBOOK_CLIENT_ID=
FACEBOOK_SECRET=
STRIPE_SECRET=
STRIPE_PUBLIC=
PAYPAL_TESTMODE=true
PAYPAL_USERNAME=
PAYPAL_PASSWORD=
PAYPAL_SIGNATURE=
PUSHBULLET_TOKEN=
ALGOLIA_ID=
ALGOLIA_SEARCH_KEY=
ALGOLIA_KEY=
RECAPTCHA_PUBLIC_KEY=
RECAPTCHA_PRIVATE_KEY=
ROLLBAR_ACCESS_TOKEN=
ROLLBAR_POST_CLIENT_ITEM=
AWS_KEY=
AWS_SECRET=
AWS_REGION=eu-central-1
AWS_BUCKET=zugy-production
AWS_BACKUP_BUCKET=zugy-backups
<file_sep>/resources/assets/js/address.js
(function( address, $, undefined ) {
var apiEndpoint = '/api/v1/address';
address.update = function(addressId, address) {
return $.ajax({
type: 'PATCH',
url: apiEndpoint + '/' + addressId,
data: address,
success: function(data) {
swal(data.message, null, "success");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
swal({
title: err.message,
type: 'error',
text: JSON.stringify(err.errors, null, "\t"),
});
}
});
};
address.delete = function(addressId) {
return $.ajax({
type: 'DELETE',
url: apiEndpoint + '/' + addressId,
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.message);
}
});
};
}( window.address = window.address || {}, jQuery ));<file_sep>/app/Http/Controllers/Admin/OrderController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Zugy\Repos\Order\OrderRepository;
class OrderController extends Controller
{
/**
* @var OrderRepository
*/
protected $orderRepository;
/**
* OrderController constructor.
*/
public function __construct(OrderRepository $orderRepository)
{
$this->orderRepository = $orderRepository;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if($request->has('filter')) {
$orders = $this->orderRepository->incomplete()->orderBy('delivery_time', 'asc')->orderBy('order_placed', 'asc')->paginate(30);
} else {
$orders = $this->orderRepository->orderBy('order_placed', 'desc')->paginate(30);
}
return view('admin.pages.order.index')->with(compact('orders'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$order = $this->orderRepository->with('activity')->findOrFail($id);
return view('admin.pages.order.show')->with(compact('order'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/resources/lang/en/buttons.php
<?php
return [
'add-cart' => 'Add to cart',
'shop-now' => 'Shop now',
'update-cart' => 'Update cart',
'continue-shopping' => 'Continue shopping',
'proceed-to-checkout' => 'Proceed to checkout',
'view-cart' => 'View cart',
'edit' => 'Edit',
'back-to-shop' => 'Back to Shop',
'add-new-address' => 'Add new address',
'proceed' => 'Proceed',
'change' => 'Change',
'login' => 'Login',
'more-info' => 'More info',
'got-it' => 'Got it!',
'toggle-navigation' => 'Toggle navigation',
'view' => 'View',
'mark-as' => 'Mark as...',
'update' => 'Update',
'show-google-maps' => 'Show on Google Maps',
'save' => 'Save',
'return-home' => 'Return to the homepage',
'apply' => 'Apply',
'cancel' => 'Cancel',
'delete' => 'Delete',
'success' => 'Success',
'search.prompt' => 'start typing and search'
];<file_sep>/app/Zugy/Facades/Stock.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class Stock extends Facade
{
protected static function getFacadeAccessor() { return 'stock'; }
}<file_sep>/app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Zugy\Repos\Product\ProductRepository;
class ProductController extends Controller
{
/**
* @var ProductRepository
*/
private $productRepo;
/**
* ProductController constructor.
* @param ProductRepository $productRepo
*/
public function __construct(ProductRepository $productRepo)
{
$this->productRepo = $productRepo;
}
/**
* Display the specified resource.
*
* @param String $slug
* @return Response
*/
public function show($slug)
{
$product = $this->productRepo->getBySlug($slug);
if($product === null) abort(404, trans('product.404'));
$thumbnail = $product->images()->where('id', $product->thumbnail_id)->first();
$translations = $product->translations()->pluck('slug', 'locale');
foreach($translations as $locale => $slug) {
$translations[$locale] = \Localization::getURLFromRouteNameTranslated($locale, 'routes.product', ['slug' => $slug]);
}
return view('pages.product.product-show')->with(['product' => $product, 'thumbnail' => $thumbnail, 'translations' => $translations]);
}
public function search($query)
{
$products = $this->productRepo->search($query);
return view('pages.product.product-list')->with(['products' => $products, 'query' => $query]);
}
}
<file_sep>/resources/lang/it/shipping.php
<?php
return [
'shipping-method' => 'Metodo di spedizione',
'time' => 'Tempo di spedizione',
'hour-delivery' => 'Consegna in 45 minuti',
'max-duration' => '45 minuti',
'cost' => 'Costo',
'standard' => 'Standard',
'hour' => '{1} 1 ora |[0,Inf] :count ore',
'free-shipping' => 'Gratis se l\'ordine è superiore ai 20€, altrimenti 3€',
'free' => 'Spedizione gratuita',
'no-minimum-order' => 'Non c\'è un ordine minimo.',
];<file_sep>/app/Zugy/Facades/DeliveryTime.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class DeliveryTime extends Facade
{
protected static function getFacadeAccessor() { return 'deliveryTime'; }
}<file_sep>/resources/lang/it/product.php
<?php
return [
'product' => 'Prodotto',
'search-results' => 'Risultati della ricerca di <i>:query</i>',
'count' => '{0} zero prodotti |{1} 1 prodotto|[2,Inf] :count i prodotti',
'stock' => 'Offerta Quantità',
'in-stock' => 'Disponibile',
'out-of-stock' => 'Non disponibile',
'stock-warning' => 'Solo :count disponibili nello store.',
'item-weight' => 'Peso dell\'oggetto',
'tabs.details' => 'Dettagli',
'quantity' => 'Quantità',
'price' => 'Prezzo',
'edit' => 'Modifica prodotto',
'search.empty' => 'Non ci sono risultati che corrispondono alla query <b>":query"</b>',
'category.empty' => 'Non ci sono prodotti in questa categoria',
'category.title' => 'Categoria',
'404' => 'Tale prodotto non esiste',
'form.name.label' => 'Nome del prodotto',
'form.add.label' => 'Aggiungere un prodotto',
'filter.search' => 'Ricerca di <b>:name</b>. :count risultati del conteggio trovati.',
'sort.popular' => 'Più popolare',
'sort.price.highest' => 'prezzo più alto',
'sort.price.lowest' => 'Prezzo più basso',
'title.category' => 'Acquista :category',
'title.search' => 'Mostra risultati per :query',
'title.shop' => 'Compra alcolici',
];<file_sep>/app/Zugy/Checkout/CheckoutServiceProvider.php
<?php
namespace Zugy\Checkout;
use Illuminate\Support\ServiceProvider;
class CheckoutServiceProvider extends ServiceProvider
{
public function register()
{
$this->app['checkout'] = $this->app->share(function($app)
{
$session = $app['session'];
return new Checkout($session);
});
}
}<file_sep>/tests/EnvTest.php
<?php
class EnvTest extends TestCase
{
public function testFacebook()
{
$this->assertTrue(config('services.facebook.client_id') !== null);
$this->assertTrue(config('services.facebook.client_secret') !== null);
}
public function testStripe()
{
$this->assertTrue(config('services.stripe.secret') !== null);
$this->assertTrue(config('services.stripe.public') !== null);
}
public function testMailgun()
{
$this->assertTrue(config('services.mailgun.domain') !== null);
$this->assertTrue(config('services.mailgun.secret') !== null);
}
public function testGoogle()
{
$this->assertTrue(config('services.google.client_id') !== null);
$this->assertTrue(config('services.google.client_secret') !== null);
}
public function testPaypal()
{
if(env('APP_ENV') == 'production') {
$this->assertFalse(config('services.paypal.testMode'));
} else {
$this->assertTrue(config('services.paypal.testMode'));
}
$this->assertTrue(config('services.paypal.username') !== null);
$this->assertTrue(config('services.paypal.password') !== null);
$this->assertTrue(config('services.paypal.signature') !== null);
}
public function testAlgolia()
{
$this->assertTrue(env('ALGOLIA_ID') !== null);
$this->assertTrue(env('ALGOLIA_SEARCH_KEY') !== null);
$this->assertTrue(env('ALGOLIA_KEY') !== null);
}
public function testRollbar()
{
$this->assertNotNull(config('services.rollbar.access_token'));
$this->assertNotNull(config('services.rollbar.post_client_item'));
}
public function testAWS()
{
$this->assertNotNull(config('filesystems.default'));
if(env('FILE_DISC') == 's3') {
$this->assertNotNull(config('services.aws.region'));
$this->assertNotNull(config('services.aws.bucket'));
$this->assertNotNull(env('AWS_KEY') !== null);
$this->assertNotNull(env('AWS_SECRET') !== null);
}
}
}
<file_sep>/resources/lang/en/admin.php
<?php
return [
'incomplete-orders' => 'Incomplete Orders',
'revenue-yesterday' => 'Revenue yesterday',
'revenue-this-month' => 'Revenue this month so far',
'details' => 'Details',
'time' => 'Time',
'user' => 'User',
'description' => 'Description',
'meta_description' => 'Meta description',
'meta_description.desc' => 'This is the description that will appear on search engine listings.',
'upload-images' => 'Upload images',
'pricing' => 'Pricing',
'incl-tax' => 'incl. tax',
'compare-price.label' => 'Compare at price',
'tax_class' => 'Tax class',
'attributes.legend' => 'Attributes',
'attributes.desc' => 'Give the product attributes like volume, alcohol content, etc.',
'organisation' => 'Organisation',
'miscellaneous' => 'Miscellaneous',
'created_at' => 'Created at',
'last_login' => 'Last login',
'current_basket' => 'Current items in cart',
'dashboard.title' => 'Dashboard',
'catalogue.title' => 'Catalogue',
'catalogue.image.thumbnail' => 'Set this as thumbnail',
'catalogue.image.delete.confirmation' => 'Are you sure you want to delete this image?',
'catalogue.product.delete.confirmation' => 'Are you sure you want to delete this product?',
'catalogue.product.delete.success' => 'Product deleted',
'customers.title' => 'Customers',
'customers.singular' => 'Customer',
'customers.name.label' => 'Customer Name',
'customers.total' => 'Total spent',
'customers.address.default' => 'Default address',
'customers.revenue.lifetime' => 'Lifetime Revenue',
'customers.orders_total' => 'Total orders',
'orders.title' => 'Orders',
'orders.show.title' => 'Order',
'orders.placed-by' => 'Placed by',
'orders.paid' => 'Paid',
'orders.form.id.label' => 'Order ID',
'orders.filter.incomplete' => 'Filter incomplete',
'orders.filter.incomplete.info' => 'Currently showing incomplete orders only.',
];<file_sep>/app/Helpers/helpers.php
<?php
if ( ! function_exists('localize_url'))
{
function localize_url($transKeyName, array $attributes = [])
{
return Localization::getURLFromRouteNameTranslated(Localization::getCurrentLocale(), $transKeyName, $attributes);
}
}
if( ! function_exists('is_bot'))
{
function is_bot() {
return (isset($_SERVER['HTTP_USER_AGENT'])
&& (preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']) || str_contains($_SERVER['HTTP_USER_AGENT'], 'Google Page Speed Insights'))
);
}
}<file_sep>/app/Listeners/SendOrderStatusMail.php
<?php
namespace App\Listeners;
use App\Events\OrderStatusChanged;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendOrderStatusMail
{
/**
* Handle the event.
*
* @param OrderStatusChanged $event
* @throws \Exception
*/
public function handle(OrderStatusChanged $event)
{
switch($event->order->order_status) {
case 2: //Out for delivery
$view = 'emails.order.status.out-for-delivery';
$subject = trans('order.email.delivery.subject', ['id' => $event->order->id]);
break;
case 4: //Cancelled
$view = 'emails.order.status.cancelled';
$subject = trans('order.email.cancelled.subject', ['id' => $event->order->id]);
break;
default:
return;
}
try {
\Mail::send($view, ['order' => $event->order], function($m) use($event, $subject) {
$m->from(config('site.email.support'), config('site.name'));
$m->to($event->order->email)->subject($subject);
});
} catch (\Exception $e) {
\Log::critical('Could not send order status email');
}
}
}
<file_sep>/resources/lang/en/shipping.php
<?php
return [
'shipping-method' => 'Shipping method',
'time' => 'Shipping time',
'hour-delivery' => 'Delivery within 45 minutes',
'max-duration' => '45 minutes',
'cost' => 'Cost',
'standard' => 'Standard',
'hour' => '{1} 1 hour|[0,Inf] :count hours',
'free-shipping' => 'FREE if order is over 20€, otherwise 3€',
'free' => 'Free shipping',
'no-minimum-order' => 'No minimum order.'
];<file_sep>/app/Zugy/Repos/Order/DbOrderRepository.php
<?php
namespace Zugy\Repos\Order;
use App\Order;
use Zugy\Repos\DbRepository;
class DbOrderRepository extends DbRepository implements OrderRepository
{
/**
* @var Order
*/
protected $model;
/**
* DbOrderRepository constructor.
*/
public function __construct(Order $model)
{
$this->model = $model;
}
public function incomplete()
{
return $this->model->incomplete();
}
}<file_sep>/resources/lang/it/email.php
<?php
return [
'thanks' => 'Grazie per aver usato :name.',
'receipt' => 'Ecco la sua ricevuta.',
'footer.tos' => 'Visualizza il :name <a href=":tosUrl">Termini di servizio</a>',
'footer.questions' => 'Domande? Email <a href="mailto::email">:email</a>',
];<file_sep>/tests/AgeSplashTest.php
<?php
class AgeSplashTest extends TestCase
{
//TODO Write tests for age splash
// @ignore
public function testSplash()
{
$this->visit('en');
}
}<file_sep>/tests/CartTest.php
<?php
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CartTest extends TestCase
{
use DatabaseTransactions;
private $user;
private $faker;
protected function setUp()
{
parent::setUp();
$this->faker = Faker\Factory::create();
$this->user = factory(App\User::class)->create();
$this->actingAs($this->user);
}
/**
* Test adding something to cart
*
* @return void
*/
public function testAddToCart()
{
$product = factory(App\Product::class)->create();
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = $this->faker->numberBetween(1, $product->stock_quantity);
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$this->json('GET', 'api/v1/cart')->seeJson([
'id' => $product->id,
'qty' => $quantity,
'price' => number_format($product->price,2),
'subtotal' => round($product->price * $quantity, 2)
]);
}
/**
* Test updating quantity in cart
*/
public function testAddExistingCart() {
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = 5;
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$secondQuantity = 2;
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $secondQuantity,
])->seeJson(['status' => 'success']);
$this->json('GET', 'api/v1/cart')->seeJson([
'id' => $product->id,
'qty' => $quantity + $secondQuantity,
'price' => number_format($product->price,2),
'subtotal' => round($product->price * ($quantity + $secondQuantity), 2)
]);
}
/**
* Test if out stock error works when bulk updating existing items in cart
*/
public function testUpdateOutOfStock() {
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = 5;
//Add item to cart
$response = $this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$json = json_decode($response->response->getContent(), true);
$rowId = key($json['cart']);
$newQuantity = 4;
$this->json('PATCH', 'api/v1/cart', [
'items' => [
[
'rowId' => $rowId,
'qty' => $newQuantity,
]
]
])->seeJson(['status' => 'success', 'qty' => $newQuantity]);
}
/**
* Test if out of stock error works when adding new item
* @return void
*/
public function testAddOutOfStock() {
$product = factory(App\Product::class)->create();
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = $product->stock_quantity + 1; //Just one over the max. stock
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'failure', 'message' => 'Out of stock']);
$this->json('GET', 'api/v1/cart')->seeJsonEquals([]); //Should be empty
}
}
<file_sep>/resources/lang/it/auth.php
<?php
return [
'failed' => 'Queste credenziali non corrispondono i nostri dischi.',
'throttle' => 'Troppi tentativi di accesso. Riprova in :seconds secondi.',
'already-logged-in' => 'Già effettuato il login',
'login.title' => 'Accesso o <a href=":registerUrl">crea un account</a>',
'login.create-email' => 'Apri un nuovo account con la tua email',
'login.success' => 'Connesso',
'login.or' => 'o',
'form.email.label' => 'E-Mail',
'form.password.change' => 'Cambia la password',
'form.password_current.label' => 'Password attuale',
'form.password.label' => 'Password',
'form.confirm-password.label' => 'Conferma password',
'form.remember' => 'Ricordami',
'form.forgot' => 'Dimenticato password?',
'form.current_password.error' => 'La password corrente non era corretta',
'form.password.change.success' => 'La tua password è stata modificata',
'register.title' => 'Creare un nuovo account',
'register.advantages' => 'Crea un account per checkout facile e veloce accesso alla cronologia degli ordini.',
'register.social-tip' => 'È possibile utilizzare Facebook e Google per creare un account più veloce!',
'register.button' => 'Elenco',
'register.success' => 'Il tuo account è pronto! Adesso divertiti!',
'reset.title' => 'Resetta la password',
'reset.button' => 'Invia Password Reset link',
'reset.email.subject' => 'La vostra Password Reset link',
'reset.email.click' => 'Clicca qui per reimpostare la password:',
'cookies-consent' => 'Questo sito web utilizza i cookie per essere sicuri di ottenere la migliore esperienza sul nostro sito',
];<file_sep>/app/Http/Middleware/RefreshCart.php
<?php
namespace App\Http\Middleware;
use App\Basket;
use Closure;
use Gloudemans\Shoppingcart\Exceptions\ShoppingcartInvalidItemException;
use Zugy\Facades\Cart;
class RefreshCart
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(auth()->check() && Cart::count(false) == 0) {
$this->refreshCart();
}
return $next($request);
}
private function refreshCart() {
foreach(auth()->user()->basket()->get() as $row) {
try {
Cart::associate('Product', 'App')->add($row->product_id, $row->name, $row->quantity, $row->price, $row->options);
} catch(ShoppingcartInvalidItemException $e) {
Basket::where('product_id', '=', $row->product_id)->where('user_id', '=', $row->user_id)->delete();
}
}
}
}
<file_sep>/app/Exceptions/PaymentMethodDeclined.php
<?php
/**
* User: <NAME>
* Date: 11.09.2015
* Time: 16:24
*/
namespace App\Exceptions;
class PaymentMethodDeclined extends \Exception
{
}<file_sep>/app/Http/Middleware/VerifyAge.php
<?php
namespace App\Http\Middleware;
use Closure;
class VerifyAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(app()->environment("testing")) {
return $next($request);
}
//Allow search crawlers, AJAX requests and Google Page Speed Insights
if(is_bot() || $request->ajax()) {
return $next($request);
}
if(!isset($_COOKIE['isOver18']) || $_COOKIE['isOver18'] != "true") {
return response()->view('pages.age-splash', [], 412);
}
return $next($request);
}
}
<file_sep>/resources/lang/en/forms.php
<?php
return [
'prompts.select-quantity' => 'Select quantity',
'prompts.select-how-many' => 'Please select how many you want!',
'prompts.postcode' => 'Enter your postcode',
'prompts.postcode.desc' => 'We currently only deliver in Milan, Italy',
'action' => 'Action',
'status' => 'Status',
'error.slug' => 'The slug can only be alphanumeric and use dashes.',
'danger-zone' => 'Danger Zone',
];<file_sep>/resources/assets/js/cart.js
(function( cart, $, undefined ) {
var apiEndpoint = '/api/v1/cart';
cart.add = function (productId, quantity) {
return $.ajax({
type: 'POST',
url: apiEndpoint,
data: {
'id': productId,
'qty': quantity
},
success: updateMiniCart,
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
swal(err.message, null, "error");
}
});
};
/**
* Update an array of items in cart
* @returns {*}
* @param items
*/
cart.update = function(items) {
return $.ajax({
type: 'PATCH',
url: apiEndpoint,
data: {
items: items
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
swal({
type: 'error',
title: err.message,
text: err.description,
});
}
});
};
cart.delete = function(rowId) {
console.log("Deleting", rowId);
$.ajax({
type: 'DELETE',
url: apiEndpoint + '/' + rowId,
success: updateMiniCart,
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.message);
}
});
};
cart.addToCartAnimation = function($productImage) {
var $cartTarget = $('.navbar .cart-icon:visible').eq(0);
if($productImage) {
var $imgClone = $productImage.clone().offset({
top: $productImage.offset().top,
left: $productImage.offset().left
}).css({
'opacity': '0.5',
'position': 'absolute',
'height': '150px',
'width': '150px',
'z-index': '100'
}).appendTo($('body')).animate({
'top': $cartTarget.offset().top + 10,
'left': $cartTarget.offset().left + 10,
'width': 75,
'height': 75
}, 1000, 'easeInOutExpo');
$imgClone.animate({
'width': 0,
'height': 0
}, function () {
$(this).detach()
});
}
};
function updateMiniCart() {
$.pjax.reload('#mini-cart-container', {timeout: 1500}).done(function() {
var subtotal = $('#cart-subtotal').text();
$('.cart-subtotal').text(subtotal);
$('#mini-cart-container .products').mCustomScrollbar(); //Re-apply custom scroll bar when reloading
});
}
/*
* Make mini cart disappear when clicking anywhere else
*/
var $navbarCart = $('#navbar-cart');
function navbarCartHideClickHandler() {
$navbarCart.collapse('hide');
}
$navbarCart.on('show.bs.collapse', function () {
$(document).click(navbarCartHideClickHandler);
$('.dropdown-toggle').click(navbarCartHideClickHandler);
$navbarCart.click(function(e) {
e.stopPropagation();
});
});
$navbarCart.on('hide.bs.collapse', function () {
$(document).unbind('click', navbarCartHideClickHandler);
$('.dropdown-toggle').unbind('click', navbarCartHideClickHandler);
});
}( window.cart = window.cart || {}, jQuery ));<file_sep>/resources/lang/en/your-account.php
<?php
return [
'title' => 'Your account',
'orders' => 'Orders',
'orders.desc' => 'View, track or cancel an order',
'orders.dispatch-to' => 'Dispatch to',
'payment.manage' => 'Manage your payment methods',
'settings.title' => 'Settings',
'settings.email' => 'Change E-Mail address or password',
];<file_sep>/app/Zugy/PaymentGateway/Gateways/Stripe.php
<?php
namespace Zugy\PaymentGateway\Gateways;
use App\Payment;
use App\PaymentMethod;
use Carbon\Carbon;
use Stripe\Customer;
class Stripe extends AbstractGateway
{
protected $methodName = 'stripe';
/**
* StripeService constructor.
* @param $paymentMethod PaymentMethod
*/
public function __construct(PaymentMethod $paymentMethod = null)
{
parent::__construct($paymentMethod);
\Stripe\Stripe::setApiKey(config('services.stripe.secret'));
}
public function addOrUpdateMethod()
{
$this->paymentMethod = $this->fetchPaymentMethod();
if($this->paymentMethod === null) {
$customer = \Stripe\Customer::create([
"source" => request('stripeToken'),
"description" => auth()->user()->name,
"email" => auth()->user()->email,
]);
$this->paymentMethod = $this->createPaymentMethod([
'stripeId' => $customer->id,
'sources' => $customer->sources
]);
} else {
$customer = \Stripe\Customer::retrieve($this->paymentMethod->payload['stripeId']);
if(request('stripeToken') !== null) { //Add a new card
$card = $customer->sources->create([
"source" => request('stripeToken')
]);
if(request('defaultPayment', false) == "true") {
$this->setCardAsDefault($customer, $card->id);
}
$customer = \Stripe\Customer::retrieve($this->paymentMethod->payload['stripeId']);
} else { //Select a different card
$customer = $this->setCardAsDefault($customer, request('cardId'));
}
$this->updatePaymentMethod([
'stripeId' => $customer->id,
'sources' => $customer->sources
]);
}
$this->setAsDefault(request('defaultPayment') !== null);
return $this->paymentMethod;
}
public function charge($amount)
{
$payment = new Payment();
$result = \Stripe\Charge::create([
'amount' => (int) ($amount * 100), //Convert 15.99 to 1599
'currency' => 'eur',
'customer' => $this->paymentMethod->payload['stripeId']
]);
$payment->paid = Carbon::now();
$payment->metadata = [
'id' => $result->id,
'source' => $result->source
];
$payment->status = 1; //Mark as paid
$payment->amount = $result->amount / 100; //Convert back to decimal form
$payment->currency = $result->currency;
$payment->method = $this->paymentMethod->method;
return $payment;
}
public function getFormatted()
{
//First card in sources array is always default card
return [
'method' => 'card',
'card' => [
'brand' => $this->paymentMethod->payload['sources']['data'][0]['brand'],
'last4' => $this->paymentMethod->payload['sources']['data'][0]['last4'],
'expiry' => $this->paymentMethod->payload['sources']['data'][0]['exp_month'] . '/' . $this->paymentMethod->payload['sources']['data'][0]['exp_year']
]
];
}
public function listCards()
{
$customer = \Stripe\Customer::retrieve($this->paymentMethod->payload['stripeId']);
$cards = [];
foreach($customer['sources']['data'] as $card) {
if($card['object'] == 'card') $cards[] = $card;
}
return $cards;
}
/**
* Set the specified card as default
* @param Customer $customer
* @param $cardId
* @return Customer
*/
public function setCardAsDefault(Customer $customer, $cardId) {
$customer->default_source = $cardId;
return $customer->save();
}
}<file_sep>/app/Exceptions/Coupons/CouponNotStartedException.php
<?php
namespace App\Exceptions\Coupons;
class CouponNotStartedException extends \Exception
{
}<file_sep>/app/Zugy/PaymentGateway/Exceptions/PaymentFailedException.php
<?php
namespace Zugy\PaymentGateway\Exceptions;
class PaymentFailedException extends \Exception
{
}<file_sep>/resources/lang/en/footer.php
<?php
return [
'email' => 'Email',
'information' => 'Information',
'my-account' => 'My Account',
'my-orders' => 'My orders',
'newsletter-subscribe-btn' => 'Subscribe',
'rights-reserved' => 'All rights reserved.',
'stay-in-touch' => 'Stay In Touch',
'support' => 'Support',
'tax-code' => 'Tax Code',
];<file_sep>/app/Http/Middleware/Checkout.php
<?php
namespace App\Http\Middleware;
use Closure;
use Zugy\Facades\Cart;
use Illuminate\Contracts\Auth\Guard;
use Carbon\Carbon;
class Checkout
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$reopeningTime = Carbon::create(2017, 9, 28, 4, 0, 0); //4 am Wednesday
if(Carbon::now() < $reopeningTime) {
return response()->view('pages.holiday-closed', [], 503);
}
if(Cart::count() == 0) {
return redirect(localize_url('routes.cart'));
}
if ($this->auth->guest() && !session()->has('checkout.guest')) {
return redirect()->guest(localize_url('routes.checkout.landing'));
}
return $next($request);
}
}
<file_sep>/resources/lang/en/order.php
<?php
return [
'status.0' => 'New order',
'status.1' => 'Being processed',
'status.2' => 'Out for delivery',
'status.3' => 'Delivered',
'status.4' => 'Cancelled',
'number' => 'Order number',
'date' => 'Order date',
'create' => 'Order placed',
'completed' => 'Order completed',
'details' => 'Order details',
'summary' => 'Order summary',
'history' => 'Order history',
'api.update.success' => 'Order updated',
'api.error.status-same' => 'Order already set to this status',
'email.confirmation.subject' => 'Your Zugy order confirmation and receipt [#:id]',
'email.confirmation.paid' => 'Total paid',
'email.delivery.subject' => 'Your Zugy order [#:id] is out for delivery',
'email.delivery.driver' => 'Our driver is now on his way to you!',
'email.delivery.trouble' => 'If anything goes wrong or we have trouble finding you, we will call you on your phone at <b>:phone</b>',
'email.cancelled.subject' => 'Your Zugy order [#:id] was cancelled',
'email.cancelled.questions' => 'If you have any questions regarding this cancellation you can reply to this email or call us at :phone.',
'email.track.description' => 'You can track the current status of your order by clicking the button below.',
'email.track' => 'Track order',
'sign-in' => '<a href=":loginUrl">Sign in</a> to view more information on your order.',
'total-before-vat' => 'Total before VAT',
'vat' => 'VAT',
'include-vat' => 'Order totals include',
];<file_sep>/app/Http/Controllers/API/PostcodeController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Zugy\Validators\PostcodeValidator;
class PostcodeController extends Controller
{
/**
* GET api/v1/postcode/{postcode}
* @param $postcode
* @return mixed
*/
public function checkPostcode($postcode)
{
$validator = Validator::make(['postcode' => $postcode], [
'postcode' => 'integer|digits:5'
]);
if($validator->fails()) {
return response()->json(['status' => 'failure', 'message' => trans('postcode.api.error.postcode.invalid'), 'errors' => $validator->getMessageBag()], 400);
}
$postcode = (int) $postcode;
if(PostcodeValidator::isInDeliveryRange($postcode)) {
$response = response()->json([
'status' => 'success',
'delivery' => true,
'storeUrl' => localize_url('routes.shop.index'),
'message' => trans('postcode.check.success'),
]);
} else {
$response = response()->json([
'status' => 'success',
'delivery' => false,
'message' => trans('postcode.check.error.title'),
'description' => trans('postcode.check.error.desc'),
'storeUrl' => localize_url('routes.shop.index'),
'confirmButtonText' => trans('postcode.browse-store'),
]);
}
return $response->withCookie(cookie()->forever('postcode', $postcode, $path = null, $domain = null, $secure = false, $httpOnly = false));
}
}<file_sep>/app/Exceptions/Coupons/CouponExpiredException.php
<?php
namespace App\Exceptions\Coupons;
class CouponExpiredException extends \Exception
{
}<file_sep>/resources/lang/it/passwords.php
<?php
return [
'user' => 'Non esiste un utente associato a questo indirizzo e-mail.',
'password' => 'Le password devono essere di almeno 6 caratteri e devono coincidere.',
'token' => 'Questo token per la reimpostazione della password non è valido.',
'sent' => 'Promemoria della password inviato!',
'reset' => 'La password è stata reimpostata!',
];
<file_sep>/resources/lang/it/status.php
<?php
return [
'payment.0' => 'Non pagato',
'payment.1' => 'Pagato',
'payment.2' => 'Rimborsato',
'payment.3' => 'Pagamento alla consegna',
];<file_sep>/app/Zugy/Facades/Maps.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class Maps extends Facade
{
protected static function getFacadeAccessor() { return 'maps'; }
}<file_sep>/app/Category.php
<?php
namespace App;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class Category extends Model
{
use Translatable;
protected $table = 'categories';
public $translatedAttributes = ['name', 'slug', 'meta_description'];
protected $casts = [
'id' => 'integer',
'parent_id' => 'integer',
];
public function products() {
return $this->belongsToMany('App\Product', 'products_to_categories');
}
static public function buildTree() {
$refs = [];
$list = [];
$rows = Category::with('translations')->get();
foreach($rows as $row) {
$ref = & $refs[$row->id];
$ref['id'] = $row->id;
$ref['parent_id'] = $row->parent_id;
$ref['position'] = $row->position;
$ref['name'] = $row->name;
$ref['slug'] = $row->slug;
$ref['product_count'] = $row->products()->inStock()->count();
if($row->parent_id == null) {
$list[$row->id] = & $ref;
} else {
$refs[$row->parent_id]['children'][$row->id] = & $ref;
//Update parent product count
$parent = & $refs[$row->parent_id];
while(1) {
$parent['product_count'] += $ref['product_count'];
if($parent['parent_id'] == null) break;
$parent = & $refs[$parent['parent_id']];
}
//FIXME If parent is added afterwards, it needs to sum up its existing children
}
}
return $list;
}
/**
* Print the category menu from cache if available
*
* @return mixed
*
* Print nested list of all categories
*/
static public function printList() {
return Cache::remember('ui.category-sidebar.lang-' . \Localization::getCurrentLocale(), 5, function() {
//Sort by position column, 0 comes first
$list = collect(Category::buildTree())->sortBy(function($menuItem, $key) {
if($menuItem['position'] === null) return PHP_INT_MAX;
else return $menuItem['position'];
});
return self::toUL($list->toArray());
});
}
static private function toUL(array $array)
{
$html = '<ul class="list-group">' . PHP_EOL;
foreach ($array as $value)
{
if($value['product_count'] == 0) continue; //Skip empty categories
$html .= '<li class="list-group-item"><a href="' . localize_url('routes.shop.category', ['slug' => $value['slug']]) . '">' . "{$value['name']} ({$value['product_count']})";
if (!empty($value['children']))
{
$html .= self::toUL($value['children']);
}
$html .= '</a></li>' . PHP_EOL;
}
$html .= '</ul>' . PHP_EOL;
return $html;
}
static public function printSelect() {
$tree = Category::buildTree();
function printTree($tree, $depth = 0, $list = []) {
foreach($tree as $t) {
$dash = ($t['parent_id'] == 0) ? '' : str_repeat(" ", $depth) .' ';
$list[] = [$t['id'], $dash . $t['name']];
if(isset($t['children'])) {
$list = array_merge($list, printTree($t['children'], $depth + 1));
}
}
return $list;
}
$result = printTree($tree);
$array = [];
foreach($result as $v) {
$array[$v[0]] = $v[1];
}
return $array;
}
static public function getDirectSubCategories(self $category) {
return self::where('parent_id', '=', $category->id)->get();
}
/**
* Cache the categories menu
*
* 0 => [
* 'parent' => []
* 'children' => []
* ]
* @param $category_id int
* @return array
*/
static public function cacheMegaMenu($category_id) {
$cache = Cache::remember('categories.menu.lang-' . \Localization::getCurrentLocale(), 5, function() {
$categories = self::all();
$return = [];
foreach($categories as $parent) {
$children = self::getDirectSubCategories($parent);
$children->load('translations');
$return[$parent->id] = [
'parent' => $parent,
'children' => $children
];
}
return $return;
});
return $cache[$category_id];
}
}
<file_sep>/resources/lang/it/notifications.php
<?php
return [
'success' => 'Successo',
'info' => 'Informazioni',
'error' => 'Errore',
'warning' => 'Attenzione',
];<file_sep>/database/migrations/2016_01_23_174515_create_coupons_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCouponsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('coupons', function (Blueprint $table) {
$table->increments('id');
$table->string('code', 255)->unique();
$table->dateTime('starts')->nullable();
$table->dateTime('expires')->nullable();
$table->decimal('minimumTotal', 10, 2)->unsigned()->nullable();
$table->integer('percentageDiscount')->unsigned()->nullable();
$table->decimal('flatDiscount', 10, 2)->unsigned()->nullable();
$table->integer('max_uses')->unsigned()->nullable();
$table->integer('uses')->unsigned()->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('coupons');
}
}
<file_sep>/tests/AdminProductTest.php
<?php
class AdminProductTest extends TestCase
{
protected $admin;
public function setUp()
{
parent::setUp();
$this->admin = factory(App\User::class, 'admin')->make();
}
public function testIndexProductView()
{
$this->actingAs($this->admin)->visit('admin/catalogue')->see('Catalogue');
}
public function testAddProductView()
{
$this->actingAs($this->admin)->visit('admin/catalogue/create')->see('Add a product');
}
}<file_sep>/resources/lang/it/ageSplash.php
<?php
return [
'prompt' => 'Inserisci la tua età per entrare.',
'over' => 'Sopra :age',
'under' => 'Sotto :age',
'sorry.title' => 'Siamo spiacenti, solo per maggiorenni!',
'sorry.desc' => 'Siamo spiacenti, ma vendiamo e consegniamo alcolici solo a maggiorenni.',
'sorry.party' => 'Noi, comunque, saremo lì con voi per festeggiare il tuo 18esimo compleanno!',
];<file_sep>/app/Coupon.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Coupon extends Model
{
protected $dates = ['starts', 'expires'];
public function getDescriptionAttribute()
{
if($this->attributes['percentageDiscount'] != null) {
return trans('coupon.percentageDiscountDescription', ['percentage' => $this->attributes['percentageDiscount']]);
} elseif($this->attributes['flatDiscount'] != null) {
return trans('coupon.flatDiscountDescription', ['amount' => $this->attributes['flatDiscount']]);
}
throw new \RuntimeException();
}
}<file_sep>/app/Zugy/PaymentGateway/PaymentGatewayServiceProvider.php
<?php
namespace Zugy\PaymentGateway;
use Illuminate\Support\ServiceProvider;
class PaymentGatewayServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('paymentGateway', function()
{
return new PaymentGateway();
});
}
}<file_sep>/database/seeds/TaxClassSeeder.php
<?php
use Illuminate\Database\Seeder;
class TaxClassSeeder extends Seeder
{
public function run() {
DB::table('tax_classes')->insert([
['id' => 1, 'title' => 'Alcohol', 'description' => 'Alcoholic Beverages', 'tax_rate' => '22.0'],
['id' => 2, 'title' => 'Food', 'description' => '', 'tax_rate' => '4.0']
]);
}
}<file_sep>/app/Basket.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Basket extends Model
{
protected $table = 'users_basket';
protected $casts = [
'options' => 'json'
];
protected $fillable = [
'product_id',
'name',
'quantity',
'price',
'options',
];
public function product() {
return $this->belongsTo('App\Product');
}
/**
* Set the keys for a save update query.
* This is a fix for tables with composite keys
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery(Builder $query)
{
$query
//Put appropriate values for your keys here:
->where('user_id', '=', $this->user_id)
->where('product_id', '=', $this->product_id);
return $query;
}
}
<file_sep>/app/Zugy/PaymentGateway/PaymentGateway.php
<?php
namespace Zugy\PaymentGateway;
use App\PaymentMethod;
use Zugy\PaymentGateway\Gateways\AbstractGateway;
use Zugy\PaymentGateway\Gateways\Cash;
use Zugy\PaymentGateway\Gateways\PayPal;
use Zugy\PaymentGateway\Gateways\Stripe;
use Zugy\PaymentGateway\Exceptions\PaymentMethodUndefinedException;
class PaymentGateway
{
/**
* Sets the payment gateway
* @param $gateway
* @return AbstractGateway|string
* @throws PaymentMethodUndefinedException
*/
public function set($gateway) {
$paymentMethod = null;
if($gateway instanceof PaymentMethod) {
$paymentMethod = $gateway;
$gateway = $paymentMethod->method;
}
switch($gateway) {
case 'stripe':
return new Stripe($paymentMethod);
break;
case 'cash':
return new Cash($paymentMethod);
break;
case 'paypal':
return new PayPal($paymentMethod);
break;
default:
throw new PaymentMethodUndefinedException("Using $gateway");
break;
}
}
}<file_sep>/app/Exceptions/Coupons/CouponOrderMinimumException.php
<?php
namespace App\Exceptions\Coupons;
class CouponOrderMinimumException extends \Exception
{
}<file_sep>/app/Policies/ProductPolicy.php
<?php
namespace App\Policies;
use App\Product;
use App\User;
class ProductPolicy extends BasePolicy
{
protected $writeAccessGroupIds = [1,2]; //Super Admins, Admins
public function create(User $user, Product $product)
{
return $this->hasWriteAccess($user);
}
public function update(User $user, Product $product)
{
return $this->hasWriteAccess($user);
}
}<file_sep>/app/Zugy/Facades/Checkout.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class Checkout extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'checkout'; }
}<file_sep>/database/migrations/2015_06_19_101843_create_orders_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('no action');
$table->tinyInteger('order_status')->unsigned();
$table->dateTime('order_placed');
$table->dateTime('order_completed')->nullable();
$table->text('comments');
$table->string('email');
$table->string('delivery_name', 64);
$table->string('delivery_line_1', 64);
$table->string('delivery_line_2', 64)->nullable();
$table->string('delivery_city', 32);
$table->string('delivery_postcode', 10);
$table->string('delivery_state', 32)->nullable();
$table->string('delivery_phone', 32);
$table->integer('delivery_country_id');
$table->foreign('delivery_country_id')
->references('id')->on('countries')
->onDelete('no action');
$table->text('delivery_instructions')->nullable();
$table->decimal('shipping_fee', 10, 2)->unsigned();
$table->char('currency', 3);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('orders');
}
}
<file_sep>/resources/lang/it/forms.php
<?php
return [
'prompts.select-quantity' => 'Seleziona quantità',
'prompts.select-how-many' => 'Si prega di selezionare il numero che si desidera!',
'prompts.postcode' => 'Inserisci codice postale',
'prompts.postcode.desc' => 'Al momento consegniamo solo a Milano, Italia',
'action' => 'Azione',
'status' => 'Stato',
'error.slug' => 'La lumaca può essere solo trattini alfanumerici e utilizzare.',
'danger-zone' => 'Occhio!',
];<file_sep>/app/Zugy/ActivityLogParser/ActivityLogParser.php
<?php
namespace Zugy\ActivityLogParser;
use Illuminate\Database\Eloquent\Collection;
class ActivityLogParser
{
public function order(Collection $activity) {
$return = [];
foreach($activity as $a) {
switch($a->action) {
case 'status-change':
$status = trans('order.status.' . $a->description);
$description = trans('activityLogParser.order.status-changed', ['status' => $status]);
$title = $status;
$type = $this->getOrderStatusType($a->description);
$icon = $this->getOrderStatusIcon($a->description);
break;
case 'create':
$type = '';
$description = trans('order.create');
$title = $description;
$icon = 'navicon';
break;
default:
throw new \Exception("Activity action does not exist");
}
$return[] = [
'user' => $a->user,
'timestamp' => $a->created_at,
'title' => $title,
'description' => $description,
'type' => $type,
'icon' => $icon,
];
}
return $return;
}
private function getOrderStatusType($statusId)
{
switch($statusId) {
case 1:
return 'warning';
case 2:
return 'primary';
case 3:
return 'success';
case 4:
return 'danger';
default:
return '';
}
}
private function getOrderStatusIcon($statusId)
{
switch($statusId) {
case 1:
return 'ellipsis-h';
case 2:
return 'truck';
case 3:
return 'check';
case 4:
return 'times';
default:
return 'check';
}
}
}<file_sep>/app/Zugy/Repos/Product/ProductRepository.php
<?php
/**
* User: <NAME>
* Date: 18.09.2015
* Time: 02:21
*/
namespace Zugy\Repos\Product;
interface ProductRepository
{
public function all($sort = 'sales', $direction = 'desc');
public function category($category_slug, $sort = 'sales', $direction = 'desc');
public function getBySlug($slug);
public function search($query);
}<file_sep>/resources/lang/it/menu.php
<?php
return [
'my-account' => 'Il mio account',
'admin-dashboard' => 'Dashboard amministrativo',
'sign-out' => 'Disconnessione',
'sign-in' => 'Registrati',
'your-account' => 'Il tuo account',
'account-settings' => 'Impostazioni del account',
'cart' => 'Carrello',
'shop' => 'Negozio',
'admin.settings' => 'Impostazioni',
'admin.settings.tax' => 'Tassa',
];<file_sep>/resources/lang/it/coupon.php
<?php
return [
'404' => 'Il coupon non esiste',
'claimed' => 'Questo coupon è già stato rivendicato, ci dispiace',
'expired' => 'Questo coupon è scaduto il :date',
'notActive' => 'Questo coupon diventa attivo a :date',
'minimum' => 'Si ordina fabbisogno totale di essere almeno :min Euro per utilizzare questo coupon',
'using' => 'Codice coupon utilizzando <b>:code</b>',
'flatDiscountDescription' => '-:amount€ di meno',
'percentageDiscountDescription' => ':percentage% di meno',
];<file_sep>/app/Listeners/CartEventsListener.php
<?php
namespace App\Listeners;
use Zugy\Facades\Cart;
use Illuminate\Support\Facades\Request;
use Zugy\Facades\Checkout;
class CartEventsListener
{
public function onAddCart($id, $name, $quantity, $price, $options = null) {
if(auth()->check() && Request::ajax()) {
$row = auth()->user()->basket()->firstOrNew(['product_id' => $id]);
$row->fill([
'quantity' => $quantity,
'price' => $price,
'name' => $name,
'options' => $options
])->save();
$this->forgetCoupon();
}
}
public function onUpdateCart($rowId) {
if(auth()->check()) {
$item = Cart::get($rowId);
$row = auth()->user()->basket()->firstOrNew(['product_id' => $item->id]);
$row->price = $item->price;
$row->quantity = $item->qty;
$row->options = $item->options;
\Log::debug('Updating basket in DB', ['productId' => $item->id, 'quantity' => $item->qty]);
$row->save();
$this->forgetCoupon();
}
}
public function onRemoveCart($rowId) {
if(auth()->check()) {
$item = Cart::get($rowId);
auth()->user()->basket()->where('product_id', '=', $item->id)->delete();
}
$this->forgetCoupon();
}
public function onDestroyCart() {
if(auth()->check()) {
auth()->user()->basket()->delete();
}
$this->forgetCoupon();
}
/**
* Synchronise guest cart to database when user logs in
*/
public function onLogin()
{
$guestCart = Cart::content();
\Log::debug('Guest cart content', ['cart' => $guestCart]);
$guestProductIds = [];
foreach($guestCart as $item) {
$row = auth()->user()->basket()->firstOrNew(['product_id' => $item->id]);
$row->fill([
'quantity' => $item->qty,
'price' => $item->price,
'name' => $item->name,
'options' => $item->options
])->save();
$guestProductIds[] = $item->id;
}
$missingDbProducts = auth()->user()->basket()->whereNotIn('product_id', $guestProductIds)->get();
foreach($missingDbProducts as $p) {
\Log::debug('Adding missing product to cart', ['name' => $p->name]);
Cart::associate('Product', 'App')->add($p->product_id, $p->name, $p->quantity, $p->price, $p->options);
}
}
private function forgetCoupon()
{
Checkout::forgetCoupon();
}
public function subscribe($events) {
$events->listen(
'cart.added',
'App\Listeners\CartEventsListener@onAddCart'
);
$events->listen(
'cart.updated',
'App\Listeners\CartEventsListener@onUpdateCart'
);
$events->listen(
'cart.remove',
'App\Listeners\CartEventsListener@onRemoveCart'
);
$events->listen(
'cart.destroy',
'App\Listeners\CartEventsListener@onDestroyCart'
);
$events->listen(
'Illuminate\Auth\Events\Login',
'App\Listeners\CartEventsListener@onLogin'
);
}
}<file_sep>/app/Exceptions/OutOfStockException.php
<?php
namespace App\Exceptions;
use App\Language;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
class OutOfStockException extends \Exception
{
protected $products = []; //Array of products that are out of stock
public function __construct($products) {
$this->products = $products;
}
public function getProducts() {
return $this->products;
}
public function getErrorMessages() {
$errors = [];
$language_id = Language::getLanguageId(LaravelLocalization::getCurrentLocale());
foreach($this->products as $p) {
if($p->stock_quantity == 0) {
$errors[] = "{$p->title} is out of stock. Please remove the item from your cart to place your order.";
} else {
$errors[] = "{$p->title} only has {$p->stock_quantity} units left in stock. Please reduce the order quantity in your cart to place your order.";
}
}
return $errors;
}
}<file_sep>/resources/lang/it/checkout.php
<?php
return [
'title' => 'Convalida ordine',
'items' => 'Articoli',
'total' => 'Totale',
'subtotal' => 'subtotale',
'shipping' => 'Spedizione',
'address.title' => 'Indirizzo',
'address.prompt' => 'Per favore inserisci il tuo indirizzo',
'address.choose-delivery' => 'Scegli un indirizzo di consegna',
'address.select-delivery' => 'Spedisci a questo indirizzo',
'address.deliver-new' => 'Spedisci ad un nuovo indirizzo',
'address.deliver-new-desc' => 'Aggiungi un nuovo indirizzo di consegna nella rubrica',
'address.form.delivery' => 'Indirizzo spedizione',
'address.form.billing' => 'Indirizzo fatturazione',
'address.form.name' => 'Nome completo',
'address.form.line_1' => 'Indirizzo numero 1',
'address.form.line_1.desc' => 'Numero civico e via, P.O. box, azienda, c/o',
'address.form.line_2' => 'Indirizzo numero 2',
'address.form.line_2.desc' => 'Numero appartamento,citofono, scala, piano, etc.',
'address.form.zip' => 'CAP/ Codice postale',
'address.form.town' => 'Località / città',
'address.form.country' => 'Nazione',
'address.form.instructions' => 'Istruzioni per la consegna',
'address.form.instructions.desc' => 'Ulteriori informazioni per il nostro autista',
'address.form.phone' => 'Telefono',
'address.form.phone.desc' => 'Nel caso in cui il nostro autista ha bisogno di contattare l\'utente per la consegna',
'address.form.default' => 'Utilizzare questo indirizzo di default per i futuri ordini',
'address.form.same' => 'Stesso come indirizzo di consegna',
'address.form.country.italy' => 'Italia',
'payment.title' => 'Pagamento',
'payment.form.title' => 'Selezionare il metodo di pagamento',
'payment.form.card' => 'Carta',
'payment.form.card.new' => 'Aggiungere una nuova carta',
'payment.form.card.show' => '<b>:brand</b> finito in :last4',
'payment.form.card.expires' => 'Scade',
'payment.form.name' => 'nome dell \'intestatario della carta',
'payment.form.cvc' => 'CVC',
'payment.form.expiration' => 'Data scad.',
'payment.form.default' => 'Impostare questo come il metodo di pagamento predefinito',
'payment.form.card.button' => 'Utilizzare carta di credito',
'payment.form.pay-with' => 'Paga con :name',
'payment.form.cash' => 'Contanti',
'payment.form.cash.desc' => 'Pagare in contanti al momento della consegna',
'payment.form.error.different' => 'Si è verificato un errore durante l\'elaborazione del vostro pagamento. Riprovare o utilizzare un altro metodo di pagamento. <a href=":paymentUrl?change">Cambiare </a>',
'review.title' => 'Rivedere ordine',
'review.age-warning' => 'Vendiamo solo l\'alcol a persone <b>di età superiore a 18 anni</b>, anche se l\'età legale per bere è 16 in Italia. I nostri autisti vi chiederà per la tua foto ID per verificare la tua età.',
'review.coupon' => 'Buono',
'review.coupon.desc' => 'Inserisci un codice coupon se ne hai uno',
'review.coupon.placeholder' => 'Inserisci il codice',
'review.items' => 'Rivedere elementi',
'review.place-order' => 'Invia ordine',
'review.accept' => 'Effettuando l\'ordine l\'utente accetta di :siteName\'s <a href=":privacyPolicyUrl">Informativa sulla privacy</a> and <a href=":termsAndConditionsUrl">Termini e condizioni</a>.',
'review.delivery-time' => 'Tempo di consegna',
'review.delivery-time.label' => 'Quando volete che il vostro ordine da consegnare?',
'review.delivery-time.asap' => 'Il prima possibile',
'review.delivery-time.slot' => 'Scegliere uno slot di consegna',
'review.delivery-time.error.late' => 'È troppo tardi per scegliere questo tempo di consegna. Si prega di selezionare un altro momento',
'review.delivery-time.error.closed' => 'Siamo spiacenti ma il servizio è attivo sono dall\'una del pomeriggio all\'una di mattina. Riprova piú tardi ¯\_(ツ)_/¯',
'order' => 'Ordine',
'order.success' => 'Il tuo ordine è stato inoltrato. Ti manderemo una notifica via email quando è fuori per la consegna.',
];<file_sep>/app/Policies/OrderPolicy.php
<?php
namespace App\Policies;
use App\Order;
use App\User;
class OrderPolicy extends BasePolicy
{
public function before(User $user, $ability) {
if($this->isSuperAdmin($user)) {
return true;
}
}
public function show(User $user, Order $order)
{
return $user->id === $order->user_id || $this->isAdmin($user);
}
public function adminUpdate(User $user, Order $order) {
return $this->isAdmin($user);
}
public function index(User $user, Order $order) {
return $this->isAdmin($user);
}
}<file_sep>/app/Http/Middleware/SetLocaleFromSession.php
<?php
namespace App\Http\Middleware;
use Closure;
/**
* Set the locale based on the session variable, only for API routes
* For the Laravel Localisation package by mcamara
* Class SetLocaleFromSession
* @package App\Http\Middleware
*/
class SetLocaleFromSession
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
* @throws \Exception
*/
public function handle($request, Closure $next)
{
$locale = session('locale');
if(!is_null($locale)) {
\Localization::setLocale($locale);
}
\Carbon::setLocale(\Localization::getCurrentLocale());
switch (\Localization::getCurrentLocale()) {
case 'it':
$success = setlocale(LC_TIME, 'it_IT.utf8');
break;
case 'en':
$success = setlocale(LC_TIME, 'en_GB.utf8');
break;
default:
throw new \Exception("Locale not found");
}
if(!$success) throw new \Exception("Failed setting locale: " . \Localization::getCurrentLocale() . " | Current Locale: " . setlocale(LC_ALL, 0));
return $next($request);
}
}
<file_sep>/resources/lang/en/auth.php
<?php
return [
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
'already-logged-in' => 'Already logged in',
'login.title' => 'Login or <a href=":registerUrl"> create an account</a>',
'login.create-email' => 'Create account with email',
'login.success' => 'Logged in',
'login.or' => 'or',
'form.email.label' => 'E-Mail',
'form.password.change' => 'Change password',
'form.password_current.label' => 'Current Password',
'form.password.label' => 'Password',
'form.confirm-password.label' => 'Confirm Password',
'form.remember' => 'Remember me',
'form.forgot' => 'Forgot password?',
'form.current_password.error' => 'Your current password was incorrect',
'form.password.change.success' => 'Your password has been changed',
'register.title' => 'Create a new account',
'register.advantages' => 'Create an account for fast checkout and easy access to order history.',
'register.social-tip' => 'You can use Facebook and Google to create an account faster!',
'register.button' => 'Register',
'register.success' => 'Created an account successfully, have fun shopping!',
'reset.title' => 'Reset Password',
'reset.button' => 'Send Password Reset Link',
'reset.email.subject' => 'Your Password Reset Link',
'reset.email.click' => 'Click here to reset your password:',
'cookies-consent' => 'This website uses cookies to ensure you get the best experience on our website',
];<file_sep>/app/Console/Commands/SyncAlgolia.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SyncAlgolia extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'algolia:sync {model}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Synchronise an Algolia model to the Algolia servers.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$model = "App\\" . $this->argument('model');
$model = new $model();
$usedTraits = class_uses($model);
if(!isset($usedTraits['AlgoliaSearch\Laravel\AlgoliaEloquentTrait'])) {
$this->error('The model is not using the AlgoliaEloquentTrait!');
return;
}
$elements = $model->all();
$bar = $this->output->createProgressBar($elements->count());
$bar->setFormat("%message%\n %current%/%max% [%bar%] %percent:3s%%");
$bar->setMessage('Starting synchronisation');
$bar->start();
foreach($elements as $element) {
$bar->setMessage("Syncing {$element->title}\n");
$element->pushToIndex();
$bar->advance();
}
$model::setSettings(); //Push index settings
$bar->finish();
}
}
<file_sep>/app/Http/Controllers/AccountController.php
<?php
namespace App\Http\Controllers;
class AccountController extends Controller
{
public function getHome()
{
return view('pages.account.home');
}
public function getOrders()
{
$orders = auth()->user()->orders()->orderBy('order_placed', 'desc')->get();
return view('pages.account.orders')->with(['orders' => $orders]);
}
public function getSettings()
{
return view('pages.account.settings');
}
}<file_sep>/resources/lang/en/pages.php
<?php
return [
'about-us.title' => 'About',
'about-us.desc' => '<p>We at Zugy operate just like a regular retail liquor store with a small but significant twist: you visit our website instead of walking into a store. You still have an equally large selection of drinks; we have about 50 different choices in stock. Simply pick what you need, place your order and we deliver it right to your front door. You can pay by card, PayPal or cash on delivery.</p>
<p>Technology has changed many industries in the past decade but it has yet to be involved in the alcohol industry. With Zugy we are revolutionizing the way in which people enjoy beverages by incorporating current technology into our operations.</p>',
'about-us.find-out-more' => 'Find out more on social media',
'about-us.partners' => 'Partners',
'about-us.partners-desc' => '<p>Zugy is proudly partnered with <a href="http://securitycourier.it/">Security Courier Express</a>, who deliver your order from our fulfilment centre to your front door.</p>
<p>We only use bicycle couriers, ensuring our deliveries arrive within 45 minutes and with zero CO2 emissions <i class="fa fa-leaf"></i>.</p>',
'about-us.mission-statement.title' => 'Mission Statement',
'about-us.mission-statement.desc' => '<p>At Zugy, our goal has always and will always be to make our customers happy. We want to make the memories last, be it that special bottle that leads to great conversation or the party pack that makes for an unforgettable birthday.</p>
<p>Whether it\'s a crazy night or you\'re just spending time with your loved ones, we hope you choose Zugy to make your night last forever.</p>',
'contact.title' => 'Contact',
'contact.address' => 'Zugy Srl. <br>Alzaia Navigli Grande 36<br> Milan, 20141 <br> Italy',
'contact.customer-service' => 'Below is the customer service line – you can direct any questions, comments, or concerns to this number :',
'contact.email.general' => 'For general inquiries:',
'contact.email.investors' => 'For investors:',
'shop.title' => 'Shop',
'home.title' => 'Home',
'home.meta_description' => 'Zugy is an online liquor store in Milan that delivers within an hour.',
'home.meta-title' => 'Alcohol Delivery on-demand for Milan',
'home.tagline' => 'Your favorite beer, wine and spirits delivered to your doorstep',
'home.marketing.address.title' => 'Set your address',
'home.marketing.address.desc' => "Select from a wide range of alcholic drinks to be delivered to your door step.",
'home.marketing.time.title' => 'Order in minutes',
'home.marketing.time.desc' => 'Add what you want to your basket, pay at the checkout and you\'re done.',
'home.marketing.delivery.title' => 'Delivery to your door',
'home.marketing.delivery.desc' => 'We\'ll start preparing your order right away, and deliver it to your doorstep. Simply present your photo ID to our friendly drivers and enjoy!',
'home.exclusive' => 'Currently serving Milan exclusively',
'home.milan' => 'Milan',
'home.expansion' => 'With many plans to expand',
'privacy-policy' => 'Privacy Policy',
'team' => 'Team',
'terms-and-conditions' => 'Terms & Conditions',
];
<file_sep>/app/Http/Controllers/Admin/ImageController.php
<?php
namespace App\Http\Controllers\Admin;
use App\ProductImage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
class ImageController extends Controller
{
public function upload(Request $request)
{
$this->validate($request, [
'file' => 'required|image|max:' . config('site.maxImageSize'),
]);
$location = $this->generateFilePath($request->file('file'));
//Avoid hash collision
while(Storage::disk(config('filesystems.default'))->exists($location)) {
$location = $this->generateFilePath($request->file('file'));
}
Storage::disk(config('filesystems.default'))->put($location, file_get_contents($request->file('file')->getRealPath()));
$image = new ProductImage();
$image->location = $location;
$image->save();
$this->garbageCollect();
\Log::info('Uploading new image', ['user_id' => auth()->user()->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'image_id' => $image->id]);
return response()->json(['status' => 'success', 'id' => $image->id]);
}
public function destroy($id)
{
$image = ProductImage::findOrFail($id);
$image->delete();
\Log::info('Deleting image', ['user_id' => auth()->user()->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'image_id' => $id]);
return response()->json(['status' => 'success', 'id' => $id]);
}
/**
* Delete orphaned images
*/
public function garbageCollect()
{
$toBeDeleted = ProductImage::whereNull('product_id')
->where('created_at', '<', Carbon::now()->subHour(24)); //Orphaned images older than 24h deleted
foreach($toBeDeleted->get() as $d) {
Storage::disk(config('filesystems.default'))->delete($d['location']);
}
$toBeDeleted->delete();
}
public function generateFilePath($file)
{
$now = Carbon::now();
$path = "product-images/" .
"{$now->year}/{$now->month}/{$now->day}/" .
str_random(32) . "." . $file->guessClientExtension();
return $path;
}
}
<file_sep>/app/Address.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $table = 'addresses';
protected $fillable = [
'isShippingPrimary', 'isBillingPrimary', 'name', 'line_1', 'line_2', 'city', 'postcode', 'state', 'phone', 'country_id', 'delivery_instructions', 'created_at', 'updated_at'];
public function user() {
return $this->belongsTo('App\User');
}
public function country() {
return $this->belongsTo('App\Country');
}
public function scopeBilling($query) {
return $query->where('isBillingPrimary', '=', 1)->first();
}
}
<file_sep>/resources/lang/it/routes.php
<?php
return [
'about-us' => 'riguardo-a-noi',
'account' => [
'index' => 'conto',
'orders' => 'conto/ordini',
'settings' => 'conto/impostazioni'
],
'cart' => 'carrello',
'checkout' => [
'landing' => 'cassa',
'address' => 'cassa/indirizzo',
'payment' => 'cassa/pagamento',
'review' => 'cassa/rivedere',
'confirmation' => 'cassa/conferma',
'gatewayReturn' => 'cassa/gatewayReturn',
],
'contact' => 'contatto',
'order' => [
'show' => 'ordini/{id}',
],
'privacy-policy' => 'informativa-sulla-privacy',
'product' => 'prodotto/{slug}',
'search' => 'ricerca/{query}',
'shop' => [
'index' => 'negozio',
'category' => 'negozio/categoria/{slug}',
],
'team' => 'team',
'terms-and-conditions' => 'termini-e-condizioni',
];<file_sep>/resources/lang/it/postcode.php
<?php
return [
'check.success' => 'Consegniamo a te!',
'browse-store' => 'Visitare lo Store',
'check.error.title' => 'Al momento non consegniamo alla vostra zona. Scusate!',
'check.error.desc' => 'È ancora possibile di visitare il nostro store.',
'api.error.postcode.invalid' => 'Il Cap non è valido.',
];<file_sep>/app/Zugy/PaymentGateway/Gateways/Cash.php
<?php
namespace Zugy\PaymentGateway\Gateways;
use App\Payment;
class Cash extends AbstractGateway
{
protected $methodName = 'cash';
public function addOrUpdateMethod() {
$this->paymentMethod = $this->fetchPaymentMethod();
if($this->paymentMethod === null) {
$this->paymentMethod = $this->createPaymentMethod();
}
$this->setAsDefault(request('defaultPayment') !== null);
return $this->paymentMethod;
}
public function charge($amount)
{
$payment = new Payment();
$payment->status = 3; //Mark as "Payment on Delivery"
$payment->amount = $amount;
$payment->currency = 'EUR';
$payment->method = $this->paymentMethod->method;
return $payment;
}
public function getFormatted()
{
return [
'method' => $this->methodName,
];
}
}<file_sep>/resources/assets/js/events.js
/**
* Add click listener for deleting items from mini cart
*/
$('#mini-cart-container').on('click', '.delete button', function() {
$(this).prop('disabled', true);
var rowId = $(this).data('row-id');
cart.delete(rowId);
$(this).prop('disabled', false);
}).on('pjax:start', function() { $(this).fadeOut(200); })
.on('pjax:end', function() { $(this).fadeIn(200); });<file_sep>/app/Zugy/DeliveryTime/Exceptions/PastDeliveryTimeException.php
<?php
namespace Zugy\DeliveryTime\Exceptions;
class PastDeliveryTimeException extends \Exception
{
}<file_sep>/app/Listeners/SendOrderConfirmationMail.php
<?php
namespace App\Listeners;
use App\Events\OrderWasPlaced;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendOrderConfirmationMail
{
/**
* Handle the event.
*
* @param OrderWasPlaced $event
* @return void
*/
public function handle(OrderWasPlaced $event)
{
\Activity::log([
'contentId' => $event->order->id,
'contentType' => 'Order',
'action' => 'create',
]);
try {
\Mail::send('emails.order-confirmation', ['order' => $event->order], function($m) use($event) {
$m->from(config('site.email.support'), config('site.name'));
$m->to($event->order->email)->subject(trans('order.email.confirmation.subject', ['id' => $event->order->id]));
});
} catch (\Exception $e) {
\Log::critical($e);
}
}
}
<file_sep>/app/Zugy/Facades/PaymentProcessor.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class PaymentProcessor extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'paymentProcessor'; }
}<file_sep>/tests/SearchTest.php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
class SearchTest extends TestCase
{
use WithoutMiddleware;
public function testVodkaSearch()
{
$this->visit('en/search/vodka')->see('vodka');
}
}<file_sep>/resources/lang/it/address.php
<?php
return [
'empty' => 'Nessun indirizzo',
'api.update.success' => 'Indirizzo aggiornato con successo',
'api.destroy.success' => 'Indirizzo rimosso con successo',
'api.error.404' => 'Indirizzo non esiste',
'api.error.invalid' => 'Indirizzo non è valido',
];<file_sep>/resources/lang/it/footer.php
<?php
return [
'email' => 'Email',
'information' => 'Informazioni',
'my-account' => 'Il mio account',
'my-orders' => 'i miei ordini',
'newsletter-subscribe-btn' => 'Abbonarsi',
'rights-reserved' => 'Tutti i diritti sono riservati.',
'stay-in-touch' => 'Resta in contatto',
'support' => 'Supporto',
'tax-code' => 'Partita IVA',
];<file_sep>/app/Product.php
<?php
namespace App;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
class Product extends Model
{
use SoftDeletes;
use Translatable;
use \AlgoliaSearch\Laravel\AlgoliaEloquentTrait;
protected $table = 'products';
protected $appends = ['thumbnail_url'];
public static $perEnvironment = true; // Index name will be 'products_{\App::environment()}';
public $algoliaSettings = [
'attributesToIndex' => [
'translation_en',
'translation_it',
'categories',
'stock_quantity',
'price',
'weight',
],
'customRanking' => [
],
];
public function getAlgoliaRecord()
{
/**
* Load the categories relation so that it's available
* in the laravel toArray method
*/
$fields = [
'stock_quantity' => $this->stock_quantity,
'price' => (float) $this->price,
'weight' => (float) $this->weight,
'categories' => $this->categories,
];
$fields['categories'] = [];
foreach($this->categories as $c) {
$fields['categories'][] = $c->id;
}
foreach($this->translations as $translation) {
$fields['translation_' . $translation->locale] = [
'title' => $translation->title,
'slug' => $translation->slug,
'description' => $translation->meta_description,
'meta_description' => $translation->meta_description
];
}
return $fields;
}
public function getFinalIndexName(Model $model, $indexName)
{
$environment = \App::environment();
if($environment == "testing") $environment = 'local';
$env_suffix = property_exists($model, 'perEnvironment') && $model::$perEnvironment === true ? '_'. $environment() : '';
return $indexName.$env_suffix;
}
public $translatedAttributes = ['slug', 'title', 'description', 'meta_description'];
protected $fillable = ['slug', 'title', 'description', 'meta_description'];
protected $with = ['tax_class'];
/*
* Relations
*/
public function images()
{
return $this->hasMany('App\ProductImage');
}
public function tax_class() {
return $this->belongsTo('App\TaxClass');
}
public function attributes()
{
return $this->belongsToMany('App\Attribute', 'products_to_attributes')->withPivot('value');
}
public function categories()
{
return $this->belongsToMany('App\Category', 'products_to_categories');
}
public function getUrl($language_code = null)
{
if(isset($this->attributes['url'])) {
return $this->attributes['url'];
}
if($language_code === null) $language_code = LaravelLocalization::getCurrentLocale();
$url = LaravelLocalization::getURLFromRouteNameTranslated($language_code, 'routes.product', ['slug' => $this->slug]);
$this->attributes['url'] = $url;
return $url;
}
/*
* Actions
*/
/**
* Also delete all basket items containing this product
* @throws \Exception
*/
public function delete()
{
Basket::where('product_id', '=', $this->attributes['id'])->delete();
parent::delete(); //Soft delete
}
/*
* Accessors
*/
/**
* Fetch URL thumbnail for product
* @return string
*/
public function getThumbnailUrlAttribute() {
if(isset($this->attributes['thumbnail_url'])) {
return $this->attributes['thumbnail_url'];
}
$thumbnailId = $this->attributes['thumbnail_id'];
if($thumbnailId !== null) {
$url = $this->images->find($thumbnailId)->url;
} else {
$images = $this->images;
if($images->count() === 0) {
$url = asset('/img/zugy-placeholder-image.png');
} else {
$url = $images->first()->url;
}
}
$this->attributes['thumbnail_url'] = $url;
return $url;
}
/**
* Generate array to form breadcrumbs
* @return array
*/
public function getBreadcrumbsAttribute()
{
$category_id = $this->categories()->first()->id;
$categories = Category::with('translations')->get()->keyBy('id');
$node = $categories[$category_id];
$parent_id = $node->parent_id;
$breadcrumbs = [];
while($parent_id !== null) {
array_unshift($breadcrumbs, ['name' => $node->name, 'slug' => $node->slug]);
$node = $categories[$parent_id];
$parent_id = $node->parent_id;
}
array_unshift($breadcrumbs, ['name' => $node->name, 'slug' => $node->slug]);
return $breadcrumbs;
}
/**
* Calculate how many times product has been sold
* @return mixed
*/
public function getSalesAttribute()
{
return DB::table('order_items')
->join('orders', 'order_items.order_id', '=', 'orders.id')
->select('order_items.*', 'orders.order_status')
->where('product_id', '=', $this->attributes['id'])
->where('orders.order_status', '!=', 4) //Ignore cancelled orders
->sum('order_items.quantity');
}
/**
* Only include products that are in stock
* @param $query
*/
public function scopeInStock($query) {
return $query->where('stock_quantity', '>', 0);
}
}
<file_sep>/app/Zugy/Facades/ActivityLogParser.php
<?php
namespace Zugy\Facades;
use Illuminate\Support\Facades\Facade;
class ActivityLogParser extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'activityLogParser'; }
}<file_sep>/app/Zugy/Charts/Charts.php
<?php
namespace Zugy\Charts;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class Charts
{
public function chart30dRevenue() {
}
public function revenueByDay($start = null, $end = null) {
if($start === null) {
$start = Carbon::now()->subDays(30);
}
if($end === null) {
$end = Carbon::now();
}
//Ignore cancelled orders
$rows = DB::select("
SELECT DATE(t.date) AS day, SUM(t.total) AS total
FROM (
SELECT o.id, o.created_at AS 'date', (SUM(i.final_price) + o.shipping_fee - IFNULL(o.coupon_deduction, 0)) AS 'total'
FROM orders o
JOIN order_items i
ON o.id = i.order_id
WHERE o.order_status != 4 AND o.created_at BETWEEN ? AND ?
GROUP BY o.id
) t
GROUP BY day
", [$start, $end]);
//Fill in missing days with zero
$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($start, $interval, $end);
$result = [
'x' => [],
'y' => []
];
$i = 0;
foreach($period as $day) {
$date = $day->format('Y-m-d');
if(isset($rows[$i]) && $rows[$i]->day == $date) {
$result['x'][] = $date;
$result['y'][] = $rows[$i]->total;
$i++;
} else {
$result['x'][] = $date;
$result['y'][] = 0;
}
}
return $result;
}
}<file_sep>/resources/lang/it/activityLogParser.php
<?php
return [
'order.status-changed' => 'Status cambiato <b>:status</b>',
];<file_sep>/app/Http/Controllers/API/CartController.php
<?php
namespace App\Http\Controllers\Api;
use App\Product;
use Gloudemans\Shoppingcart\Exceptions\ShoppingcartInvalidRowIDException;
use Illuminate\Http\Response;
use Zugy\Facades\Cart;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
/**
* List all items in cart
*
* @return Response
*/
public function index()
{
return Cart::content();
}
/**
* POST /api/v1/cart
* Add a new item to cart
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'id' => 'required|integer|exists:products',
'qty' => 'required|integer|min:1',
'options' => 'array',
]);
$qty = (int) $request->input('qty');
\Log::debug("Trying to add item to cart", ['productId' =>$request->input('id'), 'qty' => $qty]);
$product = Product::find($request->input('id'));
$cartItem = [
'id' => (int) $request->input('id'),
'name' => $product->title,
'qty' => (int) $request->input('qty'),
'price' => $product->price,
];
//Search for product ID, if exists, update quantity
if($request->has('options')) {
$searchResult = Cart::search(['id' => (int) $request->input('id'), 'options' => $request->input('options')]);
$cartItem['options'] = $request->input('options');
} else {
$searchResult = Cart::search(['id' => (int) $request->input('id')]);
}
if($searchResult === false) {
if ($qty > $product->stock_quantity) {
return response()->json([
'status' => 'failure', 'message' => trans('product.out-of-stock', ['quantity' => $product->stock_quantity])
], 422); //Unprocessable entity
}
Cart::associate('Product', 'App')->add($cartItem);
} else {
$rowId = $searchResult[0];
$totalQuantity = (int) Cart::get($rowId)->qty + $qty;
if($totalQuantity > $product->stock_quantity) {
return response()->json([
'status' => 'failure', 'message' => trans('product.out-of-stock', ['quantity' => $product->stock_quantity])
], 422); //Unprocessable Entity
}
Cart::update($rowId, (int) $totalQuantity);
$cart = $request->session()->get('cart.main');
$request->session()->put('cart.main', $cart);
}
return response()->json(['status' => 'success', 'cart' => Cart::content()]);
}
/**
* Update multiple items in the cart
* PATCH /api/v1/cart
* @param Request $request
* @param int $id
* @return Response
*/
public function bulkUpdate(Request $request)
{
$this->validate($request, [
'items.*.rowId' => 'required',
'items.*.name' => 'max:255',
'items.*.qty' => 'integer|min:0',
'items.*.options' => 'array',
]);
foreach($request->input('items') as $item) {
$update = [];
if(isset($item['name'])) $update['name'] = $item['name'];
if(isset($item['qty'])) {
$update['qty'] = (int) $item['qty'];
//Check stock
$stock_quantity = Cart::get($item['rowId'])->product->stock_quantity;
if($update['qty'] > $stock_quantity) {
return response()->json([
'status' => 'failure',
'message' => trans('product.out-of-stock') . ": " . Cart::get($item['rowId'])->product->title,
'description' => trans('product.stock-warning', ['count' => $stock_quantity])
], 422); //Unprocessable Entity
}
}
if(isset($item['options'])) $update['options'] = $item['options'];
\Log::debug('Updating cart', ['parameters' => $update]);
try {
Cart::update($item['rowId'], $update);
} catch(ShoppingcartInvalidRowIDException $e) {
return response()->json(['status' => 'failure', 'message' => 'The row ID was invalid'], 400);
}
}
return response()->json(['status' => 'success', 'cart' => Cart::content()]);
}
/**
* Remove an item from the cart.
*
* @param int $rowId
* @return Response
*/
public function destroy($rowId)
{
try {
Cart::remove($rowId);
} catch(ShoppingcartInvalidRowIDException $e) {
return response()->json(['status' => 'failure', 'message' => 'The row ID was invalid'], 400);
}
return response()->json(['status' => 'success']);
}
}
<file_sep>/database/factories/ModelFactory.php
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => <PASSWORD>(10),
'remember_token' => str_random(10),
'group_id' => 0
];
});
$factory->defineAs(App\User::class, 'admin', function($faker) use ($factory) {
$user = $factory->raw(App\User::class);
return array_merge($user, ['group_id' => 2]);
});
$factory->define(App\Address::class, function($faker) {
return [
'name' => $faker->name,
'line_1' => $faker->streetAddress,
'city' => 'Milan',
'postcode' => 20121,
'country_id' => 380, //Italy
'phone' => $faker->phoneNumber,
'delivery_instructions' => $faker->text(),
];
});
$factory->define(App\Product::class, function($faker) {
return [
'stock_quantity' => $faker->numberBetween(1, 10000),
'price' => $faker->randomNumber(2),
'compare_price' => null,
'weight' => $faker->randomFloat(2, 0, 100),
'tax_class_id' => 1,
'thumbnail_id' => null
];
});
$factory->define(App\ProductTranslation::class, function($faker) {
return [
'locale' => 'en',
'slug' => $faker->slug,
'title' => $faker->sentence(),
'description' => $faker->sentence(),
'meta_description' => $faker->sentence()
];
});<file_sep>/resources/lang/en/opening-times.php
<?php
return [
'title-delivery-time' => 'Delivery Times',
'closed' => 'We currently do not deliver.',
'times' => 'Our delivery times are:',
'delivery-time' => 'You can place your order now and select a delivery time for later during checkout.',
'prompt-select' => 'Please select a delivery time slot during our opening times',
'asap-closed-explanation' => 'If you select ASAP now, we will deliver your order when we open again at 1pm.'
];<file_sep>/app/Zugy/PaymentGateway/Exceptions/PaymentMethodUndefinedException.php
<?php
namespace Zugy\PaymentGateway\Exceptions;
class PaymentMethodUndefinedException extends \Exception
{
}<file_sep>/resources/lang/en/menu.php
<?php
return [
'my-account' => 'My account',
'admin-dashboard' => 'Admin dashboard',
'sign-out' => 'Sign out',
'sign-in' => 'Sign in',
'your-account' => 'Your account',
'account-settings' => 'Account settings',
'cart' => 'Cart',
'shop' => 'Shop',
'admin.settings' => 'Settings',
'admin.settings.tax' => 'Tax',
];<file_sep>/app/Policies/BasePolicy.php
<?php
namespace App\Policies;
use App\User;
class BasePolicy
{
private $superAdminGroupId = 1;
private $adminGroupId = 2;
private $driverGroupId = 3;
private $adminGroups;
public function __construct()
{
$this->adminGroups = [$this->superAdminGroupId, $this->adminGroupId, $this->driverGroupId];
}
protected function isSuperAdmin(User $user)
{
return $user->group_id === $this->superAdminGroupId;
}
protected function isAdmin(User $user)
{
return in_array($user->group_id, $this->adminGroups);
}
protected function hasWriteAccess(User $user)
{
return in_array($user->group_id, [
$this->superAdminGroupId,
$this->adminGroupId
]);
}
}<file_sep>/app/Zugy/Stock/Stock.php
<?php
namespace Zugy\Stock;
use App\Product;
use Zugy\Facades\Cart;
use App\Exceptions\EmptyCartException;
use App\Exceptions\OutOfStockException;
class Stock
{
/**
* Check if the cart of the current user has sufficient stock
* @return boolean
* @throws EmptyCartException
* @throws OutOfStockException
*/
public function checkCartStock() {
$productIds = [];
$cart = [];
\Log::debug('Checking stock...');
if(Cart::count() === 0) {
throw new EmptyCartException();
}
foreach (Cart::content() as $item) {
$productIds[] = $item->id;
$cart[] = ['id' => $item->id, 'qty' => $item->qty];
}
$productStock = Product::findMany($productIds, ['id', 'stock_quantity'])->keyBy('id');
$outOfStockProducts = [];
foreach(Cart::content() as $product) {
\Log::debug('Checking stock for', ['id' => $product->id, 'in_stock' => $productStock[$product->id]['stock_quantity'], 'in_cart' => $product['qty']]);
if($productStock[$product->id]['stock_quantity'] < $product['qty']) {
$outOfStockProducts[] = $product;
}
}
if(count($outOfStockProducts) > 0) throw new OutOfStockException($outOfStockProducts);
\Log::debug('Sufficient stock available');
return true;
}
}<file_sep>/tests/ProductTest.php
<?php
class ProductTest extends TestCase
{
public function testProductShow()
{
$product = \App\Product::first();
$this->visit($product->getUrl())
->see($product->title);
//$this->visit('it/prodotto/absolut-vodka')->see('Absolut Vodka');
}
public function testAlcoholCategoryShow()
{
$this->visit('en/shop/category/alcohol')->see('Alcohol');
}
}<file_sep>/app/Language.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Cache;
class Language extends Model
{
static public function getLanguageId($language_code = null) {
if($language_code == null) $language_code = LaravelLocalization::getCurrentLocale();
$languages = \Cache::remember('languages', 60, function() {
return Language::all();
});
return $languages->where('code', $language_code)->first()->id;
}
public function getCodeAttribute($value) {
return strtolower($value);
}
}
<file_sep>/app/Services/Order/PlaceOrder.php
<?php
namespace App\Services\Order;
use App\Exceptions\TooManyOrdersException;
use Illuminate\Support\Facades\Validator;
use Log;
use App\Events\OrderWasPlaced;
use App\Payment;
use App\User;
use App\Order;
use App\OrderItem;
use Carbon\Carbon;
use Zugy\DeliveryTime\Exceptions\ClosedException;
use Zugy\DeliveryTime\Exceptions\PastDeliveryTimeException;
use Zugy\Facades\Cart;
use Zugy\Facades\Stock;
use Zugy\Facades\Checkout;
use Zugy\Facades\DeliveryTime;
use Zugy\Facades\PaymentGateway;
class PlaceOrder
{
protected $user;
protected $deliveryAddress;
protected $billingAddress;
protected $paymentMethod;
private $checkoutReviewUrl;
public function __construct()
{
$this->checkoutReviewUrl = localize_url('routes.checkout.review');
}
public function handler(User $user) {
$this->user = $user;
$this->deliveryAddress = Checkout::getShippingAddress();
$this->billingAddress = Checkout::getBillingAddress();
$this->paymentMethod = Checkout::getPaymentMethod();
Log::debug('Trying to place order', ['user' => $user]);
if($this->deliveryAddress === null || $this->paymentMethod === null)
{
Log::debug('Missing details, redirecting.', [
'delivery' => $this->deliveryAddress,
'payment' => $this->paymentMethod
]);
return redirect(localize_url('routes.checkout.landing'));
}
//Use delivery address as billing address if billing address is null
if($this->billingAddress === null) {
$this->billingAddress = $this->deliveryAddress;
}
//Prevent duplicate orders, have a cooldown of 30 seconds
if($user->orders()->where('created_at', '>', Carbon::now()->subSeconds(30))->count() > 0) {
Log::info('User tried to place too many orders in a short period of time', ['user' => $user]);
throw new TooManyOrdersException();
}
Stock::checkCartStock();
//Load delivery time session if it not set
if(empty(request('delivery_date')) && empty(request('delivery_time'))) {
request()->merge(['delivery_date' => Checkout::getDeliveryDate(), 'delivery_time' => Checkout::getDeliveryTime()]);
}
$validator = Validator::make(request()->all(), [
//Create validator with empty rules
]);
$validator->sometimes('delivery_date', 'required|date', function($input) {
return $input->delivery_date !== 'asap';
});
$validator->sometimes('delivery_time', 'required', function($input) {
return $input->delivery_date !== 'asap';
});
if($validator->fails()) {
return redirect(localize_url('routes.checkout.review'))->withErrors($validator)->withInput();
}
//Validate delivery time
if(request('delivery_date') === 'asap') {
if(!DeliveryTime::isOpen(Carbon::now())) {
return redirect($this->checkoutReviewUrl)->withError(trans('opening-times.prompt-select'));
}
} else {
$delivery_time = Carbon::parse(request('delivery_date') . " " . request('delivery_time'));
try {
DeliveryTime::isValidDeliveryTime($delivery_time);
} catch (PastDeliveryTimeException $e) {
return redirect($this->checkoutReviewUrl)->withErrors(['delivery_date' => trans('checkout.review.delivery-time.error.late')]);
} catch (ClosedException $e) {
return redirect($this->checkoutReviewUrl)->withErrors(['delivery_date' => trans('checkout.review.delivery-time.error.closed')]);
}
}
//Set delivery time session variables
Checkout::setDeliveryDate(request('delivery_date'));
Checkout::setDeliveryTime(request('delivery_time'));
$coupon = Checkout::getCoupon();
if($coupon != null) {
//Validate coupon
Checkout::validateCoupon($coupon);
}
$payment = $this->processPayment();
if(!$payment instanceof Payment) return $payment; //E.g. for PayPal, return redirect to gateway processor
$order = $this->saveOrderToDB($payment);
//Empty checkout session settings
Checkout::forget();
event(new OrderWasPlaced($order));
return $order;
}
public function processPayment() {
Log::info("Charging customer", ['total' => Cart::grandTotal()]);
$payment = PaymentGateway::set($this->paymentMethod)->charge(Cart::grandTotal());
return $payment;
}
public function saveOrderToDB(Payment $payment) {
$order = new Order();
$order->order_status = 0; //New order status
$order->order_placed = Carbon::now();
$order->email = $this->user->email;
$order->delivery_name = $this->deliveryAddress->name;
$order->delivery_line_1 = $this->deliveryAddress->line_1;
$order->delivery_line_2 = $this->deliveryAddress->line_2;
$order->delivery_city = $this->deliveryAddress->city;
$order->delivery_postcode = $this->deliveryAddress->postcode;
$order->delivery_state = $this->deliveryAddress->state;
$order->delivery_phone = $this->deliveryAddress->phone;
$order->delivery_country_id = $this->deliveryAddress->country_id;
$order->delivery_instructions = $this->deliveryAddress->delivery_instructions;
$order->shipping_fee = Cart::shipping();
$coupon = Checkout::getCoupon();
if($coupon != null) {
$order->coupon_id = $coupon->id;
$order->coupon_deduction = Cart::couponDeduction();
}
$order->currency = 'EUR';
//Delivery time
if(request('delivery_date') == 'asap') {
$order->delivery_time = null;
} else {
$order->delivery_time = Carbon::parse(request('delivery_date') . " " . request('delivery_time'));
}
$order = $this->user->orders()->save($order);
//Add payment to DB, save billing address in same table
$payment->billing_name = $this->billingAddress->name;
$payment->billing_line_1 = $this->billingAddress->line_1;
$payment->billing_line_2 = $this->billingAddress->line_2;
$payment->billing_city = $this->billingAddress->city;
$payment->billing_postcode = $this->billingAddress->postcode;
$payment->billing_state = $this->billingAddress->state;
$payment->billing_phone = $this->billingAddress->phone;
$payment->billing_country_id = $this->billingAddress->country_id;
$order->payment()->save($payment);
$items = [];
foreach(Cart::content() as $item) {
//Update stock quantity
$item->product->decrement('stock_quantity', $item->qty);
$orderItem = new OrderItem();
$orderItem->product_id = $item->id;
$orderItem->quantity = $item->qty;
$orderItem->price = $item->price;
$orderItem->final_price = $item->subtotal;
$orderItem->tax = $item->product->tax_class->tax_rate;
$items[] = $orderItem;
}
$order->items()->saveMany($items);
//Increment coupon uses
if($coupon != null) {
$coupon->increment('uses');
}
return $order;
}
}<file_sep>/app/Zugy/Helpers/Maps/MapsServiceProvider.php
<?php
namespace Zugy\Helpers\Maps;
use Illuminate\Support\ServiceProvider;
class MapsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('maps', function($app) {
return new Maps();
});
}
}
<file_sep>/tests/PlaceOrderTest.php
<?php
use Carbon\Carbon;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PlaceOrderTest extends TestCase
{
use DatabaseTransactions;
private $user;
protected function setUp()
{
parent::setUp();
$this->user = factory(App\User::class)->create();
$this->actingAs($this->user);
}
/**
* Test an order that should be placed without issues.
* Should fire event OrderWasPlaced
*/
public function testPlaceOrderPositive()
{
$this->expectsEvents(App\Events\OrderWasPlaced::class);
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = 5;
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$address = factory(App\Address::class)->make();
$this->user->addresses()->save($address);
Checkout::setShippingAddress($address);
Checkout::setBillingAddress($address);
//Set payment method
$this->post('en/checkout/payment', [
'method' => 'cash',
]);
$this->post('/en/checkout/review', [
'delivery_date' => Carbon::now()->addDay(1)->toDateString(),
'delivery_time' => '18:00'
]);
//Assert that product billing is calculated correctly
$this->seeInDatabase('order_payments', ['amount' => $quantity * $product->price]);
}
/**
* Should allow order to be placed with ASAP selected when store is open, need to mock time
*/
public function testPlaceOrderPositiveAsap() {
}
/**
* Should NOT allow order to be placed with ASAP selected when store is closed, need to mock time
*/
public function testPlaceOrderNegativeAsap() {
}
/**
* Test shipping fee is added correctly for orders under free delivery limit
*/
public function testPlaceOrderShippingFeePositive()
{
$this->expectsEvents(App\Events\OrderWasPlaced::class);
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
'price' => 5.10
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
\Log::debug('product', [$product]);
$quantity = 2;
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$address = factory(App\Address::class)->make();
$this->user->addresses()->save($address);
Checkout::setShippingAddress($address);
Checkout::setBillingAddress($address);
//Set payment method
$this->post('en/checkout/payment', [
'method' => 'cash',
]);
$this->post('/en/checkout/review', [
'delivery_date' => Carbon::now()->addDay(1)->toDateString(),
'delivery_time' => '18:00'
]);
//Assert that product billing is calculated correctly with shipping fee
$this->seeInDatabase('order_payments', ['amount' => 10.20 + config('site.shippingFee')]);
}
public function testPlaceOrderOutOfHoursNegative()
{
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = 5;
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$address = factory(App\Address::class)->make();
$this->user->addresses()->save($address);
Checkout::setShippingAddress($address);
Checkout::setBillingAddress($address);
//Set payment method
$this->post('en/checkout/payment', [
'method' => 'cash',
]);
$this->post('/en/checkout/review', [
'delivery_date' => Carbon::now()->addDay(1)->toDateString(),
'delivery_time' => '06:00' // Out of hours, should fail here
], ['HTTP_REFERER' => url('en/checkout/review')])
->assertRedirectedTo('en/checkout/review')
->followRedirects()
->see(trans('checkout.review.delivery-time.error.closed'));
}
/**
* This test should fail as "asap" delivery time orders cannot be placed when the store is closed
*/
public function testPlaceAsapOrderOutOfHoursNegative()
{
$this->doesntExpectEvents(App\Events\OrderWasPlaced::class);
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
\Log::debug('product', [$product]);
$quantity = 5;
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$address = factory(App\Address::class)->make();
$this->user->addresses()->save($address);
Checkout::setShippingAddress($address);
Checkout::setBillingAddress($address);
//Set payment method
$this->post('en/checkout/payment', [
'method' => 'cash',
]);
//Set mock time that is when the store is closed
$outOfHourTime = Carbon::now()->tomorrow()->hour(4);
Carbon::setTestNow($outOfHourTime);
$this->post('/en/checkout/review', [
'delivery_date' => 'asap'
])->followRedirects()
->see(trans('opening-times.prompt-select')); //Should see the out of hours error message
}
public function testOrderOutOfStockNegative()
{
$product = factory(App\Product::class)->create([
'stock_quantity' => 10,
]);
$product->translations()->save(factory(App\ProductTranslation::class)->make());
$quantity = 5;
//Add item to cart
$this->json('POST', 'api/v1/cart', [
'id' => $product->id,
'qty' => $quantity,
])->seeJson(['status' => 'success']);
$address = factory(App\Address::class)->make();
$this->user->addresses()->save($address);
Checkout::setShippingAddress($address);
Checkout::setBillingAddress($address);
//Set payment method
$this->post('en/checkout/payment', [
'method' => 'cash',
]);
$product->stock_quantity = 3; //Another customer bought 1, only 3 left
$product->save();
$this->post('/en/checkout/review', [
'delivery_date' => Carbon::now()->addDay(1)->toDateString(),
'delivery_time' => '06:00' // Out of hours, should fail here
], ['HTTP_REFERER' => url('en/checkout/review')])
->assertRedirectedTo('en/checkout/review')
->followRedirects()
->see('out of stock');
}
}
<file_sep>/app/Zugy/Repos/Category/CategoryRepository.php
<?php
namespace Zugy\Repos\Category;
interface CategoryRepository
{
/**
* Return all child category IDs and itself
* @param $categoryId
* @return mixed
*/
public function children($categoryId);
/**
* Return the category matching the slug
* @param $slug
* @return mixed
*/
public function getBySlug($slug);
}<file_sep>/tests/PagesTest.php
<?php
class PagesTest extends TestCase
{
public function testHomepage()
{
$this->visit('en');
}
public function testCart()
{
$this->visit('en/cart')->see('Shopping Cart');
}
public function testPrivacyPolicy()
{
$this->visit('en/privacy-policy')->see('Privacy Policy');
}
public function testTermsConditions()
{
$this->visit('en/terms-and-conditions')->see('Terms and Conditions');
}
}<file_sep>/resources/lang/it/buttons.php
<?php
return [
'search.prompt' => 'digita e cerca',
'proceed' => 'Procedi',
'add-cart' => 'Aggiungi nel carrello',
'shop-now' => 'Acquistare ora',
'update-cart' => 'Aggiorna carrello',
'continue-shopping' => 'Continua a fare acquisti',
'proceed-to-checkout' => 'Procedere al checkout',
'view-cart' => 'Il tuo carrello',
'edit' => 'Modifica',
'back-to-shop' => 'Torna al negozio',
'add-new-address' => 'Aggiungi un nuovo indirizzo',
'change' => 'Cambiamento',
'login' => 'Accesso',
'more-info' => 'Ulteriori informazioni',
'got-it' => 'Fatto!',
'toggle-navigation' => 'navigazione Toggle',
'view' => 'Vere',
'mark-as' => 'Segna come ...',
'update' => 'Aggiornare',
'show-google-maps' => 'Mostra su Google Maps',
'save' => 'Salvare',
'return-home' => 'Ritorna alla home page',
'apply' => 'Applicare',
'cancel' => 'Annulla',
'delete' => 'Cancellare',
'success' => 'Successo',
];<file_sep>/app/Policies/AuthenticationPolicy.php
<?php
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use App\User;
class AuthenticationPolicy extends BasePolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Is user permitted to log into other users' accounts?
* @param User $user
* @param User $toBeSignedInAsUser
* @return bool
*/
public function signInAsUser(User $user, User $toBeSignedInAsUser) {
return $this->isSuperAdmin($user);
}
}
<file_sep>/app/Http/Controllers/API/ShopStatisticsController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Order;
class ShopStatisticsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('admin');
}
/**
* GET api/v1/shop/statistics
*/
public function getStatistics() {
return [
'status' => "success",
"payload" => [
'revenue' => [
'yesterday' => Order::uncancelled()->where('order_placed', '>', \Carbon::yesterday())->where('order_placed', '<', \Carbon::today())->get()->sum('grand_total'),
'thisMonth' => Order::uncancelled()->where('order_placed', '>', new \Carbon('first day of this month'))->where('order_placed', '<', \Carbon::today())->get()->sum('grand_total')
],
'orders' => [
'incomplete' => Order::incomplete()->count()
]
]
];
}
} | 791d0d19c2f96e590e528c157c130feb6ebd7137 | [
"JavaScript",
"Markdown",
"PHP",
"Shell"
] | 191 | PHP | Mastergalen/Zugy-Laravel-eCommerce-Store | b9a25bb14d6ddae47276ab72c72f1fed48403e44 | edbcf6749e8ac79eaacb8872d0d6eb1f15e76f55 | |
refs/heads/master | <file_sep># Protocols
Pick and choose an option from a second controller and reflecting the changes in the first using protocols and delegate methods.
<a href="https://imgflip.com/gif/2507ws"><img src="https://i.imgflip.com/2507ws.gif" title="made at imgflip.com"/></a>
<file_sep>//
// ChoosePlayerVC.swift
// CustomDelegatesProtocols
//
// Created by Apple on 21/02/18.
// Copyright © 2018 Vignesh. All rights reserved.
//
import UIKit
protocol myPlayerDelegate {
func didTapChoice(image: UIImage, name: String, color: UIColor)
}
class ChoosePlayerVC: UIViewController {
// delegate
var playerDelegate : myPlayerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
}
func dismissAction() {
dismiss(animated: true, completion: nil)
}
@IBAction func messiPicked(_ sender: Any) {
playerDelegate.didTapChoice(image: UIImage(named: "mes")!, name: "messi", color: UIColor.orange)
dismissAction()
}
@IBAction func ronaldoPicked(_ sender: Any) {
playerDelegate.didTapChoice(image: UIImage(named: "ron")!, name: "Ronaldo", color: UIColor.magenta)
dismissAction()
}
}
<file_sep>//
// ViewController.swift
// CustomDelegatesProtocols
//
// Created by Apple on 21/02/18.
// Copyright © 2018 Vignesh. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Outlets:
@IBOutlet weak var playerImageView: UIImageView!
@IBOutlet weak var playerNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func pickWinnerPressed(_ sender: Any) {
let pickPlayerVC = storyboard?.instantiateViewController(withIdentifier: "pickPlayerVC") as! ChoosePlayerVC
pickPlayerVC.playerDelegate = self as myPlayerDelegate
present(pickPlayerVC, animated: true, completion: nil)
}
}
extension ViewController: myPlayerDelegate {
func didTapChoice(image: UIImage, name: String, color: UIColor) {
playerImageView.image = image
playerNameLabel.text = "Hey, You picked \(name),Congrats!"
view.backgroundColor = color
}
}
| ca498de09446ec435197244f9ef3f6979b1157d5 | [
"Markdown",
"Swift"
] | 3 | Markdown | vigneshios/Protocols | 32bec34a94642555b7774c2ab8bcd535bdf9b8d6 | dcb2a4ba83446d201ea57ee7f900a332b760f97c | |
refs/heads/master | <file_sep>/**
* This is a class that simulates a die.
* This was copied from the example in the book, with a few abbreviations to improve text
* efficiency.
* @author <NAME>
*
*/
import java.util.Random;
/**
* This is a class that simulates a six-sided die.
* This was copied from the example in the book, with a few abbreviations to improve text
* efficiency.
* @author <NAME>
*
*/
public class Die {
private int sides; // Number of sides
private int value; // The die's value
/**
* Constructor performs initial roll of die.
* @param numSides The number of sides for this die.
*/
public Die(int numSides){
sides = numSides;
roll();
}
/**
* Simulates rolling of die.
*/
public void roll(){
// Create Random object.
Random rand = new Random();
// Get random value for die.
value = rand.nextInt(sides) + 1;
}
/**
* getSides method
* @return Number of sides of this die.
*/
public int getSides(){
return sides;
}
/**
* getValue method
* @return Value of die.
*/
public int getValue(){
return value;
}
}
<file_sep>/**
* This program runs a horribly twisted variant of fake blackjack. With dice! Gambling! Now with pretty pictures!
* @author <NAME>
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* GameOfTwentyOneGUI main class
* @author <NAME>
*
*/
public class GameOfTwentyOneGUI {
static final char[] DICE_CHARS = {'⚀', '⚁', '⚂', '⚃', '⚄', '⚅'};
static JLabel message;
static JLabel scoreBox;
static JButton rollButton;
static JButton newGameButton;
static GridBagLayout layout;
static int playerScore = 0;
static int houseScore = 0;
static int roll1 = 0;
static int roll2 = 0;
static Die rollMe = new Die(6);
/**
* GameOfTwentyOneGUI main method
* @param args command line args
*/
public static void main(String[] args) {
ActionListener listener = new MyListener();
// Create a window for our app
JFrame myFrame = new JFrame("Game of Twenty One");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
layout = new GridBagLayout();
myFrame.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
// general constraints
c.fill = GridBagConstraints.BOTH;
// label constraints
c.weightx = 0.0;
c.gridwidth = GridBagConstraints.RELATIVE;
// message label
message = new JLabel("Welcome to Game of 21! Get the highest score <= 21!");
message.setForeground(Color.BLACK);
message.setFont(new Font("Segoe UI Symbol", Font.BOLD, 24));
layout.setConstraints( message, c );
myFrame.add(message);
// button constraints
c.gridwidth = GridBagConstraints.REMAINDER;
// end game button
newGameButton = new JButton("End");
newGameButton.setFont(new Font("Segoe UI Symbol", Font.BOLD, 12));
newGameButton.addActionListener(listener);
layout.setConstraints( newGameButton, c);
myFrame.add(newGameButton);
c.gridwidth = GridBagConstraints.RELATIVE;
// score label
scoreBox = new JLabel("[New Game]");
scoreBox.setForeground(Color.BLACK);
scoreBox.setFont(new Font("Segoe UI Symbol", Font.BOLD, 24));
layout.setConstraints( scoreBox, c );
myFrame.add(scoreBox);
// add roll button
c.gridwidth = GridBagConstraints.REMAINDER;
rollButton = new JButton("Roll");
rollButton.setFont(new Font("Segoe UI Symbol", Font.BOLD, 12));
rollButton.addActionListener(listener);
layout.setConstraints(rollButton, c);
myFrame.add(rollButton);
myFrame.pack();
myFrame.setSize( myFrame.getPreferredSize() );
myFrame.setVisible(true);
}
/**
* Displays score and a message at the end of a game
*/
static void endGame() {
// display scores
scoreBox.setText("House: " + houseScore + " Player: " + playerScore);
// FIXED WIN CONDITIONS
// display message based on scores
if (playerScore > 21 && houseScore > 21) {
message.setText("Tie, you both lose.");
} else if (playerScore > 21 || (houseScore > playerScore && houseScore <= 21)) {
message.setText("House wins.");
} else if (houseScore > 21 || (playerScore > houseScore && playerScore <= 21)) {
message.setText("Player wins.");
} else {
message.setText("Tie, you both win.");
}
// // Say who wins depending on win conditions
// if (playerScore > 21 && houseScore > 21) {
// message.setText("Tie, you both lose.");
// //System.out.println("House probably keeps your money though, that cheater!");
// } else if (playerScore > 21) {
// message.setText("House wins.");
// } else if (houseScore > 21) {
// System.out.println("Player wins.");
// } else if (houseScore > playerScore) {
// message.setText("House wins.");
// } else if (playerScore > houseScore) {
// message.setText("Player wins.");
// } else {
// message.setText("Tie, you both win.");
// }
// reset scores to 0 for a new game
playerScore = 0;
houseScore = 0;
}
/**
* This class handles reactions to user input
* @author <NAME>
*
*/
static class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton eventSource = (JButton)e.getSource();
if(eventSource.getText().equals("Roll")) {
// if the "Roll" button is pressed
// Set Text
message.setText("Welcome to Game of 21! Get the highest score <= 21!");
// Roll for house
rollMe.roll();
houseScore += rollMe.getValue();
rollMe.roll();
houseScore += rollMe.getValue();
// Roll for player
rollMe.roll();
roll1 = rollMe.getValue();
rollMe.roll();
roll2 = rollMe.getValue();
// Print player's score
playerScore += roll1 + roll2;
scoreBox.setText("You roll " + DICE_CHARS[roll1 - 1] + " and " + DICE_CHARS[roll2 - 1] + ". Total: " + playerScore);
// If a score goes above 21 end the game
if (playerScore > 21 || houseScore > 21){
endGame();
}
} else {
// if the "end" button is pressed
endGame();
}
}
}
}
| 86ad92037c0a08267cf3f9d34588e664fd0f5e62 | [
"Java"
] | 2 | Java | ryluchs17/GameOfTwentyOne | 34c5601d08a3e62167896e122af1fad3a98e122f | 60d968934fb9bfb6f530ce2e8e175c7c7c5b1014 | |
refs/heads/master | <file_sep>package com.drin.mcrc;
import java.util.ArrayList;
public class Recipe {
private int result;
private Item output;
private ArrayList<Item> recipe;
private ArrayList<Item> raw;
public Recipe(ArrayList<Item> recipe, Item output, int number) {
this.result = number;
this.recipe = recipe;
this.output = output;
this.raw = generateRaw();
}
public Recipe(ArrayList<Item> recipe, Item output) {
this.result = 1;
this.recipe = recipe;
this.output = output;
this.raw = generateRaw();
}
public ArrayList<Item> generateRaw() {
ArrayList<Item> r = new ArrayList<Item>();
for (Item i : recipe) {
if (i == null) {
//do nothing, dont care if theres no crafting required
} else if (i.getRecipe() == null) {
r.add(i);
} else {
r.addAll(i.getRecipe().getRaw());
}
}
return r;
}
public ArrayList<Item> getRaw() {
return raw;
}
public String toString() {
return recipe.toString();
}
public Item getOutput() {
return output;
}
}
<file_sep>MCRC
====
Minecraft Resource Calculator
| 37087d2ea22db93e9c4ed204214e6e8aacc59e4a | [
"Markdown",
"Java"
] | 2 | Java | drinfernoo/MCRC | 5663f5451fd35c1a6f7e220a0fd08c7db8bbeb93 | 14b307e779c0daae2ad57c98cde96070429fa598 | |
refs/heads/master | <file_sep>// requires
var bluebird = require('bluebird'),
glob = require('glob');<file_sep>// requires
var bluebird = require('bluebird');<file_sep>var pJson = require('../package.json'),
core = require('./core'),
watch = require('node-watch'),
installing = false;
function throwError(err) {
console.log(core.colorizer('error', 'Ranza: ' + err ));
}
var Ranza = new Function();
Ranza.prototype.enableLogs = function(mode) {
this.logs = (typeof(mode) === 'boolean' ? mode : false);
}
Ranza.prototype.setDebug = function(debug, done, fn) {
this.debug = (typeof(debug) === 'undefined' ? true : debug);
}
Ranza.prototype.default = function() {
return core.reader('/../docs/default.md');
}
Ranza.prototype.version = function() {
return ('Ranza version: ' + pJson.version);
}
Ranza.prototype.help = function() {
return core.reader('/../docs/help.md');
}
Ranza.prototype.watch = function(install) {
var save = install || false;
return core.watcher('/').spread(function(files, root){
var searcher = core.searcher(files),
paths = searcher['validPaths'];
console.log(core.colorizer('success', '\nlivereload...\n'));
watch(paths, function(filename) {
var searcher = core.searcher(files),
requires = core.formater(searcher['requires']);
if (installing) return;
installing = true;
return core.compare(root, requires).spread(function(diffs) {
if (diffs.length <= 0) {
installing = false;
return console.log(core.colorizer('message', 'Ranza says: There is no unidentified requires!\n'));
}
return core.manager('install', root, diffs, save).then(function() {
installing = false;
});
});
});
}).catch(throwError);
}
Ranza.prototype.status = function(fn) {
var self = this;
return core.watcher('/').spread(function(files, root){
var searcher = core.searcher(files),
requires = core.formater(searcher['requires']);
return core.compare(root, requires, {debug: self.debug, where: searcher.where}).spread(function(diffs, unused, reqs, log) {
if (self.logs) console.log(log + '\n');
var status = {
undefinedUsed: diffs,
definedUnused: unused,
definedUsed: reqs
};
return ((typeof(fn) === 'function')? fn(status) : status);
});
}).catch(throwError);
}
Ranza.prototype.install = function(install) {
var save = install || false;
core.asker(function(yes) {
if (!yes) process.exit();
return core.watcher('/').spread(function(files, root){
var searcher = core.searcher(files),
requires = core.formater(searcher['requires']);
return core.manager('install', root, requires, save, true);
}).catch(throwError);
});
}
Ranza.prototype.clean = function(removeType) {
var save = removeType || false;
core.asker(function(yes) {
if (!yes) process.exit();
return core.watcher('/').spread(function(files, root){
var searcher = core.searcher(files),
requires = core.formater(searcher['requires']);
return core.compare(root, requires).spread(function(diffs, unused) {
if (unused.length <= 0)
return console.log(core.colorizer('message', '\nRanza says: There is no unused dependencies!\n'));
return core.manager('remove', root, unused, save, true);
});
}).catch(throwError);
});
}
module.exports = new Ranza();
<file_sep># Ranza
> The npm's butler
[![NPM Version](https://img.shields.io/npm/v/express.svg?style=flat)](https://www.npmjs.org/package/ranza)
[![Build Status](https://travis-ci.org/raphamorim/ranza.svg)](https://travis-ci.org/raphamorim/ranza)
Quickly spot any dependency required in the project and not listed in `package.json`. And also the other way around: quickly remove listed dependencies that are being used.
Run whenever you need or use the `watch` command to install dependencies automatically as you write `require`s on your project.
A simple **status** example:
![Ranza Status](docs/images/status.png)
## Install
With [node](http://nodejs.org/) and [npm](https://www.npmjs.org/) installed, install ranza with a single command:
```sh
$ npm install -g ranza
```
## Usage
#### Status
Checks all project for required dependencies and confirms if they are listed on `package.json`:
```sh
$ ranza status
```
You can use status with debug option as arguments, to best view requires status showing the occurrence files, ex:
**input:**
```sh
$ ranza status --debug
```
**some output example:**
```sh
Defined and used:
• babel-core
=> lib/new.js
• bluebird
=> core/src/comparer.js
=> core/src/manager.js
=> core/src/sentinel.js
Defined, but unused:
• grunt
• babel
```
#### Install
Installs all dependencies required throughout the project, but do not save them in `package.json`:
```sh
$ ranza install
```
Installs all dependencies required throughout the project and add them to `package.json` as `dependencies`:
```sh
$ ranza install --save
```
Installs all dependencies required throughout the project and save them in `package.json` as `devDependencies`:
```sh
$ ranza install --save-dev
```
#### Clean
Remove and clean all unused dependencies from `package.json`:
```sh
$ ranza clean
```
#### Watch (only for HARDCORE developers)
**The not recommended way:**
> Installs every single dependencies in each livereload
Livereload in all files, installing undefined dependencies without saving them in `package.json`:
```sh
$ ranza watch
```
**The recommended way:**
> Installs only missed dependencies in each livereload
Livereload in all files, installing undefined dependencies and saving them as `dependencies` in `package.json`:
```sh
$ ranza watch --save
```
Livereload in all files, installing undefined dependencies and saving them as `devDependencies` in `package.json`:
```sh
$ ranza watch --save-dev
```
Example:
![Ranza Watch](docs/images/watch.gif)
## History
See [Changelog](docs/changelog.md) for more details.
## Contributing
Don't be shy, send a Pull Request! Here is how:
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -m 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D
## About
**License:** MIT ® [<NAME>](https://github.com/raphamorim)
<file_sep>var assert = require('assert'),
Promises = require('bluebird'),
Ranza = Promises.promisifyAll(require('../index.js')),
realCwd = process.cwd();
function fakeCwd(path) {
process.cwd = function() {
return realCwd + '/test/fixtures/' + path;
};
}
describe('Status', function() {
context('apply status command', function() {
context('on a project without missed requires and undefined dependencies', function() {
it('should return only the used dependencies and a empty unused/undefined list', function(done) {
fakeCwd('perfectDependencies');
Ranza.status(function(status) {
assert.deepEqual(typeof(status), 'object');
assert.deepEqual(status.undefinedUsed, []);
assert.deepEqual(status.definedUnused, []);
assert.deepEqual(status.definedUsed, ['bluebird', 'glob']);
done();
});
})
})
context('on a project with unused dependencies', function() {
it('should return the unused dependencies', function(done) {
fakeCwd('unusedDependecy');
Ranza.status(function(status) {
assert.deepEqual(typeof(status), 'object');
assert.deepEqual(status.undefinedUsed, []);
assert.deepEqual(status.definedUnused, ['kenobi', 'glob']);
assert.deepEqual(status.definedUsed, ['bluebird']);
done();
});
})
})
});
});
| 72870e2c06f9cede9bc58ace8cd12de8d661400d | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | israelst/ranza | aaa1c7a11f26a820265abfd3a6680cb627a2221c | bf407d79f29dbf9a7247699ff88b9ea33e88af84 | |
refs/heads/master | <repo_name>Roboticsotago/robotics_repo<file_sep>/Projects/2017/SoccerBots/runeverything.sh
#!/bin/bash
if [[ $(hostname) == "Boris" ]]; then
sleep 7
pd_patch=goalie_control_refactored.pd
echo Goalie
xdotool mousemove --sync 0 0
sleep 3
python -u blob_tracking_cv2.py | python boris_python2.py
xmessage yo
else
echo Attacker
sleep 7
pd_patch=attacker_main.pd
urxvt -name Pd -title Pd -e sh -c "/usr/bin/pd -nomidi -alsa -noadc -r 8000 -send \"; pd dsp 1\" motor-control.pd $pd_patch sensor_input.pd" &
sleep 10
urxvt -hold -name read_sensors -title read_sensors -e sh -c "./read_sensors.tcl | pdsend 7000" &
sleep 5
xdotool mousemove --sync 0 0
sleep 1
urxvt -hold -name blob_tracking -title blob_tracking -e sh -c "python2.7 blob_tracking_cv2.py | pdsend 7001" &
xmessage yo
fi
<file_sep>/Projects/2016/MIDIBots/arduino/pwm_examples/pwm_7.ino
// MIDI note tests for Mechatronics, CME 2016-03-21
// 1. Loop sanity check. Watch for off-by-one errors!
// 2. Translate note frequency formula into C syntax and check (MIDI note 69 should give 440 Hz).
// 3. Correct integer division in formula!
// 4. Derive OCR "top" value from frequency, and print for checking.
// 5. Correct type of "top" to get the full available range.
// 6. Move the formulae into separate functions, and check that it still works!
// 7. Add stuff for generating the PWM output. Tweak range of notes for musical range.
// General settings:
const int prescale = 8;
const int serial_speed = 9600;
// On the Mega, we have timer1 attached to pins D11 and D12, D12 being the primary one.
// On "ordinary" Arduinos, it's on pins 9 and 10.
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
const int OUTPUT_PIN = 12;
const int OUTPUT_PIN_AUX = 11;
#else
const int OUTPUT_PIN = 10;
const int OUTPUT_PIN_AUX = 9;
#endif
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
// This defines which bits within the TCCRnB register determine the prescale factor:
#define TIMER_PRESCALE_MASK 0xF8 // 0B11111000
// Map desired prescale divider to register bits:
byte timer_prescale_bits(int prescale) {
if (prescale == 1)
return 0x01;
else if (prescale == 8)
return 0x02;
else if (prescale == 64)
return 0x03;
else if (prescale == 256)
return 0x04;
else if (prescale == 1024)
return 0x05;
else
return 0x00; // Error?!
}
float frequency(int note) {
return 440 * pow(2, (note - 69) / 12.0);
}
unsigned int top(float frequency) {
return round(F_CPU / (prescale * frequency) - 1);
}
void pwm(float frequency, float duty_cycle) {
TCNT1 = 0; // Reset timer counter
unsigned int wrap_limit = top(frequency);
OCR1A = wrap_limit;
OCR1B = int(wrap_limit * duty_cycle);
// TCCR1A's timer mode should already be set, so just use TCCR1B to start PWM (is that sufficient?):
TCCR1A = _BV(COM1A0) | _BV(COM1B1) | _BV(WGM11) | _BV(WGM10);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11);
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | timer_prescale_bits(prescale);
}
void setup() {
pinMode(OUTPUT_PIN, OUTPUT);
pinMode(OUTPUT_PIN_AUX, OUTPUT);
digitalWrite(OUTPUT_PIN, LOW);
digitalWrite(OUTPUT_PIN_AUX, LOW);
delay(8000); // safety delay for serial I/O
Serial.begin(serial_speed);
}
void loop() {
int prescale = 8;
for (int note = 33; note <= 96; note++) {
float f = frequency(note);
unsigned int t = top(f);
Serial.print(note);
Serial.print(": f=");
Serial.print(f);
Serial.print(", top=");
Serial.println(t);
pwm(frequency(note), 0.3);
delay(150);
}
}
<file_sep>/Projects/2016/MIDIBots/arduino/fan_test/ano/src/sketch.ino
../../fan_test.ino<file_sep>/Projects/2016/MIDIBots/Airflow requirements.txt
Notes on airflow for the woodwind instruments for the MusicBots project 2016
--
We did some testing of Chris's Aerobed fan. This is rated at 12 V ~6 A (10 A fuse), and is designed to be run off a car cigar lighter
or eight 1.5 V batteries.
V-A testing off the bench supply:
V: A: Comment:
0 0
0.3 0.5
0.6 0.4 turn-off point
1.0 0.44 turn-on point
1.5 0.5
2.0 0.59
2.5 0.71
3.0 0.83
3.5 0.96
4.0 1.12
4.5 1.30
5.0 1.48
6.0 1.9
7.0 2.4
7.5 2.73
8.0 2.99 Power supply current limit
The fan/motor is quite noisy, even at low voltages. I think the noise is mostly from the motor, not the fan impeller blades, so we
might be able to replace it with a quieter brushless fan. Alternatively, doing the 3D design and fabrication of an impeller will be
good practice for the hovercraft project later in the year..!
For playing the recorder in tune, more pressure and airflow is required for higher notes. Here is the voltage required to achieve the
correct pitch (frequency) for some test notes:
D 1.9 V
E 2.1 V
G 2.5 V
A 2.7 V
B 3.1 V
C 3.2 V
D 3.4 V
--
Required air pressure for acoustic woodwind instruments:
oboe: 20..60 mm Hg = 2.8..7.7 kPa
Rossing: reed woodwind: 3-5 kPa
flute: ~1 kPa, 20..60 m/s air jet velocity
Fuks and Sundberg (1996):
Clarinet: 25-60 cm H2O -> 2.5-6.0 kPa
Saxophone: 15-80 cm H2O -> 1.5-8.0 kPa
Oboe: 35-100 cm H2O -> 3.5-10.0 kPa
Bassoon: 10-90 cm H2O -> 1.0-9.0 kPa
Fletcher:
Flute: 0.2-2.5 kPa
--
A centrifugal blower is probably a better type of fan for high pressure (axial fans can produce a lot of airflow, but are limited in
pressure).
Centrifugal fan/impeller blades can be straight, or curved backwards or forwards. Curved-forward centrifugal blades probably have the
best characteristics:
- high pressure
- low noise
- small airflow
They do require more mechanical power to run them, however.
--
Some candidiate fans (or we could make our own):
Sunon 12V:
1.5 A @ 12 V
5400 RPM
44.2 CPM = 75 m^3/hour
3.39 in. H2O = 0.84 kPa
Probably not enough pressure
Sunon 3.5 A 12 V blower, PF97331BX-B00U-A99
97 mm x 95 mm x 33 mm
6800 RPM
93 m^3/hour
1.3 kPa
Sufficient pressure for a recorder or flute, but probably not a reed instrument.
Digi-Key has, but only in min. 30x orders
Delta-Electronics BCB1012UH-F00
1.0 kPa
9300 RPM
1.00 m^3/min
3 wire leads
Delta-Electronics BCB0812UHN-TP09
0.915 kPa
2.3 A
PWM control and tach! (4-wire)
http://www.digikey.com/product-detail/en/delta-electronics/BCB0812UHN-TP09/603-1213-ND/2034820
Could use with plain Arduino (no shield required) - with pressure sensor for control feedback
Have ordered one of these from Digi-Key
--
Fan speed control/pressure regulation
We will probably need some kind of air reservoir to help maintain steady pressure and airflow while mutliple woodwind instruments are
turning on and off. The regulation of air pressure could be done mechanically, using a weight or a spring mechanism, but we also have
the opportunity to use an active control system by monitoring the pressure in the reservoir electronically, and using PWM to vary the
fan motor speed. It might be necessary to use a PID (proportional-integral-derivative) control system to maintain the pressure
accurately enough.
Note how airflow and pressure are analogous to electrical current and voltage! The wind reservoir is like a capacitor. A narrow tube
is like a resistor (it will reduce the current and the pressure coming out). Acoustic impedance (analogous to electrical impedance) is
an important characteristic of air-column instruments such as brass and woodwind.
We will also want to be able to regulate the pressure/flow at the instrument in order to get acceptable intonation. We have tested an
arrangement using a servo motor squeezing on a thin air tube made from heatshrink tubing. The Hitec servos seem to be strong enough for
this application. If this can cut off the air supply completely, then we would not require a separate solenoid valve. An alternative
to the squeezed tube would be a butterfly valve: a disc-shaped valve rotating inside a cylindrical pipe. This would be a good match for
a servo motor, and would probably be easier to actuate as the airflow is roughly balanced on both sides of the valve (having to work
against the airflow would require more force).
<file_sep>/Projects/2016/MIDIBots/arduino/libraries/MIDIBot/MIDIBot.h
/*
Arduino library for our MIDIBot shield circuit board, Robocup 2016
Team _underscore_, Information Science Mechatronics, University of Otago
To use this library, #include it, and instantiate a la "MIDIBot drumBot;" (note: no trailing parentheses - that would make it a function declaration!).
You will also need to define a note_on() and note_off() implementation for the specific robot. These will be called from MIDIBot::process_MIDI, passing the MIDI note number and velocity as arguments.
Your sketch will also need to implement a self_test() function, which will be called from MIDIBot::process_MIDI if the Self-Test button is pressed.
Because you can't use delay() or Serial.begin() in the constructor, this class defines a separate MIDIBot::begin() method which reads the MIDI channel from the DIP switches, flashes the MIDI channel number, and starts serial communication at MIDI baud rate (after a 5-second pause to avoid reprogramming problems).
The following is a basic example:
--
#include <MIDIBot.h>
MIDIBot thisMIDIBot;
void note_on(int note, int velocity) {
digitalWrite(LED_PIN, HIGH);
analogWrite(MOSFET_PWM_PIN, 64);
}
void note_off(int note, int velocity) {
digitalWrite(LED_PIN, LOW);
analogWrite(MOSFET_PWM_PIN, 0);
}
void self_test() {
thisMIDIBot.test_MIDI_channel();
// Bot-specific tests...
}
void setup() {
thisMIDIBot.test_MIDI_channel(); // Indicate MIDI channel at startup
}
void loop() {
thisMIDIBot.process_MIDI();
}
--
*/
// NOTE: Due to apparent problems with calling delay() inside a constructor, you can't flash the MIDI channel number on the LED automatically at startup (though you can read the MIDI channel DIP switches). Therefore, call yourMIDIBot.test_MIDI_channel() it your setup() function if you want this to happen.
// TODO:
// [ ] Convert to camelCase throughout for function names? It's recommended in the Arduino API style guide. Also member variables?
// [ ] Rename _i to something more meaningful, e.g. _dataByteIndex or _MIDIBufferIndex
// [ ] #define constants? That seems to be the norm with .h files, and they'd only be defined if the header were included, and might save on processor registers?
#ifndef MIDIBot_included
#define MIDIBot_included
#include "Arduino.h"
// Define pin mappings for the MIDIBot shield:
// For a library, should these be global symbols or defined within the class?
// Also, how do we make the class a singleton?
// Should these be consts or #defines?
const int
MIDI_1x_PIN = 2,
MIDI_2x_PIN = 3,
MIDI_4x_PIN = 4, /* USBDroid has pulldown resistor on D4! */
MIDI_8x_PIN = 5,
MOSFET_PWM_PIN = 6,
SERVO_1_PIN = 9, /* USBDroid has pulldown resistor on D9! */
SERVO_2_PIN = 10,
SERVO_3_PIN = 11, /* USBDroid has pulldown resistor on D11! */
MOSFET_2_PIN = 12,
MOSFET_3_PIN = A1, /* not A3 as on the silkscreen! */
MOSFET_4_PIN = A2, /* not A4 as on the silkscreen! */
LED_PIN = 13, /* USBDroid has pulldown resistor on D13! */
LATENCY_ADJUST_PIN = A0,
SELF_TEST_PIN = A5,
SERIAL_SPEED = 31250
;
// Empty prototypes for additional functions that the sketch using this library should define (for bot-specific functionality):
// (Do these need to be declared "extern" as well?)
void note_on(int note, int velocity);
void note_off(int note, int velocity);
void self_test(); // Called from process_MIDI() when the self-test button is pressed
class MIDIBot {
public:
MIDIBot(); // Constructor method. Sets up the MIDIBot Shield's pins, sets the MIDI channel ID from the DIP switches, and starts Serial input for MIDI compatibility.
void begin(); // Start serial comms
void clearData(); // Zeroes out the buffer for received MIDI data
void flash(int on_time, int off_time); // Flash the onboard LED with specified on/off duration in milliseconds
void flash_number(int n); // Flash the LED in a pattern to indicate the value of <n>
void read_MIDI_channel(); // Read MIDI DIP switch settings and store in _MIDI_channel
void process_MIDI(); // Main MIDI-processing "loop"
// Generic self-test functions:
void test_blink(); // Blink the onboard LED once
void test_button(); // Light the onboard LED if the self-test button is pressed
void test_MIDI_channel(); // Read and flash-display the MIDI channel number
private:
int _MIDI_channel; // 1..16, 10=drums
// MIDI messages have up to 2 data bytes, which we store in an array:
// TODO: perhaps name the index more sensibly/explicitly:
int _dataByte[2], _statusByte, _i;
// For monophonic instruments, it's useful to keep track of the note currently being played, so that any note-off messages for other notes can be ignored.
int _current_note_number;
};
#endif
<file_sep>/Projects/2017/SoccerBots/arduino/buzzer/pokemon.h
//short part of Pokemon Red/Blue/Yellow opening theme
const int pokemonTempo = 200;
const int pokemonArrayLength = 37;
float pokemon[pokemonArrayLength][2] = {{69,0.5},{69,0.5},{74,1},{69,0.5},{69,0.5},{75,1},
{69,0.5},{69,0.5},{74,1},{69,0.5},{69,0.5},{73,1},
{69,0.5},{69,0.5},{74,1},{69,0.5},{69,0.5},{79,1},
{81,2},{69,2},
{77,2},{65,2},
{69,0.5},{69,0.5},{74,1},{69,0.5},{69,0.5},{75,1},
{69,0.5},{69,0.5},{74,1},{69,0.5},{69,0.5},{79,1},
{78,4},
{74,1},{0,3}};
<file_sep>/Projects/2017/SoccerBots/calibrate_vision_cv2.py
#!/usr/bin/env python2.7
#Calibration of the camera to do when lighting conditions change
import sys
def debug(msg):
sys.stderr.write(str(msg) + "\n")
from time import sleep
execfile("camera_setup.py")
debug("calibrating gain...")
sleep(2)
camera.exposure_mode = 'off'
debug("camera.analog_gain = " + str(camera.analog_gain))
# Now fix the white balace:
debug("Hold a white card in front of the camera now!")
sleep(5)
g = camera.awb_gains
debug("Thanks; camera.awb_gains = " + str(g))
camera.awb_mode = 'off'
camera.awb_gains = g
calibration_frames = 240
def calibrate_target_colour():
debug("Calibrating target colour")
debug("Put the target colour in the capture frame")
camera.start_preview(alpha=200)
sleep(3)
i=1
h_avg=0
s_avg=0
v_avg=0
h_min=180
h_max=0
s_min=255
s_max=0
v_min=255
v_max=0
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
#print("copy array")
image = frame.array
# Crop the central region of interest and convert to HSV colour space:
xres = capture_res[0]
yres = capture_res[1]
# TODO: make a function for these?
Y1 = int(round(yres * (yfrac + 1) / 2.0))
Y0 = int(round(yres * (1 - yfrac) / 2.0))
X0 = int(round(xres * (1 - xfrac) / 2.0))
X1 = int(round(xres * (xfrac + 1) / 2.0))
hsv = cv2.cvtColor(image[Y0:Y1,X0:X1], cv2.COLOR_BGR2HSV)
# Draw sampling region on the frame to assist with aiming:
cv2.rectangle(image,(X0,Y0),(X1,Y1),(0,255,0),2)
cv2.imshow("Frame",image)
key = cv2.waitKey(16) & 0xFF
# Compute the average colour for the sampling region:
average_colour = [hsv[:, :, c].mean() for c in range(hsv.shape[-1])]
#average_colour = hsv[capture_res[0]/2,capture_res[1]/2]
debug(str(average_colour) + str(i))
rawCapture.truncate(0)
if i==1:
h_avg = average_colour[0]
s_avg = average_colour[1]
v_avg = average_colour[2]
else:
h_avg = (i-1)/float(i)*h_avg + average_colour[0]/float(i)
s_avg = (i-1)/float(i)*s_avg + average_colour[1]/float(i)
v_avg = (i-1)/float(i)*v_avg + average_colour[2]/float(i)
current_h_min = hsv[:,:,0].min()
current_h_max = hsv[:,:,0].max()
current_s_min = hsv[:,:,1].min()
current_s_max = hsv[:,:,1].max()
current_v_min = hsv[:,:,2].min()
current_v_max = hsv[:,:,2].max()
if current_h_min < h_min: h_min = current_h_min
if current_h_max > h_max: h_max = current_h_max
if current_s_min < s_min: s_min = current_s_min
if current_s_max > s_max: s_max = current_s_max
if current_v_min < v_min: v_min = current_v_min
if current_v_max > v_max: v_max = current_v_max
i = i + 1
if i >= calibration_frames:
average_colour[0] = h_avg
average_colour[1] = s_avg
average_colour[2] = v_avg
debug(average_colour)
return [h_min,s_min,v_min], [h_max,s_max,v_max]
break;
calibrated_colour = calibrate_target_colour()
calibration_file_name = "camera_calibration_state_cv2.py"
def file_output(file_name, white_balance, target_colour_min_max):
filex = open(file_name, "w")
filex.write("calibrated_white_balance = " + str(white_balance) + "\n")
filex.write("calibrated_goal_colour = " + str(target_colour_min_max) + "\n")
filex.close()
file_output(calibration_file_name, g, calibrated_colour)
<file_sep>/Projects/2016/MIDIBots/arduino/midi_test/ano/src/sketch.ino
../../midi_test.ino<file_sep>/Projects/2016/MIDIBots/arduino/pwm_synth_test/ano/src/sketch.ino
../../pwm_synth_test.ino<file_sep>/Documentation/Arduino/memory-and-EEPROM/build.sh
#!/bin/sh
BASENAME=memory-and-EEPROM
pandoc -s --latex-engine=xelatex --variable=geometry:a4paper --include-in-header=fontoptions.tex --include-in-header=fullrule.tex $BASENAME.md -o $BASENAME.pdf
<file_sep>/Projects/2016/MIDIBots/arduino/uke_test/ano/src/sketch.ino
../../uke_test.ino<file_sep>/Projects/2016/MIDIBots/arduino/midi_drum/midi_drum.ino
// An Arduino program for triggering a servo-controlled drum-stick in response to MIDI note messages
// General settings:
const float DOWN = 0;
const float UP = 0.5;
const int prescale = 8;
const int SERVO_FREQUENCY = 50; // Hz (1/(20 ms))
const int channel = 0;
// MIDI messages have up to 2 data bytes, which we store in an array:
int dataByte[2], statusByte = 0, i = 0;
void clearData(){
dataByte[0] = 0;
dataByte[1] = 0;
i = 0;
}
// Even though this is only monophonic, it's still useful to keep track of the note currently being played, so that any note-off messages for other notes can be ignored.
int current_note_number = 0;
// On the Mega, we have timer1 attached to pins D11 and D12, D12 being the primary one.
// On "ordinary" Arduinos, it's on pins 9 and 10.
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
const int OUTPUT_PIN = 12;
const int OUTPUT_PIN_AUX = 11;
#else
const int OUTPUT_PIN = 10;
const int OUTPUT_PIN_AUX = 9;
#endif
// Some PWM control definitions:
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
// This defines which bits within the TCCRnB register determine the prescale factor:
#define TIMER_PRESCALE_MASK 0xF8 // 0B11111000
// Map desired prescale divider to register bits:
byte timer_prescale_bits(int prescale) {
if (prescale == 1)
return 0x01;
else if (prescale == 8)
return 0x02;
else if (prescale == 64)
return 0x03;
else if (prescale == 256)
return 0x04;
else if (prescale == 1024)
return 0x05;
else
return 0x00; // Error?!
}
float frequency(int note) {
return 440 * pow(2, (note - 69) / 12.0);
}
unsigned int top(float frequency) {
return round(F_CPU / (prescale * frequency) - 1);
}
void pwm(float frequency, float duty_cycle) {
TCNT1 = 0; // Reset timer counter
unsigned int wrap_limit = top(frequency);
OCR1A = wrap_limit;
OCR1B = int(wrap_limit * duty_cycle);
// TCCR1A's timer mode should already be set, so just use TCCR1B to start PWM (is that sufficient?):
TCCR1A = _BV(COM1A0) | _BV(COM1B1) | _BV(WGM11) | _BV(WGM10);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11);
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | timer_prescale_bits(prescale);
}
void pwm_off() {
return;
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | TIMER_CLK_STOP;
TCNT1 = 0;
digitalWrite(OUTPUT_PIN, LOW); // This seems to be necessary to silence it properly (sometimes gets stuck at 5 V otherwise!)
}
void setup() {
pinMode(OUTPUT_PIN, OUTPUT);
pinMode(OUTPUT_PIN_AUX, OUTPUT);
digitalWrite(OUTPUT_PIN, LOW);
digitalWrite(OUTPUT_PIN_AUX, LOW);
clearData();
pwm(50, calcDutyCicle(UP));
delay(2000); // safety delay for serial I/O
Serial.begin(31250);
}
float calcDutyCicle(float in){
if(in < 0)
in = 0;
if(in > 1)
in = 1;
return (in + 1)/20.0;
}
void drum(){
int spd = 100; // ms; 80 ms is OK up to about 220 BPM
pwm(SERVO_FREQUENCY, calcDutyCicle(DOWN));
delay(spd);
pwm(SERVO_FREQUENCY, calcDutyCicle(UP));
delay(spd);
}
void loop () {
if (Serial.available() > 0) {
int data = Serial.read();
if (data > 127) {
// It's a status byte. Store it for future reference.
statusByte = data;
clearData();
} else {
// It's a data byte.
dataByte[i] = data;
if (statusByte == (0x90 | channel) && i == 1) {
// Note-on message received
if (dataByte[1] == 0 && dataByte[0] == current_note_number) {
// Stop note playing
pwm_off();
} else {
// Start note playing
current_note_number = dataByte[0];
// pwm(frequency(current_note_number), dataByte[1] / 127.0 / 2); // TODO: map velocity to PWM duty
drum();
}
} else if (statusByte == (0x80 | channel) && i == 1 && dataByte[0] == current_note_number) {
// Note-off message received
// Stop note playing
pwm_off();
}
i++;
// TODO: error detection if i goes beyond the array size.
}
}
}
<file_sep>/Projects/2017/SoccerBots/arduino/magnetometer_test/magnetometer_test.ino
/*
Magnetometer Test
Reads data from the LIS3MDL sensor and calculate a compass heading and can
return the angle to a specified heading
The y-axis points in the forwards direction of the robot
TODO:
- implement correction for magmetic north
*/
/*
The sensor outputs provided by the library are the raw 16-bit values
obtained by concatenating the 8-bit high and low magnetometer data registers.
They can be converted to units of gauss using the
conversion factors specified in the datasheet for your particular
device and full scale setting (gain).
Example: An LIS3MDL gives a magnetometer X axis reading of 1292 with its
default full scale setting of +/- 4 gauss. The GN specification
in the LIS3MDL datasheet (page 8) states a conversion factor of 6842
LSB/gauss (where LSB means least significant bit) at this FS setting, so the raw
reading of 1292 corresponds to 1292 / 6842 = 0.1888 gauss.
*/
#include <Wire.h>
#include <LIS3MDL.h>
#include <math.h>
char report[80];
int cal_x, cal_y;
float reference_heading;
LIS3MDL mag;
LIS3MDL::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32768, -32768, -32768};
// calibrate the magnetometer, the magnetometer must be moved through its full axis of rotation while calibrating
void calibrateSensor(){
for (int i = 0; i < 200; i += 1) {
mag.read();
// minimum values
running_min.x = min(running_min.x, mag.m.x);
running_min.y = min(running_min.y, mag.m.y);
running_min.z = min(running_min.z, mag.m.z);
// maximum values
running_max.x = max(running_max.x, mag.m.x);
running_max.y = max(running_max.y, mag.m.y);
running_max.z = max(running_max.z, mag.m.z);
// print limits
snprintf(report, sizeof(report), "min: {%+6d, %+6d, %+6d} max: {%+6d, %+6d, %+6d}",
running_min.x, running_min.y, running_min.z,
running_max.x, running_max.y, running_max.z);
// Serial.println(report);
delay(50);
}
// calculate calibrated origin
cal_x = (running_max.x + running_min.x) / 2;
cal_y = (running_max.y + running_min.y) / 2;
}
// read raw data from magnetometer and adjust from calibration
void read() {
mag.read();
// adjust raw data for calibration
mag.m.x -= cal_x;
mag.m.y -= cal_y;
// print adjusted values
snprintf(report, sizeof(report), "M: %6d, %6d, %6d",
mag.m.x, mag.m.y, mag.m.z);
//Serial.println(report);
}
// returns the compass heading from magnetometer, range [0, 360]
float getCompassHeading() {
read();
float heading = calcAngle(mag.m.x, mag.m.y) * -1; // compass heading is angle clockwise from North, hence the * -1
if (heading < 0) {
return heading + 360.0;
} else {
return heading;
}
}
// calculate the angle of point (x, y)
float calcAngle(int x, int y) {
return degrees(atan2(x, y));
}
// stores the compass angle that is the desired direction
float saveHeading() {
reference_heading = getCompassHeading();
}
// returns the angle that the robot is off the reference_heading, range [-180, 180]
float getRelativeAngle(float my_heading) {
float angle_diff = (my_heading - reference_heading) * -1.0;
Serial.print("Actual heading: "); Serial.print(my_heading);
Serial.print(" Angle difference: "); Serial.println(angle_diff);
if (angle_diff < -180.0) {
return angle_diff + 360.0;
} else if (angle_diff > 180.0) {
return angle_diff - 360.0;
} else {
return angle_diff;
}
}
// checks to see if facing target dirrection
int isTargetGoal(float my_heading) {
if ((my_heading < 90.0) && (my_heading > -90.0)) {
return 1;
} else {
return 0;
}
}
// functions to run at start for testing
void startFunctionsTest() {
// calibrate the sensor
Serial.println("Calibration started");
calibrateSensor();
Serial.println("Calibration finished");
// store the current direction after short delay
Serial.print("Saving direction in: ");
for (int n = 4; n > 0; n -= 1) {
Serial.print(n);
delay(1000);
}
Serial.println();
saveHeading();
Serial.print("Saved heading is: "); Serial.println(reference_heading);
delay(2000);
}
void loopTest() {
Serial.print("Angle to desired heading is: ");
Serial.println(isTargetGoal(getRelativeAngle(getCompassHeading())));
}
void setup() {
Serial.begin(9600);
Serial.println("Magnetometer Test");
Wire.begin();
if (!mag.init()) {
Serial.println("Failed to detect and initialize magnetometer!");
while (1);
}
mag.enableDefault();
startFunctionsTest();
}
void loop() {
loopTest();
delay(1000);
}
<file_sep>/Projects/2017/SoccerBots/trigonometry/Makefile
atan2: atan2.c
gcc -std=c99 -o atan2 atan2.c -lm
./atan2
.PHONY: clean
clean:
rm atan2
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_ukebot/firmware_ukebot.ino
// UkeBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
/*
TODO:
[ ] Consider refactoring to use Servo.writeMicroseconds() for more accurate control over positioning. Maybe add a wrapper function that accepts target angle as a float.
[ ] Calibrate slide positions to correspond to musical intervals
[ ] Add note-on messages for slide positioning
[ ] Add note-on messages for plucking indiviual strings (think of it as having 5 positions which can be reached: top, between first two strings, between middle strings, between last two strings, and bottom). Could be tricky to get the timing right, as the time to pluck will depend on the current strumming position. Perhaps just pick a single value that generally works OK.
[ ] Refactor to use arrays (2-dimensional?) for slide and strum (note, position pairs).
*/
// Define pin mappings for the MIDIBot shield:
#include <Servo.h>
#include <MIDIBot.h>
MIDIBot UkeBot;
Servo strum;
Servo slide;
int pos = 0; // variable to store the servo position
// Deprecated:
const int UP_NOTE = 50; // Middle C
const int DOWN_NOTE = 52; // D
// Servo angles for strumming...
const int STRUM_MIN = 92;
const int STRUM_MAX = 105;
const int
STRUM_0 = 92, // OK
STRUM_1 = 93, //
STRUM_2 = 95, //
STRUM_3 = 97, //
STRUM_4 = 98, //
STRUM_5 = 100, //
STRUM_6 = 101, // OK
STRUM_7 = 103, // Maybe 102 - sometimes hits the next string
STRUM_8 = 104, //
STRUM_9 = 105; // OK
// ..and the slide.
// For slide max/min, we probably want min to be at the nut end, and max at the soundhole end.
const int SLIDE_MIN = 29;
const int SLIDE_MAX = 83;
const int
SLIDE_0 = 29,
SLIDE_1 = 37,
SLIDE_2 = 45,
SLIDE_3 = 52,
SLIDE_4 = 59,
SLIDE_5 = 65,
SLIDE_6 = 71,
SLIDE_7 = 77,
SLIDE_8 = 83;
// MIDI note numbers for strumming...
const int
STRUM_0_NOTE = 0,
STRUM_1_NOTE = 1,
STRUM_2_NOTE = 2,
STRUM_3_NOTE = 3,
STRUM_4_NOTE = 4,
STRUM_5_NOTE = 5,
STRUM_6_NOTE = 6,
STRUM_7_NOTE = 7,
STRUM_8_NOTE = 8,
STRUM_9_NOTE = 9;
// ...and picking:
const int
SLIDE_0_NOTE = 12,
SLIDE_1_NOTE = 13,
SLIDE_2_NOTE = 14,
SLIDE_3_NOTE = 15,
SLIDE_4_NOTE = 16,
SLIDE_5_NOTE = 17,
SLIDE_6_NOTE = 18,
SLIDE_7_NOTE = 19,
SLIDE_8_NOTE = 20;
// TODO: constants (or an array?) of servo positions that correspond to musical notes.
// Keep track of last slide position set, in case we end up getting really fancy with the logic and trying to optimise the timings or something.
int slide_position = SLIDE_MIN;
// Unused?
const int STRUM_DELAY = 100;
const int SLIDE_DELAY = 300; // Worst-case slide motion time (HOME..MIN). Unconfirmed!
int i;
void move_slide(int pos) {
// Clip motion to valid range:
if (pos < SLIDE_MIN) {pos = SLIDE_MIN;}
if (pos > SLIDE_MAX) {pos = SLIDE_MAX;}
// Move it:
slide.write(pos);
}
// TODO: similar to move_slide() but for picking, maybe?
void note_on(int note, int velocity) {
switch (note) {
case STRUM_0_NOTE: strum.write(STRUM_0); break;
case STRUM_1_NOTE: strum.write(STRUM_1); break;
case STRUM_2_NOTE: strum.write(STRUM_2); break;
case STRUM_3_NOTE: strum.write(STRUM_3); break;
case STRUM_4_NOTE: strum.write(STRUM_4); break;
case STRUM_5_NOTE: strum.write(STRUM_5); break;
case STRUM_6_NOTE: strum.write(STRUM_6); break;
case STRUM_7_NOTE: strum.write(STRUM_7); break;
case STRUM_8_NOTE: strum.write(STRUM_8); break;
case STRUM_9_NOTE: strum.write(STRUM_9); break;
case SLIDE_0_NOTE: move_slide(SLIDE_0); break;
case SLIDE_1_NOTE: move_slide(SLIDE_1); break;
case SLIDE_2_NOTE: move_slide(SLIDE_2); break;
case SLIDE_3_NOTE: move_slide(SLIDE_3); break;
case SLIDE_4_NOTE: move_slide(SLIDE_4); break;
case SLIDE_5_NOTE: move_slide(SLIDE_5); break;
case SLIDE_6_NOTE: move_slide(SLIDE_6); break;
case SLIDE_7_NOTE: move_slide(SLIDE_7); break;
case SLIDE_8_NOTE: move_slide(SLIDE_8); break;
}
}
void note_off(int note, int velocity) {}
void setup()
{
UkeBot.begin();
// Servo setup:
strum.attach(SERVO_3_PIN);
slide.attach(SERVO_2_PIN);
// Set initial position
strum.write(STRUM_MIN);
slide.write(SLIDE_MIN);
}
void self_test_picking() {
strum.write(STRUM_1); delay(500);
strum.write(STRUM_0); delay(500);
strum.write(STRUM_3); delay(500);
strum.write(STRUM_2); delay(500);
strum.write(STRUM_5); delay(500);
strum.write(STRUM_4); delay(500);
strum.write(STRUM_7); delay(500);
strum.write(STRUM_6); delay(500);
strum.write(STRUM_9); delay(500);
strum.write(STRUM_8); delay(500);
strum.write(STRUM_8); delay(500);
strum.write(STRUM_9); delay(500);
strum.write(STRUM_6); delay(500);
strum.write(STRUM_7); delay(500);
strum.write(STRUM_4); delay(500);
strum.write(STRUM_5); delay(500);
strum.write(STRUM_2); delay(500);
strum.write(STRUM_3); delay(500);
strum.write(STRUM_0); delay(500);
strum.write(STRUM_1); delay(500);
strum.write(STRUM_0); delay(500); // Return home
}
void self_test() {
// TODO: test each semitone, not just min/max slide position. This would be easier if we used an array for the slide positions.
digitalWrite(LED_PIN, HIGH);
move_slide(SLIDE_MIN); delay(SLIDE_DELAY);
self_test_picking();
move_slide(SLIDE_MAX); delay(SLIDE_DELAY);
self_test_picking();
move_slide(SLIDE_MIN); delay(SLIDE_DELAY);
digitalWrite(LED_PIN, LOW);
}
void loop()
{
UkeBot.process_MIDI();
}
<file_sep>/Projects/2017/RescueBot/arduino/motor_test/motor_test.ino
//#include <line_follower.h>
//#include <robot.h>
//#include <seeed.h>
// Simple demonstration LED blinker for the DSpace Robot board
// The onboard LEDs are on digital pins 6-10.
// D6: LED1, red
// D7: LED2, orange
// D8: LED3, yellow
// D9: LED4, green
// D10: LED5, blue
// Note that we have generally modified our boards to allow PWM control of both H-bridge channels. On the stock boards, pins 4 and 5 are enable, but pin 4 has no PWM support. Also 6,7 motor A, 9,10 motor B.
// Left motor is on pin 0, right motor is on pin 1.
// RobotMotor class provides Init(), Stop(), Brake(), Forwards(), Backwards().
// RobotDrive is for higher-level control. Doesn't have a turn-on-the spot behaviour. We probably want PWM control over speed as well, so we might have to devise our own library for this.
// Might not even have to be hardcoded for the DSpace Robot board - perhaps any dual H-bridge configuration.
// Change pin 4 to 11 for our modified DSpace boards (PWM on fwd)
#define MOTOR_R_ENABLE 11
#define MOTOR_L_ENABLE 5
#define MOTOR_R_1_PIN 6
#define MOTOR_R_2_PIN 7
#define MOTOR_L_1_PIN 9
#define MOTOR_L_2_PIN 10
#define LEFT_MOTOR 0
#define RIGHT_MOTOR 1
const int MOTOR_L_DUTY=180;
const int MOTOR_R_DUTY=150;
//#include <line_follower.h>
//#include <robot.h>
//#include <seeed.h>
//static const int LED_PIN = 10;
void setup() {
pinMode(MOTOR_L_ENABLE, OUTPUT); digitalWrite(MOTOR_L_ENABLE, LOW);
pinMode(MOTOR_R_ENABLE, OUTPUT); digitalWrite(MOTOR_R_ENABLE, LOW);
pinMode(MOTOR_L_1_PIN, OUTPUT); digitalWrite(MOTOR_L_1_PIN, LOW);
pinMode(MOTOR_L_2_PIN, OUTPUT); digitalWrite(MOTOR_L_2_PIN, HIGH);
pinMode(MOTOR_R_1_PIN, OUTPUT); digitalWrite(MOTOR_R_1_PIN, LOW);
pinMode(MOTOR_R_2_PIN, OUTPUT); digitalWrite(MOTOR_R_2_PIN, HIGH);
}
// Low-level functions for driving the L and R motors independently...
void L_Fwd() {
digitalWrite(MOTOR_L_1_PIN, LOW);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, 120);
// digitalWrite(MOTOR_L_ENABLE, HIGH);
}
void L_Rev() {
digitalWrite(MOTOR_L_1_PIN, HIGH);
digitalWrite(MOTOR_L_2_PIN, LOW);
analogWrite(MOTOR_L_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_L_ENABLE, HIGH);
}
void L_Stop() {
digitalWrite(MOTOR_L_1_PIN, LOW);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, 0);
// digitalWrite(MOTOR_L_ENABLE, LOW);
}
void L_Brake() {
digitalWrite(MOTOR_L_1_PIN, HIGH);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_L_ENABLE, HIGH);
}
void R_Fwd() {
digitalWrite(MOTOR_R_1_PIN, LOW);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
}
void R_Rev() {
digitalWrite(MOTOR_R_1_PIN, HIGH);
digitalWrite(MOTOR_R_2_PIN, LOW);
analogWrite(MOTOR_R_ENABLE, MOTOR_R_DUTY);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
}
void R_Stop() {
digitalWrite(MOTOR_R_1_PIN, LOW);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, 0);
// digitalWrite(MOTOR_R_ENABLE, LOW);
}
void R_Brake() {
digitalWrite(MOTOR_R_1_PIN, HIGH);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
}
// High-level functions for driving both motors at once:
void Fwd() {
L_Fwd(); R_Fwd();
}
void Rev() {
L_Rev(); R_Rev();
}
void Stop() {
L_Stop(); R_Stop();
}
void Brake() {
L_Brake(); R_Brake();
}
void veerL() {
L_Stop(); R_Fwd();
}
void veerR() {
L_Fwd(); R_Stop();
}
void spinL() {
L_Rev(); R_Fwd();
}
void spinR() {
L_Fwd(); R_Rev();
}
void low_level_test() {
L_Fwd(); delay(2500); L_Stop(); delay(2500);
L_Rev(); delay(2500); L_Stop(); delay(2500);
R_Fwd(); delay(2500); L_Stop(); delay(2500);
R_Rev(); delay(2500); L_Stop(); delay(2500);
}
void high_level_test() {
Fwd(); delay(2500); Stop(); delay(2500);
Rev(); delay(2500); Stop(); delay(2500);
veerL(); delay(2500); Stop(); delay(2500);
veerR(); delay(2500); Stop(); delay(2500);
spinL(); delay(2500); Stop(); delay(2500);
spinR(); delay(2500); Stop(); delay(2500);
delay(5000);
}
void loop() {low_level_test(); high_level_test();}
void loop__() {
L_Fwd();
R_Fwd();
delay(1500);
L_Stop();
R_Stop();
delay(1000);
L_Rev();
R_Rev();
delay(1500);
L_Stop();
R_Stop();
delay(1000);
}
void loop_() {
// digitalWrite(MOTOR_L_ENABLE, HIGH);
analogWrite(MOTOR_L_ENABLE, 180);
delay(2000);
digitalWrite(MOTOR_L_ENABLE, LOW);
delay(2000);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
analogWrite(MOTOR_R_ENABLE, 150);
delay(2000);
digitalWrite(MOTOR_R_ENABLE, LOW);
delay(2000);
}
<file_sep>/Projects/2017/SoccerBots/arduino/buzzer/fnaf.h
//Freddy's Jingle from Five Nights at Freddy's games/small section of Carmen Overture by <NAME>
const int fnafTempo = 110;
const int fnafArrayLength = 37;
float fnaf[fnafArrayLength][2] = {{72,1},{74,0.75},{72,0.25},{69,1},{69,1},
{69,0.75},{67,0.25},{69,0.75},{70,0.25},{69,2},
{70,1},{67,0.75},{72,0.25},{69,2},
{65,1},{62,0.75},{67,0.25},{60,2},
{62,2.5},{70,0.5},{69,0.5},{67,0.5},
{69,0.5},{67,0.5},{69,0.5},{70,0.5},{69,2},
{64,1},{69,1},{69,1},{68,0.75},{71,0.25},
{76,4}};
<file_sep>/Projects/2017/SoccerBots/arduino/sensors_boris/magnetometer.h
/*
Magnetometer
Reads data from the LIS3MDL sensor and calculate a compass heading, aswell as
return the angle to a specified heading
The y-axis points in the forwards direction of the robot for a correct heading
TODO:
- implement correction for magmetic north
*/
/*
The sensor outputs provided by the library are the raw 16-bit values
obtained by concatenating the 8-bit high and low magnetometer data registers.
They can be converted to units of gauss using the
conversion factors specified in the datasheet for your particular
device and full scale setting (gain).
Example: An LIS3MDL gives a magnetometer X axis reading of 1292 with its
default full scale setting of +/- 4 gauss. The GN specification
in the LIS3MDL datasheet (page 8) states a conversion factor of 6842
LSB/gauss (where LSB means least significant bit) at this FS setting, so the raw
reading of 1292 corresponds to 1292 / 6842 = 0.1888 gauss.
*/
#include <Wire.h>
#include <LIS3MDL.h>
#include <math.h>
char report[80];
int cal_x, cal_y;
float target_heading;
float magnetometer_getCompassHeading();
LIS3MDL mag;
LIS3MDL::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32768, -32768, -32768};
float magnetometer_saveHeading() { // stores the compass angle that is the desired direction
target_heading = magnetometer_getCompassHeading();
EEPROM_write_int(EEPROM_TARGET_HEADING, target_heading);
beep();
}
void magnetometer_reset() { // reset the running max and min values for each axis to allow a complete calibration
running_min.x = 32767;
running_min.y = 32767;
running_min.z = 32767;
running_max.x = -32768;
running_max.y = -32768;
running_max.z = -32768;
}
void magnetometer_calculateOrigin(int min_x, int min_y, int min_z, int max_x, int max_y, int max_z) {
cal_x = (max_x + min_x) / 2;
cal_y = (max_y + min_y) / 2;
}
void magnetometer_saveCalibration() { // stores the new calibrated origin in the EEPROM
EEPROM_write_int(EEPROM_MIN_X, running_min.x);
EEPROM_write_int(EEPROM_MIN_Y, running_min.y);
EEPROM_write_int(EEPROM_MIN_Z, running_min.z);
EEPROM_write_int(EEPROM_MAX_X, running_max.x);
EEPROM_write_int(EEPROM_MAX_Y, running_max.y);
EEPROM_write_int(EEPROM_MAX_Z, running_max.z);
beep();
delay(50);
beep();
delay(250);
}
void magnetometer_restoreCalibration() { // restores the calibrated origin stored in the EEPROM
magnetometer_calculateOrigin(EEPROM_read_int(EEPROM_MIN_X), EEPROM_read_int(EEPROM_MIN_Y), EEPROM_read_int(EEPROM_MIN_Z),
EEPROM_read_int(EEPROM_MAX_X), EEPROM_read_int(EEPROM_MAX_Y), EEPROM_read_int(EEPROM_MAX_Z));
//playTune(nokia, nokiaTempo, nokiaArrayLength); FOR BORIS
playTune(mk_shortened, mk_shortened_tempo, mk_shortened_array_length); //FOR SHUTTER
//playTune(sherlock, sherlockTempo, sherlockArrayLength);
/*beep();
delay(50);
beep();
delay(250);*/
}
void magnetometer_beepUntilHeadingSaved() { // beeps the buzzer untill the save heading button is pressed
while (digitalRead(SAVE_HEADING_BUTTON_PIN)) {
beep();
delay(200);
}
noTone(BUZZER);
magnetometer_saveHeading();
}
void magnetometer_calibrateMagnetometer() { // calibrate the magnetometer, the magnetometer must be moved through its full axis of rotation while calibrating
DEBUG("starting magnetometer calibration");
magnetometer_reset();
while(!digitalRead(CALIBRATION_MODE_SWITCH_PIN)){
mag.read();
// minimum values
running_min.x = min(running_min.x, mag.m.x);
running_min.y = min(running_min.y, mag.m.y);
running_min.z = min(running_min.z, mag.m.z);
// maximum values
running_max.x = max(running_max.x, mag.m.x);
running_max.y = max(running_max.y, mag.m.y);
running_max.z = max(running_max.z, mag.m.z);
// print limits
// snprintf(report, sizeof(report), "min: {%+6d, %+6d, %+6d} max: {%+6d, %+6d, %+6d}",
// running_min.x, running_min.y, running_min.z,
// running_max.x, running_max.y, running_max.z);
// DEBUG(report);
}
magnetometer_saveCalibration();
magnetometer_restoreCalibration(); // also calculates the origin
magnetometer_beepUntilHeadingSaved(); // prompt for save heading
DEBUG("ending magnetometer calibration");
}
void magnetometer_read() { // read raw data from magnetometer and adjust from calibration
mag.read();
// adjust raw data for calibration
mag.m.x -= cal_x;
mag.m.y -= cal_y;
// print adjusted values
// snprintf(report, sizeof(report), "M: %6d, %6d, %6d", mag.m.x, mag.m.y, mag.m.z);
// DEBUG(report);
}
float magnetometer_calcAngle(int x, int y) { // calculate the angle of point (x, y)
return degrees(atan2(x, y));
}
float magnetometer_getCompassHeading() { // returns the compass heading from magnetometer, range [0, 360]
magnetometer_read();
float heading = magnetometer_calcAngle(mag.m.x, mag.m.y) * -1; // compass heading is angle clockwise from North, hence the * -1
if (heading < 0) {
return heading + 360.0;
} else {
return heading;
}
}
float magnetometer_getRelativeAngle(float actual_heading) { // returns the angle that the robot is off the target heading, range [-180, 180]
float angle_diff = (actual_heading - target_heading) * -1.0;
DEBUG_NOEOL("Actual heading: "); DEBUG_NOEOL(actual_heading);
DEBUG_NOEOL(" Angle difference: "); DEBUG(angle_diff);
if (angle_diff < -180.0) {
return angle_diff + 360.0;
} else if (angle_diff > 180.0) {
return angle_diff - 360.0;
} else {
return angle_diff;
}
}
int magnetometer_isTargetDirection(float actual_heading) { // checks to see if facing in the general target dirrection
if ((actual_heading < 70.0) && (actual_heading > -70.0)) {
return 1;
} else {
return 0;
}
}
float magnetometer_getAngleToTarget() { // returns the angle needed to turn towards the target heading
return magnetometer_getRelativeAngle(magnetometer_getCompassHeading());
}
void magnetometerTestLoop() {
DEBUG_NOEOL("Angle to desired heading is: ");
DEBUG(magnetometer_isTargetDirection(magnetometer_getAngleToTarget()));
}
void magnetometerSetup() {
// Serial.begin(9600);
// DEBUG("Magnetometer Test");
Wire.begin();
if (!mag.init()) {
DEBUG("Failed to detect and initialize magnetometer!");
while (1);
}
mag.enableDefault();
magnetometer_restoreCalibration();
target_heading = EEPROM_read_int(EEPROM_TARGET_HEADING);
}
<file_sep>/Documentation/Computer Vision/notes.txt
Computer Vision for Info Sci Mechatronics club
There are a variety of image processing and analysis methods that could be useful for projects such as our soccer and rescue robots for 2017. I'll record a plain list of things here, and explore/explain in separate files...
- Object recognition (ball, goal, rescue can, features of the playing field, other robots)
- Lens distortion removal (image warping), for easier recognition of straight (and parallel, perpendicular) lines.
- Stereoscopic imaging: identifying depth (distance) by comparing two images taken from slightly different vantage points (left and right)
It might be possible, given the limited features and locations in the soccer field, to use a single camera and infer position and orientation just from 2D analysis of the perspective.
General Image Processing/Computer Vision
http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf
<file_sep>/Documentation/Arduino/memory-and-EEPROM/memory-and-EEPROM.md
% Arduino EEPROM (and other memory types)
% <NAME> \<mailto:<EMAIL>\>
% 2017-06-29
## Arduino/ATmega/AVR?!
Some preliminary notes about the relationship between Arduino, the ATmega chip family, and the AVR architecture:
* **AVR** is the processor architecture. This is an abstract specification that defines the instruction set, memory model, etc. AVR is an 8-bit architecture, meaning that processor registers are 8 bits in length.
* **ATmega328p, ATmega2560, etc.** are specific types of microcontroller chip made by Atmel, which implement the AVR architecture.
* **Arduino** is a family of hobbyist-friendly circuit boards that integrate an ATmega chip, USB interface, power management, and a set of header pins having a standard layout.
The AVR architecture uses the Harvard memory model (named after the US university), which has separate memory and access buses for data and program code. This is in contrast to the Von Neumann architecture, which has a combined memory for data and code with one memory access bus.
## SI vs. binary multiplier prefixes
In the SI system, prefixes such as kilo, micro, and so on are defined in terms of powers of 10 (kilo = 1000 = `10^3` = `1e3`). However, computer memories are usually arranged in powers of 2, so there is a family of related binary multiplier prefixes that are close to the powers of 10:
----
kilobinary = kibi = ki = 2^10 = 1024
megabinary = mebi = Mi = 2^20 = 1048576
gigabinary = gibi = Gi = 2^30 = 1073741824
terabinary = tebi = Ti = 2^40 = 1099511627776
----
(Note that Frink does not recognise the "kilobinary" and "ki" forms.)
## Arduino memory types, sizes, and characteristics
There are several types of memory built into the microcontroller chips used on the Arduino:
### Registers:
These are the internal working memory of the processor. To perform operations on variables, their values must be loaded into processor registers. The result of operations are also stored in registers prior to being copied back out to RAM.
General-purpose registers are very fast, but there are very few of them (32 in the AVR architecture), and their names are fixed (`R0`..`R31`). Each register is 8 bits in length.
See also: <https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set#Processor_registers>
When programming in assembly language, you address and manipulate registers directly and have to manage their use yourself. When using compiled Arduino C/C++ code, you can name variables how you like and the compiler will take care of mapping them to processor registers.
### Static RAM (SRAM):
This is the working memory of your program. Values of program variables are stored here (when not being worked on by the processor), along with runtime data structures such as the stack and the heap.
The ATmega328 has 2 kiB of SRAM, and the ATmega2560 has 8 kiB. This is a tiny amount compared to a desktop PC, which likely has over a million times as much RAM!
### Flash program memory:
This is where program code is stored. When you upload a sketch, the compiled and linked binary code is written to the chip's flash memory. The program flash memory is non-volatile, so it will remain intact when the chip is powered off. When the chip powers up, it loads and runs whatever program is stored in flash.
The flash memory capacity is 32 kiB on the ATmega328, and 256 kiB on the ATmega2560.
### EEPROM:
This stands for Electrically Eraseable Programmable Read-Only Memory. This memory provides a non-volatile storage that your programs can use. It is a little like a computer's hard drive, only very basic: instead of files and folders, you are limited to reading and writing one byte at a time. EEPROM capacity is also extremely small: the Atmega chips used on Arduino boards provide between 1 and 4 kiB of EEPROM storage.
EEPROM cells have a limited lifespan: around 100,000 write cycles before they wear out.
Arduino-based 3D printers typically use the EEPROM to store machine-specific settings such as the X, Y and Z dimensions, axis homing directions, acceleration settings, etc. A climate-control microcontroller might use the EEPROM for storing set-points for temperature and humidity, or information about what times of the day to run the climate control system.
### Conserving SRAM
The SRAM is very limited on the basic Arduino chips, and you can easily exhaust it by storing lots of strings in your program (e.g. for debugging messages). Your program will likely behave very strangely if it runs out of SRAM (there is no memory checking)! A handy way to save space is to declare string constants as `PROGMEM`. This will cause them to be stored only in program flash memory, not in SRAM. For example:
___
```c
#include <avr/pgmspace.h>
const char GREETING[] PROGMEM = "Welcome to Awesome Firmware v1.2\
(c) 2017 The Visionaries";
// ...
Serial.println(GREETING);
// ...
```
___
(Hmm, I tested this and it doesn't seem to work...also, the `#include` doesn't seem to be necessary.)
See also: <https://www.arduino.cc/en/Reference/PROGMEM>
Using larger data types than necessary is also a waste of memory. If you know that a variable will never hold a value outside the range of 0..255, use a `byte` rather than an `int`.
When logging data, consider streaming the data to a larger host computer via serial or Internet, rather than storing it in SRAM.
## Using the EEPROM
In practice, the EEPROM behaves a lot like a fixed-size non-volatile array of bytes. Since the EEPROM capacity varies from chip to chip, it is useful to be able to find out how much is there (especially if you want to use a lot of it). The `EEPROM.length()` function returns the number of bytes in the EEPROM.
(Hmm, only `EEPROM.length()` doesn't seem to be available in the Arduino version I'm testing on. Apparently this got dropped when the EEPROM library was updated, and was later re-introduced.)
You can also use the precompiler constant `E2END` to find out the last available address on the EEPROM for the selected chip. This value is determined an compile-time rather than run-time, and relies on choosing the correct board type in the Arduino IDE. The size of the EEPROM would be `E2END+1`.
The Arduino API provides the following low-level functions for reading/writing EEPROM data (one byte at a time; the address values are byte-level):
_____________________________________________
```c
void EEPROM.write(int address, byte value)
byte EEPROM.read(int address)
```
_____________________________________________
It also provides these higher-level functions, that allow you to read/write larger/more complex data:
___
```c
EEPROM.put(address, value)
EEPROM.get(address, value)
```
___
However, not all Arduino versions seem to support this. If reading/writing int values (signed or unsigned---but watch for overflow!), you could use the following:
___
```c
void EEPROM_write_int(int address, int value) {
EEPROM.write(address, highByte(value));
EEPROM.write(address + sizeof(byte), lowByte(value));
}
int EEPROM_read_int(int address) {
byte highByte = EEPROM.read(address);
byte lowByte = EEPROM.read(address + sizeof(byte));
return word(highByte, lowByte);
}
// You could combine the two reads and the return into a one-liner:
int EEPROM_read_int(int address) {
return word(EEPROM.read(address), EEPROM.read(address + sizeof(byte)));
}
```
___
Values of type `int` occupy two bytes, so you will need to leave room in your addressing scheme for both bytes. There is nothing stopping you from overwriting part of an `int` in EEPROM, so be careful! You should sketch out your EEPROM addressing scheme before implementing and using it, and document it in your program.
Since EEPROM supports only a limited number of write cycles, you should try to avoid unnecessary writes. To help you with this, the Arduino API provides the `EEPROM.update()` function, which only writes if the data would be changing (it does a read first to see if the write is necessary):
___
```c
EEPROM.update(int address, byte value)
```
___
(This also is absent from the Arduino version I'm testing with!)
You can check the EEPROM contents for data corruption using the CRC function. This won't let you recover or correct the data corruption---only detect it. There is example code here:
<https://www.arduino.cc/en/Tutorial/EEPROMCrc>
## Further reading/reference:
- <https://www.arduino.cc/en/Tutorial/EEPROM>
- <https://www.arduino.cc/en/Reference/EEPROM>
<file_sep>/Projects/2016/MIDIBots/arduino/digital_pin_test/ano/src/sketch.ino
../../digital_pin_test.ino<file_sep>/Projects/2017/SoccerBots/arduino/sensors/nokia.h
//default ringtone on Nokia phones
const int nokiaTempo = 194;
const int nokiaArrayLength = 13;
float nokia[nokiaArrayLength][2] = {{88,0.5},{86,0.5},{78,1},{80,1},
{85,0.5},{83,0.5},{74,1},{76,1},
{83,0.5},{81,0.5},{73,1},{76,1},
{81,4}};
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_template/ano/src/sketch.ino
../../firmware_template.ino<file_sep>/Projects/2017/SoccerBots/python-opencv-picamera-test.py
#!/usr/bin/env python2
# Demo/test of the Python OpenCV bindings (wot I built from source) with the picamera (Python-MMAL) module.
# Based on http://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/
# <NAME>'s excellent picamera library:
from picamera.array import PiRGBArray
from picamera import PiCamera
# The OpenCV library:
import cv2
from time import sleep,time
import sys
import numpy
# Set up camera and a NumPy array wrapper suitable for transferring the image data into OpenCV
target_framerate = 20
# 0.08 s frame capture with 50 Hz target
# Had originally thought 1640 x 922 (scaled down to 820 x 461) would be suitable
# However: "PiCameraResolutionRounded: frame size rounded up from 820x461 to 832x464"
# Perhaps 1640 x 1232 capture, scaled down by 4 to 410 x 308?
# Nope: "PiCameraResolutionRounded: frame size rounded up from 410x308 to 416x320"
# 640 x 360 for 16:9?
# Argh: "PiCameraResolutionRounded: frame size rounded up from 640x360 to 640x368" (360 is not divisible by 16)
capture_res = (1640,922)
#capture_res = (3280,2464)
#capture_res = (1640,1232)
capture_res = (640,480)
capture_res = (320,240)
capture_res = (128,96)
# Nope, even then: PiCameraResolutionRounded: frame size rounded up from 3280x2464 to 3296x2464
# Hmm, but at full res, we can't capture faster than 15 Hz.
# Argh, 1640 is not divisible by 16 either!: "PiCameraResolutionRounded: frame size rounded up from 1640x1232 to 1664x1232"
# So maybe we have to capture at full res (3280x2464)? At least those are div by 16...
#resized_res = (capture_res[0]/4, capture_res[1]/4)
#resized_res = (640,480)
#resized_res = (1640,1232)
# But we need a resolution where x and y are both divisible by 16 that has a usefully scaled down version that's also divisible by 16.
# I think given that the capture resolutions are so limited, don't worry about those or the integer scaling part.
# But we will need the resized resolution to be the correct aspect ratio and divisble by 16 in both axes.
# Ah, here are some:
# 16:9 modes:
resized_res = (768,432)
#resized_res = (512,288)
resized_res = (256,144)
resized_res = (640,480)
resized_res = (320,240)
resized_res = (128,96)
# 4:3 modes:
#resized_res = (512,384)
#camera = PiCamera()
#camera = PiCamera(sensor_mode=4, resolution=capture_res, framerate=target_framerate)
camera = PiCamera(resolution=capture_res, framerate=target_framerate)
camera.iso = 400
camera.shutter_speed = 20000
#camera.shutter_speed = 15000
print("calibrating gain...")
sleep(2)
camera.exposure_mode = 'off'
print("camera.analog_gain = ",camera.analog_gain)
# Now fix the white balace:
print("Hold a white card in front of the camera now!")
sleep(5)
g = camera.awb_gains
print("Thanks; camera.awb_gains = ",g)
camera.awb_mode = 'off'
camera.awb_gains = g
# That's it for the camera setup.
#camera.start_preview(alpha=127)
#sleep(60)
# array wrapper:
rawCapture = PiRGBArray(camera)
# If resizing, you likely have to tell the array how big to be:
#rawCapture = PiRGBArray(camera, size=resized_res)
sleep(0.1)
def capture_still():
# The camera provides different ports for still images and video, specified via use_video_port. Specify False for better quality still images, or True when streaming video.
camera.capture(rawCapture, format="bgr", use_video_port=False, resize=resized_res)
image = rawCapture.array
cv2.imshow("Image", image)
# Image doesn't display until this:
cv2.waitKey(0)
# Oh, wait, do we have to clear it before continuing?!
rawCapture.truncate(0)
# Yes, that was it!
#capture_still()
#exit()
then = 0
now = 0
end_time = 0
# For colour matching testing:
# Helper for converting a decimal <r,g,b> triple into an integer [b,g,r] array:
def bgr(r,g,b):
return [int(round(b*255)), int(round(g*255)), int(round(r*255))]
blue_lo = bgr(0.1, 0.24, 0.4)
blue_hi = bgr(0.2, 0.4, 0.6)
lower = numpy.array(blue_lo, dtype="uint8")
upper = numpy.array(blue_hi, dtype="uint8")
# What about HSV, which worked pretty well for the original SimpleCV attempt?
# OpenCV docs: For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]
# Goal blue H was about 102/180, S=190/255, V=50/255 (or 50/100?)
goal_hsv = (102, 190, 100)
goal_hsv_tolerance = (12, 65, 100)
# Um, does bad stuff happen if the range results in a min below 0 or a max above 255?
# Should the range be applied additively or multiplicatively?
def lower(hsv, hsv_tolerance):
return [float(hsv[0])-hsv_tolerance[0], float(hsv[1])-hsv_tolerance[1], float(hsv[2])-hsv_tolerance[2]]
def upper(hsv, hsv_tolerance):
return [float(hsv[0])+hsv_tolerance[0], float(hsv[1])+hsv_tolerance[1], float(hsv[2])+hsv_tolerance[2]]
goal_hsv_lo = numpy.array(lower(goal_hsv, goal_hsv_tolerance), dtype="uint8")
goal_hsv_hi = numpy.array(upper(goal_hsv, goal_hsv_tolerance), dtype="uint8")
# capture frames from the camera
# CME: can we specify resize with use_video_port=True? Seems so
# Hmm, why is the video capture noticeably dimmer than the still?
# And why is the frame rate so jittery? Hmm, it seems to be slow to capture the next frame every second frame. Setting the capture frame rate low makes it more obvious.
# Hmm, it's not just every second frame that's pausing...and how long the pause is when capturing the new frame depends on the timing of the loop!
# Sometimes there's a delay of over 2 s while restarting the loop!
# Ah-ha: looks like it's the resizing that causes the jitter.
# Note that when use_video_port=False, reading each image takes about 0.3 s!
print("Press 'q' to quit...")
# , resize=resized_res
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
#while True:
#camera.capture_sequence(rawCapture, format="bgr", use_video_port=True, resize=resized_res)
#print(time() - end_time)
#print("start loop")
now = time()
elapsed_time = now - then
sys.stderr.write('Frame rate: ' + str(round(1.0/elapsed_time,1)) + ' Hz\n')
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
#print("copy array")
image = frame.array
#image = rawCapture.array
# show the frame
#print("show raw frame")
#cv2.imshow("Frame", image)
#print(" wait >")
#key = cv2.waitKey(16) & 0xFF
# if the `q` key was pressed, break from the loop
#if key == ord("q"):
# break
# Let's try some basic colour matching:
# Should we convert to HSV first?
# Hmm, it seems that the chroma resolution is quite poor at certain camera settings (low res)...or maybe it's just the lower res exaggerating it.
#print("BGR -> HSV...")
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Remember, it's (B,G,R) otherwise!
mask = cv2.inRange(hsv, goal_hsv_lo, goal_hsv_hi)
#output = cv2.bitwise_and(image, image, mask=mask)
# show the matching area:
#print("show masked frame")
cv2.imshow("Frame", mask)
#print(" wait >")
key = cv2.waitKey(16) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# clear the stream in preparation for the next frame
#print("truncating...")
rawCapture.truncate(0)
then = now
#print("end loop")
#end_time = time()
<file_sep>/Projects/2016/MIDIBots/arduino/midi_input_test/ano/src/sketch.ino
../../midi_input_test.ino<file_sep>/Projects/2017/SoccerBots/stopeverything.sh
#!/bin/sh
killall tclsh
killall pd
killall python
<file_sep>/Projects/2016/MIDIBots/arduino/midi_input_test/midi_input_test.ino
void setup() {
// Set up serial port for MIDI baud rate (31.25 kbit/s):
Serial.begin(31250);
// We might want to use the LED to indicate activity (though don't use delay() unnecessarily (e.g. blink())).
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
flash(); flash(); flash();
}
void loop() {
int readByte;
if (Serial.available() > 0) {
readByte = Serial.read();
if (readByte == 0x90)
flash();
}
}
void ledOn() {digitalWrite(LED_BUILTIN, HIGH);}
void ledOff() {digitalWrite(LED_BUILTIN, LOW);}
void flash() {
ledOn();
delay(50);
ledOff();
}
<file_sep>/Projects/2016/MIDIBots/arduino/drum_roll/ano/src/sketch.ino
../../drum_roll.ino<file_sep>/Projects/2016/MIDIBots/arduino/midi_test/midi_test.ino
// MIDI output testing, CME 2016
// Tempo:
const int del = 100;
//const int del = 200;
//const int del = 60;
//const int switchPin = 2;
//int switchState = 0;
const int ledPin = 13;
// Arrays for the current and previous state of all the key switches:
// Notably, we need to keep the TX pin free for MIDI transmission.
// NOTE: on the Arduino Mega, the big double-row of pins starts has a pair of 5V pins, then digital pins 22 and 23. The last digital pin is 53, and then there are two grounds at the end.
const int numKeys = 56;
const int firstKeyPin = 2;
// NOTE: awkward mismatch of pin numbers and array indexes, since we're not necessarily starting at 0! It's a bit wasteful of memory, but let's just make the array bigger, and ignore any we aren't using, and use the same numbering for the array elements as for the pin numbers for the input switches.
int currSwitchState[numKeys + firstKeyPin];
int prevSwitchState[numKeys + firstKeyPin];
void setup() {
// Set up serial port for MIDI baud rate (31.25 kbit/s):
Serial.begin(31250);
// Serial.begin(9600);
// Serial.println("setup()...");
// pinMode(switchPin, INPUT); digitalWrite(switchPin, HIGH); // Microswitch input, needs internal pull-up resistor.
pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW);
// Set up input pins and initialise switch state arrays:
for (int pin = firstKeyPin; pin <= firstKeyPin + numKeys - 1; pin++) {
// Serial.println(pin);
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);
currSwitchState[pin] = 0;
prevSwitchState[pin] = 0;
}
}
void loop() {
readSwitches();
// switchTest(); delay(2);
// glissando();
// playRandomNote();
// discoBeat();
// hecticBeat();
// playArpeggios();
}
void glissando() {
// play notes from F#-0 (0x1E) to F#-5 (0x5A):
for (int note = 0; note < 128; note ++) {
// Note on channel 1 (0x90), some note value (note), middle velocity (0x45):
playNote(1, note, 100);
delay(50);
// Note on channel 1 (0x90), same note value (note), silent velocity (0x00):
playNote(1, note, 0x00);
// delay(100);
}
}
// This function from example Arduino code:
// plays a MIDI note. Doesn't check to see that
// cmd is greater than 127, or that data values are less than 127:
void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}
// IMO, a more sensible way would be to construct the first byte based on the channel number, and not require the 0x9 to be passed at all:
// NOTE: channel numbers here are the logical user-friendly channel numbers (1..16), not the internal values used to represent them.
void playNote(int channel, int pitch, int velocity) {
// Convert channel to a 4-bit value:
if (channel > 16 || channel < 1) channel = 0;
Serial.write(0x90 | channel);
Serial.write(pitch);
Serial.write(velocity);
}
void playRandomNote() {
int pitch = random(30, 110);
int velocity = random(40, 120);
int duration = random(20, 100);
int pause = random(0, 100);
noteOn(0x90, pitch, velocity);
delay(duration);
noteOn(0x90, pitch, 0); // off
// delay(pause);
}
void playArpeggios() {
int octave = random(0,4) + 4;
int arpDegree = random(0,3);
int note = octave * 12 + scaleDegreeToSemitone(arpeggioDegreeToScaleDegree(arpDegree));
playNote(1, note, 100);
delay(70);
playNote(1, note, 0);
}
int scaleDegreeToSemitone(int scaleDegree) {
if (scaleDegree == 0) return 0;
else if (scaleDegree == 1) return 2;
else if (scaleDegree == 2) return 4;
else if (scaleDegree == 3) return 5;
else if (scaleDegree == 4) return 7;
else if (scaleDegree == 5) return 9;
else if (scaleDegree == 6) return 11;
else return 0;
}
int arpeggioDegreeToScaleDegree(int arpeggioDegree) {
if (arpeggioDegree == 0) return 0;
else if (arpeggioDegree == 1) return 3;
else if (arpeggioDegree == 2) return 5;
else return 0;
}
void discoBeat() {
int velocity = random(64, 128);
playNote(10, 36, velocity); delay(del); playNote(10, 36, 0);
playNote(10, 42, velocity); delay(del); playNote(10, 42, 0);
playNote(10, 38, velocity); delay(del); playNote(10, 38, 0);
playNote(10, 42, velocity); delay(del); playNote(10, 42, 0);
}
void hecticBeat() {
int velocity = random(48, 128);
playNote(10, 36, velocity); delay(del); playNote(10, 36, 0);
playNote(10, 41, velocity); delay(del); playNote(10, 41, 0);
playNote(10, 38, velocity); delay(del); playNote(10, 38, 0);
playNote(10, 41, velocity); delay(del); playNote(10, 41, 0);
}
// Trigger a MIDI note based on an attached switch. We'll use polling for this (so it can be scaled up to a polyphonic keyboard controller), and we'll also need to remember the state of the switch(es) for triggering note on/off.
/*
void switchTest() {
if (!digitalRead(switchPin) != switchState) {
switchState = !switchState;
playNote(1, 69, switchState * 100);
}
digitalWrite(ledPin, switchState);
}
*/
void blink() {
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
}
// Read the state of the input key switches and trigger note on/off MIDI events as necessary.
void readSwitches() {
for (int pin = firstKeyPin; pin <= firstKeyPin + numKeys - 1; pin++) {
currSwitchState[pin] = !digitalRead(pin); // Active-low; negate here.
// digitalWrite(ledPin, currSwitchState[pin]);
if (currSwitchState[pin] != prevSwitchState[pin]) {
// blink();
// playNote(1, 60 + pin, 60);
playNote(1, 36 + pin, currSwitchState[pin] * 100); // Note on/off depending on whether the key is pressed.
}
prevSwitchState[pin] = currSwitchState[pin]; // Store the state for next time.
}
delay(1); // Hold off just a little do reduce spurious note on/off due to switch contact bouncing.
}
<file_sep>/Projects/2016/MIDIBots/arduino/pwm_examples/pwm_3.ino
// MIDI note tests for Mechatronics, CME 2016-03-21
// 1. Loop sanity check. Watch for off-by-one errors!
// 2. Translate note frequency formula into C syntax and check (MIDI note 69 should give 440 Hz).
// 3. Correct integer division in formula!
void setup() {
delay(8000); // safety delay for serial I/O
Serial.begin(9600);
}
void loop() {
for (int n = 0; n < 128; n++) {
float f = 440 * pow(2, (n - 69) / 12.0);
Serial.print(n);
Serial.print(": ");
Serial.println(f);
}
delay(5000);
}
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_synthbot.old/firmware_synthbot.ino
// SynthBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
// NOTE: there's a limit to how low a frequency this can play, given the PWM settings. Note frequencies will jump around below this limit.
// Define pin mappings for the MIDIBot shield:
const int
MIDI_1x_PIN = 2,
MIDI_2x_PIN = 3,
MIDI_4x_PIN = 4,
MIDI_8x_PIN = 5,
MOSFET_PWM_PIN = 6,
SERVO_1_PIN = 9,
SERVO_2_PIN = 10,
SERVO_3_PIN = 11,
MOSFET_2_PIN = 12,
MOSFET_3_PIN = A1, /* not A3 as on the silkscreen! */
MOSFET_4_PIN = A2, /* not A4 as on the silkscreen! */
LED_PIN = 13,
LATENCY_ADJUST_PIN = A0,
SELF_TEST_PIN = A5
;
int
MIDI_channel = 0; // 1..16, 10=drums
// MIDI messages have up to 2 data bytes, which we store in an array:
int dataByte[2], statusByte = 0, i = 0;
void clearData(){
dataByte[0] = 0;
dataByte[1] = 0;
i = 0;
}
// Even though this is only monophonic, it's still useful to keep track of the note currently being played, so that any note-off messages for other notes can be ignored.
int current_note_number = 0;
// Tricky low-level code from Chris for programming the PWM output for precise frequencies...
// On the Mega, we have timer1 attached to pins D11 and D12, D12 being the primary one.
// On "ordinary" Arduinos, it's on pins 9 and 10. On the MIDIBot shield, pin 10 is Servo 2 (middle pin).
// Ideally we'd use the PWM MOSFET output on D6, but that uses Timer 0 and doesn't support frequency-accurate PWM, as far as I can tell.
// This will need an external circuit anyway to limit the current and block DC, so it's not a huge hassle to add a MOSFET circuit (with resistors and protection diode) to this as well. It can be powered from one of the aux 12 V headers.
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
const int OUTPUT_PIN = 12;
const int OUTPUT_PIN_AUX = 11;
#else
const int OUTPUT_PIN = 10;
const int OUTPUT_PIN_AUX = 9;
#endif
// General settings:
const int prescale = 8;
// Some PWM control definitions:
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
// This defines which bits within the TCCRnB register determine the prescale factor:
#define TIMER_PRESCALE_MASK 0xF8 // 0B11111000
// Map desired prescale divider to register bits:
byte timer_prescale_bits(int prescale) {
if (prescale == 1)
return 0x01;
else if (prescale == 8)
return 0x02;
else if (prescale == 64)
return 0x03;
else if (prescale == 256)
return 0x04;
else if (prescale == 1024)
return 0x05;
else
return 0x00; // Error?!
}
// Map MIDI note numbers to frequency in Hz:
float frequency(int note) {
return 440 * pow(2.0, (note - 69) / 12.0);
}
// Function for computing the PWM wrap limit ("top" value) based on the desired frequency (and the CPU clock speed and prescaler setting):
unsigned int top(float frequency) {
return round(F_CPU / (prescale * frequency) - 1);
}
void pwm(float frequency, float duty_cycle) {
TCNT1 = 0; // Reset timer counter
// pwm_off(); // Maybe necessary to avoid stuck at 5 V condition? Nope, not enough...
unsigned int wrap_limit = top(frequency);
OCR1A = wrap_limit;
OCR1B = int(wrap_limit * duty_cycle);
// TCCR1A's timer mode should already be set, so just use TCCR1B to start PWM (is that sufficient?):
TCCR1A = _BV(COM1A0) | _BV(COM1B1) | _BV(WGM11) | _BV(WGM10);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11);
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | timer_prescale_bits(prescale);
}
void pwm_off() {
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | TIMER_CLK_STOP;
TCNT1 = 0;
digitalWrite(OUTPUT_PIN, LOW); // This seems to be necessary to silence it properly (sometimes gets stuck at 5 V otherwise!)
}
void flash(int on_time, int off_time) {
digitalWrite(LED_PIN, HIGH);
delay(on_time);
digitalWrite(LED_PIN, LOW);
delay(off_time);
}
// Routine for displaying a number by blinking the LED (since hardware serial will be taken already by the MIDI comms):
void flash_number(int n) {
delay(500);
// Hundreds:
for (int i = 0; i < (n % 1000 / 100); i++) {
flash(800, 800);
}
delay(500);
// Tens:
for (int i = 0; i < (n % 100 / 10); i++) {
flash(400, 400);
}
delay(500);
// Fastest flashing for the ones:
for (int i = 0; i < (n % 10); i++) {
flash(200, 200);
}
delay(500);
}
// Read MIDI channel DIP switches and store the result:
// NOTE: Freetronics USBDroid has a pull-down resistor on pin D4, which makes that pin unusable! It acts as if D4 is always grounded, i.e. the switch is on.
// Multiply the 4x bit by 4 on a normal Arduino, or 0 to force it off.
void read_MIDI_channel() {
MIDI_channel =
!digitalRead(MIDI_8x_PIN) * 8 +
!digitalRead(MIDI_4x_PIN) * 4 +
!digitalRead(MIDI_2x_PIN) * 2 +
!digitalRead(MIDI_1x_PIN);
}
void self_test() {
// Robot-specific self-test routine goes here
// flash(50, 50); flash(50, 50); flash(50, 50); flash(50, 50);
read_MIDI_channel();
flash_number(MIDI_channel);
pwm(frequency(40), 0.1); delay(250);
pwm(frequency(52), 0.1); delay(250);
pwm(frequency(64), 0.1); delay(250);
pwm(frequency(76), 0.1); delay(250);
pwm_off();
}
void setup()
{
// Set up pin modes for the MIDIBot Shield (input, internal pull-up resistor enabled):
pinMode(MIDI_1x_PIN, INPUT_PULLUP);
pinMode(MIDI_2x_PIN, INPUT_PULLUP);
pinMode(MIDI_4x_PIN, INPUT_PULLUP);
pinMode(MIDI_8x_PIN, INPUT_PULLUP);
// Ditto for self-test button:
pinMode(SELF_TEST_PIN, INPUT_PULLUP);
// TODO: output pins (servos, MOSFETs, LED)
pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW);
pinMode(MOSFET_PWM_PIN, OUTPUT); analogWrite(MOSFET_PWM_PIN, 0);
pinMode(MOSFET_2_PIN, OUTPUT); digitalWrite(MOSFET_2_PIN, LOW);
pinMode(MOSFET_3_PIN, OUTPUT); digitalWrite(MOSFET_3_PIN, LOW);
pinMode(MOSFET_4_PIN, OUTPUT); digitalWrite(MOSFET_4_PIN, LOW);
pinMode(SERVO_1_PIN, OUTPUT); digitalWrite(SERVO_1_PIN, LOW);
pinMode(SERVO_2_PIN, OUTPUT); digitalWrite(SERVO_2_PIN, LOW);
pinMode(SERVO_3_PIN, OUTPUT); digitalWrite(SERVO_3_PIN, LOW);
// Initialise MIDI channel number according to DIP switch settings:
read_MIDI_channel();
flash_number(MIDI_channel);
// Set up MIDI communication:
Serial.begin(31250);
clearData();
// Attach interrupt for self-test button and function:
// attachInterrupt(digitalPinToInterrupt(SELF_TEST_PIN), self_test, FALLING);
// Only available on certain pins? Just poll in main loop instead.
// Flash to indicate startup/ready:
// flash(50, 200); flash(50, 400); flash(50, 200); flash(400, 0);
// or not, since we're flashing the MIDI channel ID number anyway. ;)
// Run self-test at startup as well?
// self_test();
pwm_off();
}
void loop()
{
if (!digitalRead(SELF_TEST_PIN)) {
self_test();
}
process_MIDI();
// test_blink();
// test_button();
// test_flash_number();
// test_MIDI_channel();
// test_MOSFETs();
// test_MOSFETs_cycle();
// test_PWM();
}
void process_MIDI() {
if (Serial.available() > 0) {
int data = Serial.read();
if (data > 127) {
// It's a status byte. Store it for future reference.
statusByte = data;
clearData();
} else {
// It's a data byte.
dataByte[i] = data;
if (statusByte == (0x90 | MIDI_channel) && i == 1) {
// Note-on message received
if (dataByte[1] == 0 && dataByte[0] == current_note_number) {
// Stop note playing
pwm_off();
digitalWrite(LED_PIN, LOW);
analogWrite(MOSFET_PWM_PIN, 0);
} else {
// Start note playing
current_note_number = dataByte[0];
pwm(frequency(current_note_number), dataByte[1] / 127.0 / 2); // TODO: map velocity to PWM duty
// Plus illumination:
digitalWrite(LED_PIN, HIGH);
analogWrite(MOSFET_PWM_PIN, 64);
}
} else if (statusByte == (0x80 | MIDI_channel) && i == 1 && dataByte[0] == current_note_number) {
// Note-off message received
// TODO: also respond to note-on with vel=0 as note-off
// Stop note playing
pwm_off();
digitalWrite(LED_PIN, LOW);
analogWrite(MOSFET_PWM_PIN, 0);
}
i++;
// TODO: error detection if i goes beyond the array size.
}
}
}
void test_blink() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}
void test_button() {
digitalWrite(LED_PIN, !digitalRead(SELF_TEST_PIN));
}
void test_flash_number() {
if (!digitalRead(SELF_TEST_PIN)) {
flash_number(3);
delay(2000);
flash_number(16);
delay(2000);
flash_number(235);
delay(2000);
flash_number(127);
delay(2000);
}
}
void test_MIDI_channel() {
if (!digitalRead(SELF_TEST_PIN)) {
read_MIDI_channel();
Serial.println(MIDI_channel);
flash_number(MIDI_channel);
}
}
void test_MOSFETs() {
if (!digitalRead(SELF_TEST_PIN)) {
analogWrite(MOSFET_PWM_PIN, 64);
digitalWrite(MOSFET_2_PIN, HIGH);
digitalWrite(MOSFET_3_PIN, HIGH);
digitalWrite(MOSFET_4_PIN, HIGH);
} else {
analogWrite(MOSFET_PWM_PIN, 0);
digitalWrite(MOSFET_2_PIN, LOW);
digitalWrite(MOSFET_3_PIN, LOW);
digitalWrite(MOSFET_4_PIN, LOW);
}
}
void test_MOSFETs_cycle() {
digitalWrite(MOSFET_PWM_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_PWM_PIN, LOW);
digitalWrite(MOSFET_2_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_2_PIN, LOW);
digitalWrite(MOSFET_3_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_3_PIN, LOW);
digitalWrite(MOSFET_4_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_4_PIN, LOW);
}
void test_PWM() {
analogWrite(MOSFET_PWM_PIN, 64);
delay(250);
analogWrite(MOSFET_PWM_PIN, 0);
delay(500);
}
<file_sep>/Projects/2017/SoccerBots/testpipe2pd.py
import time
message = 0
def send2pd(message):
print(str(message) + ";" )
while True:
message += 1
send2pd(message)
<file_sep>/Projects/2017/SoccerBots/rpicam-setup.sh
#!/bin/sh
#config raspberry pi camera
v4l2-ctl -c power_line_frequency=1 -c iso_sensitivity_auto=0 -c auto_exposure=1 -c exposure_time_absolute=100 -c white_balance_auto_preset=3 -c iso_sensitivity=4 -c scene_mode=0
<file_sep>/Projects/2016/MIDIBots/kicad/TODO.txt
[ ] Find a footprint for the Molex 8981 power connector with larger through-holes
[ ] Reposition MIDI IN connector in case it interferes with the IOREF and spare header pin above it (present on newer Arduino models).
[ ] Add some more net labels to assist with assigning track styles on PCB.
[ ] Filter and bypass caps as part of each MOSFET circuit? Think DC motor, solenoid, lamp, etc.
[ ] Check for conflict with big USB-B on some Arduino boards
[ ] Remove mounting holes in board?
[ ] Decorative logo? Maybe for rev. 2! (Ideas: musical note logo, smiley face)
--
[Y] Move LAT_ADJ label so it won't be covered by the PC900V IC socket
[Y] Move the servo headers to the left a little
[Y] Label SW2 as CH or MIDI_CH
[Y] Corrected layout orientation of input diode D1
[Y] Moved some part reference labels to be visible
--
[Y] Added Current_Loop track style
[Y] Assigned some more track styles and ran a few additional tracks
--
[Y] Remap pins for MOSFET 3 and 4 to make PCB routing easier
[Y] Break out remaining Arduino pins (there's only about 2!) and put header with a GND in the bottom left corner.
[Y] Fixed unexpected mess with use of old DIP socket footprints
[Y] Various footprints remapped
--
[Y] Flip resistors around MOSFET circuits and reroute tracks
[Y] Add 12V aux track
[Y] Route VCC tracks/zones
[Y] Fixed some unconnected track segments
[Y] Moved some reference labels
[Y] Finalise outline and add ground plane!
--
[Y] Fix weird grounding layout on the decoupling cap on the PC900V.
--
[Y] Remove shield silkscreening to allow more legible text.
[Y] Remove stray "P3" from back silkscreening.
--
[Y] Remove 10 cm x 10 cm alignment markers (in case they will be unwanted)
--
[Y] Move entire board to be nearer the origin (in case that's important for keeping within the size limit)? Or set origin, if that's possible. Paul says the origin should be at the bottom-left of the board. There is also a "Use auxiliary axis as origin" option when plotting to Gerber - relevant? Seems so. Oh, don't forget to do the same with the drill settings!
[Y] Add copyright information and tidy up notice
--
[Y] Tidy up +12V trace supplying the Arduino VIN.
--
[Y] Move the MOSFET output flyback diodes to the other side of the connector and LED, for slightly tidier layout.
--
[Y] Make MOSFET connector labels more consistent.
--
[Y] Swap power and signal lines on the servo connectors!
<file_sep>/Projects/2017/SoccerBots/arduino/dspace_servo_motor_test/dspace_servo_motor_test.ino
//New file location at motor_control.
// Testing the IR reflectance sensors with the DSpace Robot board
// Working towards a line-following robot for Robocup 2017
// Current config (on the 2013 Dalek test-bed) uses pin 2 on each of sensor blocks SENSOR0, SENSOR1, SENSOR2, and SENSOR3.
// These correspond to A0..A3.
// A4 and A5 are also available
// Will need light/dark thresholds for each sensor for calibration...
// ...or just one for all, if they read consistently enough
#define BAUD_RATE 115200
// TODO: this was true of the Dalek, but what about the SoccerBot?:
// Right Dalek motor is considerably more powerful, so we need to be able to regulate each separately...
// Don't go too high with these on the Dalek as it will draw too much current and cause resets!
#include <Servo.h> //incldued for kicker
Servo Kicker;
const int SERVO_PIN = 13; //Servo 2, Pin 2 SDK.
const int KICKER_MIN = 100;
const int KICKER_MAX = 60; //these will need testing.
const int KICKER_DELAY = 1000;
const int MOTOR_L_DUTY=128;
const int MOTOR_R_DUTY=128;
const int DIR_MASK = 0b00100000;
const int MOTOR_MASK = 0b01000000;
const int SPEED_MASK = 0b00011111;
const int MESSAGE_TYPE_MASK = 0b10000000;
const int KICKER_MASK = 0b00000001;
#define MOTOR_R_ENABLE 5
#define MOTOR_L_ENABLE 11
#define MOTOR_R_1_PIN 10
#define MOTOR_R_2_PIN 9
#define MOTOR_L_1_PIN 7
#define MOTOR_L_2_PIN 6
// Unused?
#define LEFT_MOTOR 0
#define RIGHT_MOTOR 1
#define R_LED 11
#define O_LED 2
#define Y_LED 12
#define G_LED 13
#define BUZZER 3
#define L_BUTTON 19
#define R_BUTTON 8
#define DEBUGGING 0
/*
#define debug(message) \
do { if (DEBUGGING) Serial.println(message); } while (0)
*/
#ifdef DEBUGGING
#define DEBUG(x) Serial.println (x)
#else
#define DEBUG(x)
#endif
const int MOTOR_TOGGLE_SWITCH = 18; //physical pin 2 on sensor block 4.
int motors_enabled = 0;
void setup() {
Kicker.attach(SERVO_PIN);
Kicker.write(KICKER_MIN);
pinMode(MOTOR_TOGGLE_SWITCH, INPUT); digitalWrite(MOTOR_TOGGLE_SWITCH, 1);
pinMode(R_LED, OUTPUT); digitalWrite(R_LED, LOW);
pinMode(O_LED, OUTPUT); digitalWrite(O_LED, LOW);
pinMode(Y_LED, OUTPUT); digitalWrite(Y_LED, LOW);
pinMode(G_LED, OUTPUT); digitalWrite(G_LED, LOW);
pinMode(BUZZER, OUTPUT);
pinMode(L_BUTTON, INPUT); digitalWrite(L_BUTTON, HIGH); // or INPUT_PULLUP on newer Arduino
pinMode(R_BUTTON, INPUT); digitalWrite(R_BUTTON, HIGH); // NOTE: hardware problem with Sensor 0 Pin 1 on the Dalek board? It's stuck at only about 1.7 V when pulled high. Oh, hardwired onboard LED! Have now removed resistor R4 to open that circuit. :)
pinMode(MOTOR_L_ENABLE, OUTPUT); digitalWrite(MOTOR_L_ENABLE, LOW);
pinMode(MOTOR_R_ENABLE, OUTPUT); digitalWrite(MOTOR_R_ENABLE, LOW);
pinMode(MOTOR_L_1_PIN, OUTPUT); digitalWrite(MOTOR_L_1_PIN, LOW);
pinMode(MOTOR_L_2_PIN, OUTPUT); digitalWrite(MOTOR_L_2_PIN, HIGH);
pinMode(MOTOR_R_1_PIN, OUTPUT); digitalWrite(MOTOR_R_1_PIN, LOW);
pinMode(MOTOR_R_2_PIN, OUTPUT); digitalWrite(MOTOR_R_2_PIN, HIGH);
Serial.begin(BAUD_RATE);
#ifdef DEBUGGING
Serial.println("\n\nDspace Motor Controller - Info Sci Mechatronics v0.01");
#endif
}
// TODO: we don't have a buzzer on the SoccerBot, so this can go:
// Around 2100-2500 Hz sounds good on the piezo buzzer we have, with 2100 Hz being quite loud (near resonant frequency).
/* digitalWrite(G_LED, HIGH); tone(BUZZER, 2100, 100); delay(200);
digitalWrite(G_LED, LOW); tone(BUZZER, 2200, 100); delay(200);
digitalWrite(G_LED, HIGH); tone(BUZZER, 2300, 100); delay(200);
digitalWrite(G_LED, LOW); tone(BUZZER, 2400, 100); delay(200);
digitalWrite(G_LED, HIGH); tone(BUZZER, 2500, 100); delay(200);
delay(200); digitalWrite(G_LED, LOW);
}
// Audible click for debugging
// WARNING: using click() as defined below makes the right motor not work at all. Shared pins, maybe? Perhaps it needs a delay() of at least the duration of the click?
void click() {
tone(BUZZER, 2100, 2);
}
void beep_bad() {
tone(BUZZER, 2500, 100); delay(200);
tone(BUZZER, 2100, 200); delay(200);
}
void beep_good() {
tone(BUZZER, 2100, 100); delay(100);
tone(BUZZER, 2500, 100); delay(100);
}
*/
// Low-level functions for driving the L and R motors independently...
void L_Fwd() {
if (!motors_enabled) return;
digitalWrite(MOTOR_L_1_PIN, LOW);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_L_ENABLE, HIGH);
}
void L_Rev() {
if (!motors_enabled) return;
digitalWrite(MOTOR_L_1_PIN, HIGH);
digitalWrite(MOTOR_L_2_PIN, LOW);
analogWrite(MOTOR_L_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_L_ENABLE, HIGH);
}
void L_Stop() {
digitalWrite(MOTOR_L_1_PIN, LOW);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, 0);
// digitalWrite(MOTOR_L_ENABLE, LOW);
}
void L_Brake() {
if (!motors_enabled) return;
digitalWrite(MOTOR_L_1_PIN, HIGH);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, MOTOR_L_DUTY);
// digitalWrite(MOTOR_L_ENABLE, HIGH);
}
void R_Fwd() {
if (!motors_enabled) return;
digitalWrite(MOTOR_R_1_PIN, LOW);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, MOTOR_R_DUTY);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
}
void R_Rev() {
if (!motors_enabled) return;
digitalWrite(MOTOR_R_1_PIN, HIGH);
digitalWrite(MOTOR_R_2_PIN, LOW);
analogWrite(MOTOR_R_ENABLE, MOTOR_R_DUTY);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
}
void R_Stop() {
digitalWrite(MOTOR_R_1_PIN, LOW);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, 0);
// digitalWrite(MOTOR_R_ENABLE, LOW);
}
void R_Brake() {
if (!motors_enabled) return;
digitalWrite(MOTOR_R_1_PIN, HIGH);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, MOTOR_R_DUTY);
// digitalWrite(MOTOR_R_ENABLE, HIGH);
}
void L_Drive(float speed){
if (!motors_enabled) return;
if (speed < 0){
digitalWrite(MOTOR_L_1_PIN, HIGH);
digitalWrite(MOTOR_L_2_PIN, LOW);
}else{
digitalWrite(MOTOR_L_1_PIN, LOW);
digitalWrite(MOTOR_L_2_PIN, HIGH);
}
analogWrite(MOTOR_L_ENABLE, (int) round(speed * MOTOR_L_DUTY));
}
void R_Drive(float speed){
if (!motors_enabled) return;
if (speed < 0){
digitalWrite(MOTOR_R_1_PIN, HIGH);
digitalWrite(MOTOR_R_2_PIN, LOW);
}else{
digitalWrite(MOTOR_R_1_PIN, LOW);
digitalWrite(MOTOR_R_2_PIN, HIGH);
}
analogWrite(MOTOR_R_ENABLE, (int) round(speed * MOTOR_R_DUTY));
}
// High-level functions for driving both motors at once:
void Veer(float left_speed, float right_speed){
L_Drive(left_speed); R_Drive(right_speed);
}
void Fwd() {
L_Fwd(); R_Fwd();
}
void Rev() {
L_Rev(); R_Rev();
}
void Stop() {
L_Stop(); R_Stop();
}
void Brake() {
L_Brake(); R_Brake();
}
void veerL() {
L_Stop(); R_Fwd();
}
void veerR() {
L_Fwd(); R_Stop();
}
void spinL() {
L_Rev(); R_Fwd();
}
void spinR() {
L_Fwd(); R_Rev();
}
void L_Spd(int speed, bool dir) {
if (!motors_enabled) {speed = 0;}
digitalWrite(MOTOR_L_1_PIN, dir);
digitalWrite(MOTOR_L_2_PIN, !dir);
analogWrite(MOTOR_L_ENABLE, speed);
}
void R_Spd(int speed, bool dir) {
if (!motors_enabled) {speed = 0;}
digitalWrite(MOTOR_R_1_PIN, dir);
digitalWrite(MOTOR_R_2_PIN, !dir);
analogWrite(MOTOR_R_ENABLE, speed);
}
void kick(){
Kicker.write(KICKER_MAX);
delay(KICKER_DELAY);
Kicker.write(KICKER_MIN);
delay(KICKER_DELAY);
}
void kicker_move(int direction) {
Kicker.write(direction? KICKER_MAX: KICKER_MIN);
}
/*
void calc_track(int move)
{
if (backtrack[move][0] > 0)
{
backtrack[move][0]++;
}
else
{
for (int i = 0; i < 5; i++)
{
for (int j = 9; j > 0; j--)
{
backtrack[i][j] = backtrack[i][j-1];
}
}
for (int i = 0; i < 5; i++)
{
backtrack[i][0] = 0;
}
backtrack[move][0] = 1;
}
}
void retrace()
{
for (int i = 0; i < 10; i++)
{
if (backtrack[i][0] > 0)
{
//spin right, so spin left
for (int j = 0; j < backtrack[i][0]; j++)
spinL();
}
if (backtrack[i][1] > 0)
{
//veer right, so veer left
for (int j = 0; j < backtrack[i][1]; j++)
Veer(0.7,1);
}
if (backtrack[i][2] > 0)
{
//forward, so move back
for (int j = 0; j < backtrack[i][2]; j++)
Rev();
}
if (backtrack[i][3] > 0)
{
//veer left, so veer right
for (int j = 0; j < backtrack[i][3]; j++)
Veer(1,0.7);
}
if (backtrack[i][4] > 0)
{
//spin left, so spin right
for (int j = 0; j < backtrack[i][4]; j++)
spinR();
}
}
}
*/
// For detecting the line, we'll have a function to read an analog value for each sensor and compare with a light/dark threshold.
/*
void control() {
// digitalWrite(Y_LED, LOW);
l_line = isBlack(L_PIN);
m_line = isBlack(M_PIN);
r_line = isBlack(R_PIN);
debug_line_sensors_with_LEDs();
// TODO: could shift and combine the boolean values for more readable code
// e.g. switch bits ... 0b000 -> lost ... 0b010 -> fwd ...
if (!l_line && !m_line && !r_line) {
DEBUG("Lost!");
// Would be nice to light red LED if lost.
// digitalWrite(Y_LED, HIGH);
// beep_bad();
// Fwd();
Rev();
// Veer(-0.9,-0.7); // TODO: figure out why the left motor doesn't work here.
// retrace();
}
if (!l_line && !m_line && r_line) {
DEBUG("spin right");
spinR();
// calc_track(0);
}
if (!l_line && m_line && !r_line) {
DEBUG("fwd");
// beep_good();
Fwd();
// calc_track(2);
}
if (!l_line && m_line && r_line) {
DEBUG("veer right");
Veer(1.0,0.8);
// calc_track(1);
}
if ( l_line && !m_line && !r_line) {
DEBUG("spin left");
spinL();
// calc_track(4);
}
if ( l_line && !m_line && r_line) {
DEBUG("?!");
// digitalWrite(Y_LED, HIGH);
Stop();
// calc_track(1);
}
if ( l_line && m_line && !r_line) {
DEBUG("veer left");
Veer(0.8,1.0);
// calc_track(3);
}
if ( l_line && m_line && r_line) {
DEBUG("perpendicular?!");
// digitalWrite(Y_LED, HIGH);
// Fwd();
Veer(1.0,0.6);
// calc_track(2);
}
}
void toggleLED(){
led_state = !led_state;
digitalWrite(G_LED, led_state);
}
*/
/*void motor_control(){
if(Serial.available() > 0){
int data = Serial.read();
if((data&MOTOR_MASK)>>7 == 1){
R_Spd((data&SPEED_MASK)<<2, (data&DIR_MASK)>>6);
Serial.println("R forward");
Serial.println((data&SPEED_MASK)<<2);
}
else{
L_Spd((data&SPEED_MASK)<<2, (data&DIR_MASK)>>6);
Serial.println("L forward");
Serial.println((data&SPEED_MASK)<<2);
}
}
}
void test_loop() {
//TODO: Add servo control code.
if (!digitalRead(MOTOR_TOGGLE_SWITCH)) {motors_enabled = 1;}
if (digitalRead(MOTOR_TOGGLE_SWITCH)) {motors_enabled = 0;}
if (!motors_enabled) {Stop();}else(){motor_control();}
//delay(CYCLE_TIME);
}
*/
void motor_control(){
if (Serial.available() > 0) {
int data = Serial.read();
if ((data&MESSAGE_TYPE_MASK)>>7==0){
kicker_move(data&KICKER_MASK);
}else{
if ((data&MOTOR_MASK)>>6) {
R_Spd((data&SPEED_MASK)<<3, (data&DIR_MASK)>>5);
Serial.println("R forward (DIR, Speed): ");
Serial.println((data&DIR_MASK)>>5);
Serial.println((data&SPEED_MASK)<<3);
} else {
L_Spd((data&SPEED_MASK)<<3, (data&DIR_MASK)>>5);
Serial.println("L forward (DIR, Speed): ");
Serial.println((data&DIR_MASK)>>5);
Serial.println((data&SPEED_MASK)<<3);
}
}
} else {
if (!motors_enabled) {Stop();}
}
}
void servo_midpoint(){
Kicker.write(95); // TODO: fix hardcoding
}
void loop(){
motors_enabled = !digitalRead(MOTOR_TOGGLE_SWITCH);
motor_control();
}
void _loop() {
motors_enabled = !digitalRead(MOTOR_TOGGLE_SWITCH);
Serial.println(motors_enabled);
Fwd();
delay(1000);
Stop();
kicker_move(1);
delay(500);
Rev();
delay(1000);
Stop();
kicker_move(0);
delay(500);
}
<file_sep>/Projects/2018/Rubik's Cube/stepper_test/stepper_test.ino
const int steps_per_rev = 200;
const int degrees_per_step = 360 / steps_per_rev;
const int motor_pin = 10;
void spin(float rpm, float num_rotations) {
float min_delay = 300/rpm - 1;
for(int i = 0; i <= num_rotations*200; i++) {
digitalWrite(motor_pin, HIGH);
delay(min_delay);
digitalWrite(motor_pin, LOW);
delay(1);
}
}
void accel(float rpm, float ramp_up) {
for(float current_rpm = 0; current_rpm <= rpm; current_rpm += rpm / 10) {
spin(current_rpm, ramp_up/10);
}
}
void decel(float initial_rpm, float ramp_down) {
for(float current_rpm = initial_rpm; current_rpm >= 0; current_rpm -= initial_rpm / 10) {
spin(current_rpm, ramp_down);
}
digitalWrite(motor_pin, HIGH);
}
void ninety() { //total: 0.25 rotations
accel(10,);
spin(10,);
decel(10,);
}
void setup() {
pinMode(motor_pin, OUTPUT);
accel(10);
}
void loop() {
spin(10, 100);
//digitalWrite(motor_pin, HIGH);
}
<file_sep>/Projects/2017/SoccerBots/arduino/sensors_boris/ultrasonic.h
// NOTE: DFRobot sensor board must be jumpered correctly for TTL operation and have been programmed (EEPROM via serial) to passive PWM mode!
// See https://www.dfrobot.com/wiki/index.php/URM37_V3.2_Ultrasonic_Sensor_(SKU:SEN0001)
const int trig = 5;
const int pwm = 8;
const int unit_division_factor = 40; // Supposedly 50 us/cm but Tobias found that 40 gave better accuracy.
int us_distance;
const int RANGE_SENSOR_TIMEOUT = 15000; // microseconds for pulseIn() timeout (to avoid excessive blocking delay)
void ultrasonic_setup() {
pinMode(trig, OUTPUT); digitalWrite(trig, HIGH);
pinMode(pwm, INPUT);
}
int getUSDistance() {
digitalWrite(trig, LOW);
delayMicroseconds(10);
digitalWrite(trig, HIGH);
us_distance = pulseIn(pwm, LOW, RANGE_SENSOR_TIMEOUT);
return us_distance / unit_division_factor;
}
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_synthbot/firmware_synthbot.ino
// SynthBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
// NOTE: there's a limit to how low a frequency this can play, given the PWM settings. Note frequencies will jump around below this limit.
/*
* TODO:
* [ ] Fix note-playing glitch at startup (first note is a weird bleep). Is it due to calling pwm_off() at startup? Should we always play a dummy test tone at startup?
* [ ] Also, even with a duty cycle of 0 it doesn't shut off completely. This appears to explain the problem: http://stackoverflow.com/questions/23853066/how-to-achieve-zero-duty-cycle-pwm-in-avr-without-glitches
*/
#include <MIDIBot.h>
MIDIBot synthBot;
int current_note_number = 0;
// Tricky low-level code from Chris for programming the PWM output for precise frequencies...
// There's a good explanation of how this works here:
// http://maxembedded.com/2011/08/avr-timers-pwm-mode-part-i/
// On the Mega, we have timer1 attached to pins D11 and D12, D12 being the primary one.
// On "ordinary" Arduinos, it's on pins 9 and 10. On the MIDIBot shield, pin 10 is Servo 2 (middle pin).
// Ideally we'd use the PWM MOSFET output on D6, but that uses Timer 0 and doesn't support frequency-accurate PWM, as far as I can tell.
// This will need an external circuit anyway to limit the current and block DC, so it's not a huge hassle to add a MOSFET circuit (with resistors and protection diode) to this as well. It can be powered from one of the aux 12 V headers.
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
const int OUTPUT_PIN = 12;
const int OUTPUT_PIN_AUX = 11;
#else
const int OUTPUT_PIN = 10;
const int OUTPUT_PIN_AUX = 9;
#endif
// General settings first:
// The prescale is applied to the CPU clock (F_CPU) by frequency division.
// Only certain values are supported: /1, /8, /64, /256, /1024
const int prescale = 8;
// Some PWM control definitions:
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
// This defines which bits within the TCCRnB register determine the prescale factor:
#define TIMER_PRESCALE_MASK 0xF8 // 0B11111000
// Map desired prescale divider to register bits:
byte timer_prescale_bits(int prescale) {
if (prescale == 1)
return 0x01;
else if (prescale == 8)
return 0x02;
else if (prescale == 64)
return 0x03;
else if (prescale == 256)
return 0x04;
else if (prescale == 1024)
return 0x05;
else
return 0x00; // Error?!
}
// Map MIDI note numbers to frequency in Hz:
float frequency(int note) {
return 440 * pow(2.0, (note - 69) / 12.0);
}
// Function for computing the PWM wrap limit ("top" value) based on the desired frequency (and the CPU clock speed and prescaler setting):
unsigned int top(float frequency) {
return round(F_CPU / (prescale * frequency) - 1);
}
void pwm(float frequency, float duty_cycle) {
TCNT1 = 0; // Reset timer counter
// pwm_off(); // Maybe necessary to avoid stuck at 5 V condition? Nope, not enough...
unsigned int wrap_limit = top(frequency);
OCR1A = wrap_limit;
OCR1B = int(wrap_limit * duty_cycle);
// TCCR1A's timer mode should already be set, so just use TCCR1B to start PWM (is that sufficient?):
TCCR1A = _BV(COM1A0) | _BV(COM1B1) | _BV(WGM11) | _BV(WGM10);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11);
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | timer_prescale_bits(prescale);
}
void pwm_off() {
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | TIMER_CLK_STOP;
TCNT1 = 0;
digitalWrite(OUTPUT_PIN, LOW); // This seems to be necessary to silence it properly (sometimes gets stuck at 5 V otherwise!)
}
void self_test() {
// Robot-specific self-test routine goes here
pwm(frequency(40), 0.1); delay(250);
pwm(frequency(52), 0.1); delay(250);
pwm(frequency(64), 0.1); delay(250);
pwm(frequency(76), 0.1); delay(250);
pwm_off();
}
void setup()
{
synthBot.begin();
pwm_off();
}
void loop()
{
synthBot.process_MIDI();
}
void note_on(int note, int velocity){
// Start note playing
current_note_number = note; // Store current note for future reference (since we're monophonic)
// We map MIDI velocity to PWM duty cycle. Divide by two since the upper half (1..0.5) sounds the same as the lower half (0..0.5).
pwm(frequency(current_note_number), velocity / 127.0 / 2.0);
// Plus illumination:
digitalWrite(LED_PIN, HIGH);
analogWrite(MOSFET_PWM_PIN, 64);
}
void note_off(int note, int velocity){
// Because this is monophonic, we only want to turn the note off if the note-off message we just received is for the note we're currently playing.
// That is, ignore any note-offs for notes other than the current one.
if (note == current_note_number) {
pwm_off();
digitalWrite(LED_PIN, LOW);
analogWrite(MOSFET_PWM_PIN, 0);
}
}
<file_sep>/Documentation/Arduino/EEPROM_demo/EEPROM_demo.ino
#include <EEPROM.h>
void setup() {
Serial.begin(9600);
Serial.println("EEPROM demo");
/*
// Not available in the Arduino version I'm using for testing.
Serial.print("EEPROM length = ");
Serial.print(EEPROM.length());
Serial.println(" bytes");
*/
// Alternatively, you can also determine the EEPROM size at compile time (which relies on the board type being correctly selected when you compile):
Serial.print("EEPROM length = ");
Serial.print(E2END + 1);
Serial.println(" bytes");
}
void stop() {while(1) {}}
// To write an int to EEPROM requires two write() calls, since write() works only in bytes and an int is two.
// Not sure whether to have address be a specific byte address or to multiply by sizeof(int) within the functions to create a virtual addressing scheme for int values only.
// Probably safer to leave as raw byte addresses in case we have to mix and match, but watch for accidental overwriting!
void EEPROM_write_int(int address, int value) {
EEPROM.write(address, highByte(value));
EEPROM.write(address + sizeof(byte), lowByte(value));
}
// Ditto for reading:
int EEPROM_read_int(int address) {
/*
byte highByte = EEPROM.read(address);
byte lowByte = EEPROM.read(address + sizeof(byte));
return word(highByte, lowByte);
*/
// Or simply:
return word(EEPROM.read(address), EEPROM.read(address + sizeof(byte)));
}
// TODO: ditto for unsigned int? Or will this approach work for both? Note that overflows can happen silently, e.g.
void loop() {
// Writing a single byte:
EEPROM.write(0, 42);
Serial.print(EEPROM.read(0));
Serial.println();
// Writing a multi-byte value:
int val = 12345;
// int val = 0;
EEPROM.write(0,val); // NOTE: only writes the first byte!
Serial.print(EEPROM.read(0));
Serial.print(" ");
Serial.print(EEPROM.read(1));
Serial.println();
// EEPROM I/O using the higher-level update() and get() functions:
// Hmm, also not available in the Arduino version I'm using here. :(
// Will use DIY functions for reading/writing int values instead...
val = -12345;
int out = 0;
// EEPROM.update(0,val);
// EEPROM.put(0,val);
EEPROM_write_int(0, val);
out = EEPROM_read_int(0);
// EEPROM.get(0,out);
Serial.print(out);
Serial.println();
// Dump out the entire EEPROM contents:
for (int addr = 0; addr < E2END; addr++) {
Serial.print(addr, HEX);
Serial.print(' ');
Serial.println(EEPROM.read(addr), HEX);
}
stop();
}
<file_sep>/Projects/2017/SoccerBots/a_blob_test_cv2.py
import cv2
import numpy as np;
import camera_setup
# Read image
execfile("camera_setup.py")
camera.capture(rawCapture, format="bgr")
image = rawCapture.array
im = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Set up the detector with default parameters.
params = cv2.SimpleBlobDetector_Params()
# Change thresholds
params.minThreshold = 10; # the graylevel of images
params.maxThreshold = 200;
params.filterByColor = True
params.blobColor = 255
# Filter by Area
params.filterByArea = False
params.minArea = 10000
params.filterByInertia = False
params.filterByConvexity = False
detector = cv2.SimpleBlobDetector(params)
# Detect blobs.
keypoints = detector.detect(im)
print keypoints
# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(im, keypoints, numpy.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
largest_blob = [0,0]
x = 0
for key in keypoints:
if key.size > largest_blob[1]:
largest_blob[0] = x
largest_blob[1] = key.size
x = x+1
print largest_blob
# Show keypoints
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)
<file_sep>/Projects/2017/SoccerBots/arduino/sensors/sensors.ino
// TODO: main statement of the purpose of this code!
#include <LIS3MDL.h>
#include <Wire.h>
#include <math.h>
#include <EEPROM.h>
#include <HTInfraredSeeker.h>
#define SHUTTER 1
#define DEBUGGING 0
const int NUM_SENSORS = 8;
const int analog_sensor_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7};
const int ir_sensor_angles[] = {180, -107, -80, -53, -27, 0, 27, 53, 80, 107};
float ir_values[NUM_SENSORS];
const float IR_GAIN_THRESHOLD = 0.5; // For culling reflections, hopefully
const int IR_THRESHOLD = 980; // About 0.15 after converting to 0..1 float looked about right, which would be ~870 raw. In practice, with no IR ball present, we never see a raw value less than 1000
const int CALIBRATION_MODE_SWITCH_PIN = 2;
const int SAVE_HEADING_BUTTON_PIN = 7;
const int EEPROM_MIN_X = 0;
const int EEPROM_MIN_Y = 2;
const int EEPROM_MIN_Z = 4;
const int EEPROM_MAX_X = 6;
const int EEPROM_MAX_Y = 8;
const int EEPROM_MAX_Z = 10;
const int EEPROM_TARGET_HEADING = 12;
const int hall_effect = A9;
const int BUZZER = 10;
int ball_detected = 0;
float ball_angle = 0;
float ball_distance;
int front_range = 0;
int back_range = 0; // so far unused
float angle_to_goal = 0;
int calibration_mode_switch = 0;
int light_sensor = 0;
int crotchet;
#if DEBUGGING ==1
#define DEBUG(x) Serial.println (x)
#define DEBUG_NOEOL(x) Serial.print (x)
#else
#define DEBUG(x)
#define DEBUG_NOEOL(x)
#endif
#include "nokia.h"
#include "mk_shortened.h"
#include "sherlockShort.h"
#include "magnetometer.h"
#include "ultrasonic.h"
#include "reflectance.h"
// int ir_val;
const float TAU = 2 * PI;
// To write an int to EEPROM requires two write() calls, since write() works only in bytes and an int is two.
// Not sure whether to have address be a specific byte address or to multiply by sizeof(int) within the functions to create a virtual addressing scheme for int values only.
// Probably safer to leave as raw byte addresses in case we have to mix and match, but watch for accidental overwriting!
void EEPROM_write_int(int address, int value) {
EEPROM.write(address, highByte(value));
EEPROM.write(address + sizeof(byte), lowByte(value));
}
// Ditto for reading:
int EEPROM_read_int(int address) {
/*
byte highByte = EEPROM.read(address);
byte lowByte = EEPROM.read(address + sizeof(byte));
return word(highByte, lowByte);
*/
// Or simply:
return word(EEPROM.read(address), EEPROM.read(address + sizeof(byte)));
}
void setup() {
for(int n=0; n<NUM_SENSORS; n++) {
pinMode(analog_sensor_pins[n], INPUT);
}
pinMode(CALIBRATION_MODE_SWITCH_PIN, INPUT_PULLUP);
pinMode(SAVE_HEADING_BUTTON_PIN, INPUT_PULLUP);
pinMode(hall_effect, INPUT);
pinMode(BUZZER,OUTPUT);
Serial.begin(115200);
Serial.println("Shutter Starting");
InfraredSeeker::Initialize();
magnetometerSetup();
ultrasonic_setup();
}
void test_loop() {
for(int n=0; n<=NUM_SENSORS; n++) {
DEBUG_NOEOL(analogRead(analog_sensor_pins[n]) + " ");
}
DEBUG();
delay(50);
}
void loopy() {
get_ball_angle();
delay(500);
}
void loop() {
calibration_mode_switch = digitalRead(CALIBRATION_MODE_SWITCH_PIN);
if (!calibration_mode_switch) {
magnetometer_calibrateMagnetometer();
}
if (!digitalRead(SAVE_HEADING_BUTTON_PIN)) { // allows the heading to be saved during use
magnetometer_saveHeading();
}
readReflectance();
//readIRsensors();
//printIRsensors();
get_ball_angle();
angle_to_goal = magnetometer_getAngleToTarget();
ball_detected = 1;
//Serial.println("Sending Output");
send_output();
#if DEBUGGING == 1
delay(2000);
#else
delay(20);
#endif
}
void beep() {
tone(BUZZER, 3600);
delay(100);
noTone(BUZZER);
}
float frequency(int note) {
return 440 * pow(2.0, (note - 69) / 12.0);
}
void playNote(int pitch, int duration) {
tone(BUZZER, (int)round(frequency(pitch)), duration);
delay(duration+5);
noTone(BUZZER);
delay(5);
}
void setNoteDurations(int bpm) {
crotchet = 60000 / bpm;
}
void playTune(float tune[][2], int tempo, int arrayLength) {
setNoteDurations(tempo);
for(int x=0; x<arrayLength; x+=1) {
if(tune[x][0] == 0) {
delay(tune[x][1]*crotchet);
} else {
playNote(tune[x][0], tune[x][1]*crotchet);
}
}
}
void printIRsensors() { // used for debugging
DEBUG_NOEOL("Raw sensor readings: ");
for (int i=0; i<NUM_SENSORS; i++) {
DEBUG_NOEOL(ir_values[i]);
DEBUG_NOEOL(" ");
}
DEBUG();
}
void send_output() {
Serial.print(ball_detected);Serial.print(" ");
Serial.print(ball_angle);Serial.print(" ");
Serial.print(ball_distance);Serial.print(" ");
Serial.print(analogRead(hall_effect));Serial.print(" ");
Serial.print(back_range);Serial.print(" ");
Serial.print(angle_to_goal);Serial.print(" ");
Serial.print(calibration_mode_switch);Serial.print(" ");
Serial.print(reflectance);Serial.print(" ");
Serial.println(";");
}
int posneg(int input) {
if(input > 180) {
return(input - 360);
}
return input;
}
float get_ball_angle() {
DEBUG("ball angle called!");
int small=2000;
int sens=0;
for(int x=0; x<NUM_SENSORS; x++) {
//Serial.print(analogRead(analog_sensor_pins[x]));
//Serial.print(" ");
if(analogRead(analog_sensor_pins[x]) < small) {
small=analogRead(analog_sensor_pins[x]);
sens=x;
}
}
if(small>900) {
ball_detected = 0;
ball_angle = 999;
} else {
ball_detected = 1;
ball_angle = sens*45;
ball_angle = posneg(ball_angle);
InfraredResult InfraredBall = InfraredSeeker::ReadAC();
ball_distance = InfraredBall.Strength;
//ball_angle = ir_sensor_angles[InfraredBall.Direction];
}
//Serial.print(ball_angle);
//Serial.println("");
}
<file_sep>/Tools/Arduiglue/Makefile
# BIN=arduiglue-arduino-folder-setup
install:
cp -v arduiglue-arduino-folder-setup /usr/local/bin
cp -v arduiglue-arturo-folder-setup /usr/local/bin
<file_sep>/Projects/2017/SoccerBots/picamera-test.py
#!/usr/bin/env python
from time import sleep
from picamera import PiCamera
print("Starting camera...")
# Recommended parameters for initialisation: sensor_mode, resolution, framerate, framerate_range, and clock_mode
camera = PiCamera(resolution=(1640,922), framerate=25)
# Pi Camera v2 Modes:
# #2 is 3280 x 2464, full FoV, 4:3
# #4 is 1640 x 1232, full FoV, 4:3
# #5 is 1640 x 922, full H FoV, 16:9
#camera.resolution = (1640, 922)
camera.iso = 400
#camera.start_preview()
# Pause briefly to allow automatic settings to settle:
# NOTE:
# <<
# Exposure mode 'off' is special: this disables the camera's automatic gain control, fixing the values of digital_gain and analog_gain.
# Please note that these properties are not directly settable (although they can be influenced by setting iso prior to fixing the gains), and default to low values when the camera is first initialized. Therefore it is important to let them settle on higher values before disabling automatic gain control otherwise all frames captured will appear black.
# >>
print("camera.exposure_speed = ",camera.exposure_speed)
# Is this measured in microseconds?
# 1 / (28649 microseconds) is about 35 Hz..?!
#camera.shutter_speed = camera.exposure_speed
# Can't set exposure_speed manually? Only shutter_speed?
print("setting shutter_speed...")
#camera.exposure_speed = 100000
# 1 / (20 Hz) = 50000 microseconds
#camera.shutter_speed = 50000
# 1 / (25 Hz) = 40000 microseconds
#camera.shutter_speed = 40000
# 1 / (50 Hz) = 20000 microseconds
camera.shutter_speed = 20000
# 1 / (100 Hz) = 10000 microseconds
#camera.shutter_speed = 10000
# Give analog and digital gains time to adjust...
print("recalibrating...")
sleep(2)
camera.exposure_mode = 'off'
#print("camera.analog_gain = ",camera.analog_gain)
# ~7.5 indoors under fluorescent lighting
#camera.analog_gain = 8
#camera.analog_gain = Fraction(241, 32)
print("Hold a white card in front of the camera now!")
sleep(5)
g = camera.awb_gains
print("camera.awb_gains = ",g)
camera.awb_mode = 'off'
camera.awb_gains = g
#camera.rotation = 180
# TODO: fix focus settings? Ah, this requires a hardware adjustment! The cameras are set to focus at infinity from the factory, but I've 3D printed a couple of wrenches for adjusting it.
print("You can take away the white card now. :)")
#camera.capture('picamera-test.jpg', resize=(820,461))
# .resize()
camera.start_preview(alpha=127)
# Can we use resize with other capture functions as well? Seems so..also with start_recording().
#camera.capture_sequence(['image%02d.jpg' % i for i in range(99)], resize=(820,461))
# What's the best way to capture for sharing with SimpleCV or OpenCV? A shell pipeline? A socket? A NumPy array?
sleep(3600)
# Cature to a video file:
# Note that the video file is raw h.264, with no frame rate information!
#camera.start_recording('my_video.h264')
#camera.wait_recording(60)
#camera.stop_recording()
<file_sep>/Tools/Arduiglue/arduiglue-arturo-folder-setup
#!/bin/sh
# Take an existing Arduino IDE compatible project and set it up for use also with Arturo/ano.
# Command-line argument is expected to be the path to the directory containing an existing Arduino IDE project.
# e.g.
# arduiglue-arturo-folder-setup ~/Documents/Arduino/Blink
# Or, pass no argument and have it work on the current directory.
# We create an "ano" folder within that folder to satisfy Arturo's `ano init` requirement for an empty folder.
# We then replace the default ano sketch with a symlink to the existing Arduino sketch file.
# TODO:
# [ ] Make safe for with space-containing filenames/paths.
# [ ] Optionally file everything away in the default sketchbook folder?
SKETCH_PATH=${1:-$(pwd)}
SKETCH_NAME=$(basename $SKETCH_PATH)
#SKETCH_NAME="$(basename $(dirname $SKETCH_PATH))"
cd $SKETCH_PATH
mkdir -v ano
cd ano
ano init
cd src
rm -v sketch.ino
ln -s ../../$SKETCH_NAME.ino sketch.ino
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_whistlebot/firmware_whistlebot.ino
// WhistleBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
// Define pin mappings for the MIDIBot shield:
#include <Servo.h>
#include <MIDIBot.h>
MIDIBot whistleBot;
Servo valve;
Servo slide;
int pos = 0; // variable to store the servo position
const int VALVE_MIN = 92;
const int VALVE_MAX = 105;
const int
VALVE_0 = 92, // OK
VALVE_1 = 93, //
VALVE_2 = 95, //
VALVE_3 = 97, //
VALVE_4 = 98, //
VALVE_5 = 100, //
VALVE_6 = 101, // OK
VALVE_7 = 103, // Maybe 102 - sometimes hits the next string
VALVE_8 = 104, //
VALVE_9 = 105; // OK
// ..and the slide.
// For slide max/min, we probably want min to be at the nut end, and max at the soundhole end.
const int SLIDE_MIN = 29; //29
const int SLIDE_MAX = 83; //83
const int
SLIDE_0 = 29,
SLIDE_1 = 37,
SLIDE_2 = 45,
SLIDE_3 = 52,
SLIDE_4 = 59,
SLIDE_5 = 65,
SLIDE_6 = 71,
SLIDE_7 = 77,
SLIDE_8 = 83;
// MIDI note numbers for valveming...
const int
VALVE_0_NOTE = 0,
VALVE_1_NOTE = 1,
VALVE_2_NOTE = 2,
VALVE_3_NOTE = 3,
VALVE_4_NOTE = 4,
VALVE_5_NOTE = 5,
VALVE_6_NOTE = 6,
VALVE_7_NOTE = 7,
VALVE_8_NOTE = 8,
VALVE_9_NOTE = 9;
// ...and picking:
const int
SLIDE_0_NOTE = 12,
SLIDE_1_NOTE = 13,
SLIDE_2_NOTE = 14,
SLIDE_3_NOTE = 15,
SLIDE_4_NOTE = 16,
SLIDE_5_NOTE = 17,
SLIDE_6_NOTE = 18,
SLIDE_7_NOTE = 19,
SLIDE_8_NOTE = 20;
// TODO: constants (or an array?) of servo positions that correspond to musical notes.
// Keep track of last slide position set, in case we end up getting really fancy with the logic and trying to optimise the timings or something.
int slide_position = SLIDE_MIN;
// Unused?
const int VALVE_DELAY = 100;
const int SLIDE_DELAY = 300; // Worst-case slide motion time (HOME..MIN). Unconfirmed!
int i;
void move_slide(int pos) {
// Clip motion to valid range:
if (pos < SLIDE_MIN) {pos = SLIDE_MIN;}
if (pos > SLIDE_MAX) {pos = SLIDE_MAX;}
// Move it:
slide.write(pos);
}
// TODO: similar to move_slide() but for picking, maybe?
void note_on(int note, int velocity) {
switch (note) {
case VALVE_0_NOTE: valve.write(VALVE_0); break;
case VALVE_1_NOTE: valve.write(VALVE_1); break;
case VALVE_2_NOTE: valve.write(VALVE_2); break;
case VALVE_3_NOTE: valve.write(VALVE_3); break;
case VALVE_4_NOTE: valve.write(VALVE_4); break;
case VALVE_5_NOTE: valve.write(VALVE_5); break;
case VALVE_6_NOTE: valve.write(VALVE_6); break;
case VALVE_7_NOTE: valve.write(VALVE_7); break;
case VALVE_8_NOTE: valve.write(VALVE_8); break;
case VALVE_9_NOTE: valve.write(VALVE_9); break;
case SLIDE_0_NOTE: move_slide(SLIDE_0); break;
case SLIDE_1_NOTE: move_slide(SLIDE_1); break;
case SLIDE_2_NOTE: move_slide(SLIDE_2); break;
case SLIDE_3_NOTE: move_slide(SLIDE_3); break;
case SLIDE_4_NOTE: move_slide(SLIDE_4); break;
case SLIDE_5_NOTE: move_slide(SLIDE_5); break;
case SLIDE_6_NOTE: move_slide(SLIDE_6); break;
case SLIDE_7_NOTE: move_slide(SLIDE_7); break;
case SLIDE_8_NOTE: move_slide(SLIDE_8); break;
}
}
void note_off(int note, int velocity) {}
void setup()
{
// UkeBot.begin();
Serial.begin(9600);
// Servo setup:
valve.attach(SERVO_3_PIN);
slide.attach(SERVO_2_PIN);
// Set initial position
valve.write(VALVE_MIN);
slide.write(126);
}
void self_test_picking() {
valve.write(VALVE_1); delay(500);
valve.write(VALVE_0); delay(500);
valve.write(VALVE_3); delay(500);
valve.write(VALVE_2); delay(500);
valve.write(VALVE_5); delay(500);
valve.write(VALVE_4); delay(500);
valve.write(VALVE_7); delay(500);
valve.write(VALVE_6); delay(500);
valve.write(VALVE_9); delay(500);
valve.write(VALVE_8); delay(500);
valve.write(VALVE_8); delay(500);
valve.write(VALVE_9); delay(500);
valve.write(VALVE_6); delay(500);
valve.write(VALVE_7); delay(500);
valve.write(VALVE_4); delay(500);
valve.write(VALVE_5); delay(500);
valve.write(VALVE_2); delay(500);
valve.write(VALVE_3); delay(500);
valve.write(VALVE_0); delay(500);
valve.write(VALVE_1); delay(500);
valve.write(VALVE_0); delay(500); // Return home
}
void self_test() {
// TODO: test each semitone, not just min/max slide position. This would be easier if we used an array for the slide positions.
digitalWrite(LED_PIN, HIGH);
move_slide(SLIDE_MIN); delay(SLIDE_DELAY);
self_test_picking();
move_slide(SLIDE_MAX); delay(SLIDE_DELAY);
self_test_picking();
move_slide(SLIDE_MIN); delay(SLIDE_DELAY);
digitalWrite(LED_PIN, LOW);
}
int angle = 126;
void angle_increase() {
angle++;
if (angle > 180) {angle = 180;}
slide.write(angle);
}
void angle_decrease() {
angle--;
if (angle < 0) {angle = 0;}
slide.write(angle);
}
int control_byte;
void loop()
{
if (Serial.available()) {
control_byte = Serial.read();
// TODO: error-checking?
switch (control_byte) {
case '+': angle_increase(); break;
case '-': angle_decrease(); break;
case ' ': slide.write(180); break;
}
Serial.println(angle);
}
}
/*
void loop()
{
UkeBot.process_MIDI();
}
*/
<file_sep>/Projects/2016/MIDIBots/arduino/midi_receive/midi_receive.ino
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
#define GREEN 8
#define RED 10
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
// const int greenLed = 8,
// redLed = 10;
int dataByte[2], statusByte = 0, i = 0;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(31250);
// initialize the digital pin as an output.
pinMode(GREEN, OUTPUT);
pinMode(RED, OUTPUT);
clearData();
}
void clearData(){
dataByte[0] = 0;
dataByte[1] = 0;
i = 0;
}
void flash(int color){
digitalWrite(color, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(color, LOW); // turn the LED off by making the voltage LOW
delay(20); // wait for a second
}
// the loop routine runs over and over again forever:
void loop() {
if(Serial.available() > 0){
int data = Serial.read();
if(data > 127){
statusByte = data;
clearData();
}else{
dataByte[i] = data;
if(statusByte == 0x90 && i == 1){
if(dataByte[1] == 0){
flash(RED);
}else{
flash(GREEN);
}
}
else if (statusByte == 0x80 && i == 1){
flash(RED);
}
i++;
}
}
}
<file_sep>/Projects/2016/MIDIBots/arduino/libraries/MIDIBot/Makefile
# TODO: make platform-aware:
# see http://stackoverflow.com/questions/714100/os-detecting-makefile
# Mac OS:
#SKETCHBOOK=~/Documents/Arduino/
# Linux (recent Arduino versions):
SKETCHBOOK=~/Arduino
# (NOTE: earlier versions had ~/sketchbook)
TARGET=${SKETCHBOOK}/libraries/MIDIBot
install: MIDIBot.h MIDIBot.cpp
mkdir -p ${TARGET}
cp -v MIDIBot.h MIDIBot.cpp ${TARGET}
<file_sep>/Tools/Arduiglue/arduiglue-arduino-folder-setup
#!/bin/sh
# Take an existing unfiled Arduino sketch filename as an argument and set it up with an Arduino IDE compatible filesystem subtree.
# e.g.:
# arduiglue-arduino-folder-setup ~/Documents/Arduino/untitled.ino
# Arduino IDE expects the structure $SKETCHBOOK/$SKETCH/$SKETCH.ino
# Older sketches might have had the name $SKETCH.pde but let's not worry about that initially.
# Note also that Arduino IDE would normally normalise filenames (e.g. 's/ /_/g'). Maybe this should do that too.
# TODO:
# [ ] Handle paths containing spaces
# [ ] Normalise filename a la Arduino IDE rules.
# [ ] Error handling (e.g. sketch folder or file already exists, preflight check for existence of source file)
FILENAME="$1"
SKETCH=`basename $FILENAME .ino`
FOLDER=`dirname $FILENAME`
# TODO: determine proper Sketchbook path...
#cd ~/Documents/Arduino
# or just assume we're given the full path to the existing sketch file.
cd $FOLDER
mkdir -v $SKETCH
mv -v -n $SKETCH.ino $SKETCH/
<file_sep>/Projects/2017/SoccerBots/boris_python.py
import serial
import time
serinput = serial.Serial('/dev/serial/by-id/usb-Arduino__www.arduino.cc__0042_852313632363516031B2-if00', 115200)
seroutput = serial.Serial('/dev/serial/by-id/usb-DSpace__www.dspace.org.nz__DSpace_Robot_2.0_55234313335351A0D161-if00', 19200)
left_motor_string = 0b10000000 #first bit 1 means motor message
right_motor_string = 0b11000000 #second bit 1 means right motor
kicker_mask = 0b00000000 #first bit - 0 means kicker message
speed_threshold = 0.4 #deadzone threshold
ball_angle=0
def readsensors():
line = str(serinput.readline()).strip(' ;\r\n ').split(" ")
print(len(line))
print(line)
try:
ball_detected=line[0]
ball_angle=line[1]
ball_distance=line[2]
hall_effect=line[3]
rangee=line[4]
compass_heading=line[5]
calibration_mode=line[6]
colour=line[7]
except(serial.SerialException, ValueError, IndexError) as error:
time.sleep(1)
def motoroutput(left, right):
x = left_motor(left).strip("0b")
print(x)
seroutput.write(str(x).encode())
y = right_motor(right).strip("0b")
print(y)
seroutput.write(str(y).encode())
def deadzone(speed, threshold):
if(speed > 0):
out = speed + threshold
elif(speed < 0):
out = speed - threshold
elif(speed==0):
out = 0
if(out<-1):
return -1
elif(out > 1):
return 1
else:
return out
def left_motor(speed): # input -1 to +1
speed = deadzone(speed, speed_threshold)
if speed >= 0:
dir_bit_string = 0b00100000
else:
dir_bit_string = 0b00000000
speedbits = (int(abs(speed)*255))>>3
return bin(dir_bit_string | speedbits | left_motor_string)
def right_motor(speed):
speed = deadzone(speed, speed_threshold)
if speed >= 0:
dir_bit_string = 0b00100000
else:
dir_bit_string = 0b00000000
speedbits = (int(abs(speed)*255))>>3
return bin(dir_bit_string | speedbits | right_motor_string)
def kicker(kick):
return bin(kicker_mask | kick)
while True:
motoroutput(-1,-1)
time.sleep(1)
#motoroutput(1,1)
#time.sleep(1)
#readsensors()
#print(ball_angle)
<file_sep>/Projects/2016/MIDIBots/arduino/arduino-timeslice-shell.c
//Timeslice global variables
unsigned long TimeSlice_TC1_Interval = 20;
unsigned long TimeSlice_TC2_Interval = 100;
unsigned long TimeSlice_TC3_Interval = 500;
unsigned long TimeSlice_TC1_Start_Time;
unsigned long TimeSlice_TC2_Start_Time;
unsigned long TimeSlice_TC3_Start_Time;
void loop()
{
//----------------------------------------------------------TimeSlice code-----------------------------------------------------------
while(1){
//-------------------
//Timeclass 1 20 ms
//-------------------
TimeSlice_TC1_Start_Time = millis();
// ---------------------------------------------------------User application code
// ---------------------------------------------------------End of user application code
// Toggle TC1 LED
toggle_LED(1);
// check timeout
if (((millis() - TimeSlice_TC1_Start_Time) > TimeSlice_TC1_Interval)) // 20 ms
{
while(1){
over_run_Fault(1); // abort program and loop forever and flash Time class 1 LED
}
}
else
{
while (((millis() - TimeSlice_TC1_Start_Time) <= TimeSlice_TC1_Interval)){ // remove to save MIPS but it removes precise timeclass execution
}
}
//-------------------
//Timeclass 2 100 ms
//-------------------
TimeSlice_TC2_Start_Time = millis();
// ----------------------------------------------------------User application code
// ----------------------------------------------------------End of user application code
// Toggle TC2 LED
toggle_LED(2);
if (((millis() - TimeSlice_TC2_Start_Time) > TimeSlice_TC2_Interval)) // 100 ms
{
while(1){
over_run_Fault(2); // abort program and loop forever flash Time class 2 LED
}
}
else
{
while (((millis() - TimeSlice_TC2_Start_Time) <= TimeSlice_TC2_Interval)){ // remove to save MIPS but it removes precise timeclass execution
}
}
//------------------
//Timeclass 3 500 ms
//------------------
TimeSlice_TC3_Start_Time = millis();
//------------------------------------------------------------------User application code
// -----------------------------------------------------------------End of user application code
// Toggle TC3 LED
toggle_LED(3);
if (((millis() - TimeSlice_TC3_Start_Time) > TimeSlice_TC3_Interval)) // 500 ms
{
while(1){
over_run_Fault(3); // abort program loop forever flash Time class 3 LED
}
}
else
{
while (((millis() - TimeSlice_TC3_Start_Time) <= TimeSlice_TC3_Interval)){ // remove to save MIPS but it removes precise timeclass execution
}
}
} // End of main while loop
}// end of main loop
<file_sep>/Projects/2017/SoccerBots/blob_tracking_cv2.py
#!/usr/bin/env python2
# Demo/test of the Python OpenCV bindings (wot I built from source) with the picamera (Python-MMAL) module.
# Based on http://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/
execfile("camera_setup.py")
# That's it for the camera setup.
average_colour=(0,0,0)
sleep(0.1)
from fractions import Fraction
calibration_file_name = "camera_calibration_state_cv2.py"
execfile(calibration_file_name)
camera.awb_mode = 'off'
camera.awb_gains = calibrated_white_balance
def debug(msg):
#sys.stderr.write(str(msg) + "\n")
pass
def send2pd(message):
print(str(message) + ";")
sys.stdout.flush()
def x_coordinate_to_angle(coord):
#return coord*35.543 #calibrated for LogiTech Camera.
return coord*33.0 #calibrated for RPi Camera.
then = 0
now = 0
end_time = 0
# For colour matching testing:
# Helper for converting a decimal <r,g,b> triple into an integer [b,g,r] array:
def bgr(r,g,b):
return [int(round(b*255)), int(round(g*255)), int(round(r*255))]
blue_lo = bgr(0.1, 0.24, 0.4)
blue_hi = bgr(0.2, 0.4, 0.6)
lower = numpy.array(blue_lo, dtype="uint8")
upper = numpy.array(blue_hi, dtype="uint8")
# What about HSV, which worked pretty well for the original SimpleCV attempt?
# OpenCV docs: For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]
# Goal blue H was about 102/180, S=190/255, V=50/255 (or 50/100?)
goal_hsv = (104.3136,251.977,89.199)
#goal_hsv = average_colour
#goal_hsv = (average_colour[0], 127, 127)
debug(average_colour[0])
debug(goal_hsv)
# Should the range be applied additively or multiplicatively?
def clip8bit(x):
if isinstance(x, int):
if x < 0:
return 0
elif x > 255:
return 255
else:
return x
elif isinstance(x, list):
for y in range(len(x)):
if x[y] < 0:
x[y] = 0
elif x[y] > 255:
x[y] = 255
else:
x[y] = x[y]
return x
#goal_hsv_lo = numpy.array(lower(goal_hsv, goal_hsv_tolerance), dtype="uint8")
#goal_hsv_hi = numpy.array(upper(goal_hsv, goal_hsv_tolerance), dtype="uint8")
calibration = calibrated_goal_colour
tolerance = 20
debug(calibration)
for x in range(3):
calibration[0][x] = calibration[0][x] - tolerance
calibration[1][x] = calibration[1][x] + tolerance
debug(calibration)
clipped_cal = (clip8bit(calibration[0]),clip8bit(calibration[1]))
debug(clipped_cal)
goal_hsv_lo = numpy.array(clipped_cal[0], dtype="uint8")
goal_hsv_hi = numpy.array(clipped_cal[1], dtype="uint8")
debug(goal_hsv_lo)
debug(goal_hsv_hi)
debug("Press 'q' to quit...")
# , resize=resized_res
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
rawCapture.truncate(0)
now = time()
elapsed_time = now - then
debug('Frame rate: ' + str(round(1.0/elapsed_time,1)) + ' Hz\n')
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
#print("copy array")
image = frame.array
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Remember, it's (B,G,R) otherwise!
mask = cv2.inRange(hsv, goal_hsv_lo, goal_hsv_hi)
#output = cv2.bitwise_and(image, image, mask=mask)
# show the matching area:
#print("show masked frame")
# Detect blobs.
keypoints = detector.detect(mask)
for keypoint in keypoints:
debug(keypoint)
debug("Size: " + str(keypoint.size))
debug("Co-ordinates: " + str(keypoint.pt))
debug("Number of blobs " + str(len(keypoints)))
# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob
mask_with_keypoints = cv2.drawKeypoints(mask, keypoints, numpy.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# Show keypoints
#cv2.imshow("Keypoints", mask_with_keypoints)
# Show hsv image
#cv2.imshow("HSV", hsv)
# Show raw image
#cv2.imshow("Raw Image", image)
blob_size = 0
largest_blob_index = 0
n=0
if len(keypoints) == 0:
debug("No blobs detected!")
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
send2pd(-180)
continue
for keypoint in keypoints:
if keypoint.size > blob_size:
blob_size = keypoint.size
largest_blob_index = n
n = n+1
largest_blob = keypoints[largest_blob_index]
debug(largest_blob_index)
if numpy.isnan(largest_blob.pt[0]) | numpy.isnan(largest_blob.pt[1]):
debug("Not a Number")
send2pd(-180)
continue
#Show largest blob
mask_with_largest_blob = cv2.drawKeypoints(mask, [largest_blob], numpy.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
blob_x = largest_blob.pt[0]
blob_y = largest_blob.pt[1]
debug(str(blob_x) + str(blob_y))
cv2.line(mask_with_largest_blob,(int(blob_x),0),(int(blob_x),96),(255,0,0),2)
cv2.line(mask_with_largest_blob,(0,int(blob_y)) ,(128,int(blob_y)),(0,255,0),2)
cv2.imshow("Largest Blob", mask_with_largest_blob)
normalised_x = 2.0/capture_res[0] * blob_x - 1
send2pd(str(x_coordinate_to_angle(normalised_x)) + " " + str(largest_blob.size))
#print(" wait >")
key = cv2.waitKey(16) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# clear the stream in preparation for the next frame
#print("truncating...")
then = now
#print("end loop")
#end_time = time()
<file_sep>/Projects/2017/SoccerBots/Makefile
install: bash_aliases
ln -f -s ~/robotics_repo/Projects/2017/SoccerBots/bash_aliases ~/.bash_aliases
echo "Start a new shell or run source for new aliases to take affect."
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_lightingbot/firmware_lightingbot.ino
// ____Bot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
#include <MIDIBot.h>
MIDIBot thisMIDIBot;
// Additional constants for the lighting setup:
const int BLUE_PIN = MOSFET_4_PIN;
const int WHITE_PIN = MOSFET_3_PIN;
const int BLUE_NOTE = 60; // MIDI middle C
const int WHITE_NOTE = 62; // MIDI D above middle C
// RGB LED strip setup:
const int R_PIN = SERVO_1_PIN; // red
const int G_PIN = SERVO_2_PIN; // green
const int B_PIN = SERVO_3_PIN; // blue
// RGB LED strip control notes:
const int R_NOTE = 67; // G above middle C
const int G_NOTE = 69; // A above middle C
const int B_NOTE = 71; // B above middle C
// TODO: refactor to use switch statements in note_on(), note_off():
// (see PercussionBot firmware for example)
void note_on(int note, int velocity) {
if (note == BLUE_NOTE) {digitalWrite( BLUE_PIN, HIGH);}
if (note == WHITE_NOTE) {digitalWrite(WHITE_PIN, HIGH);}
if (note == R_NOTE) {analogWrite(R_PIN, velocity*2);}
if (note == G_NOTE) {analogWrite(G_PIN, velocity*2);}
if (note == B_NOTE) {analogWrite(B_PIN, velocity*2);}
}
void note_off(int note, int velocity) {
if (note == BLUE_NOTE) {digitalWrite( BLUE_PIN, LOW);}
if (note == WHITE_NOTE) {digitalWrite(WHITE_PIN, LOW);}
if (note == R_NOTE) {analogWrite(R_PIN, 0);}
if (note == G_NOTE) {analogWrite(G_PIN, 0);}
if (note == B_NOTE) {analogWrite(B_PIN, 0);}
}
void self_test() {
digitalWrite(BLUE_PIN, HIGH);
digitalWrite(WHITE_PIN, LOW);
delay(500);
digitalWrite(BLUE_PIN, LOW);
digitalWrite(WHITE_PIN, HIGH);
delay(500);
digitalWrite(WHITE_PIN, LOW);
RGB_colour_test();
RGB_fade_integer();
}
void setup() {
thisMIDIBot.begin();
}
void loop() {
thisMIDIBot.process_MIDI();
}
const float EXP = 2.0; // Stevens power-law brightness exponent
// Human perception of brightness is non-linear. This function attempts to compensate and provide linear control over perceived brightness. Input and output are (assumed to be) normalised to the range 0..1.
float brightness(float level) {
// Exponential (to compensate for logarithmic response):
// TODO: ...
// Stevens (power-law) model:
return pow(level, EXP); // Min. step size = (1/255)^(1/exponent)
}
// Compute minimum step size to achive full output resolution with 0..255 PWM (STEP computed WRT 0..1 range):
//const float STEP = pow(1.0 / 255.0, 1.0 / EXP); // Stevens
const float STEP = 0.0001;
// Plus another function to quantise to the 0..255 levels provided by the PWM output:
int quantise(float value) {
return (int) round(value * 255.0);
}
void RGB_blink() {
digitalWrite(R_PIN, HIGH);
digitalWrite(G_PIN, LOW);
digitalWrite(B_PIN, LOW);
delay(150);
digitalWrite(R_PIN, LOW);
digitalWrite(G_PIN, HIGH);
digitalWrite(B_PIN, LOW);
delay(150);
digitalWrite(R_PIN, LOW);
digitalWrite(G_PIN, LOW);
digitalWrite(B_PIN, HIGH);
delay(150);
digitalWrite(R_PIN, LOW);
digitalWrite(G_PIN, LOW);
digitalWrite(B_PIN, LOW);
// delay(1500);
}
long r, g, b;
const int FADE_DELAY = 1;
void RGB_fade_integer() {
digitalWrite(R_PIN, LOW);
digitalWrite(G_PIN, LOW);
digitalWrite(B_PIN, LOW);
// Fade in:
for (r = 0; r < 256; r++) {
analogWrite(R_PIN, r);
delay(FADE_DELAY);
}
for (g = 0; g < 256; g++) {
analogWrite(G_PIN, g);
delay(FADE_DELAY);
}
for (b = 0; b < 256; b++) {
analogWrite(B_PIN, b);
delay(FADE_DELAY);
}
// Fade out:
for (r = 255; r >= 0; r--) {
analogWrite(R_PIN, r);
delay(FADE_DELAY);
}
for (g = 255; g >= 0; g--) {
analogWrite(G_PIN, g);
delay(FADE_DELAY);
}
for (b = 255; b >= 0; b--) {
analogWrite(B_PIN, b);
delay(FADE_DELAY);
}
}
// TODO: finish testing this and complete it:
void RGB_fade() {
digitalWrite(R_PIN, LOW);
digitalWrite(G_PIN, LOW);
digitalWrite(B_PIN, LOW);
// Fade in:
// for (r = 0; r < 256; r++) {
// analogWrite(R_PIN, quantise(brightness(r));
// delay(FADE_DELAY);
// }
for (g = 0; g < (long) round(1.0/STEP); g++) {
analogWrite(G_PIN, quantise(brightness(g * STEP)));
// delay(FADE_DELAY);
}
// for (b = 0; b < 256; b++) {
// analogWrite(B_PIN, b);
// delay(FADE_DELAY);
// }
// Fade out:
// for (r = 255; r >= 0; r--) {
// analogWrite(R_PIN, r);
// delay(FADE_DELAY);
// }
for (g = (long) round(1.0/STEP); g >= 0; g--) {
analogWrite(G_PIN, quantise(brightness(g * STEP)));
// delay(FADE_DELAY);
}
// for (b = 255; b >= 0; b--) {
// analogWrite(B_PIN, b);
// delay(FADE_DELAY);
// }
}
void RGB_colour_test() {
const int DELAY = 500;
RGB_write(255, 0, 0); delay(DELAY); // red
RGB_write( 0, 255, 0); delay(DELAY); // green
RGB_write( 0, 0, 255); delay(DELAY); // blue
RGB_write( 0, 255, 255); delay(DELAY); // cyan
RGB_write(255, 0, 255); delay(DELAY); // magenta
RGB_write(255, 255, 0); delay(DELAY); // yellow
RGB_write(255, 255, 255); delay(DELAY); // white
delay(DELAY);
}
void RGB_write(int R, int G, int B) {
analogWrite(R_PIN, R);
analogWrite(G_PIN, G);
analogWrite(B_PIN, B);
}
<file_sep>/Projects/2016/MIDIBots/arduino/uke_test/uke_test.ino
// Testing servo strumming ukulele
#include <Servo.h>
Servo servos [1];
int pos = 0; // variable to store the servo position
const int CENTRE = 90;
const int RANGE = 20;
const int MAX_POS = CENTRE + RANGE/2;
const int MIN_POS = CENTRE - RANGE/2;
const int SERVO_TIME = 500; // ms delay to allow motion to happen
void setup()
{
servos[0].attach(11);
}
void strum(Servo servo)
{
servo.write(MAX_POS);
delay(SERVO_TIME);
servo.write(MIN_POS);
delay(SERVO_TIME);
}
void loop() {
strum(servos[0]);
}
<file_sep>/Projects/2016/MIDIBots/arduino/servo_drum_test/ano/src/sketch.ino
../../servo_drum_test.ino<file_sep>/Projects/2016/MIDIBots/arduino/firmware_drumbot/ano/src/sketch.ino
../../firmware_drumbot.ino<file_sep>/Projects/2017/SoccerBots/trigonometry/atan2.c
// Demonstrate/test the use of the two-argument atan2() function
// The atan2(x,y) function has a couple of advantages over conventional atan(), namely it avoids the division-by-zero problem, and returns values that correctly indicate the quadrant of the angle, based on the sign* of the inputs.
// * not the sin()!
#include <math.h>
#include <stdio.h>
const double TAU = asin(1) * 4.0;
double degrees(double radians) {return 360.0 / TAU * radians;}
int main() {
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
printf("atan2(%i,%i) = %f\n", x, y, degrees(atan2(x,y)));
}
}
return 0;
}
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_lightingbot/ano/src/sketch.ino
../../firmware_lightingbot.ino<file_sep>/Settings/Geany/Readme.txt
(Better) Arduino integration in Geany
CME 2016-07-18
Geany seems to have two kinds of file type handling:
- Built-in filetypes
- Custom filetypes
Custom filetypes are simpler to define, but less powerful.
Built-in filetypes
Tags: I think these are things like function names that Geany can index for ease of navigation using the Symbols panel.
tag_parser: e.g. "C"
build_settings, build-menu sections
http://www.geany.org/manual/dev/index.html#custom-filetypes
http://www.geany.org/manual/dev/index.html#build-menu-configuration
http://geany.org/manual/dev/#symbols-and-tags-files
--
Files to perhaps edit:
~/.config/geany/filetype_extensions.conf
Add Arduino file type to the Programming group.
<<
...
[Extensions]
# <CME>
Arduino=*.ino;*.pde;
# </CME>
...
[Groups]
# <CME>
Programming=Arduino;Clojure;CUDA;Cython;Genie;Scala;
# </CME>
...
>>
Alternatively, could we just add .ino to the list of C++ suffixes in filetype_extensions.conf?
Yes, but then it just inherits the C++ build/toolchain commands, which we don't want.
Create a new:
filedefs/filetypes.ino
NOTE: can include a build-menu section (see above)
Create a new:
templates/files/sketch.ino
MIME type:
text/x-arduino
Files added (to be installed):
~/.config/geany/filetype_extensions.conf
~/.config/geany/filedefs/filetypes.Arduino.conf
~/.config/geany/templates/files/sketch.ino
Hmm, it's reading the file_type_extensions.conf file (cos if I add *.pde to the C++ list it gets set as that type), but it's ignoring my Arduino definition line from the same.
<<
sbis4114:geany admin$ /Applications/Geany.app/Contents/MacOS/geany -v
Geany-INFO: Geany 1.28, en_US.UTF-8
Geany-INFO: GTK 2.24.30, GLib 2.48.0
Geany-INFO: System data dir: /Applications/Geany.app/Contents/Resources/share/geany
Geany-INFO: User config dir: /Users/admin/.config/geany
Geany-INFO: System plugin path: /Applications/Geany.app/Contents/Resources/lib/geany
Geany-INFO: Added filetype Clojure (61).
Geany-INFO: Added filetype CUDA (62).
Geany-INFO: Added filetype Cython (63).
Geany-INFO: Added filetype Genie (64).
Geany-INFO: Added filetype Graphviz (65).
Geany-INFO: Added filetype JSON (66).
Geany-INFO: Added filetype Scala (67).
Geany-INFO: Could not find filetype 'Arduino'.
Geany-INFO: Filetype 'Arduino' not found for group 'Programming'!
Geany-INFO: /Users/admin/.config/geany/filetype_extensions.conf : Conf (UTF-8)
>>
Ah, it needs to be called filetypes.Arduino.conf
[ ] Problem: New file should be called sketch.ino, but it's getting named as untitled.ino
[ ] Symbols (function names, constants, etc.) are not being picked up, even when using C as the file type. Ah, they don't get scanned until you save the file!
--
Geany/ino/Arduino on Mac OS X
Sebastian discovered that ino doesn't work with the latest version of the Ardunio IDE installation, on which it depends.
lsusb equivalent on Mac OS X:
https://github.com/jlhonora/lsusb
ioreg -p IOUSB -l -w 0 -x -c IOUSBDevice -r
-p -> I/O kit plane (dev type)
-l -> list properties (including handy attributes such as idVendor, idProduct, "USB Vendor Name", "USB Product Name", bDeviceClass, bDeviceSubClass
-w 0 -> no text wrapping
-x -> show numbers as hexadecimal
-a -> archive format (relatively nasty XML output)
-c IOUSBDevice -> limit to IOUSBDevice classes (and subclasses)
-r -> root subtrees according to filter criteria
Ugh, will still have to parse a lump of text to get the useful data out...
system_profiler SPUSBDataType
Would be preferable not to require installation of additional scripts/programs/packages.
/dev/cu.usbmodem1a21
/dev/tty.usbmodem1a21
USBDroid 20A0:4150
Tcl OS detection:
if {$tcl_platform(os) eq "Darwin"} {...}
# New toplevel for .boards? Or just use the main "." frame?
toplevel .boards
wm title .boards {Available Arduino Devices}
label .boards.label -text {Choose the device to program:}
pack .boards.label -expand 0 -fill x
# NOTE: column #0 is always the tree column (even if not shown).
ttk::treeview .boards.tree -columns {<tree> Device USB_ID Model Type} -selectmode browse -show headings
pack .boards.tree -expand 1 -fill both
.boards.tree heading #0 -anchor w -text <tree>
.boards.tree heading #1 -anchor w -text Device:
.boards.tree heading #2 -anchor w -text {USB ID:}
.boards.tree heading #3 -anchor w -text {Model ID:}
.boards.tree heading #4 -anchor w -text {Device Type:}
# To insert a row:
.boards.tree insert {} end -text the_text -values [list dev id model type]
# A more realistic one:
.boards.tree insert {} end -text NoMatter -values [list /dev/ttyACM0 dead:beef uno {Arduino Uno}]
# TODO: column widths
# TODO: scrolling
# Buttons
button .boards.cancel_button -text Cancel -command {}
button .boards.ok_button -text OK -command {}
pack .boards.ok_button .boards.cancel_button -side right
<file_sep>/Projects/2016/MIDIBots/arduino/midi_receive/ano/src/sketch.ino
../../midi_receive.ino<file_sep>/Documentation/Computer Vision/infoscimechatronics/camera_calibration_state.py
#!/usr/bin/env python2.7
import SimpleCV
import sys
import os
sys.path.append(os.environ['HOME'] + '/robotics_repo/Documentation/Computer Vision/infoscimechatronics')
import cvutils
#ser = serial.Serial('/dev/serial/by-id/usb-www.freetronics.com_Eleven_64935343233351909241-if00')
#camera = SimpleCV.Camera(0, {"width":320,"height":240})
#os.system(os.environ['HOME'] + '/robotics_repo/Projects/2017/SoccerBots/uvcdynctrl-settings.tcl')
#lab_grey_sample = cvutils.calibrate_white_balance(camera)
calibrated_grey_sample = (212.8181818181818, 205.9090909090909, 205.0909090909091)
#lab_goal_blue = cvutils.calibrate_colour_match(camera, lab_grey_sample)
calibrated_goal_sample = ((104.5, 0.5), (170.0, 31.0), (83.0, 37.0))
def col_grey():
return calibrated_grey_sample
def col_blue():
return calibrated_goal_sample
<file_sep>/Projects/2016/MIDIBots/kicad/make-package.sh
#!/bin/sh
# Put the Gerber files together for sending to DirtyPCBs...
BASENAME=MIDI_Shield
# ls $BASENAME*{.gto,.gts,.gtl,.gbl,.gbs,.gbo,.gml,.txt}
# Fix up file names:
mv ${BASENAME}-F.Cu.gtl ${BASENAME}.gtl
mv ${BASENAME}-B.Cu.gbl ${BASENAME}.gbl
mv ${BASENAME}-B.SilkS.gbo ${BASENAME}.gbo
mv ${BASENAME}-F.SilkS.gto ${BASENAME}.gto
mv ${BASENAME}-B.Mask.gbs ${BASENAME}.gbs
mv ${BASENAME}-F.Mask.gts ${BASENAME}.gts
mv ${BASENAME}-Edge.Cuts.gm1 ${BASENAME}.gml
# ...and the drill file:
mv ${BASENAME}.drl ${BASENAME}.txt
# Now archive them up:
#zip $BASENAME.zip $BASENAME*{.gto,.gts,.gtl,.gbl,.gbs,.gbo,.gml,.txt}
# Nope, the additional filename elements mean that won't work. And maybe `zip` doesn`t play nicely with wildcards.
#zip $BASENAME.zip $BASENAME-F.SilkS.gto $BASENAME-F.Mask.gts $BASENAME-F.Cu.gtl $BASENAME-B.Cu.gbl $BASENAME-B.Mask.gbs $BASENAME-B.SilkS.gbo $BASENAME.gml $BASENAME.txt
zip $BASENAME.zip $BASENAME.gto $BASENAME.gts $BASENAME.gtl $BASENAME.gbl $BASENAME.gbs $BASENAME.gbo $BASENAME.gml $BASENAME.txt
<file_sep>/Projects/2017/SoccerBots/arduino/ir_test/ir_test.ino
// TODO: main statement of the purpose of this code!
#include <math.h>
const int IR_1 = 2;
const int IR_2 = 3;
const int IR_3 = 4;
const int IR_4 = 5;
const int NUM_SENSORS = 8;
//this is now finished, go and look at ir_ball_tracker.ino instead
//const int sensor_pins[] = {2,3,4,5,6,7,8,9};
const int analog_sensor_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7};
float ir_values[8];
float IR_COORDINATES[NUM_SENSORS][2] = {{0.0,1.0},{0.71,0.71},{1.0,0.0},{0.71,-0.71},{0.0,-1.0},{-0.71, -0.71},{-1.0, 0.0},{-0.71, 0.71}};
const int IR_THRESHOLD = 980; // About 0.15 after converting to 0..1 float looked about right, which would be ~870 raw. In practice, with no IR ball present, we never see a raw value less than 1000.
#define DEBUGGING 0
/*
#define debug(message) \
do { if (DEBUGGING) Serial.println(message); } while (0)
*/
#ifdef DEBUGGING
#define DEBUG(x) Serial.println (x)
#else
#define DEBUG(x)
#endif
int ir_val;
const float TAU = 2 * PI;
void setup() {
for(int n=0; n<NUM_SENSORS; n++) {
//pinMode(sensor_pins[n], INPUT);
pinMode(analog_sensor_pins[n], INPUT);
}
Serial.begin(115200);
//Serial.println("Welcome Uno");
}
void test_loop() {
for(int n=0; n<=NUM_SENSORS; n++) {
Serial.print(analogRead(analog_sensor_pins[n]) + " ");
}
Serial.println();
delay(50);
}
void loop() {
readIRsensors();
printIRsensors();
ball_angle();
delay(500);
}
float readIRsensor(int sensor_num){
int reading = analogRead(analog_sensor_pins[sensor_num]);
// TODO: debugging
Serial.print("sensor "); Serial.print(sensor_num); Serial.print(": "); Serial.println(reading);
if (reading>IR_THRESHOLD){
return 0.0;
}else{
return (1023-reading)/1023.0;
}
}
void readIRsensors(){
for (int i=0; i<NUM_SENSORS; i++) {
ir_values[i] = readIRsensor(i);
}
}
void printIRsensors(){
Serial.print("Raw sensor readings: ");
for (int i=0; i<NUM_SENSORS; i++) {
Serial.print(ir_values[i]);
Serial.print(" ");
}
Serial.println();
}
void rad2degTest(){
for (int i=0; i < 8; i ++) {
Serial.println(i / 8.0 * TAU);
Serial.println(normaliseDegrees(rad2deg(i / 8.0 * TAU)));
}
}
float rad2deg(float rad){
return (rad * -1.0 + TAU / 4.0) * (360.0 / TAU);
}
float normaliseDegrees(float d){
//return fmod(d + 180, 360);
if (d < -180){
return d + 360;
}else if(d>180){
return d - 360;
}else{
return d;
}
}
float vector2distance(float vector_magnitude){
return exp(0.33/vector_magnitude) * 0.03;
}
float ball_angle() {
//Serial.println("ball angle called!");
// Calculate the centroid of the ball detection vectors...
float x_total = 0; float y_total = 0; int count = 0;
for(int n=0; n<NUM_SENSORS; n++) {
x_total += IR_COORDINATES[n][0]*ir_values[n];
y_total += IR_COORDINATES[n][1]*ir_values[n];
/*
Serial.print(n);
Serial.print(": (");
Serial.print(IR_COORDINATES[n][0]*ir_values[n]);
Serial.print(",");
Serial.print(IR_COORDINATES[n][1]*ir_values[n]);
Serial.print("); ");
*/
count += 1;
}
//Serial.println();
float x_average = x_total/(float)count;
float y_average = y_total/(float)count;
/*
Serial.print(" X AVERAGE: ");
Serial.print(x_average);
Serial.print(" Y AVERAGE: ");
Serial.print(y_average);
Serial.println(" ");
*/
// Calculate angle:
// This will use the atan2() function to determine the angle from the average x and y co-ordinates
// You can use the degrees() function to convert for output/debugging.
float angle = atan2(x_average, y_average);
Serial.print("Angle to ball: ");
Serial.print(degrees(angle));
// Calculate approximate distance:
// First, determine the length of the vector (use the Pythagorean theorem):
float vector_magnitude = sqrt(pow(x_average, 2)+pow(y_average,2)); // TODO: your code here
// We need to map the raw vector magnitudes to real-world distances. This is probably not linear! Will require some calibration testing...
float distance = vector2distance(vector_magnitude); // TODO: your code here
Serial.print(" Vector magnitude: ");
Serial.print(vector_magnitude);
Serial.print(" Distance: ");
Serial.print(distance);
Serial.println("");
// TODO: maybe also check for infinity, and map that to a usable value (e.g. 0).
}
<file_sep>/Projects/2016/MIDIBots/arduino/pwm_examples/pwm_4.ino
// MIDI note tests for Mechatronics, CME 2016-03-21
// 1. Loop sanity check. Watch for off-by-one errors!
// 2. Translate note frequency formula into C syntax and check (MIDI note 69 should give 440 Hz).
// 3. Correct integer division in formula!
// 4. Derive OCR "top" value from frequency, and print for checking.
void setup() {
delay(8000); // safety delay for serial I/O
Serial.begin(9600);
}
void loop() {
int prescale = 8;
for (int n = 0; n < 128; n++) {
float f = 440 * pow(2, (n - 69) / 12.0);
int top = round(F_CPU / (prescale * f) - 1);
Serial.print(n);
Serial.print(": f=");
Serial.print(f);
Serial.print(", top=");
Serial.println(top);
}
while (1) {}
}
<file_sep>/Projects/2016/MIDIBots/arduino/ukulele_test/ukulele_test.ino
// Testing multiple servo motors
#include <Servo.h>
Servo servo1;
int pos = 0; // variable to store the servo position
const int STRUM_MAX_POS = 100; //sets MAX and MIN servo postions for all strings
const int STRUM_MIN_POS = 80;
const int G_MAX_POS = 85;
const int G_MIN_POS = 82;
const int C_MAX_POS = 87;
const int C_MIN_POS = 85;
const int E_MAX_POS = 91;
const int E_MIN_POS = 88;
const int A_MAX_POS = 94;
const int A_MIN_POS = 92;
const int SERVO_TIME = 200 ; // ms delay to allow motion to happen
const int SERVO_1_PIN = 11; //Servo is connected to pin 11(pwm)
byte byteRead; //temporary storage of serial bytes
void setup()
{
pinMode(SERVO_1_PIN, OUTPUT);
digitalWrite(SERVO_1_PIN, LOW);
servo1.attach(SERVO_1_PIN);
Serial.begin(9600); //start serial protocol
}
void G() //A function to play the G string on the Uke
{
servo1.write(G_MAX_POS);
delay(SERVO_TIME);
servo1.write(G_MIN_POS);
delay(SERVO_TIME);
}
void C()
{
servo1.write(C_MAX_POS);
delay(SERVO_TIME);
servo1.write(C_MIN_POS);
delay(SERVO_TIME);
}
void E()
{
servo1.write(E_MAX_POS);
delay(SERVO_TIME);
servo1.write(E_MIN_POS);
delay(SERVO_TIME);
}
void A()
{
servo1.write(A_MAX_POS);
delay(SERVO_TIME);
servo1.write(A_MIN_POS);
delay(SERVO_TIME);
}
void strum()
{
servo1.write(STRUM_MAX_POS);
delay(SERVO_TIME);
servo1.write(STRUM_MIN_POS);
delay(SERVO_TIME);
}
void manual(int max_pos, int min_pos, int servo_delay)
{
servo1.write(max_pos);
delay(servo_delay);
servo1.write(min_pos);
delay(servo_delay);
}
void serial_read()
{
if (Serial.available() > 0) //checks if a serial device is listening
{
byteRead = Serial.read(); //captures serial data byte
if(byteRead == 'G') //checks weather the user has typped "G"
{
G(); //if so call the G function which will play the G string on the ukulele.
Serial.println("recived G"); //Alerts the user that it has been played
}
if(byteRead == 'C')
{
C();
Serial.println("recived C");
}
if(byteRead == 'E')
{
E();
Serial.println("recived E");
}
if(byteRead == 'A')
{
A();
Serial.println("recived A");
}
if(byteRead == 'S')
{
strum();
Serial.println("recived strum");
}
}
}
void loop() {
serial_read();
}
<file_sep>/Projects/2017/SoccerBots/restarteverything.sh
#!/bin/bash
./stopeverything.sh
./runeverything.sh
<file_sep>/Projects/2017/SoccerBots/initial_blob_tracking.py
#!/usr/bin/env python2.7
import SimpleCV
import os
import sys
sys.path.append(os.environ['HOME'] + '/robotics_repo/Documentation/Computer Vision/infoscimechatronics')
import cvutils
import time
import serial
#sys.path.append(os.environ['HOME'] + '/robotics_repo/Projects/2017/SoccerBots')
execfile("camera_calibration_state.py")
#ser = serial.Serial('/dev/serial/by-id/usb-www.freetronics.com_Eleven_64935343233351909241-if00')
camera = SimpleCV.Camera(0, {"width":320,"height":240})
os.system(os.environ['HOME'] + '/robotics_repo/Projects/2017/SoccerBots/uvcdynctrl-settings.tcl')
speed = 0
#global current_angle
#current_angle = 0
prev_error = 0
integral = 0
derivative = 0
#global hunt_dir
hunt_dir = 1
hunt_step = 15
#blobs_threshold = 0.0075
blobs_threshold = 0.00005
times = []
output = False
def average(numbers):
x = 0
for num in numbers:
x += num
x = float(x) / len(numbers)
return x
def x_coordinate_to_angle(coord):
#return coord*35.543 #calibrated for LogiTech Camera.
return coord*33.0 #calibrated for RPi Camera.
def plant(control): #control input from -1...1 so -90...90 deg / sec
current_angle += speed
speed = control * 90
return current_angle
#Sends serial data to connected Arduino, input data between -90 to 90, output data to servo is 0 to 180 deg
def servo(target_angle):
current_angle = get_current_angle() + 90
sys.stderr.write("current angle: " + str(current_angle) + ' ')
sys.stderr.write("target angle:: " + str(target_angle) + '\n')
for i in range(abs(int(target_angle))):
if target_angle > 0:
if current_angle < 180:
ser.write('+')
if target_angle < 0:
if current_angle > 0:
ser.write('-')
#time.sleep(0.2)
def get_current_angle():
global ser
ser.write("?")
return int(ser.readline().strip()) - 90
def clip_angle(angle):
if angle < -90:
return -90
if angle > 90:
return 90
else:
return angle
def servo_abs(target_angle):
servo(target_angle - get_current_angle())
def seek():
sys.stderr.write("Seek called & hunt_dir = " + str(hunt_dir) + "\n")
global hunt_step
global hunt_dir
current_angle = get_current_angle()
if current_angle >= 90 or current_angle <= -90:
hunt_dir *= -1
servo_abs(clip_angle(current_angle + hunt_dir * hunt_step))
time.sleep(0.05)
def control(target):
kp = 1
ki = 1
kd = 1
error = target - current_angle
integral += error
derivative = error - prev_error
prev_error = error
control = kp * error + ki * integral + kd * derivative
sys.stderr.write(control)
sys.stderr.write(error * kp)
sys.stderr.write(integral * ki)
sys.stderr.write(derivative * kd)
sys.stderr.write(plant(control))
return plant(control)
def send2pd(message):
print(str(message) + ";")
sys.stdout.flush()
while True:
start_time = time.clock()
image = cvutils.wb(camera.getImage().scale(0.075), calibrated_grey_sample)
v,s,h = image.toHSV().splitChannels()
hue_match = h.colorDistance((calibrated_goal_sample[0][0],calibrated_goal_sample[0][0],calibrated_goal_sample[0][0])).binarize(calibrated_goal_sample[0][1]*3)
sat_match = s.colorDistance((calibrated_goal_sample[1][0],calibrated_goal_sample[1][0],calibrated_goal_sample[1][0])).binarize(calibrated_goal_sample[1][1]*3)
matched = ((hue_match / 16) * (sat_match / 16))
matched.show()
blobs = matched.findBlobs(100, 1)
if blobs is not None:
blob_size = blobs[-1].area()
image_size = image.area()
sys.stderr.write ("Blob size / image size: " + str(blob_size / image_size) + "\n")
if blob_size / image_size < blobs_threshold:
sys.stderr.write("Blobs too small! \n")
send2pd(-180) #404 not found
#seek()
else:
(x,y) = blobs[-1].centroid()
image.dl().line((x,0), (x,image.height), (255,0,0), antialias=False)
image.dl().line((0,y), (image.width,y), (0,255,0), antialias=False)
image.show()
#sys.stderr.write float(x) / image.width
converted_coord = float(x) / image.width
converted_coord = x_coordinate_to_angle(converted_coord*2-1)
sys.stderr.write("converted_coord: " + str(converted_coord) + ' ' + '\n')
#servo(converted_coord*0.3)
send2pd(converted_coord)
else:
sys.stderr.write("No blobs found! \n")
#seek()
send2pd(-180)
end_time = time.clock()
elapsed_time = end_time - start_time
times.append(elapsed_time)
frame_rate = 1 / average(times)
sys.stderr.write('Frame rate:' + str(frame_rate) + '\n')
#image.show()
<file_sep>/Projects/2017/SoccerBots/arduino/atan2_test/atan2_test.ino
#include <math.h>
const float TAU = asin(1);
// Oh, there's already a degrees() in math.h?
//float degrees(float radians) {return 360.0 / TAU * radians;}
void atan2_test() {
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
Serial.print("atan2("); Serial.print(x); Serial.print(","); Serial.print(y); Serial.print(") = ");
Serial.println(degrees(atan2(x,y)));
}
}
}
void setup() {
Serial.begin(9600);
}
void halt() {
while (1) {}
}
void loop() {
atan2_test();
halt();
}
<file_sep>/Projects/2016/MIDIBots/arduino/drum_roll/drum_roll.ino
#include "Timer.h"
#include <Servo.h>
Timer *phase_timer = new Timer(50); //starts a new timer
Servo servos [2];
int pos = 0; // variable to store the servo position
const int CENTRE = 90;
const int RANGE = 46;
const int MAX_POS = CENTRE + RANGE/2;
const int MIN_POS = CENTRE - RANGE/2;
const int SERVO_TIME = 100; // ms delay to allow motion to happen
int phase = 0;
void setup()
{
servos[0].attach(9);
servos[1].attach(10);
phase_timer->setOnTimer(&hit); //sets new timer
phase_timer->Start(); //starts new timer
}
void hit(){
phase = !phase;
down_strum(servos[phase]);
up_strum(servos[!phase]);
}
void down_strum(Servo servo){
for (int i = 0; i < 4; i++)
servo.write(MAX_POS);
}
void up_strum(Servo servo){
for (int i = 0; i < 4; i++)
servo.write(MIN_POS);
}
void loop() {
phase_timer->Update();
}
<file_sep>/Projects/2017/SoccerBots/arduino/sensors/mk_shortened.h
//shortened version of In The Hall of The Mountain King for Shutter on startup
const int mk_shortened_tempo = 150;
const int mk_shortened_array_length = 13;
float mk_shortened[mk_shortened_array_length][2] = {{62,0.5},{64,0.5},{65,0.5},{67,0.5},{69,0.5},{65,0.5},{69,0.5},{74,0.5},
{73,0.5},{69,0.5},{73,0.5},{76,0.5},{74,2}};
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_recorderbot/firmware_recorderbot.ino
// RecorderBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
#include <MIDIBot.h>
MIDIBot recorderBot;
const int pipe1 = MOSFET_PWM_PIN;
const int pipe2 = MOSFET_2_PIN;
const int pipe3 = MOSFET_3_PIN;
const int pipe4 = MOSFET_4_PIN;
//midi note numbers
const int note1 = 60;
const int note2 = 61;
const int note3 = 62;
const int note4 = 63;
void note_on(int note, int velocity) {
if(note == note1) {
digitalWrite(pipe1, HIGH);
} else if(note == note2) {
digitalWrite(pipe2, HIGH);
} else if(note == note3) {
digitalWrite(pipe3, HIGH);
} else if(note == note4) {
digitalWrite(pipe4, HIGH);
}
digitalWrite(LED_PIN, HIGH);
}
void note_off(int note, int velocity) {
if(note == note1) {
digitalWrite(pipe1, LOW);
} else if(note == note2) {
digitalWrite(pipe2, LOW);
} else if(note == note3) {
digitalWrite(pipe3, LOW);
} else if(note == note4) {
digitalWrite(pipe4, LOW);
}
digitalWrite(LED_PIN, LOW);
}
void self_test() {
// thisMIDIBot.test_MIDI_channel();
// TODO: Bot-specific self-test routine...
note_on(60, 100); delay(500);
note_off(60, 100); delay(500);
note_on(61, 100); delay(500);
note_off(61, 100); delay(500);
note_on(62, 100); delay(500);
note_off(62, 100); delay(500);
note_on(63, 100); delay(500);
note_off(63, 100); delay(500);
note_on(60, 100); delay(3000);
note_off(60, 100); note_on(61, 100); delay(3000);
note_off(61, 100); note_on(62, 100); delay(3000);
note_off(62, 100); note_on(63, 100); delay(3000);
note_off(63, 100); delay(1000);
note_on(60, 100); delay(1000);
note_on(61, 100); delay(1000);
note_on(62, 100); delay(1000);
note_on(63, 100); delay(1000);
note_off(60, 100); note_off(61, 100); note_off(62, 100); note_off(63, 100);
/*for(int x=0; x<= 10; x += 1) {
note_on(60, 100); delay(2500);
note_off(60, 100); delay(2500);
}*/
}
void setup() {
//recorderBot.test_MIDI_channel(); // Indicate MIDI channel at startup
recorderBot.begin();
}
void loop() {
recorderBot.process_MIDI();
}
<file_sep>/Projects/2017/SoccerBots/todo.txt
Things to be done for the 2017 SoccerBots project
[ ] Register for Nationals!!!
[ ] Move this list to github's issue tracker?
Software:
[ ] Prioritise and complete Pd behaviour for Shutter(attacker)
[ ] Define a DEBUG function or macro for Arduino programs
[?] Rewrite "#ifdef"s to use "#if" conditionals (where it makes sense)
e.g. "#if DEBUGGING==1" instead of "#ifdef DEBUGGING"
[ ] Robot control behaviour (in Pd)
[Y] Arrange for control program to launch when Raspberry Pi boots
Pd startup: pd -noaudio -nomidi patch-filename.pd
[.] EEPROM goodness (motor PWM limits, servo ranges, magnetometer calibration data, etc.)
[Y] Have done this for magnetometer stuff...
[ ] ...but not for machine-dependent motor speed PWM values and servo ranges
[Y] Add restart-on-error to read_sensors.tcl
[ ] Could still add catching of write errors if the pipe (TCP from pdsend to Pd) fails..perhaps restart Pd if so.
[Y] Implement shell "until" loops in runeverything.sh for more graceful and efficient startup.
[ ] Edit /etc/hosts (or equivalent) on remote client computers to add:
192.168.43.253 shutter
192.168.43.237 boris
[ ] ...and aliases:
alias shutter='ssh -Y pi@shutter'
alias boris='ssh -Y pi@boris'
alias attack='ssh -Y pi@shutter'
alias goalie='ssh -Y pi@boris'
[Y] Have runeverything.sh launch separate terminal windows for each task, e.g.
urxvt -name Blah -title Blah -e sh -c "mycmd | targetcmd" &
(might be different for LXTerminal...ah, but both bots already have urxvt as well)
[Y] Fix slow report frequency on sensor board
This was due to the DFRobot board being in the wrong mode, and pulseIn() blocking for a long time when the ultrasound sensor got no reflection.
[Y] sensors.ino: reinstate debugging delay (now that we've figured out why the sensor reporting frequency was so low)
[ ] Get Pd patches to properly handle the 0 values reported by the ultrasonic sensor (these mean "out of range", not 0 cm distance)
[Y] Music for the buzzer!
Tobias has created a nice library of tunes. :)
IR system:
[Y] Implement trigonometry stuff for ball direction finding (use atan2() function)
[Y] Calibrate IR ball distance sensing (want to determine approx. distance based on magnitude of the ball sense vector)
Will probably need to talk about what a vector is and how you can use and combine them. :)
To pipe input from serial:
cu -l ttyUSB0 -s 115200
To pipe a text stream (in FUDI format) into Pd:
pdsend 7000
Combining the two using a shell pipeline:
cu -l ttyUSB0 -s 115200 | pdsend 7000
[N] The RCJ IR beacon pattern varies the signal strength! Might be a good idea for our Arduino program to read frequently and calculate the mean signal strength every n samples.
NOTE: average the raw co-ordinates, not the angle (the sign flip at 180 degrees will cause problems otherwise)
Probably not necessary now that we've added a hardware-based analog low-pass filter to each sensor. :)
Vision system:
[ ] refine debug function for debug levels
[ ] fix white balance bug when click off image
[Y] Add separate calibration program, and handle saving/loading calibration state
[ ] Try to reduce latency with the Pi Camera and SimpleCV
General:
[Y] Design and implement serial protocol for motor control
Hardware:
[ ] Design and build circuits for detecting and alerting on low battery.
Could just have a big red LED that comes on when low.
Or it could provide a signal to the sensor Arduino.
What threshold? Somewhere around 5.5 V?
For NiMH, 1.0-1.1 V per cell is probably about the beginning of the end.
So around 6.0-6.6 V would be a sensible warning threshold.
Of course, under load, the battery voltage will be a bit lower.
http://www.edn.com/design/analog/4427219/Simple-circuit-indicates-a-low-battery
For a threshold around 6-6.6 V, try R1 = 51..56 kohm (or a 100k trimpot)
Also, R5 (100k) might need to be increased to prevent the LED from turning on slightly under normal conditions. Try 1M.
[Y] Redesign main chassis and see if we can get it lasercut (it might be too large for Chris's 3D printer)
The revised design was just small enough to print. :)
[Y] Design and fab main robot platform (3D print? lasercut?)
[ ] Implement servo mechanism for wheels? Optical? Hall sensor?
[.] Design and test kicker mechanism. Servo? Maybe a high-speed one from Pololu.
[, ] Trial using a DSpace Robot board for motor and servo control (rather than separate Arduino + H-bridge)
[Y] Motor Enable switch (just a software switch for the DSpace board)
[Y] Build a power+ground bus board (screw terminals for input, header pins for multiple outputs)
[Y] Main power switch (to save having to disconnect the battery when not in use!)
[ ] A pushbutton switch to safely shut down the Pi (with accompanying software)
[ ] A pushbutton switch to set the orientation to the target goal (once EEPROM saving of magnetometer calibration is done)
[?] Add buzzer, and use it to warn of low voltage as reported by the DC-DC converter
[?] Maybe add lights? Just decorative? Must not confuse other robots!
[Y] Build second robot as Goalie.
[Y] Apply threadlocker (e.g. Loctite) to fasteners before competition
or (perhaps better) use nylock locking nuts
[.] Build IR sensors for ball detection
The high platform and horizontal sensor mounting means the ball can't reliably be detected when close!
Could redesign the platform with an angled (conical?) base perhaps.
[.] Compass sensor (Sebastian and Tobias have been working on this)
[Y] Install range sensors front and/or back for collision avoidance.
[ ] Finish CAD model of mounting bracket and print
[.] Colour sensors for approximate location on the field
Need to get some - Adafruit?
We have a prototype using just an active IR reflectance sensor, which seems to work pretty well.
<file_sep>/Projects/2016/MIDIBots/arduino/pwm_examples/pwm_1.ino
// MIDI note tests for Mechatronics, CME 2016-03-21
// 1. Loop sanity check. Watch for off-by-one errors!
void setup() {
delay(8000); // safety delay for serial I/O
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 128; i++) {
Serial.println(i);
}
while (1) {}
}
<file_sep>/Projects/2017/SoccerBots/arduino/sensors/reflectance.h
const int reflectancePin = A8;
int reflectance;
void readReflectance() {
reflectance = analogRead(reflectancePin);
}
<file_sep>/Projects/2017/SoccerBots/camera_calibration_state.py
calibrated_grey_sample = (175.0, 164.57142857142858, 166.42857142857142)
calibrated_goal_sample = ((101.5, 1.5), (189.5, 19.5), (50.0, 14.0))
<file_sep>/Projects/2016/MIDIBots/arduino/Readme.txt
NOTE: to make these files available in the Arduino IDE Sketchbook menu, you will need to symlink the containing "arduino" folder from the sketchbook folder.
The location of the sketchbook folder is customisable, and the default location varies by platform:
Linux: ~/sketchbook
Mac OS: ~/Documents/Arduino
Windows:
%USERPROFILE%\My Documents\Arduino
%USERPROFILE%\Documents\Arduino
or search the Registry for the path to "My Documents" at "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
There might also be useful Registry entries created by the Arduino IDE.
It might be possible to call the Arduino IDE in command-line mode to find out the sketchbook path, although even that would vary by platform ("Arduino"/"arduino", and it might not be in the path or have a standard installation location).
On Mac OS, assuming you've cloned the git repo into ~/robotics_repo:
ln -s ~/robotics_repo/Projects/2016/MIDIBots/arduino ~/Documents/Arduino/MIDIBots
--
Timer.h is from the PNG library:
https://github.com/aron-bordin/PNG-Arduino-Framework/blob/master/docs/installation.rst
<file_sep>/Projects/2016/MIDIBots/TODO.txt
2016 Otago Regional event was a success! We placed 1st in the Senior Theatre, yay! :)
National event is in Auckland on Saturday, September 10 (entries close Friday, August 26). Some things to work on between now and then:
[ ] Test the spare PSUs (power supply units) in case they're needed
Oh dear. One shuts down, the other blows up! :(
[Y] Make custom Molex power wiring? See Power.txt
[ ] Double-check latency settings for the bots that need it
[ ] Check that the latest code compiles and runs correctly, and that it's all in the repository and pushed to github
This will be very important if we have to make last-minute code changes at the event!
[ ] Sequence the music and lighting in Rosegarden!
See Music.txt for suggestions for the medley
[ ] Add triangle hit between We Will Rock You and Smoke on the Water, to mark the transition.
[ ] Change chords at end of Trololo - maybe should be
[ ] Occasional percussion during Fuer Elise?
[ ] Check latency (delay) setting for each segment. Parts for one channel might need to be split across multiple tracks or segments, e.g. for PercussionBot's shaker, which has more delay I think.
[ ] Check which system timer is being used for Rosegarden's sequencer. The default 250 Hz one might be a bit coarse.
[Y] Refactor the firmware programs to use our MIDIBot library:
[Y] UkeBot
[Y] LightingBot
[Y] PercussionBot
[Y] DrumBot
[Y] SynthBot
[ ] Tweak lighting on individual bots (placement, colour, fading)
Maybe illuminated balloon idea? They look great using the 12 V LED modules from Jaycar
SynthBot
PercussionBot
LightingBot?
[ ] Fix bug in conditionally-compiled code for the ATmega1280/2560 in programs that use custom PWM control (comma should be semicolon)
We're only using one Mega (for FanBot) but just in case...
[ ] Also, the custom PWM code doesn't correctly handle a duty cycle of 0, it seems - on the oscilloscope on the FanBot firmware test, a setting of 0 still gives a narrow pulse.
Try phase-correct PWM. See:
http://stackoverflow.com/questions/23853066/how-to-achieve-zero-duty-cycle-pwm-in-avr-without-glitches
UkeBot:
[Y] Cut off excess board behind tuning pegs for easier access.
[N] Upgrade tuners to geared ones? Maybe not worth the expense. Also, with some force, they're more stable now.
[Y] Reduce friction in slide guideway: reshape a little, rub wax into wood.
[Y] Slide mechanism for UkeBot (stepper motor)
In the end we used a servo motor and a linkage
DrumBot:
[ ] Get a proper snare drum for DrumBot (or adapt existing one)?
PercussionBot:
[Y] Troubleshoot PercussionBot
The shield was not properly seated, and digital pins 10 and 11 do not work properly any more (tested on oscilloscope). With a new Arduino board it seems OK.
I think the old board is more fried than just those two pins - it's been getting very hot, both in the power circuits and the main microcontroller chip it seems. Better not use it!
[ ] Fix backlash in triangle striker
[ ] Fix resonance in triangle mount
[ ] add rattle (DC motor - fan with blade striker?)
[ ] Tweak latencies per instrument
[Y] use alternating note numbers for shaker movement
LightingBot:
[Y] Finalise firmware for LightingBot to include driving the RGB lighting strip(s), maybe look at MIDI CC messages
Works fine with MIDI note messages; don't bother with MIDI CC for now.
[Y] Laser-cut logo (Henry)
FanBot:
[Y] Solder a wire onto the shield for 3.3 V supply for the BMP085 pressure sensor
[N] Add break-out headers to the stripboard for the pressure sensor (already have ground, but will need 3.3 V supply, and SDA and SCL for I2C. These will go to pins 20 and 21 on the Mega.
[Y] Wire up stripboard breakout for the fan. There's no connection yet between the tach output and the Mega, but everything else (including pull-up resistor) is there.
[Y] Solder on a wire from pin 12 on the shield, since that's the pin that's used for custom PWM on the Mega. This is for fan speed control, which is supposed to be ~25 kHz.
[Y] Air reservoir system for woodwind instruments (learn about control systems in the process)
[ ] WhistleBot (slide whistle)
[ ] RecorderBot. With a taped-over thumb-hole and solenoid finger-hole valves on the first four holes, we can play the important bits of the melody from "We Will Rock You".
[ ] Harmonica? Bird Whistle? Pan Pipes?
[ ] Could extend music to include a medley of different music. Suggestions..?
Uke can now play bits of the melody from Fuer Elise (perhaps duet with SynthBot)
Smoke on the Water?
Percussion section solo (funky beats, with lighting show)
Chris:
[N] Buy a set of Chinese Arduino clones
No, we have enough if we use Paul Campbell's and use a Mega for the FanBot (in order to get access to the I2C pins).
<file_sep>/Projects/2017/RescueBot/arduino/sensor_test/sensor_test.ino
// Testing the IR reflectance sensors with the DSpace Robot board
// Working towards a line-following robot for Robocup 2017
// Current config (on the 2013 Dalek test-bed) uses pin 2 on each of sensor blocks SENSOR0, SENSOR1, SENSOR2, and SENSOR3.
// These correspond to A0..A3.
// A4 and A5 are also available
#define L_PIN A0
#define M_PIN A1
#define R_PIN A2
#define WHITE_ON_BLACK 1
// Will need light/dark thresholds for each sensor for calibration...
// ...or just one for all, if they read consistently enough
const int SENSOR_THRESHOLD=250;
// TODO: a #define flag for black line on white background or vice versa.
void setup() {
pinMode(A0, INPUT); digitalWrite(A0, LOW);
pinMode(A1, INPUT); digitalWrite(A1, LOW);
pinMode(A2, INPUT); digitalWrite(A2, LOW);
Serial.begin(9600);
}
// Read and compare with threshold:
bool line_detected(int analogPin) {
int raw_reading = analogRead(analogPin);
// TODO: if debugging, print raw reading to serial output
// If you need to flip the light/dark sense, do it here
#ifdef WHITE_ON_BLACK
return (raw_reading < SENSOR_THRESHOLD); // White line, black background
#else
return (raw_reading > SENSOR_THRESHOLD); // Black line, white background
#endif
}
void control() {
bool l_line = isBlack(L_PIN);
bool m_line = isBlack(M_PIN);
bool r_line = isBlack(R_PIN);
// TODO: could shift and combine the boolean values for more readable code
// e.g. switch bits ... 0b000 -> lost ... 0b010 -> fwd ...
if (!l_line && !m_line && !r_line) {Serial.println("Lost!");}
if (!l_line && !m_line && r_line) {Serial.println("spin right");}
if (!l_line && m_line && !r_line) {Serial.println("fwd");}
if (!l_line && m_line && r_line) {Serial.println("veer right");}
if ( l_line && !m_line && !r_line) {Serial.println("spin left");}
if ( l_line && !m_line && r_line) {Serial.println("?!");}
if ( l_line && m_line && !r_line) {Serial.println("veer left");}
if ( l_line && m_line && r_line) {Serial.println("perpendicular?!");}
}
void debug() {
Serial.print(line_detected(A0)); Serial.print(" ");
Serial.print(line_detected(A1)); Serial.print(" ");
Serial.print(line_detected(A2)); Serial.print(" ");
Serial.println();
delay(100);
}
bool isBlack(int pin) { return analogRead(pin) > SENSOR_THRESHOLD;}
void loop() {
control();
//delay(100);
//Serial.print("A0:"); Serial.print(analogRead(A0)); Serial.print(" ");
//Serial.print("A1:"); Serial.print(analogRead(A1)); Serial.print(" ");
//Serial.print("A2:"); Serial.println(analogRead(A2));
//Serial.print(isBlack(A0)); Serial.print(" ");
//Serial.print(isBlack(A1)); Serial.print(" ");
//Serial.print(i475sBlack(A2)); Serial.print(" ");
//Serial.println();
delay(250);
}
<file_sep>/Projects/2017/SoccerBots/arduino/buzzer/buzzer.ino
#include "pokemon.h"
#include "nokia.h"
#include "mountainKing.h"
#include "fnaf.h"
#include "sherlock.h"
const int buzzerPin = 10;
int crotchet;
float frequency(int note) {
return 440 * pow(2.0, (note - 69) / 12.0);
}
void playNote(int pitch, int duration) {
tone(buzzerPin, (int)round(frequency(pitch)), duration);
delay(duration+5);
noTone(buzzerPin);
delay(5);
}
void setNoteDurations(int bpm) {
crotchet = 60000 / bpm;
}
void playTune(float tune[][2], int tempo, int arrayLength) {
setNoteDurations(tempo);
for(int x=0; x<arrayLength; x+=1) {
if(tune[x][0] == 0) {
delay(tune[x][1]*crotchet);
} else {
playNote(tune[x][0], tune[x][1]*crotchet);
}
}
}
void setup() {
Serial.begin(9600);
}
void loop() {
/*playTune(pokemon, pokemonTempo, pokemonArrayLength);
playTune(nokia, nokiaTempo, nokiaArrayLength);
playTune(mountainKing, mountainKingTempo, mountainKingArrayLength);
playTune(fnaf, fnafTempo, fnafArrayLength);*/
playTune(sherlock, sherlockTempo, sherlockArrayLength);
}
<file_sep>/Projects/2017/SoccerBots/opencv-install.sh
# Clear some space:
sudo apt-get purge wolfram-engine
sudo apt-get clean
sudo apt-get install localepurge
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install build-essential cmake pkg-config
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev
sudo apt-get install libgtk2.0-dev
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install python2.7-dev python3-dev
# That should be it for the dependencies
# Now get the OpenCV sources:
# At present (2017-09-17), v3.3.0 is the latest.
cd /usr/local/src
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd opencv
git checkout tags/3.3.0
cd ../opencv_contrib
git checkout tags/3.3.0
# Then virtualenv setup using Python pip...
# ...
# Calling cmake:
cd /usr/local/src/opencv
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=/usr/local/src/opencv_contrib/modules \
-D BUILD_EXAMPLES=ON ..
make -j 4
cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so
exit
# Oh dear
[ 86%] Building CXX object samples/cpp/CMakeFiles/cpp-tutorial-pnp_registration.dir/tutorial_code/calib3d/real_time_pose_estimation/src/PnPProblem.cpp.o
c++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.9/README.Bugs> for instructions.
modules/python2/CMakeFiles/opencv_python2.dir/build.make:324: recipe for target 'modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o' failed
make[2]: *** [modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o] Error 4
CMakeFiles/Makefile2:20896: recipe for target 'modules/python2/CMakeFiles/opencv_python2.dir/all' failed
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[ 86%] Building CXX object samples/cpp/CMakeFiles/cpp-tutorial-pnp_registration.dir/tutorial_code/calib3d/real_time_pose_estimation/src/RobustMatcher.cpp.o
[ 86%] Building CXX object samples/cpp/CMakeFiles/cpp-tutorial-pnp_registration.dir/tutorial_code/calib3d/real_time_pose_estimation/src/Utils.cpp.o
[ 86%] Building CXX object modules/stitching/CMakeFiles/opencv_perf_stitching.dir/perf/perf_stich.cpp.o
[ 86%] Linking CXX executable ../../bin/cpp-tutorial-pnp_registration
[ 86%] Built target cpp-tutorial-pnp_registration
[ 86%] Linking CXX executable ../../bin/opencv_perf_stitching
[ 86%] Built target opencv_perf_stitching
[ 86%] Linking CXX shared module ../../lib/python3/cv2.cpython-34m.so
[ 86%] Built target opencv_python3
Makefile:160: recipe for target 'all' failed
make: *** [all] Error 2
# Out of memory while compiling, maybe?
# Yep:
[26030.153193] Out of memory: Kill process 22510 (cc1plus) score 328 or sacrifice child
[26030.153206] Killed process 22510 (cc1plus) total-vm:348648kB, anon-rss:300820kB, file-rss:0kB, shmem-rss:0kB
# Tried again without -j 4, and it got there. It was building the cv2.cpp.o object that was the big obstacle (took some minutes for that one file!).
# The build folder after compiling contains about 3.4 GB of data, so that much will need to be left free before building.
<file_sep>/Documentation/Computer Vision/infoscimechatronics/cvutils.py
# A collection of handy functions built on SimpleCV for our robotics projects
# TODO: sort out image.show() vs image.save(display) pros/cons and scaling weirdness.
# We need this, obviously:
import SimpleCV
import numpy
import time
import sys
# Some colour space conversion functions:
# These might be handy when converting from an HSV colour reported by GIMP to one that SimpleCV can use directly.
def hue_from_angle(degrees): return degrees / 360.0 * 255
def sat_from_percent(percent): return percent / 100.0 * 255
# Actually doesn't give the right numbers?! TODO: test!
# Generate a solid colour image, matching the resolution and format of the supplied image:
# (I couldn't see any way to create a new blank image using Image - supposedly you can call the constructor with a width and height, but not sure about setting the default colour)
def solid(image, colour):
solid = image.copy()
solid[0:solid.width, 0:solid.height] = colour
return solid
# Or, now that I know about this:
#def solid(image, colour):
# solid=image.copy()
# solid.drawRectangle(0,0,solid.width,solid.height, color=colour)
# return solid
# No! drawRectangle draws only the border, not a solid area!
# Oh, wait, you pass Image() an (x,y) dimension tuple when creating it.
def solid_(template_image, colour):
solid = SimpleCV.Image(template_image.width,template_image.height)
solid[0:solid.width, 0:solid.height] = colour
return solid
# Bah, problems with numpy array format...
def solid__(width, height, colour):
solid = SimpleCV.Image(width,height)
solid[0:width, 0:height] = colour
return solid
# or would it be better to pass (width,height) as a tuple in our function too?
# e.g.
# image = camera.getImage()
# red = solid(image, (255,0,0))
# Pixel function for highlighting pixels (e.g. to assist in troubleshooting image processing)
# Actually, applying Python-based pixel functions is ridiculously slow, so maybe this is no use...
# Also, scaling the image first seems to bork things. Maybe different pixel format? Oh, well..
def highlight(pixels):
r=pixels[0]
g=pixels[1]
b=pixels[2]
return (int(255*pow(r/255.0, 0.25)), int(255*pow(g/255.0, 0.25)), int(255*pow(b/255.0, 0.25)))
# Correct an image for white balance based on a sample grey point:
# NOTE: assumes RGB - should probably check for that and warn/convert if necessary.
def wb(image,grey_sample):
grey=numpy.mean(grey_sample)
r_corr = grey / grey_sample[0]
g_corr = grey / grey_sample[1]
b_corr = grey / grey_sample[2]
#print('r_corr=' + str(r_corr) + ', g_corr=' + str(g_corr) + ', b_corr=' + str(b_corr))
r,g,b=image.splitChannels()
r = r * float(r_corr)
g = g * float(g_corr)
b = b * float(b_corr)
return SimpleCV.Image.mergeChannels(r,r,g,b)
# Test it:
#camera.live()
## coord: (225,264), color: (158.0, 164.0, 184.0)
#x=225
#y=264
#grey_sample=(158.0, 164.0, 184.0)
#image=camera.getImage()
#image.getPixel(x,y) # Um, row/column transposition?!
#corrected=wb(camera.getImage(), grey_sample)
#corrected.getPixel(x,y)
## How fast (slow!) is it?:
##while True:
# wb(camera.getImage(), grey_sample).show()
## And with the undistortion?
#while True:
# wb(camera.getImageUndistort(), grey_sample).show()
## And at reduced resolution?
#while True:
# wb(camera.getImageUndistort().scale(0.25), grey_sample).show()
# Helper function for setting the white balance manually, based on a series of samples from the camera.
# NOTE: Display.mouseLeft returns the current state of the button, whereas Display.leftButtonDownPosition() returns None unless the button was only JUST pressed. We want Display.mouseX and Display.mouseY instead, I think.
def calibrate_white_balance(camera):
display=SimpleCV.Display()
#camera=SimpleCV.Camera()
prev_mouse_state = False
sample_pixels = []
image = camera.getImage().scale(0.5)
image.drawText("Hold mouse button over white/grey", 8,8,color=SimpleCV.Color.YELLOW,fontsize=14)
image.save(display)
time.sleep(2)
sys.stderr.write('Press and hold left mouse button over a region that should be white/grey...')
while display.isNotDone():
image = camera.getImage().scale(0.5)
image.save(display)
if display.mouseLeft:
x = display.mouseX
y = display.mouseY
if not prev_mouse_state:
# Button just pressed - initialise new list:
sample_pixels = []
#print(sample_pixels)
colour_sample = image.getPixel(x,y)
# Indicate the point being sampled:
image.drawCircle((x,y),rad=5,color=SimpleCV.Color.VIOLET,thickness=1)
image.save(display)
sys.stderr.write(str(x) + ', ' + str(y) + ': ' + str(colour_sample))
sample_pixels.append(colour_sample)
prev_mouse_state = True
else:
if prev_mouse_state:
# Button just released:
# Um, how to take the mean of a list of tuples?
mean_sample = tuple(map(lambda y: sum(y) / float(len(y)), zip(*sample_pixels)))
sys.stderr.write('mean grey sample: ' + str(mean_sample))
return mean_sample # or rinse and repeat? Maybe not - fn can just be called again if needed.
prev_mouse_state = False
# Usage:
#camera=SimpleCV.Camera()
#grey_sample = calibrate_white_balance()
#while True:
# wb(camera.getImage(), grey_sample).show()
# TODO: might be nice to calculate the correct colour temperature so at least the camera could be set to that in a fixed way...might give better colour resolution than doing it in SimpleCV, which seems to have only 8-bit colour depth per channel.
# Function for identifying black regions in the image:
def find_black(image,value_threshold=75,saturation_threshold=90):
v,s,h = image.toHSV().splitChannels()
dark = v.binarize(value_threshold) # had 90 on ProBook cam
grey = s.binarize(saturation_threshold)
return (dark/16) * (grey/16)
# Function for calibrating the colour matcher, which will be quite similar to the white-balance sampler.
# Hmm, this should really use WB-corrected images! But how does it know what correction to apply? Might have to add a grey-sample parameter.
def calibrate_colour_match(camera, grey_point):
display=SimpleCV.Display()
#camera=SimpleCV.Camera()
prev_mouse_state = False
sample_pixels = []
image = wb(camera.getImage().scale(0.5), grey_point).toHSV()
image.drawText("Hold mouse button over target", 8,8,color=SimpleCV.Color.YELLOW,fontsize=14)
image.save(display)
time.sleep(2)
sys.stderr.write('Press and hold left mouse button over the region whose colour you wish to match...')
while display.isNotDone():
image = wb(camera.getImage().scale(0.5), grey_point).toHSV()
image.save(display)
if display.mouseLeft:
x = display.mouseX
y = display.mouseY
if not prev_mouse_state:
# Button just pressed - initialise new list:
sample_pixels = []
#print(sample_pixels)
colour_sample = image.getPixel(x,y)
# Indicate the point being sampled:
image.drawCircle((x,y),rad=5,color=SimpleCV.Color.VIOLET,thickness=1)
image.save(display)
sys.stderr.write(str(x) + ', ' + str(y) + ': ' + str(colour_sample))
sample_pixels.append(colour_sample)
prev_mouse_state = True
else:
if prev_mouse_state:
# Button just released:
# Find the mean hue, saturation, and value...
sample_pixels_transposed = zip(*sample_pixels)
mean_sample = tuple(map(lambda y: sum(y) / float(len(y)), zip(*sample_pixels)))
sys.stderr.write('mean sample (HSV): ' + str(mean_sample))
# ...and also the max and min in order to determine the range to match within each (probably ignore value, ultimately).
# Could perhaps just take the smaller of the ranges symmetrically around the mean...or the larger...
# Of course, the min and max are not necessarily equidistant from the mean...maybe better to use the midpoint of the min and max only...though I think it would be nice to recognise the mean somehow...
# We could get super-fancy and build a probability distribution function, I guess...
# ...but note that we are kind of assuming that the hue and saturation dimensions are completely independent, which is probably not realistic (even for diffuse reflections?).
sample_min = tuple(map(min, sample_pixels_transposed))
sample_max = tuple(map(max, sample_pixels_transposed))
# Ugh, you can't just subtract two tuples in Python?!
hue_midpoint = (sample_max[0] + sample_min[0]) / 2.0
sat_midpoint = (sample_max[1] + sample_min[1]) / 2.0
val_midpoint = (sample_max[2] + sample_min[2]) / 2.0
hue_tolerance = sample_max[0] - hue_midpoint
sat_tolerance = sample_max[1] - sat_midpoint
val_tolerance = sample_max[2] - val_midpoint
# Alternatively, mean-based tolerance:
#hue_tolerance=min(sample_max[0]-mean_sample[0], mean_sample[0]-sample_min[0])
#sat_tolerance=min(sample_max[1]-mean_sample[1], mean_sample[1]-sample_min[1])
sys.stderr.write('hue midpoint:' + str(hue_midpoint))
sys.stderr.write('hue tolerance:' + str(hue_tolerance))
sys.stderr.write('saturation midpoint:' + str(sat_midpoint))
sys.stderr.write('saturation tolerance:' + str(sat_tolerance))
sys.stderr.write('value midpoint:' + str(val_midpoint))
sys.stderr.write('value tolerance:' + str(val_tolerance))
# What structure to return? Perhaps a pair of triples, each having the HSV means and thresholds?
# Or a triple of pairs?
return ((hue_midpoint,hue_tolerance),(sat_midpoint,sat_tolerance),(val_midpoint,val_tolerance))
#return mean_sample # or rinse and repeat?
prev_mouse_state = False
# Hmm, those .5s are suspicious - is something being quantised to integers somewhere?
# Oh, no, it's OK - the min and max will always be integers, therefore the precision of the midpoints will be 0.5.
#h,s,v=sample
#hue_midpoint,hue_tolerance=h
#sat_midpoint,sat_tolerance=s
#v_midpoint,v_tolerance=v
# Can we simply write:
# Nice. Let's do likewise for colour matching:
# TODO: refine saturation matching. I suspect we want to match any saturation below the threshold, not just within a range, because of specular highlights.
def find_colour_1(image, hue, hue_thresh, sat, sat_thresh):
colour_hue = (hue,hue,hue)
colour_sat = (sat,sat,sat)
v,s,h = image.toHSV().splitChannels()
hue_proximity = h.colorDistance(colour_hue).binarize(hue_thresh)
sat_proximity = s.colorDistance(colour_sat).binarize(sat_thresh)
return ((hue_proximity/16.0) * (sat_proximity/16.0))
# Now that we have a function that returns an HSV triple of midpoints and tolerances, let's use those.
# Also, probably more efficient to convert to greyscale somewhere along the line...
def find_colour(image, hsv_midpoints_and_tolerances):
# Unpack HSV target midpoints and tolerances:
h,s,v = hsv_midpoints_and_tolerances
hue_midpoint,hue_tolerance = h
sat_midpoint,sat_tolerance = s
#v_midpoint,v_tolerance=v
# (we ignore value for now)
colour_hue = (hue_midpoint,hue_midpoint,hue_midpoint)
colour_sat = (sat_midpoint,sat_midpoint,sat_midpoint)
v,s,h = image.toHSV().splitChannels(grayscale=True)
# NOTE: v,s,h at this point are each BGR images..why? Supposedly, Image.splitChannels() has a grayscale parameter, which is True by default. But even with that explicitly set to true, the resulting images are BGR.
h = h.toGray()
s = s.toGray()
#v = v.toGray()
# Not sure why the tolerances are coming out too small, but I'm having to multiply them by a minimum of about 3 to get good matching overall.
hue_proximity = h.colorDistance(colour_hue).binarize(hue_tolerance*3)
sat_proximity = s.colorDistance(colour_sat).binarize(sat_tolerance*3)
return ((hue_proximity/16.0) * (sat_proximity/16.0))
# Next we need a way to find the centroid of the matching (white) pixels in an image, e.g. for targeting.
# Also, how much of the horizontal field of vision is occupied by a particular colour, since when the goal is near, the angle is not critical.
# Could probably just use blobs for that, using the bounding box.
<file_sep>/Projects/2017/SoccerBots/goal-tracking.py
import SimpleCV
import os
import sys
sys.path.append(os.environ['HOME'] + '/robotics_repo/Documentation/Computer Vision/infoscimechatronics')
import cvutils
import time
import serial
ser = serial.Serial('/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_85431303736351D070E0-if00')
camera = SimpleCV.Camera(0, {"width":960,"height":540})
os.system(os.environ['HOME'] + '/robotics_repo/Projects/2017/SoccerBots/uvcdynctrl-settings.tcl')
speed = 0
#global current_angle
#current_angle = 0
prev_error = 0
integral = 0
derivative = 0
#global hunt_dir
hunt_dir = 1
hunt_step = 15
#blobs_threshold = 0.0075
blobs_threshold = 0.0005
times = []
output = True
image_output = True
calibrating = False
scale_factor = 1/64.0
def debug(msg):
global output
if output == True:
sys.stderr.write(str(msg) + '\n')
lab_grey_sample = (155.40740740740742, 150.55555555555554, 160.07407407407408)
lab_goal_blue = ((104, 2), (218.5, 6.5), (127.5, 14.5))
if calibrating:
grey_sample = cvutils.calibrate_white_balance(camera)
target_colour = cvutils.calibrate_colour_match(camera, grey_sample)
else:
grey_sample = lab_grey_sample
target_colour = lab_goal_blue
debug(target_colour)
def average(numbers):
x = 0
for num in numbers:
x += num
x = float(x) / len(numbers)
return x
def x_coordinate_to_angle(coord):
return coord*35.543
def image_debug(img):
global image_output
if image_output:
img.show()
#Sends serial data to connected Arduino, input data between -90 to 90, output data to servo is 0 to 180 deg
def servo(target_angle):
current_angle = get_current_angle() + 90
debug("current angle: " + str(current_angle) + ' ' + "target angle: " + str(target_angle))
for i in range(abs(int(target_angle))):
if target_angle > 0:
if current_angle < 180:
ser.write('+')
if target_angle < 0:
if current_angle > 0:
ser.write('-')
#time.sleep(0.2)
def get_current_angle():
global ser
ser.write("?")
return int(ser.readline().strip()) - 90
def clip_angle(angle):
if angle < -90:
return -90
if angle > 90:
return 90
else:
return angle
def servo_abs(target_angle):
servo(target_angle - get_current_angle())
def seek():
debug('Seek called & hunt_dir = ' + str(hunt_dir))
global hunt_step
global hunt_dir
current_angle = get_current_angle()
if current_angle >= 90 or current_angle <= -90:
hunt_dir *= -1
servo_abs(clip_angle(current_angle + hunt_dir * hunt_step))
time.sleep(0.05)
while True:
start_time = time.clock()
image = cvutils.wb(camera.getImage().scale(scale_factor), grey_sample)
v,s,h = image.toHSV().splitChannels()
hue_match = h.colorDistance((target_colour[0][0],target_colour[0][0],target_colour[0][0])).binarize(target_colour[0][1]*3)
sat_match = s.colorDistance((target_colour[1][0],target_colour[1][0],target_colour[1][0])).binarize(target_colour[1][1]*3)
matched = ((hue_match / 16) * (sat_match / 16))
image_debug(matched)
blobs = matched.findBlobs(100, 1)
if blobs is not None:
blob_size = blobs[-1].area()
image_size = image.area()
#print blob_size / image_size
if blob_size / image_size < blobs_threshold:
print 'Blobs too small!'
seek()
else:
(x,y) = blobs[-1].centroid()
image.dl().line((x,0), (x,image.height), (255,0,0), antialias=False)
image.dl().line((0,y), (image.width,y), (0,255,0), antialias=False)
image_debug(image)
#print float(x) / image.width
converted_coord = float(x) / image.width
converted_coord = x_coordinate_to_angle(converted_coord*2-1)
debug('converted_coord: ' + str(converted_coord) + ' ')
servo(converted_coord*0.3)
else:
print 'No blobs found!'
seek()
end_time = time.clock()
elapsed_time = end_time - start_time
times.append(elapsed_time)
frame_rate = 1 / average(times)
sys.stderr.write('Frame rate:' + str(frame_rate) + '\n')
#image_debug(image)
<file_sep>/Projects/2017/SoccerBots/arduino/ultrasonic_test/ultrasonic_test.ino
const int trig = 5;
const int pwm = 8;
const int unit_division_factor = 40;
int us_distance;
void setup() {
pinMode(trig, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trig, LOW);
digitalWrite(trig, HIGH);
us_distance = pulseIn(pwm, LOW);
Serial.println(us_distance / unit_division_factor);
delay(20);
}
<file_sep>/Projects/2016/MIDIBots/arduino/digital_pin_test/digital_pin_test.ino
// We've had so many issues with flaky digital pins that it's probably worth having a test program that toggles each one a few times for easy testing on the oscilloscope...
const int FIRST_PIN = 8;
const int LAST_PIN = 13;
void setup()
{
for (int pin = FIRST_PIN; pin <= LAST_PIN; pin++) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
}
void loop()
{
for (int pin = FIRST_PIN; pin <= LAST_PIN; pin++) {
multiflash(pin, 4);
}
}
void multiflash(int pin, int times) {
for (int i = 0; i < times; i++) {
flash(pin);
}
}
void flash(int pin) {
digitalWrite(pin, HIGH);
delay(100);
digitalWrite(pin, LOW);
delay(150);
}
<file_sep>/Projects/2016/MIDIBots/arduino/bmp085_demo/bmp085_demo.ino
// Put this line at the top of your program
#define BMP085_ADDRESS 0x77 // I2C address of BMP085
// Read 1 byte from the BMP085 at 'address'
char bmp085Read(unsigned char address)
{
unsigned char data;
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 1);
while(!Wire.available())
;
return Wire.read();
}
// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(unsigned char address)
{
unsigned char msb, lsb;
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 2);
while(Wire.available()<2)
;
msb = Wire.read();
lsb = Wire.read();
return (int) msb<<8 | lsb;
}
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_fanbot/firmware_fanbot.ino
// Fan control firmware for 2016 MIDIBots
// Possibly doesn't need to use MIDIBot library, but the MIDI control is handy for testing.
/*
TODO:
[ ] Add code to read from pressure sensor. Should take initial reading for "zero" reference at startup, since the sensor is absolute, not relative (differential) and ambient pressure can vary.
[ ] Add code to control fan speed to maintain desired pressure. PID control? Have some sanity checks, e.g. spin down if fault detected/suspected (if monitoring the fan's tachometer output).
https://www.youtube.com/watch?v=UR0hOmjaHp0
http://robotics.stackexchange.com/questions/10127/pid-with-position-and-velocity-goal/10128#10128
http://robotics.stackexchange.com/questions/5260/the-aerial-refueling-problem-sketch-of-a-feedback-controller
https://www.youtube.com/watch?v=H4YlL3rZaNw
https://www.youtube.com/watch?v=taSlxgvvrBM
*/
#include <Servo.h>
#include <Wire.h>
#include <MIDIBot.h>
MIDIBot fanBot;
Servo partyPopperServo;
#define BMP085_ADDRESS 0x77 // I2C address of BMP085
#define DEBUG 1
#define NO_PID 1
const unsigned char OSS = 0; // Oversampling Setting
long target_pressure = 250; // Pa relative to initial reference reading
#ifdef DEBUG
int control_enabled = 1;
#else
int control_enabled = 0;
#endif
unsigned long last_micros = 0;
const float Kp = 0.001,
Ki = 0.0003 * 300000, //original constant were for 300ms sampling period //0.0003
Kd = 0.0001 * 300000; //0.0001
long ref_pressure = 0;
float integral = 0;
long prev_error = 0;
float control = 0;
const int PARTY_POPPER_MAX = 170;
const int PARTY_POPPER_MIN = 40;
// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;
// MIDI note mapping:
const int FAN_NOTE_ON = 1;
const int FAN_NOTE_OFF = 0;
const int FAN_UP_NOTE = 5;
const int FAN_DOWN_NOTE = 6;
const int PARTY_POPPER_FIRE_NOTE = 3;
const int PART_POPPER_RELEASE_NOTE= 4;
// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
// so ...Temperature(...) must be called before ...Pressure(...).
long b5;
short temperature;
long pressure;
// Use these for altitude conversions
const float p0 = 101325; // Pressure at sea level (Pa)
float altitude;
const int PWM_FREQUENCY = 25000; // Intel 4-wire fan spec. The Delta fan datasheet indicates 30 kHz .. 300 kHz, however.
void setup() {
#ifdef DEBUG
Serial.begin(115200);
#else
fanBot.begin();
#endif
// fan_speed(0); // Bit dodgy setting this before the setup routine, but the fan spools up for some seconds otherwise.
Wire.begin();
bmp085Calibration();
partyPopperServo.attach(SERVO_3_PIN);
partyPopperServo.write(PARTY_POPPER_MIN);
#ifdef NOPID
// Start up immediately
#else
// NOTE: the Mega tends to output HIGH on pin 12 during programming, so we need to wait a bit for the fan to stop completely and the pressure to return to ambient before taking our initial reading.
digitalWrite(LED_PIN, HIGH); // Light the LED to indicate we're busy
delay(13000);
digitalWrite(LED_PIN, LOW);
#endif
calibrate();
// Gah, can't get fan speed control to work when using MIDI input. Works OK using plain serial?! Dunno....
// set_fan_speed(0.5);
party_popper_fire();
}
int control_byte = 0;
// For testing:
int fan_speed = 0;
//const int FAN_SPEED_INCREMENT = 5,
const int MIN_SPEED = 0,
MAX_SPEED = 255;
/*
void speed_increase() {
fan_speed += FAN_SPEED_INCREMENT ;
if (fan_speed > MAX_SPEED) {fan_speed = MAX_SPEED;}
set_fan_speed(fan_speed / 255.0);
}
void speed_decrease() {
fan_speed -= FAN_SPEED_INCREMENT;
if (fan_speed < MIN_SPEED) {fan_speed = MIN_SPEED;}
set_fan_speed(fan_speed / 255.0);
}
*/
void calibrate(){
temperature = bmp085GetTemperature(bmp085ReadUT());
ref_pressure = bmp085GetPressure(bmp085ReadUP());
// Serial.println(ref_pressure);
}
int rel_pressure(){
temperature = bmp085GetTemperature(bmp085ReadUT());
return bmp085GetPressure(bmp085ReadUP()) - ref_pressure;
}
unsigned long elapsed_micros(){
unsigned long current_micros = micros();
unsigned long micros_difference = current_micros - last_micros;
last_micros = current_micros;
return micros_difference;
}
void loop() {
#ifdef NOPID
// Fan speed controlled directly by MIDI note-on velocity
#else
unsigned long delta_t = elapsed_micros();
long pressure = rel_pressure();
//altitude = (float)44330 * (1 - pow(((float) pressure/p0), 0.190295));
//fanBot.test_blink();
// Proportional:
long error = target_pressure - pressure;
// Integral:
if (control <= 1 && control >= 0)
{
integral += error / float(delta_t) ;
}
// Derivative:
float derivative = (error - prev_error ) / float(delta_t);
// Combined control:
if(control_enabled){
control = error * Kp + integral * Ki + derivative * Kd;
set_fan_speed(control); //control
} else{
set_fan_speed(0);
}
prev_error = error;
#endif
#ifdef DEBUG
if (Serial.available()) {
int control_byte = Serial.read();
// TODO: error-checking?
switch (control_byte) {
case '+': target_pressure_increase(); break;
case '=': target_pressure_increase(); break;
case '-': target_pressure_decrease(); break;
case '_': target_pressure_decrease(); break;
}
}
Serial.print("Target pressure: ");
Serial.println(target_pressure);
Serial.print("pressure: ");
Serial.println(pressure);
Serial.print("Proportional: ");
Serial.println(error * Kp, 6);
Serial.print("Integral: ");
Serial.println(integral * Ki, 6);
Serial.print("Derivative: ");
Serial.println(derivative * Kd, 6);
Serial.print("Combined control: ");
Serial.println(control, 6);
Serial.println("Elapsed Micros:");
Serial.println(elapsed_micros());
Serial.println();
delay(300);
#else
fanBot.process_MIDI();
#endif
}
// Tricky low-level code from Chris for programming the PWM output for precise frequencies...
// Delta fan speed control requires a PWM signal with a base frequency of about 25 kHz.
// The standard Arduino PWM runs much lower than this, so we have to program it directly using the AVR control registers.
// On the Mega, we have timer1 attached to pins D11 and D12, D12 being the primary one.
// On "ordinary" Arduinos, it's on pins 9 and 10. On the MIDIBot shield, pin 10 is Servo 2 (middle pin).
// Ideally we'd use the PWM MOSFET output on D6, but that uses Timer 0 and doesn't support frequency-accurate PWM, as far as I can tell.
// This will need an external circuit anyway to limit the current and block DC, so it's not a huge hassle to add a MOSFET circuit (with resistors and protection diode) to this as well. It can be powered from one of the aux 12 V headers.
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
const int OUTPUT_PIN = 12;
const int OUTPUT_PIN_AUX = 11;
#else
const int OUTPUT_PIN = 10;
const int OUTPUT_PIN_AUX = 9;
#endif
// General settings:
const int prescale = 8;
// Some PWM control definitions:
#define TIMER_CLK_STOP 0x00 ///< Timer Stopped
#define TIMER_CLK_DIV1 0x01 ///< Timer clocked at F_CPU
#define TIMER_CLK_DIV8 0x02 ///< Timer clocked at F_CPU/8
#define TIMER_CLK_DIV64 0x03 ///< Timer clocked at F_CPU/64
#define TIMER_CLK_DIV256 0x04 ///< Timer clocked at F_CPU/256
#define TIMER_CLK_DIV1024 0x05 ///< Timer clocked at F_CPU/1024
// This defines which bits within the TCCRnB register determine the prescale factor:
#define TIMER_PRESCALE_MASK 0xF8 // 0B11111000
// Map desired prescale divider to register bits:
byte timer_prescale_bits(int prescale) {
if (prescale == 1)
return 0x01;
else if (prescale == 8)
return 0x02;
else if (prescale == 64)
return 0x03;
else if (prescale == 256)
return 0x04;
else if (prescale == 1024)
return 0x05;
else
return 0x00; // Error?!
}
// Function for computing the PWM wrap limit ("top" value) based on the desired frequency (and the CPU clock speed and prescaler setting):
// TO0xBCDO: parameterise for prescale, rather than relying on it being globally defined?
unsigned int top(float frequency) {
return round(F_CPU / (prescale * frequency) - 1);
}
void pwm(float frequency, float duty_cycle) {
TCNT1 = 0; // Reset timer counter
// pwm_off(); // Maybe necessary to avoid stuck at 5 V condition? Nope, not enough...
if (duty_cycle < 0.0) {duty_cycle = 0.0;}
if (duty_cycle > 1.0) {duty_cycle = 1.0;}
unsigned int wrap_limit = top(frequency);
OCR1A = wrap_limit;
OCR1B = int(wrap_limit * duty_cycle);
// TCCR1A's timer mode should already be set, so just use TCCR1B to start PWM (is that sufficient?):
TCCR1A = _BV(COM1A0) | _BV(COM1B1) | _BV(WGM11) | _BV(WGM10);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11);
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | timer_prescale_bits(prescale);
}
void pwm_off() {
TCCR1B = (TCCR1B & TIMER_PRESCALE_MASK) | TIMER_CLK_STOP;
TCNT1 = 0;
digitalWrite(OUTPUT_PIN, LOW); // This seems to be necessary to silence it properly (sometimes gets stuck high otherwise!)
}
void set_fan_speed(float target) {
pwm(PWM_FREQUENCY, target);
}
void self_test() {
party_popper_fire();
/*
fan_speed(0.1);
delay(2000);
fan_speed(0.5);
delay(5000);
// fan_speed(1.0);
// delay(6000);
fan_speed(0);
delay(6000);
*/
}
void target_pressure_increase() {
target_pressure++;
if (target_pressure > 1000) {target_pressure = 1000;}
}
void target_pressure_decrease() {
target_pressure--;
if (target_pressure < 0) {target_pressure = 0;}
}
void party_popper_fire() {
partyPopperServo.write(PARTY_POPPER_MAX);
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
partyPopperServo.write(PARTY_POPPER_MIN);
}
void note_on(int note, int velocity) {
digitalWrite(LED_PIN, HIGH);
switch (note) {
// case FAN_NOTE_ON: control_enabled = 1; set_fan_speed(velocity / 127.0); break;
// case FAN_NOTE_ON: control_enabled = 1; set_fan_speed(0.4); break;
case FAN_NOTE_OFF: control_enabled = 0; break;
case FAN_UP_NOTE: target_pressure_increase(); break;
case FAN_DOWN_NOTE: target_pressure_decrease(); break;
case PARTY_POPPER_FIRE_NOTE: party_popper_fire(); break;
// Could also derive fan speed or target pressure (TODO!) from note velocity
}
}
void note_off(int note, int velocity) {
digitalWrite(LED_PIN, LOW);
}
// Code below taken from example demo code from the Sparkfun
#ifdef NOPID
void bmp085Calibration()
{
ac1 = bmp085ReadInt(0xAA);
ac2 = bmp085ReadInt(0xAC);
ac3 = bmp085ReadInt(0xAE);
ac4 = bmp085ReadInt(0xB0);
ac5 = bmp085ReadInt(0xB2);
ac6 = bmp085ReadInt(0xB4);
b1 = bmp085ReadInt(0xB6);
b2 = bmp085ReadInt(0xB8);
mb = bmp085ReadInt(0xBA);
mc = bmp085ReadInt(0xBC);
md = bmp085ReadInt(0xBE);
}
// Calculate temperature given ut.
// Value returned will be in units of 0.1 deg C
short bmp085GetTemperature(unsigned int ut)
{
long x1, x2;
x1 = (((long)ut - (long)ac6)*(long)ac5) >> 15;
x2 = ((long)mc << 11)/(x1 + md);
b5 = x1 + x2;
return ((b5 + 8)>>4);
}
// Calculate pressure given up
// calibration values must be known
// b5 is also required so bmp085GetTemperature(...) must be called first.
// Value returned will be pressure in units of Pa.
long bmp085GetPressure(unsigned long up)
{
long x1, x2, x3, b3, b6, p;
unsigned long b4, b7;
b6 = b5 - 4000;
// Calculate B3
x1 = (b2 * (b6 * b6)>>12)>>11;
x2 = (ac2 * b6)>>11;
x3 = x1 + x2;
b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;
// Calculate B4
x1 = (ac3 * b6)>>13;
x2 = (b1 * ((b6 * b6)>>12))>>16;
x3 = ((x1 + x2) + 2)>>2;
b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;
b7 = ((unsigned long)(up - b3) * (50000>>OSS));
if (b7 < 0x80000000)
p = (b7<<1)/b4;
else
p = (b7/b4)<<1;
x1 = (p>>8) * (p>>8);
x1 = (x1 * 3038)>>16;
x2 = (-7357 * p)>>16;
p += (x1 + x2 + 3791)>>4;
return p;
}
// Read 1 byte from the BMP085 at 'address'
char bmp085Read(unsigned char address)
{
unsigned char data;
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 1);
while(!Wire.available())
;
return Wire.read();
}
// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(unsigned char address)
{
unsigned char msb, lsb;
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 2);
while(Wire.available()<2)
;
msb = Wire.read();
lsb = Wire.read();
return (int) msb<<8 | lsb;
}
// Read the uncompensated temperature value
unsigned int bmp085ReadUT()
{
unsigned int ut;
// Write 0x2E into Register 0xF4
// This requests a temperature reading
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF4);
Wire.write(0x2E);
Wire.endTransmission();
// Wait at least 4.5ms
delay(5);
// Read two bytes from registers 0xF6 and 0xF7
ut = bmp085ReadInt(0xF6);
return ut;
}
// Read the uncompensated pressure value
unsigned long bmp085ReadUP()
{
unsigned char msb, lsb, xlsb;
unsigned long up = 0;
// Write 0x34+(OSS<<6) into register 0xF4
// Request a pressure reading w/ oversampling setting
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF4);
Wire.write(0x34 + (OSS<<6));
Wire.endTransmission();
// Wait for conversion, delay time dependent on OSS
delay(2 + (3<<OSS));
// Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF6);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 3);
// Wait for data to become available
while(Wire.available() < 3)
;
msb = Wire.read();
lsb = Wire.read();
xlsb = Wire.read();
up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8-OSS);
return up;
}
#endif
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_synthbot/ano/src/sketch.ino
../../firmware_synthbot.ino<file_sep>/Projects/2016/MIDIBots/arduino/firmware_percussionbot/firmware_percussionbot.ino
// PercussionBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
// TODO: implement seperate right/left command notes for the shaker.
// TODO: add a DC motor operating a football/cog rattle? And a similar mechanism for repeatedly striking the triangle?
#include <MIDIBot.h>
MIDIBot percussionBot;
#include "Timer.h"
#include <Servo.h>
Servo
triangle_servo,
shaker_servo,
drum_servo
;
// TODO: Unused? Remove if so.
int pos = 0; // variable to store the servo position
// TODO: carefully test required delay for each instrument and tweak *_DELAY constants below.
const int TRIANGLE_NOTE = 60; // Middle C
const int TRIANGLE_MIN = 20;
const int TRIANGLE_MAX = 4;
const int TRIANGLE_DELAY = 100;
// Checked!
const int SHAKER_MID = 90;
const int SHAKER_L_NOTE = 39;
const int SHAKER_R_NOTE = 40;
//const int SHAKER_R_MIN = 100;
const int SHAKER_L_MAX = 70;
const int SHAKER_R_MAX = 110;
const int SHAKER_L_DELAY = 100;
const int SHAKER_R_DELAY = 100;
// Checked!
const int DRUM_NOTE = 36; //64
const int DRUM_MIN = 160;
const int DRUM_MAX = 137;
const int DRUM_DELAY = 100;
// Checked!
// Simple on/off motor for rattle:
const int RATTLE_PIN = MOSFET_PWM_PIN;
const int RATTLE_NOTE = 43;
const int RATTLE_SPEED = 255;
// Timers for asynchronous release of drum hits:
Timer *triangle_timer = new Timer(TRIANGLE_DELAY, &triangle_release, 1);
//Timer *shaker_l_timer = new Timer(SHAKER_L_DELAY, &shaker_l_release, 1);
//Timer *shaker_r_timer = new Timer(SHAKER_R_DELAY, &shaker_r_release, 1);
Timer *drum_timer = new Timer(DRUM_DELAY, &drum_release, 1);
// Separate functions for hit and release for each drum:
void triangle_hit() {
triangle_servo.write(TRIANGLE_MAX);
triangle_timer->Start();
}
void shaker_l_hit() {
shaker_servo.write(SHAKER_L_MAX);
// shaker_timer->Start();
}
void shaker_r_hit() {
shaker_servo.write(SHAKER_R_MAX);
// shaker_timer->Start();
}
void drum_hit() {
drum_servo.write(DRUM_MAX);
drum_timer->Start();
}
void triangle_release() {triangle_servo.write(TRIANGLE_MIN);}
//void shaker_release() { shaker_servo.write(SHAKER_MIN);}
void drum_release() { drum_servo.write(DRUM_MIN);}
//void rattle_start() {digitalWrite(RATTLE_PIN, HIGH);}
//void rattle_stop() {digitalWrite(RATTLE_PIN, LOW);}
// Could also analogWrite() if full-speed not required.
void rattle_start() {analogWrite(RATTLE_PIN, RATTLE_SPEED);}
void rattle_stop() {analogWrite(RATTLE_PIN, 0);}
void note_on(int note, int velocity) {
switch (note) {
case TRIANGLE_NOTE: triangle_hit(); break;
case SHAKER_L_NOTE: shaker_l_hit(); break;
case SHAKER_R_NOTE: shaker_r_hit(); break;
case DRUM_NOTE: drum_hit(); break;
case RATTLE_NOTE: rattle_start(); break;
}
}
void note_off(int note, int velocity) {
// Nothing to do for percussion!
// Oh, except maybe the fan/rattle thing
switch (note) {
case RATTLE_NOTE: rattle_stop(); break;
}
}
void test_servo() {
triangle_servo.write(60);
delay(500);
triangle_servo.write(110);
delay(500);
}
void self_test() {
digitalWrite(LED_PIN, HIGH);
triangle_hit();
shaker_r_hit();
drum_hit();
// And rattle? Tricky, cos we'd need to schedule an OFF event for it somehow..
rattle_start();
delay(1000);
rattle_stop();
digitalWrite(LED_PIN, LOW);
}
void setup()
{
// Servo setup:
triangle_servo.attach(SERVO_1_PIN);
shaker_servo.attach(SERVO_2_PIN);
drum_servo.attach(SERVO_3_PIN);
// Set initial position to _MIN values
triangle_servo.write(TRIANGLE_MIN);
shaker_servo.write(SHAKER_MID);
drum_servo.write(DRUM_MIN);
percussionBot.begin();
}
void loop()
{
triangle_timer->Update();
// shaker_timer->Update();
drum_timer->Update();
percussionBot.process_MIDI();
}
<file_sep>/Settings/Geany/1.28/Makefile
install:
cp -v filetype_extensions.conf ~/.config/geany/filetype_extensions.conf
cp -v filedefs/filetypes.Arduino.conf ~/.config/geany/filedefs/filetypes.Arduino.conf
cp -v templates/files/sketch.ino ~/.config/geany/templates/files/sketch.ino
<file_sep>/Projects/2017/SoccerBots/arduino/switch_test/switch_test.ino
const int switch_pin = 18;
void setup(){
pinMode(switch_pin, INPUT); digitalWrite(switch_pin,HIGH);
Serial.begin(9600);
}
void loop(){
Serial.println(digitalRead(switch_pin));
delay(50);
}
<file_sep>/Projects/2016/MIDIBots/arduino/multi_servo_test/multi_servo_test.ino
// Testing multiple servo motors
#include <Servo.h>
Servo servo1;
Servo servo2;
int pos = 0; // variable to store the servo position
const int MAX_POS = 100;
const int MIN_POS = 80;
const int SERVO_TIME = 50; // ms delay to allow motion to happen
const int SERVO_1_PIN = 11;
const int SERVO_2_PIN = 10;
void setup()
{
pinMode(SERVO_1_PIN, OUTPUT);
digitalWrite(SERVO_1_PIN, LOW);
servo1.attach(SERVO_1_PIN);
pinMode(SERVO_2_PIN, OUTPUT);
digitalWrite(SERVO_2_PIN, LOW);
servo2.attach(SERVO_2_PIN);
}
void playbeat (Servo servo, int duration)
{
servo.write(MAX_POS);
delay(SERVO_TIME);
servo.write(MIN_POS);
delay(SERVO_TIME);
delay(duration - 2 * SERVO_TIME);
}
void loop() {
rhythm_4();
}
void rhythm_4()
{
playbeat(servo1, 400);
playbeat(servo1, 400);
playbeat(servo1, 200);
playbeat(servo1, 200);
playbeat(servo2, 400);
playbeat(servo1, 200);
playbeat(servo2, 200);
playbeat(servo2, 200);
playbeat(servo1, 200);
}
void rhythm_3()
{
playbeat(servo1, 200);
playbeat(servo2, 100);
playbeat(servo2, 100);
playbeat(servo1, 100);
playbeat(servo1, 100);
playbeat(servo2, 200);
playbeat(servo1, 200);
playbeat(servo2, 200);
playbeat(servo1, 200);
playbeat(servo2, 100);
playbeat(servo2, 100);
}
void rhythm_2()
{
playbeat(servo1, 400);
playbeat(servo2, 400);
playbeat(servo1, 400);
playbeat(servo2, 200);
playbeat(servo1, 100);
playbeat(servo2, 100);
}
void rhythm_1()
{
playbeat(servo1, 200);
playbeat(servo2, 200);
playbeat(servo1, 200);
playbeat(servo2, 200);
playbeat(servo1, 200);
playbeat(servo2, 200);
playbeat(servo1, 100);
playbeat(servo1, 100);
playbeat(servo2, 100);
playbeat(servo2, 100);
}
<file_sep>/Projects/2016/MIDIBots/arduino/ukulele_test/ano/src/sketch.ino
../../ukulele_test.ino<file_sep>/Projects/2017/SoccerBots/arduino/sensors_boris/sensors_boris.ino
// TODO: main statement of the purpose of this code!
#include <LIS3MDL.h>
#include <Wire.h>
#include <math.h>
#include <EEPROM.h>
#define DEBUGGING 0
const int NUM_SENSORS = 8;
const int analog_sensor_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7};
float ir_values[NUM_SENSORS];
const float IR_GAIN_THRESHOLD = 0.5; // For culling reflections, hopefully
const int IR_THRESHOLD = 980; // About 0.15 after converting to 0..1 float looked about right, which would be ~870 raw. In practice, with no IR ball present, we never see a raw value less than 1000
const int CALIBRATION_MODE_SWITCH_PIN = 2;
const int SAVE_HEADING_BUTTON_PIN = 7;
const int EEPROM_MIN_X = 0;
const int EEPROM_MIN_Y = 2;
const int EEPROM_MIN_Z = 4;
const int EEPROM_MAX_X = 6;
const int EEPROM_MAX_Y = 8;
const int EEPROM_MAX_Z = 10;
const int EEPROM_TARGET_HEADING = 12;
const int BUZZER = 10;
int ball_detected = 0;
float ball_angle = 0;
float ball_distance = 0;
int front_range = 0;
int back_range = 0; // so far unused
float angle_to_goal = 0;
int calibration_mode_switch = 0;
int light_sensor = 0;
int crotchet;
const int hall_effect = A9;
const int battery_voltage_pin = A10;
float battery_voltage = 0;
#if DEBUGGING ==1
#define DEBUG(x) Serial.println (x)
#define DEBUG_NOEOL(x) Serial.print (x)
#else
#define DEBUG(x)
#define DEBUG_NOEOL(x)
#endif
const float IR_COORDINATES[NUM_SENSORS][2] = {{0.0,1.0},{0.71,0.71},{1.0,0.0},{0.71,-0.71},{0.0,-1.0},{-0.71, -0.71},{-1.0, 0.0},{-0.71, 0.71}};
#include "mk_shortened.h"
#include "magnetometer.h"
#include "ultrasonic.h"
#include "reflectance.h"
// int ir_val;
const float TAU = 2 * PI;
// To write an int to EEPROM requires two write() calls, since write() works only in bytes and an int is two.
// Not sure whether to have address be a specific byte address or to multiply by sizeof(int) within the functions to create a virtual addressing scheme for int values only.
// Probably safer to leave as raw byte addresses in case we have to mix and match, but watch for accidental overwriting!
void EEPROM_write_int(int address, int value) {
EEPROM.write(address, highByte(value));
EEPROM.write(address + sizeof(byte), lowByte(value));
}
// Ditto for reading:
int EEPROM_read_int(int address) {
/*
byte highByte = EEPROM.read(address);
byte lowByte = EEPROM.read(address + sizeof(byte));
return word(highByte, lowByte);
*/
// Or simply:
return word(EEPROM.read(address), EEPROM.read(address + sizeof(byte)));
}
void setup() {
for(int n=0; n<NUM_SENSORS; n++) {
pinMode(analog_sensor_pins[n], INPUT);
}
pinMode(CALIBRATION_MODE_SWITCH_PIN, INPUT_PULLUP);
pinMode(SAVE_HEADING_BUTTON_PIN, INPUT_PULLUP);
pinMode(BUZZER, OUTPUT);
analogWrite(BUZZER, 50);
pinMode(hall_effect, INPUT);
pinMode(battery_voltage_pin, INPUT);
Serial.begin(115200);
magnetometerSetup();
ultrasonic_setup();
}
void test_loop() {
for(int n=0; n<=NUM_SENSORS; n++) {
DEBUG_NOEOL(analogRead(analog_sensor_pins[n]) + " ");
}
DEBUG();
delay(50);
}
void loop() {
calibration_mode_switch = digitalRead(CALIBRATION_MODE_SWITCH_PIN);
if (!calibration_mode_switch) {
magnetometer_calibrateMagnetometer();
}
if (!digitalRead(SAVE_HEADING_BUTTON_PIN)) { // allows the heading to be saved during use
magnetometer_saveHeading();
}
readReflectance();
readIRsensors();
//printIRsensors();
get_ball_angle();
//get_calibration_mode_switch();
angle_to_goal = magnetometer_getAngleToTarget();
front_range = getUSDistance();
battery_voltage = analogRead(battery_voltage_pin)*(10/1023.0);
//TODO: get_compass etc.
send_output();
#if DEBUGGING == 1
delay(2000);
#else
delay(20);
#endif
}
void beep() {
tone(BUZZER, 3600);
delay(100);
noTone(BUZZER);
}
float frequency(int note) {
return 440 * pow(2.0, (note - 69) / 12.0);
}
void playNote(int pitch, int duration) {
tone(BUZZER, (int)round(frequency(pitch)), duration);
delay(duration+5);
noTone(BUZZER);
delay(5);
}
void setNoteDurations(int bpm) {
crotchet = 60000 / bpm;
}
void playTune(float tune[][2], int tempo, int arrayLength) {
setNoteDurations(tempo);
for(int x=0; x<arrayLength; x+=1) {
if(tune[x][0] == 0) {
delay(tune[x][1]*crotchet);
} else {
playNote(tune[x][0], tune[x][1]*crotchet);
}
}
}
float readIRsensor(int sensor_num) { // takes single reading from one IR sensor
int reading = analogRead(analog_sensor_pins[sensor_num]);
DEBUG_NOEOL("sensor "); DEBUG_NOEOL(sensor_num); DEBUG_NOEOL(": "); DEBUG(reading);
if (reading>IR_THRESHOLD) {
return 0.0;
} else {
return (1023-reading)/1023.0;
}
}
void readIRsensors() { // takes readings from all 8 sensors and stores them in an array.
for (int i=0; i<NUM_SENSORS; i++) {
ir_values[i] = readIRsensor(i);
}
printIRsensors();
irAutoGain();
printIRsensors();
}
void irAutoGain() { // stretch out the IR sensor values, apply a threshold, then scale back again, in an attempt to ignore IR reflections off the goal.
float irMax = 0.0;
float irMin = 1.0;
// First, determine the min and max for the latest readings:
for (int i=0; i<NUM_SENSORS; i++) {
if(ir_values[i] < irMin && ir_values[i] != 0){irMin = ir_values[i];}
if(ir_values[i] > irMax){irMax = ir_values[i];}
}
// Then scale to full scale, apply threshold, and scale back down:
for(int i=0; i<NUM_SENSORS; i++){
if((ir_values[i]-irMin)/(irMax-irMin) < IR_GAIN_THRESHOLD){
ir_values[i]=0;
}
}
}
void printIRsensors() { // used for debugging
DEBUG_NOEOL("Raw sensor readings: ");
for (int i=0; i<NUM_SENSORS; i++) {
DEBUG_NOEOL(ir_values[i]);
DEBUG_NOEOL(" ");
}
DEBUG();
}
void rad2degTest() {
for (int i=0; i < 8; i ++) {
DEBUG(i / 8.0 * TAU);
DEBUG(normaliseDegrees(rad2deg(i / 8.0 * TAU)));
}
}
float rad2deg(float rad) { // redundant as math.h provides degrees function
return (rad * -1.0 + TAU / 4.0) * (360.0 / TAU);
}
float normaliseDegrees(float d) {
//return fmod(d + 180, 360);
if (d < -180) {
return d + 360;
} else if (d>180) {
return d - 360;
} else {
return d;
}
}
float vector2distance(float vector_magnitude) { // calculates an approx. dist. to the ball from the IR array
return exp(0.33/vector_magnitude) * 0.03;
}
void send_output() {
Serial.print(ball_detected);Serial.print(" ");
Serial.print(ball_angle);Serial.print(" ");
Serial.print(ball_distance);Serial.print(" ");
Serial.print(analogRead(hall_effect));Serial.print(" ");
Serial.print(front_range);Serial.print(" ");
Serial.print(angle_to_goal);Serial.print(" ");
Serial.print(calibration_mode_switch);Serial.print(" ");
Serial.print(reflectance);Serial.print(" ");
Serial.print(battery_voltage);Serial.print(" ");
Serial.println(";");
}
int posneg(int input) {
if(input > 180) {
return(input - 360);
}
return input;
}
float get_ball_angle() {
DEBUG("ball angle called!");
// Calculate the centroid of the ball detection vectors...
float x_total = 0.0; float y_total = 0.0;
for (int n=0; n<NUM_SENSORS; n++) {
x_total += IR_COORDINATES[n][0]*ir_values[n];
y_total += IR_COORDINATES[n][1]*ir_values[n];
DEBUG_NOEOL("Sensor #:");
DEBUG_NOEOL(n);
DEBUG_NOEOL("; value=");
DEBUG_NOEOL(ir_values[n]);
DEBUG_NOEOL(": (");
DEBUG_NOEOL(IR_COORDINATES[n][0]*ir_values[n]);
DEBUG_NOEOL(",");
DEBUG_NOEOL(IR_COORDINATES[n][1]*ir_values[n]);
DEBUG_NOEOL("); ");
}
float x_average = x_total/(float)NUM_SENSORS;
float y_average = y_total/(float)NUM_SENSORS;
DEBUG_NOEOL(" X AVERAGE: ");
DEBUG_NOEOL(x_average);
DEBUG_NOEOL(" Y AVERAGE: ");
DEBUG_NOEOL(y_average);
DEBUG(" ");
// Calculate angle:
// This will use the atan2() function to determine the angle from the average x and y co-ordinates
// You can use the degrees() function to convert for output/debugging.
//ball_angle = degrees(atan2(x_average, y_average));
int small=2000;
int sens=0;
for(int x=0; x<NUM_SENSORS; x++) {
//Serial.print(analogRead(analog_sensor_pins[x]));
//Serial.print(" ");
if(analogRead(analog_sensor_pins[x]) < small) {
small=analogRead(analog_sensor_pins[x]);
sens=x;
}
}
if(small>900) {
ball_detected = 0;
ball_angle = 999;
} else {
ball_detected = 1;
ball_angle = sens*45;
ball_angle = posneg(ball_angle);
}
DEBUG_NOEOL("Angle to ball: ");
DEBUG_NOEOL(ball_angle);
// Calculate approximate distance:
// First, determine the length of the vector (use the Pythagorean theorem):
float vector_magnitude = sqrt(pow(x_average, 2)+pow(y_average,2));
if (ball_angle == 0 && vector_magnitude == 0) {
ball_detected = 0;
} else {
ball_detected = 1;
}
// We need to map the raw vector magnitudes to real-world distances. This is probably not linear! Will require some calibration testing...
ball_distance = vector2distance(vector_magnitude);
DEBUG_NOEOL(" Vector magnitude: ");
DEBUG_NOEOL(vector_magnitude);
DEBUG_NOEOL(" Distance: ");
DEBUG_NOEOL(ball_distance);
DEBUG("");
// TODO: maybe also check for infinity, and map that to a usable value (e.g. 0).
}
//TODO: define other get functions (getCompass etc)
<file_sep>/Projects/2016/MIDIBots/arduino/folder_format.sh
#!/bin/bash
SAVE_DIR="/home/henry/Documents/robotics_repo/Projects/2016/MIDIBots/arduino/"
cd $SAVE_DIR
: '
task:
need to locate the sketch.ino file under each folder (*/src/sketch.ino)
then we need to rename the sketch.ino file to the name of the folder containing the src folder.
move the renamed file to the arduino directory of git.
then run "arduiglue-arduino-folder-setup "%f" on the file.
finally run "arduiglue-arturo-folder-setup "%d" on the directory
echo the path tree of the folder in question?
'
#This is not polished it was a quick and dirty program for one time use with folder setup.
while [ 1 ]
do
FILE=`zenity --file-selection --directory --title="Select sketch.ino" --separator="+++"`
parent=${FILE%/*}
finalName=${parent##*/}
mv $FILE/sketch.ino $finalName.ino
rm -R "$finalName/"
arduiglue-arduino-folder-setup "$finalName.ino"
arduiglue-arturo-folder-setup "$finalName/"
done
<file_sep>/Projects/2016/MIDIBots/arduino/servo_serial_test/servo_serial_test.ino
#include <Servo.h>
Servo servo;
int angle = 90;
void setup()
{
Serial.begin(9600);
// Servo setup:
servo.attach(10);
// Set initial position
servo.write(angle);
}
void angle_increase() {
angle++;
if (angle > 180) {angle = 180;}
servo.write(angle);
}
void angle_decrease() {
angle--;
if (angle < 0) {angle = 0;}
servo.write(angle);
}
int control_byte;
void loop()
{
if (Serial.available()) {
control_byte = Serial.read();
// TODO: error-checking?
switch (control_byte) {
case '+': angle_increase(); break;
case '=': angle_increase(); break;
case '-': angle_decrease(); break;
case '_': angle_decrease(); break;
}
Serial.println(angle);
}
}
<file_sep>/Projects/2017/SoccerBots/arduino/sensors_boris/sherlockShort.h
//Pursuit from Sherlock Season 1
const int sherlockTempo = 200;
const int sherlockArrayLength = 15;
float sherlock[sherlockArrayLength][2] = {{72,0.5},{74,0.5},
{75,1},{75,0.5},{77,0.5},{74,1},{74,0.5},{75,0.5},
{72,1},{72,0.5},{74,0.5},{71,1},{68,0.5},{65,0.5},
{72,8}};
<file_sep>/Projects/2016/MIDIBots/arduino/servo_drum_test/servo_drum_test.ino
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
const int max_pos = 100;
const int min_pos = 0;
const int servo_pin = 11;
void setup()
{
pinMode(servo_pin, OUTPUT);
myservo.attach(servo_pin); // attaches the servo on pin 9 to the servo object
}
void playbeat (int posttime)
{
myservo.write(max_pos);
delay(80);
myservo.write(min_pos);
delay(posttime-80);
}
void loop()
{
playbeat(400);
playbeat(400);
playbeat(200);
playbeat(200);
playbeat(200);
playbeat(200);
}
<file_sep>/Projects/2016/MIDIBots/arduino/fan_test/fan_test.ino
// FanBot speed test code
// Control fan speed using serial data
// "+" to increase speed
// "-" to decrease speed
const int FAN_OUTPUT = 6,
MAX_SPEED = 255,
MIN_SPEED = 0;
int fan_speed = 0;
int control_byte = 0;
void setup()
{
pinMode(FAN_OUTPUT, OUTPUT);
analogWrite(FAN_OUTPUT, LOW);
Serial.begin(9600);
}
void speed_increase() {
fan_speed++;
if (fan_speed > MAX_SPEED) {fan_speed = MAX_SPEED;}
analogWrite(FAN_OUTPUT, fan_speed);
}
void speed_decrease() {
fan_speed--;
if (fan_speed < MIN_SPEED) {fan_speed = MIN_SPEED;}
analogWrite(FAN_OUTPUT, fan_speed);
}
void loop()
{
if (Serial.available()) {
control_byte = Serial.read();
// TODO: error-checking?
switch (control_byte) {
case '+': speed_increase(); break;
case '-': speed_decrease(); break;
}
Serial.println(fan_speed);
}
}
<file_sep>/Projects/2016/MIDIBots/arduino/midi_keyboard/ano/src/sketch.ino
../../midi_keyboard.ino<file_sep>/Projects/2017/SoccerBots/arduino/servo_test/servo_test.ino
// Emergency PopperBot code! FanBot problems!
#include <Servo.h>
#include <MIDIBot.h>
//#include "/home/pi/robotics_repo/Projects/2016/MIDIBots/arduino/libraries/MIDIBot/MIDIBot.h"
MIDIBot popperBot;
Servo partyPopperServo;
const int PARTY_POPPER_MAX = 50;
const int PARTY_POPPER_MIN = 140;
const int PARTY_POPPER_MID = 95;
// MIDI note mapping:
const int PARTY_POPPER_FIRE_NOTE = 3;
const int PART_POPPER_RELEASE_NOTE= 4;
void setup() {
popperBot.begin();
partyPopperServo.attach(SERVO_3_PIN);
partyPopperServo.write(PARTY_POPPER_MIN);
}
void loop() {
popperBot.process_MIDI();
}
void self_test() {
party_popper_fire();
}
void party_popper_fire() {
partyPopperServo.write(PARTY_POPPER_MIN);
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
partyPopperServo.write(PARTY_POPPER_MAX);
delay(1000);
partyPopperServo.write(PARTY_POPPER_MID);
}
void note_on(int note, int velocity) {
switch (note) {
case PARTY_POPPER_FIRE_NOTE: party_popper_fire(); break;
}
}
void note_off(int note, int velocity) {
}
<file_sep>/Projects/2016/MIDIBots/arduino/multitasking_test/ano/src/sketch.ino
../../multitasking_test.ino<file_sep>/Tools/Arduiglue/Readme.txt
Some scripts for Arduino development without being so dependent on the (somewhat yucky) Arduino IDE.
inotool (`ino`) and its fork Arturo (`ano`) provide efficient command-line front-ends to the Arduino build tools (mainly gcc and its binutils friends plus avrdude).
I'd like to make these cross-platform (Linux, Mac OS, Windows, at least), support various front-end IDEs (Geany, Visual Studio, TextWrangler, etc.) and fall back to the Arduino IDE if necessary.
One basic script would be for taking an existing file and adjusting the path to match the Arduino IDE's requirements.
Mac: ~/Documents/Arduino/$SKETCH/$SKETCH.ino
Linux:
Windows:
A function for determining the platform's sketchbook folder might be handy.
On Windows, it might be a Registry entry.
In general, it can be changed through the preferences.
Mac default: ~/Documents/Arduino
A function for determining the location of the preferences file, e.g.
Mac: ~/Library/Arduino15/preferences.txt
--
There are a number of hassles in getting the ino/ano folder structure to match the Arduino IDE's requirements. Notably, the Arduino IDE will recursively try to build everything under the main folder for the sketch, so it looks like putting an ano-compatible subfolder under the main sketch folder is not an option. I'd hoped that symlinks would allow us to keep both happy, but the Arduino IDE has problems either way:
~/sketchbook/MySketch/MySketch.ino -> ~/sketchbook/MySketch/ano/src/sketch.ino
Fails to build because Arduino IDE follows the symlink and ends up in the wrong dir (ano/src).
~/sketchbook/MySketch/ano/src/sketch.ino -> ~/sketchbook/MySketch/MySketch.ino
Fails to build in Arduino IDE because it tries to build the ano copy as well.
However, recent versions of ano support a --source-dir argument, allowing you to compile wherever the file happens to be, and some discussion on github indicates that it should now work with the Arduino IDE's folder structure. That would make like much easier!
See:
https://github.com/scottdarch/Arturo/issues/7
<file_sep>/Projects/2016/MIDIBots/arduino/midi_keyboard_random/ano/src/sketch.ino
../../midi_keyboard_random.ino<file_sep>/Documentation/Assemblies.sql
create table Manufacturer
(
manufacturer_name varchar primary key
);
create table Part
(
part_name varchar primary key,
manufacturer_name varchar references Manufacturer,
mass number,
cost number
);
create table Assembly
(
assembly_name varchar primary key
);
create table Assembly_Part
(
part_name varchar references Part,
assembly_name varchar references Assembly,
quantity number,
primary key(part_name, assembly_name)
);
<file_sep>/Projects/2017/SoccerBots/bash_aliases
alias l='ls -hal'
alias frink="rlwrap java -cp /usr/share/java/frink.jar frink.parser.Frink"
alias jdiskreport='java -jar /usr/share/java/jdiskreport.jar'
alias lsserial='find /dev/serial/by-id -type l -print0 | xargs -0 -i ls -l {}'
alias re='./runeverything.sh'
alias se='./stopeverything.sh'
alias old_arduino="/usr/local/arduino-0105/arduino"
alias shutter="ssh -Y pi@shutter"
alias boris="ssh -Y pi@boris"
<file_sep>/Projects/2016/MIDIBots/arduino/multitasking_test/multitasking_test.ino
#include "Timer.h"
#include <Servo.h>
Timer *servo_0_timer = new Timer(300); //starts a new timer
Timer *servo_1_timer = new Timer(250); //starts a new timer
Servo servos [6];
int pos = 0; // variable to store the servo position
const int CENTRE = 90;
const int RANGE = 46;
const int MAX_POS = CENTRE + RANGE/2;
const int MIN_POS = CENTRE - RANGE/2;
const int SERVO_TIME = 100; // ms delay to allow motion to happen
void setup()
{
servos[0].attach(3);
servos[1].attach(5);
servos[2].attach(6);
servos[3].attach(9);
servos[4].attach(10);
servos[5].attach(11);
servo_0_timer->setOnTimer(&up_strum); //sets new timer
servo_1_timer->setOnTimer(&down_strum); //sets new timer
servo_0_timer->Start(); //starts new timer
servo_1_timer->Start(); //starts new timer
}
void down_strum(){
for (int i = 0; i < 6; i++)
servos[i].write(MAX_POS);
}
void up_strum(){
for (int i = 0; i < 6; i++)
servos[i].write(MIN_POS);
}
void loop() {
servo_1_timer->Update();
servo_0_timer->Update();
}
<file_sep>/Projects/2016/MIDIBots/kicad/MIDI_Shield.pro
update=Mon 13 Jun 2016 21:31:57 NZST
last_client=kicad
[cvpcb]
version=1
NetIExt=net
[cvpcb/libraries]
EquName1=devcms
[pcbnew]
version=1
LastNetListRead=MIDI_Shield.net
UseCmpFile=1
PadDrill=0.600000000000
PadDrillOvalY=0.600000000000
PadSizeH=1.500000000000
PadSizeV=1.500000000000
PcbTextSizeV=1.500000000000
PcbTextSizeH=1.500000000000
PcbTextThickness=0.300000000000
ModuleTextSizeV=1.000000000000
ModuleTextSizeH=1.000000000000
ModuleTextSizeThickness=0.150000000000
SolderMaskClearance=0.000000000000
SolderMaskMinWidth=0.000000000000
DrawSegmentWidth=0.200000000000
BoardOutlineThickness=0.100000000000
ModuleOutlineThickness=0.150000000000
[pcbnew/libraries]
LibDir=
LibName1=sockets
LibName2=connect
LibName3=discret
LibName4=pin_array
LibName5=divers
LibName6=smd_capacitors
LibName7=smd_resistors
LibName8=smd_crystal&oscillator
LibName9=smd_dil
LibName10=smd_transistors
LibName11=libcms
LibName12=display
LibName13=led
LibName14=dip_sockets
LibName15=pga_sockets
LibName16=valves
LibName17=/home/cedwards/Documents/Settings/KiCAD/arduino-kicad-nicholasclewis/arduino_shields
[eeschema]
version=1
LibDir=/home/cedwards/Documents/Settings/KiCAD/freetronics_kicad_library;/home/cedwards/Documents/Settings/KiCAD/xess.pretty;/home/cedwards/Documents/Settings/KiCAD
NetFmtName=
RptD_X=0
RptD_Y=100
RptLab=1
LabSize=60
[eeschema/libraries]
LibName1=power
LibName2=device
LibName3=transistors
LibName4=conn
LibName5=linear
LibName6=regul
LibName7=74xx
LibName8=cmos4000
LibName9=adc-dac
LibName10=memory
LibName11=xilinx
LibName12=microcontrollers
LibName13=dsp
LibName14=microchip
LibName15=analog_switches
LibName16=motorola
LibName17=texas
LibName18=intel
LibName19=audio
LibName20=interface
LibName21=digital-audio
LibName22=philips
LibName23=display
LibName24=cypress
LibName25=siliconi
LibName26=opto
LibName27=atmel
LibName28=contrib
LibName29=valves
LibName30=lib/dips-s
LibName31=lib/arduino-kicad-nicholasclewis/arduino_shieldsNCL
LibName32=lib/freetronics_kicad_library/freetronics_schematic
[schematic_editor]
version=1
PageLayoutDescrFile=
PlotDirectoryName=
SubpartIdSeparator=0
SubpartFirstId=65
NetFmtName=
SpiceForceRefPrefix=0
SpiceUseNetNumbers=0
LabSize=60
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_drumbot/firmware_drumbot.ino
// DrumBot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
#include <MIDIBot.h>
MIDIBot drumBot;
#include "Timer.h"
#include <Servo.h>
Servo
bass_drum_servo,
snare_drum_servo,
cymbal_servo
;
const int BASS_DRUM_NOTE = 36;
const int BASS_DRUM_MIN = 30;
const int BASS_DRUM_MAX = 12;
const int BASS_DRUM_DELAY = 100;
const int SNARE_DRUM_NOTE = 38;
const int SNARE_DRUM_MIN = 40;
const int SNARE_DRUM_MAX = 62;
const int SNARE_DRUM_DELAY = 100;
const int CYMBAL_NOTE = 42;
const int CYMBAL_MIN = 75;
const int CYMBAL_MAX = 105;
const int CYMBAL_DELAY = 100;
// Timers for asynchronous release of drum hits:
Timer *bass_drum_timer = new Timer(BASS_DRUM_DELAY, &bass_drum_release, 1);
Timer *snare_drum_timer = new Timer(SNARE_DRUM_DELAY, &snare_drum_release, 1);
Timer *cymbal_timer = new Timer(CYMBAL_DELAY, &cymbal_release, 1);
// Separate functions for hit and release for each drum:
void bass_drum_hit() {
bass_drum_servo.write(BASS_DRUM_MAX);
bass_drum_timer->Start();
digitalWrite(MOSFET_PWM_PIN, HIGH);
}
void snare_drum_hit() {
snare_drum_servo.write(SNARE_DRUM_MAX);
snare_drum_timer->Start();
}
void cymbal_hit() {
cymbal_servo.write(CYMBAL_MAX);
cymbal_timer->Start();
}
void bass_drum_release() {bass_drum_servo.write(BASS_DRUM_MIN); digitalWrite(MOSFET_PWM_PIN, LOW);}
void snare_drum_release() {snare_drum_servo.write(SNARE_DRUM_MIN);}
void cymbal_release() {cymbal_servo.write(CYMBAL_MIN);}
void self_test() {
digitalWrite(LED_PIN, HIGH);
bass_drum_hit();
snare_drum_hit();
cymbal_hit();
digitalWrite(LED_PIN, LOW);
}
void note_on(int note, int velocity) {
switch (note) {
case BASS_DRUM_NOTE: bass_drum_hit(); break;
case CYMBAL_NOTE: cymbal_hit(); break;
case SNARE_DRUM_NOTE: snare_drum_hit(); break;
}
}
void note_off(int note, int velocity) {
//nothing for drumBot.
}
void setup()
{
// Servo setup:
bass_drum_servo.attach(SERVO_1_PIN);
snare_drum_servo.attach(SERVO_2_PIN);
cymbal_servo.attach(SERVO_3_PIN);
// Move motors to starting positions
bass_drum_servo.write(BASS_DRUM_MIN);
snare_drum_servo.write(SNARE_DRUM_MIN);
cymbal_servo.write(CYMBAL_MIN);
drumBot.begin();
}
void loop()
{
bass_drum_timer->Update();
snare_drum_timer->Update();
cymbal_timer->Update();
drumBot.process_MIDI();
}
<file_sep>/Projects/2017/SoccerBots/arduino/motor_control/motor_control.ino
//Currently working Motor Control using the DSpace robot board for RoboCup Soccer 2017.
// MOST IMPORTANT!!! Make sure this is set correctly before uploading:
#define SHUTTER 0
// (it might be nice to have the robot's identity stored in EEPROM and detected automatically by this program)
// Stuff below here shouldn't need to change very often.
#define BAUD_RATE 19200
// TODO: Do the duty cycles of the SoccerBot motors need adjusting?
// TODO: Move the duty cycles into the eeprom
// TODO: Remove unused stuff copied from the Dalek program.
#include <Servo.h> //incldued for kicker
Servo Kicker;
const int SERVO_PIN = 13; //Servo 2, Pin 2 SDK.
const int KICKER_DELAY = 1000;
// For PWM limiting output power to 4.5 V equivalent from an 8 V supply:
// duty = 4.5 V / (8 V) x 255 = 143
#if (SHUTTER==1)
// Motor speed and servo limits tweaked for Shutter (attacker):
const int MOTOR_L_DUTY=123;
const int MOTOR_R_DUTY=130;
const int KICKER_MIN = 105; //tested
const int KICKER_MAX = 145;
#else
// Motor speed and servo limits tweaked for Boris (goalie):
const int MOTOR_L_DUTY=134;
const int MOTOR_R_DUTY=143;
const int KICKER_MAX = 125; //tested
const int KICKER_MIN = 85; //tested
#endif
const int MESSAGE_TYPE_MASK = 0b10000000;
const int MOTOR_MASK = 0b01000000;
const int DIR_MASK = 0b00100000;
const int SPEED_MASK = 0b00011111;
const int KICKER_MASK = 0b00000001;
const int MOTOR_TOGGLE_SWITCH = 18; //physical pin 2 on sensor block 2.
int motors_enabled = 0;
#define MOTOR_R_ENABLE 5
#define MOTOR_L_ENABLE 11
#define MOTOR_R_1_PIN 10
#define MOTOR_R_2_PIN 9
#define MOTOR_L_1_PIN 7
#define MOTOR_L_2_PIN 6
#define DEBUGGING 0
/*
#define debug(message) \
do { if (DEBUGGING) Serial.println(message); } while (0)
*/
#if DEBUGGING == 1 //Do we need to print some values all the time? Pure data isn't expecting anything in return to the motor driving protocol.
#define DEBUG(x) Serial.println (x)
#define DEBUG_NOEOL(x) Serial.print (x)
#else
#define DEBUG(x)
#define DEBUG_NOEOL(x)
#endif
void setup() {
Kicker.attach(SERVO_PIN);
pinMode(MOTOR_TOGGLE_SWITCH, INPUT); digitalWrite(MOTOR_TOGGLE_SWITCH, 1);
pinMode(MOTOR_L_ENABLE, OUTPUT); digitalWrite(MOTOR_L_ENABLE, LOW);
pinMode(MOTOR_R_ENABLE, OUTPUT); digitalWrite(MOTOR_R_ENABLE, LOW);
pinMode(MOTOR_L_1_PIN, OUTPUT); digitalWrite(MOTOR_L_1_PIN, LOW);
pinMode(MOTOR_L_2_PIN, OUTPUT); digitalWrite(MOTOR_L_2_PIN, HIGH);
pinMode(MOTOR_R_1_PIN, OUTPUT); digitalWrite(MOTOR_R_1_PIN, LOW);
pinMode(MOTOR_R_2_PIN, OUTPUT); digitalWrite(MOTOR_R_2_PIN, HIGH);
Serial.begin(BAUD_RATE);
#ifdef DEBUGGING
DEBUG("\n\nDspace Motor Controller for SoccerBots - Info Sci Mechatronics v0.01");
#endif
// Flap kicker paddle to signal startup (even if motors disabled):
Kicker.write(KICKER_MAX); delay(100);
Kicker.write(KICKER_MIN); delay(100);
Kicker.write(KICKER_MAX); delay(100);
Kicker.write(KICKER_MIN); delay(100);
Kicker.write(KICKER_MAX); delay(100);
Kicker.write(KICKER_MIN);
}
void Stop() {
digitalWrite(MOTOR_L_1_PIN, LOW);
digitalWrite(MOTOR_L_2_PIN, HIGH);
analogWrite(MOTOR_L_ENABLE, 0);
digitalWrite(MOTOR_R_1_PIN, LOW);
digitalWrite(MOTOR_R_2_PIN, HIGH);
analogWrite(MOTOR_R_ENABLE, 0);
}
//speed argument expected to be between 0-255
void L_Spd(int speed, bool dir) {
if (!motors_enabled) {speed = 0;}
if (speed < 0) {speed = 0;}
if (speed > 255) {speed = 255;}
digitalWrite(MOTOR_L_1_PIN, dir);
digitalWrite(MOTOR_L_2_PIN, !dir);
analogWrite(MOTOR_L_ENABLE, (int) round(speed/255.0 * MOTOR_L_DUTY));
}
void R_Spd(int speed, bool dir) {
if (!motors_enabled) {speed = 0;}
if (speed < 0) {speed = 0;}
if (speed > 255) {speed = 255;}
digitalWrite(MOTOR_R_1_PIN, dir);
digitalWrite(MOTOR_R_2_PIN, !dir);
analogWrite(MOTOR_R_ENABLE, (int) round(speed/255.0 * MOTOR_R_DUTY));
}
void kick(){ //this is unused, but it could be useful so it can stay.
Kicker.write(KICKER_MAX);
delay(KICKER_DELAY);
Kicker.write(KICKER_MIN);
delay(KICKER_DELAY);
}
void kicker_move(int direction) {
if (!motors_enabled) {
Kicker.write(KICKER_MIN);
} else{
Kicker.write(direction ? KICKER_MAX : KICKER_MIN);
}
}
void motor_control(){
if (Serial.available() > 0) {
int data_int = Serial.read();
if (data_int < 0) {
return;
}
byte data = byte(data_int);
if ((data&MESSAGE_TYPE_MASK)>>7==0){
kicker_move(data&KICKER_MASK);
} else {
if ((data&MOTOR_MASK)>>6) {
R_Spd((data&SPEED_MASK)<<3, (data&DIR_MASK)>>5);
DEBUG("R forward (DIR, Speed): ");
DEBUG((data&DIR_MASK)>>5);
DEBUG((data&SPEED_MASK)<<3);
} else {
L_Spd((data&SPEED_MASK)<<3, (data&DIR_MASK)>>5);
DEBUG("L forward (DIR, Speed): ");
DEBUG((data&DIR_MASK)>>5);
DEBUG((data&SPEED_MASK)<<3);
}
}
} else {
if (!motors_enabled) {Stop();}
}
}
void loop(){
motors_enabled = !digitalRead(MOTOR_TOGGLE_SWITCH);
motor_control();
}
<file_sep>/Projects/2017/SoccerBots/old_calibrate_vision.py
#!/usr/bin/env python2.7
import SimpleCV
import sys
import os
sys.path.append(os.environ['HOME'] + '/robotics_repo/Documentation/Computer Vision/infoscimechatronics')
import cvutils
calibration_file_name = "camera_calibration_state.py"
camera = SimpleCV.Camera(0, {"width":320,"height":240})
os.system(os.environ['HOME'] + '/robotics_repo/Projects/2017/SoccerBots/rpicam-setup.sh')
grey_sample = cvutils.calibrate_white_balance(camera)
blue_sample = cvutils.calibrate_colour_match(camera, grey_sample)
#grey_sample = (221.5625, 219.75, 225.8125)
#blue_sample = ((108.0, 2.0), (159.0, 30.0), (90.5, 26.5))
def file_output():
output_file = open(calibration_file_name, "w")
output_file.write("calibrated_grey_sample = " + str(grey_sample) + "\n")
output_file.write("calibrated_goal_sample = " + str(blue_sample) + "\n")
output_file.close()
file_output()
<file_sep>/Projects/2017/SoccerBots/boris_python2.py
import serial
import time
import sys
from threading import Thread
serinput = serial.Serial('/dev/serial/by-id/usb-Arduino__www.arduino.cc__0042_852313632363516031B2-if00', 115200)
seroutput = serial.Serial('/dev/serial/by-id/usb-DSpace__www.dspace.org.nz__DSpace_Robot_2.0_55234313335351A0D161-if00', 19200)
left_motor_string = 0b10000000 #first bit 1 means motor message
right_motor_string = 0b11000000 #second bit 1 means right motor
kicker_mask = 0b00000000 #first bit - 0 means kicker message
speed_threshold = 0.4 #deadzone threshold
intercept_time = 1 #time for intercepting the ball
distance_threshold = 0.8
ball_near = 0
homed = 0
inside_goal_zone = 0
goal_detected = 0
ball_detected = 0
ball_angle = 0
ball_distance = 0
hall_effect = 0
rangee = 0
compass_heading = 0
calibration_mode = 0
colour = 0
voltage = 0
angle_to_goal = 0
blob_size = 0
def read_sensors(): #function which constantly reads sensors
while True:
serinput.flush()
line = str(serinput.readline()).strip(' ;\r\n ').split(" ")
#print(len(line))
#print(line)
global ball_near, homed, inside_goal_zone, goal_detected, ball_detected, ball_angle, ball_distance, hall_effect, rangee, compass_heading, calibration_mode, colour, voltage, angle_to_goal, blob_size
try:
ball_detected = line[0]
ball_angle = float(line[1])
ball_distance = float(line[2])
hall_effect = line[3]
rangee = float(line[4])
compass_heading = float(line[5])
calibration_mode = line[6]
colour = float(line[7])
voltage = float(line[8])
time.sleep(0.1)
except(serial.SerialException, ValueError, IndexError) as error:
#time.sleep(1)
#print(error)
pass
#calculate and set ball side variable
if ball_angle<900:
if compass_heading-ball_angle<-180:
temp_ball_side = compass_heading-ball_angle+360
else:
temp_ball_side = compass_heading-ball_angle
if abs(temp_ball_side)<90:
ball_side = 1
else:
ball_side = 0
#print("voltage: " + str(voltage))
#read angle to goal and blob size from stdin
stdin_line = sys.stdin.readline().strip(";").split()
try:
angle_to_goal = float(stdin_line[0].strip(";"))
except(IndexError) as error:
#print(error)
pass
try:
blob_size = stdin_line[1]
except(IndexError) as error:
#print(error)
pass
#print("angle to goal: " + angle_to_goal)
#decide how close the ball is
#TODO: see if battery voltage affects the ball distance
if ball_distance < distance_threshold:
ball_near = True
else:
ball_near = False
#calculate whether the goal is detected
if angle_to_goal != -180:
goal_detected = 1
else:
goal_detected = 0
#calculate whether we are inside the goal zone
if colour > 800:
inside_goal_zone = True
else:
inside_goal_zone = False
#calculate whether we are homed
if (inside_goal_zone==1 and goal_detected==1 and rangee<25 and abs(compass_heading)<90):
homed = True
else:
homed = False
#print("homed in thread " + str(homed))
#print("gd: " + str(goal_detected) + " in gz: " + str(inside_goal_zone) + " range: " + str(rangee) + " cmps: " + str(compass_heading))
serinput.flushInput()
reading_of_sensors = Thread(target=read_sensors)
reading_of_sensors.start() #start thread to read sensors constantly
def clip(x): #clip x within the range -1..1
if x<-1:
return -1
elif x>1:
return 1
else:
return x
def homing():
global homed
#print("homing: " + str(homed))
while homed == False:
#print(angle_to_goal)
if angle_to_goal < 10 and angle_to_goal > -10:
motor_output(-0.5, -0.5)
if angle_to_goal < -11:
motor_output(-0.3, -0.7)
elif angle_to_goal > 11:
motor_output(-0.7, -0.3)
def deadzone(speed, threshold):
if speed>0:
out = speed + threshold
elif speed<0:
out = speed - threshold
elif speed==0:
out = 0
return clip(out)
def speed_to_bin(speed): #convert speed to binary number
speed = deadzone(speed, speed_threshold)
if speed>=0:
dir_bit_string = 0b00100000
else:
dir_bit_string = 0b00000000
speedbits = (int(abs(speed)*255))>>3
return dir_bit_string | speedbits
def left_motor(speed):
return speed_to_bin(speed) | left_motor_string
def right_motor(speed):
return speed_to_bin(speed) | right_motor_string
def send_byte(i):
# For debugging:
#print(bin(i))
# Output for real:
seroutput.write(chr(i))
def motor_output(left_speed, right_speed): #drive both motors with left_speed and right_speed as the left and right motor speeds
send_byte(int(left_motor(left_speed*(voltage*-0.5 + 5))))
send_byte(int(right_motor(right_speed*(voltage*-0.5 + 5))))
def turn_to_ball():
#read_sensors()
#print(ball_angle)
while ball_angle != 0:
if ball_angle<0:
#print("turn left")
motor_output(-0.5,0.5)
elif ball_angle>0:
#print("turn right")
motor_output(0.5,-0.5)
else:
#print("0!")
motor_output(0,0)
def intercept_ball():
motor_output(1,1)
time.sleep(intercept_time)
motor_output(-0.75,-0.75)
time.sleep(intercept_time)
motor_output(0,0)
while True:
"""if ball_near == False:
print("turning to ball")
turn_to_ball()
motor_output(0,0)
elif ball_near == True:
print("intercepting ball")
intercept_ball()
if homed == True:
print("homed")
pass
elif homed == False:
print(rangee)
print(colour)
print("homing")
homing()"""
# homing()
motor_output(0,0)
motor_output(-0.8,-0.2)
time.sleep(1)
motor_output(0,0)
motor_output(-0.2,-0.8)
time.sleep(1)
<file_sep>/Projects/2016/MIDIBots/arduino/midi_keyboard/midi_keyboard.ino
// A simple MIDI keyboard for Arduino
// CME 2016-03
// This polls for input switch states and outputs MIDI note on/off messages when they change, i.e. when a switch is pressed/released.
// We reserve a block of contiguous input pins to keep the code simple and scalable.
// To monitor MIDI messages:
// aseqdump -p 20:0
// To play via Yoshimi:
// yoshimi --alsa-midi=20:0 --alsa-audio=pulse --load-instrument=/usr/share/yoshimi/banks/Will_Godfrey_Collection/0033-Medium\ Saw.xiz
// Here we define a couple of arrays for the current and previous state of all the key switches:
// Notably, we need to keep the TX pin free for MIDI transmission. Also the LED_BUILTIN pin so we can indicate activity.
// NOTE: on the Arduino Mega, the big double-row of pins starts has a pair of 5V pins, then digital pins 22 and 23. The last digital pin is 53, and then there are two grounds at the end.
const int NUM_KEYS = 32;
const int FIRST_KEY_PIN = 22;
// Here are the arrays.
// NOTE: awkward mismatch of pin numbers and array indexes, since we're not necessarily starting at 0! It's a bit wasteful of memory, but let's just make the array bigger, and ignore any we aren't using, and use the same numbering for the array elements as for the pin numbers for the input switches.
int currSwitchState[NUM_KEYS + FIRST_KEY_PIN];
int prevSwitchState[NUM_KEYS + FIRST_KEY_PIN];
void setup() {
// Set up serial port for MIDI baud rate (31.25 kbit/s):
Serial.begin(31250);
// We might want to use the LED to indicate activity (though don't use delay() unnecessarily (e.g. blink())).
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
// Set up input pins and initialise switch state arrays:
for (int pin = FIRST_KEY_PIN; pin <= FIRST_KEY_PIN + NUM_KEYS - 1; pin++) {
pinMode(pin, INPUT_PULLUP);
currSwitchState[pin] = 0;
prevSwitchState[pin] = 0;
}
}
void loop() {
readSwitches();
}
void ledOn() {digitalWrite(LED_BUILTIN, HIGH);}
void ledOff() {digitalWrite(LED_BUILTIN, LOW);}
// This function is used to conveniently generate note on/off MIDI messages.
// The first message byte is called the status byte, and indicates the type of message and the channel number being addressed.
// Status bytes have a 1 for the MSB, and data bytes always have a 0 there.
// 0x9 (0b1001) is the Note On status nybble.
// NOTE: the channel number parameter should be the logical (user-centric) channel numbers (1..16), not the internal values used to represent them.
void playNote(int channel, int pitch, int velocity) {
if (channel > 16 || channel < 1) channel = 1; // Clip to valid range
Serial.write(0x90 | (channel-1)); // write status byte, converting channel number to wire format
Serial.write(pitch); // data byte 1
Serial.write(velocity); // data byte 2
}
// Trigger a MIDI note based input switch activity. We'll use polling for this (there wouldn't be enough interrupts available for an interrupt-based approach). As a result, we need to remember the state of the switch(es) from the last poll so we can recognise on/off transitions.
void readSwitches() {
// Check each of the pins:
for (int pin = FIRST_KEY_PIN; pin <= FIRST_KEY_PIN + NUM_KEYS - 1; pin++) {
currSwitchState[pin] = !digitalRead(pin); // Active-low; negate here.
// If state changed, output note on/off:
if (currSwitchState[pin] != prevSwitchState[pin]) {
ledOn();
playNote(1, 36 + pin, currSwitchState[pin] * 100); // Note on/off depending on whether the key is pressed.
ledOff();
}
prevSwitchState[pin] = currSwitchState[pin]; // Store the state for next time.
}
delay(1); // Hold off just a little do reduce spurious note on/off due to switch contact bouncing.
}
<file_sep>/Projects/2017/SoccerBots/old_blob_tracking.py
#!/usr/bin/env python2.7
import SimpleCV
import os
import sys
sys.path.append(os.environ['HOME'] + '/robotics_repo/Documentation/Computer Vision/infoscimechatronics')
import cvutils
import time
import serial
execfile("camera_calibration_state.py")
camera = SimpleCV.Camera(0, {"width":320,"height":240})
os.system(os.environ['HOME'] + '/robotics_repo/Projects/2017/SoccerBots/rpicam-setup.sh')
speed = 0
prev_error = 0
integral = 0
derivative = 0
hunt_dir = 1
hunt_step = 15
#blobs_threshold = 0.0075
blobs_threshold = 0.00005
times = []
output = False
then = 0
now = 0
scaling_factor = 0.250 #0.075
def average(numbers):
x = 0
for num in numbers:
x += num
x = float(x) / len(numbers)
return x
def x_coordinate_to_angle(coord):
#return coord*35.543 #calibrated for LogiTech Camera.
return coord*33.0 #calibrated for RPi Camera.
def clip_angle(angle):
if angle < -90:
return -90
if angle > 90:
return 90
else:
return angle
def send2pd(message):
print(str(message) + ";")
sys.stdout.flush()
while True:
now = time.time()
elapsed_time = now - then
sys.stderr.write('Frame rate:' + str(1.0/elapsed_time) + '\n')
#times.append(elapsed_time)
#frame_rate = 1 / average(times) not calcultating the correct result
image = cvutils.wb(camera.getImage().scale(scaling_factor), calibrated_grey_sample)
v,s,h = image.toHSV().splitChannels()
hue_match = h.colorDistance((calibrated_goal_sample[0][0],calibrated_goal_sample[0][0],calibrated_goal_sample[0][0])).binarize(calibrated_goal_sample[0][1]*3)
sat_match = s.colorDistance((calibrated_goal_sample[1][0],calibrated_goal_sample[1][0],calibrated_goal_sample[1][0])).binarize(calibrated_goal_sample[1][1]*3)
matched = ((hue_match / 16) * (sat_match / 16))
matched.show()
blobs = matched.findBlobs(threshval=100, minsize=1, maxsize=0, threshblocksize=0, threshconstant=5)
if blobs is not None:
blob_size = blobs[-1].area()
image_size = image.area()
sys.stderr.write ("Blob size / image size: " + str(blob_size / image_size) + "\n")
if blob_size / image_size < blobs_threshold:
sys.stderr.write("Blobs too small! \n")
send2pd(-180) #404 not found
time.sleep(0.02)
else:
(x,y) = blobs[-1].centroid()
image.dl().line((x,0), (x,image.height), (255,0,0), antialias=False)
image.dl().line((0,y), (image.width,y), (0,255,0), antialias=False)
image.show()
#sys.stderr.write float(x) / image.width
converted_coord = float(x) / image.width
converted_coord = x_coordinate_to_angle(converted_coord*2-1)
sys.stderr.write("converted_coord: " + str(converted_coord) + ' ' + '\n')
send2pd(converted_coord)
else:
sys.stderr.write("No blobs found! \n")
send2pd(-180)
time.sleep(0.1)
time.sleep(0.03)
then = now
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_percussionbot/ano/src/sketch.ino
../../firmware_percussionbot.ino<file_sep>/Projects/2016/MIDIBots/arduino/libraries/MIDIBot/MIDIBot.cpp
/*
* Arduino library for our MIDIBot shield circuit board, Robocup 2016
* Team _underscore_, Information Science Mechatronics, University of Otago
*/
#include "Arduino.h"
#include "MIDIBot.h"
// Constructor method:
// This performs most of the low-level setup. Much of this will be standard, but some firmware-specific setup code will also be likely. That can be done in the usual setup() in the main sketch.
// Some setup functions cannot be done in the constructor (notably Serial.begin() and anything that uses delay()). Thus there is a separate begin() method that should be called from the main sketch during setup().
// self_test() will need to be implemented by the sketch using this library.
// Ditto note_on(), note_off().
MIDIBot::MIDIBot()
{
// Set up pin modes for the MIDIBot Shield (input, internal pull-up resistor enabled):
pinMode(MIDI_1x_PIN, INPUT_PULLUP);
pinMode(MIDI_2x_PIN, INPUT_PULLUP);
pinMode(MIDI_4x_PIN, INPUT_PULLUP);
pinMode(MIDI_8x_PIN, INPUT_PULLUP);
// Ditto for self-test button:
pinMode(SELF_TEST_PIN, INPUT_PULLUP);
// TODO: output pins (servos, MOSFETs, LED)
pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW);
pinMode(MOSFET_PWM_PIN, OUTPUT); analogWrite(MOSFET_PWM_PIN, 0);
pinMode(MOSFET_2_PIN, OUTPUT); digitalWrite(MOSFET_2_PIN, LOW);
pinMode(MOSFET_3_PIN, OUTPUT); digitalWrite(MOSFET_3_PIN, LOW);
pinMode(MOSFET_4_PIN, OUTPUT); digitalWrite(MOSFET_4_PIN, LOW);
pinMode(SERVO_1_PIN, OUTPUT); digitalWrite(SERVO_1_PIN, LOW);
pinMode(SERVO_2_PIN, OUTPUT); digitalWrite(SERVO_2_PIN, LOW);
pinMode(SERVO_3_PIN, OUTPUT); digitalWrite(SERVO_3_PIN, LOW);
// Initialise MIDI channel number according to DIP switch settings:
read_MIDI_channel();
// flash_number(_MIDI_channel + 1); // This seems to be the cause of the problems with using this as a library! I suspect it's because it uses delay() internally.
// NOTE: MIDI serial communication must be set up elsewhere, in the ::begin() method. If it's done here, the program won't hang, but serial communication will not work!
// Also note that use of the delay() function in this constructor will cause the program to hang!
clearData();
}
void MIDIBot::begin(){
delay(250);
test_MIDI_channel();
delay(1500);
// self_test();
flash(100, 100);
Serial.begin(SERIAL_SPEED);
}
// erase the MIDI data buffer
void MIDIBot::clearData(){
_dataByte[0] = 0;
_dataByte[1] = 0;
_i = 0;
}
void MIDIBot::flash(int on_time, int off_time) {
digitalWrite(LED_PIN, HIGH);
delay(on_time);
digitalWrite(LED_PIN, LOW);
delay(off_time);
}
// Routine for displaying a number by blinking the LED (since hardware serial will be taken already by the MIDI comms):
void MIDIBot::flash_number(int n) {
delay(500);
// Hundreds:
for (int i = 0; i < (n % 1000 / 100); i++) {
flash(800, 800);
}
delay(500);
// Tens:
for (int i = 0; i < (n % 100 / 10); i++) {
flash(400, 400);
}
delay(500);
// Fastest flashing for the ones:
for (int i = 0; i < (n % 10); i++) {
flash(200, 200);
}
delay(1000);
}
// Read MIDI channel DIP switches and store the result:
// NOTE: Freetronics USBDroid has a pull-down resistor on pin D4, which makes that pin unusable! It acts as if D4 is always grounded, i.e. the switch is on. Multiply that bit by 0 (instead of 4) here to force it off.
void MIDIBot::read_MIDI_channel() {
_MIDI_channel =
!digitalRead(MIDI_8x_PIN) * 8 +
!digitalRead(MIDI_4x_PIN) * 4 +
!digitalRead(MIDI_2x_PIN) * 2 +
!digitalRead(MIDI_1x_PIN);
}
// The process_MIDI() function performs receiving incoming MIDI data via serial, recognising note-on and note-off messages (and, perhaps later on, things like Control Change messages), and calls the note_on(pitch, velocity), note_off(pitch, velocity) functions defined by the calling sketch. It should be called repeatedly by the loop() function in the main sketch.
// It also handles calling the self_test() function (defined by the sketch using this library) if the self-test button is pressed. That's done here so that no extra code is required in the calling sketch for this to work.
// TODO: Perhaps define constants, such as NOTE_ON=0x90 (or 0x9)?
// TODO: copy _dataByte[0..1] to meaningfully-named variables (pitch/note, velocity) for better readability? Though it's not really necessary, and possibly inefficient.
void MIDIBot::process_MIDI() {
if (!digitalRead(SELF_TEST_PIN)) {
self_test();
}
if (Serial.available() > 0) {
// flash(20,0); // Consider enabling this for debugging. Warning: blocks!
int data = Serial.read();
if (data > 127) {
// It's a status byte. Store it for future reference.
_statusByte = data;
clearData();
} else {
// It's a data byte.
_dataByte[_i] = data;
if (_statusByte == (0x90 | _MIDI_channel) && _i == 1) {
// Note-on message received
if (_dataByte[1] == 0) {
// Note-on with velocity=0: equialent to note-off, so stop note playing (nothing to do for percussion!)
note_off(_dataByte[0], _dataByte[1]);
} else {
// Start note playing
note_on(_dataByte[0], _dataByte[1]);
}
} else if (_statusByte == (0x80 | _MIDI_channel) && _i == 1) {
// Note-off message received
note_off(_dataByte[0], _dataByte[1]);
}
_i++;
// TODO: error detection if _i goes beyond the array size.
}
}
}
// Some standard self-test routines:
void MIDIBot::test_blink() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}
void MIDIBot::test_button() {
digitalWrite(LED_PIN, !digitalRead(SELF_TEST_PIN));
}
void MIDIBot::test_MIDI_channel() {
read_MIDI_channel();
flash_number(_MIDI_channel + 1);
}
void test_MOSFETs() {
if (!digitalRead(SELF_TEST_PIN)) {
analogWrite(MOSFET_PWM_PIN, 64);
digitalWrite(MOSFET_2_PIN, HIGH);
digitalWrite(MOSFET_3_PIN, HIGH);
digitalWrite(MOSFET_4_PIN, HIGH);
} else {
analogWrite(MOSFET_PWM_PIN, 0);
digitalWrite(MOSFET_2_PIN, LOW);
digitalWrite(MOSFET_3_PIN, LOW);
digitalWrite(MOSFET_4_PIN, LOW);
}
}
void test_MOSFETs_cycle() {
analogWrite(MOSFET_PWM_PIN, 64);
delay(250);
analogWrite(MOSFET_PWM_PIN, 0);
digitalWrite(MOSFET_2_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_2_PIN, LOW);
digitalWrite(MOSFET_3_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_3_PIN, LOW);
digitalWrite(MOSFET_4_PIN, HIGH);
delay(250);
digitalWrite(MOSFET_4_PIN, LOW);
}
void test_PWM() {
analogWrite(MOSFET_PWM_PIN, 64);
delay(250);
analogWrite(MOSFET_PWM_PIN, 0);
delay(500);
}
<file_sep>/Projects/2016/MIDIBots/arduino/firmware_template/firmware_template.ino
// ____Bot code for the 2016 MIDIBots
// Team _underscore_, Information Science Mechatronics, University of Otago
#include <MIDIBot.h>
MIDIBot thisMIDIBot;
void note_on(int note, int velocity) {
// TODO...
}
void note_off(int note, int velocity) {
// TODO...
}
void self_test() {
// thisMIDIBot.test_MIDI_channel();
// TODO: Bot-specific self-test routine...
}
void setup() {
thisMIDIBot.test_MIDI_channel(); // Indicate MIDI channel at startup
}
void loop() {
if (!digitalRead(SELF_TEST_PIN)) {
self_test();
}
thisMIDIBot.process_MIDI();
}
<file_sep>/Projects/2016/MIDIBots/arduino/midi_drum/ano/src/sketch.ino
../../midi_drum.ino<file_sep>/Projects/2016/MIDIBots/arduino/firmware_ukebot/ano/src/sketch.ino
../../firmware_ukebot.ino<file_sep>/Documentation/Computer Vision/cvutils2.py
# A collection of handy functions built on SimpleCV for our robotics projects
# Do we need to import SimpleCV? I assume the import statement will ignore/fail gracefully if asked to import something that's already been imported...
import SimpleCV
import numpy
# Basic setup and check:
#camera = SimpleCV.Camera(prop_set={'width':320, 'height':240})
#camera.loadCalibration('default')
#camera.getCameraMatrix()
#camera.live()
# NOTE: it may be necessary to set many of the camera's capture settings externally, using guvcview or uvcdynctrl
# uvcdynctrl -c -v
# Some colour space conversion functions:
def hue_from_angle(degrees): return degrees / 360.0 * 255
def sat_from_percent(percent): return percent / 100.0 * 255
# Actually doesn't give the right numbers?! TODO: test and correct...
# Generate a solid colour image, matching the resolution and format of the supplied image:
# (I couldn't see any way to create a new blank image using Image)
def solid(image, colour):
solid = image.copy()
solid[0:solid.width, 0:solid.height] = colour
return solid
# Various also-rans follow...
#def solid(image, colour):
# solid=image.copy()
# solid.drawRectangle(0,0,solid.width,solid.height, color=colour)
# return solid
# No! drawRectangle draws only the border, not a solid area!
# Oh, wait, you pass Image() an (x,y) dimension tuple when creating it.
#def solid_(template_image, colour):
# solid = Image(template_image.width,template_image.height)
# solid[0:solid.width, 0:solid.height] = colour
# return solid
# Bah, problems with numpy array format...
#def solid__(width, height, colour):
# solid = Image(width,height)
# solid[0:width, 0:height] = colour
# return solid
# or would it be better to pass (width,height) as a tuple in our function too?
# e.g.
# image = camera.getImage()
# red = solid(image, (255,0,0))
# Pixel function for highlighting pixels (e.g. to assist in troubleshooting image processing)
# Actually, applying Python-based pixel functions is ridiculously slow, so maybe this is no use...
# Also, scaling the image first seems to bork things. Maybe different pixel format? Oh, well..
def highlight(pixels):
r=pixels[0]
g=pixels[1]
b=pixels[2]
return (int(255*pow(r/255.0, 0.25)), int(255*pow(g/255.0, 0.25)), int(255*pow(b/255.0, 0.25)))
# The following code relates to white balance correction (it will often be preferable to set the camera to a fixed white-balance, and correct for it in software in a more controlled and uniform fashion).
# This function corrects an image's white balance based on a sample "grey" point:
# (The calibrate_white_balance() function below can be used to sample a "supposed-to-be-grey" pixel by clicking with the mouse)
def wb(image,grey_sample):
grey=numpy.mean(grey_sample)
r_corr = grey / grey_sample[0]
g_corr = grey / grey_sample[1]
b_corr = grey / grey_sample[2]
#print('r_corr=' + str(r_corr) + ', g_corr=' + str(g_corr) + ', b_corr=' + str(b_corr))
r,g,b=image.splitChannels()
r = r * float(r_corr)
g = g * float(g_corr)
b = b * float(b_corr)
return SimpleCV.ImageClass.Image.mergeChannels(r,r,g,b)
# Test it:
#camera.live()
## coord: (225,264), color: (158.0, 164.0, 184.0)
#x=225
#y=264
#grey_sample=(158.0, 164.0, 184.0)
#image=camera.getImage()
#image.getPixel(x,y) # Um, row/column transposition?!
#corrected=wb(camera.getImage(), grey_sample)
#corrected.getPixel(x,y)
## How fast (slow!) is it?:
##while True:
# wb(camera.getImage(), grey_sample).show()
## And with the undistortion?
#while True:
# wb(camera.getImageUndistort(), grey_sample).show()
## And at reduced resolution?
#while True:
# wb(camera.getImageUndistort().scale(0.25), grey_sample).show()
# Helper function for setting the white balance manually, based on a series of samples from the camera.
# NOTE: Display.mouseLeft returns the current state of the button, whereas Display.leftButtonDownPosition() returns None unless the button was only JUST pressed. We want Display.mouseX and Display.mouseY instead, I think.
def calibrate_white_balance(camera):
display=SimpleCV.Display()
#camera=Camera()
prev_mouse_state = False
sample_pixels = []
print('Press and hold left mouse button over a region that should be white/grey...')
while display.isNotDone():
image = camera.getImage()
image.save(display)
if display.mouseLeft:
x = display.mouseX
y = display.mouseY
if not prev_mouse_state:
# Button just pressed - initialise new list:
sample_pixels = []
#print(sample_pixels)
colour_sample = image.getPixel(x,y)
# Indicate the point being sampled:
image.drawCircle((x,y),rad=5,color=SimpleCV.Color.VIOLET,thickness=1)
image.save(display)
print(str(x) + ', ' + str(y) + ': ' + str(colour_sample))
sample_pixels.append(colour_sample)
prev_mouse_state = True
else:
if prev_mouse_state:
# Button just released:
# Um, how to take the mean of a list of tuples?
mean_sample = tuple(map(lambda y: sum(y) / float(len(y)), zip(*sample_pixels)))
print('mean grey sample: ' + str(mean_sample))
return mean_sample # or rinse and repeat?
prev_mouse_state = False
# Usage:
#grey_sample = calibrate_white_balance(camera)
#while True:
# wb(camera.getImage(), grey_sample).show()
# Some functions for identifying which regions of the image match a certain colour. Let's try with black first:
def find_black(image):
v,s,h = image.toHSV().splitChannels()
dark = v.binarize(75) # had 90 on ProBook cam
grey = s.binarize(90)
return (dark/16) * (grey/16)
# The same, but with parameters for value and saturation thresholds:
def find_black(image,v_thresh,s_thresh):
v,s,h = image.toHSV().splitChannels()
dark = v.binarize(v_thresh) # had 90 on ProBook cam
grey = s.binarize(s_thresh)
return (dark/16) * (grey/16)
# It wouldn't be too hard to identify which regions of the image are (close enough to) grey as well, using just the saturation channel...
# ...although consider that specular highlights will basically appear white/light grey no matter what the actual hue of the surface
def find_grey(image,s_thresh):
v,s,h = image.toHSV().splitChannels()
return(s.binarize(s_thresh))
# For finding colours, we might be able to do reasonably well just by examining the hue channel, and perhaps the saturation as well.
# TODO: refine saturation matching. I suspect we want to match any saturation below the threshold, not just within a range, because of specular highlights.
# Specular reflections will likely cause problems, though, as parts of the image will have a very low saturation, high value, and likely completely wrong hue (the hue for greys defaults to red).
# TODO: might be able to speed this up a little by converting things to greyscale images..?
# Image.toGrey() or Image.greyscale()?!
# Note that we don't have to invert() here, when going from the colour distance to proximity to the target hue/saturation, because, bizarrely, binarize() seems to do that as well.
def find_colour(image, hue, hue_thresh, sat, sat_thresh):
colour_hue = (hue,hue,hue)
colour_sat = (sat,sat,sat)
v,s,h = image.toHSV().splitChannels()
hue_proximity = h.colorDistance(colour_hue).binarize(hue_thresh)
sat_proximity = s.colorDistance(colour_sat).binarize(sat_thresh)
return ((hue_proximity/16.0) * (sat_proximity/16.0))
# Also, note that there is a hueDistance() function as well, which might be more efficient than using colorDistance() in these sorts of situations.
# Presumably there is also a saturationDistance() and valueDistance()...?
# Here's a helper function for finding the target hue, hue threshold, saturation, and saturation threshold for matching a colour.
# TODO: implement a clickable colour picker using Display, similar to calibrate_white_balance() above. Could infer the target centre and thresholds automatically, based on the range of colours selected.
def calibrate_colour_finder(camera):
image = camera.getImage()
image.show()
highlight=solid(image, (255,0,255))
v,s,h = image.toHSV().splitChannels()
target_hue = 0
target_sat = 0
hue_threshold=0
sat_threshold=0
# Hue:
response = raw_input('\nTarget Hue (or Enter when found) => ')
while response != '':
# TODO: handle bogus response robustly...
target_hue = int(response)
match = h.colorDistance((target_hue,target_hue,target_hue)).invert()
((image * 0.1) + (match * 0.1) + (match.binarize(250).invert()/255 * highlight)).show()
response = raw_input('\nTarget Hue => ')
response = raw_input('\nHue Threshold => ')
while response != '':
# TODO: handle bogus response robustly...
hue_threshold=int(response)
#print(type(hue_threshold))
# Gah, binarize() and it's built-in invert behaviour!! >:^p
match = h.colorDistance((target_hue,target_hue,target_hue)).binarize(hue_threshold)
((image * 0.1) + (match/255 * highlight)).show()
response = raw_input('\nHue Threshold => ')
response = raw_input('\nTarget Saturation (or Enter when found) => ')
while response != '':
# TODO: handle bogus response robustly...
target_sat = int(response)
match = s.colorDistance((target_sat,target_sat,target_sat)).invert()
((image * 0.1) + (match * 0.1) + (match.binarize(250).invert()/255 * highlight)).show()
response = raw_input('\nTarget Saturation => ')
response = raw_input('\nSaturation Threshold => ')
while response != '':
# TODO: handle bogus response robustly...
sat_threshold=int(response)
match = s.colorDistance((target_sat,target_sat,target_sat)).binarize(sat_threshold)
((image * 0.1) + (match/255 * highlight)).show()
response = raw_input('\nSaturation Threshold => ')
print('Target hue:', target_hue)
print('Hue threshold:', hue_threshold)
print('Target saturation:', target_sat)
print('Saturation threshold:', sat_threshold)
return (target_hue, hue_threshold, target_sat, sat_threshold)
# Try it out:
#calibrate_colour_finder()
# Trial hue distances:
#h.colorDistance((54,54,54)).show()
# Trial hue threshold:
#h.colorDistance((54,54,54)).binarize(48).show()
# Likewise for saturation:
#s.colorDistance((150,150,150)).show()
#s.colorDistance((150,150,150)).binarize(160).show()
<file_sep>/Documentation/Arduino/stepper_tests/stepper_tests.ino
// Test program for Pololu-style Allegro stepper driver carrier, CME 2015-11-02
// Wantai 42BYGHW811 test: at 4 kHz (1200 RPM) a lower frequency vibration starts to appear.
// Interestingly, it won't start reliably at high frequencies - you have to ramp it up I guess. Acceleration setting in CNC control! Reaches 7 kHz (2100 RPM) OK. Fails to reach 10 kHz (3000 RPM) with ~1 A current limit. 8 kHz, indeed.
// It's also very rough and skips steps at low speeds as well. The severity of this seems to be somewhat sensitive to the current limiting, with more current being a bigger problem.
// 17HS42 motor: 8 kHz is very marginal. More current not necc better!
// Wantai can achieve 10 kHz but nees more current to do so.
// Microstepping: initial experiment with 4x microstepping: I think higher speeds MIGHT be achievable, and the resonance problem is reduced. Of course, you need 4x the pulse frequency to achieve the same speeds! The Wantai can do 90 kHz -> 3375 RPM. 120 kHz -> 4500 RPM (erm, sometimes! It's pretty marginal).
// 2015-11-04: Have rigged up the 24-V power supply and the modded-for-24-V RAMPS board for testing. Need to pull the enable pin for the stepper drive low. Also, the RAMPS is jumpered for 16x microstepping, so the frequency-to-RPM mapping is changed again. 192 kHz would be 3600 RPM, I think
// 192 kHz / 200 / 16 -> min^-1 = 3600
// With delayMicroseconds(), I think it's a bit tough to reach high frequencies, and certainly not with any precision. I managed to get it to just over 30 kHz
//17HS19 reached 690RPM with no load
// For initial testing:
//const int STEP_PIN = 2;
//const int DIR_PIN = 3;
// RAMPS E0 stepper:
const int STEP_PIN = 26;
const int DIR_PIN = 28;
const int EN_PIN = 24; // Maybe this has to be set high^H^H^H^Hlow(!) for anything much to happen...
const int STEPS_PER_REVOLUTION = 200; // Depends on the stepper motor
const int MICROSTEPPING = 1; // Typically 16 on RAMPS boards for 3D printing.
// Should define constants for the timing signals too..
const int PULSE_LOW_TIME = 1000; // A4988
const int PULSE_HIGH_TIME = 1000;
// MadRobot router's YAKO drives have 2500 us
const int LED_PIN = 13;
const int MIN_FREQ = 50;
const long int MAX_FREQ = 1500; // Max step frequency in Hz. Typical stepper motors are 1.8 degrees/step (200 steps/revolution), although microstepping could increase this up to 16-fold. Hmm, but I'm seeing the frequency not go any higher than about 12 kHz on the scope..may need more optimised code...
const float FREQ_STEP = 10;
float freq = 0.0;
long int period_int = 0; // Global variable for current stepping pulse period (so it can be reused without recomputing every time).
int current_direction = 1;
void setup() {
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(EN_PIN, OUTPUT);
digitalWrite(EN_PIN, LOW);
cw();
pinMode(LED_PIN, OUTPUT);
}
// Compute and store the per-symbol period as an integer:
void set_period(float period) {
period_int = (long int)round(period / 2.0); // Account for time for both high and low period.
}
void step() {
digitalWrite(STEP_PIN, HIGH); digitalWrite(LED_PIN, HIGH); delayMicroseconds(period_int);
digitalWrite(STEP_PIN, LOW); digitalWrite(LED_PIN, LOW); delayMicroseconds(period_int);
}
// Set direction to clockwise:
void cw() {
digitalWrite(DIR_PIN, HIGH);
// TODO: direction hold delay
}
// ...and counterclockwise:
void ccw() {
digitalWrite(DIR_PIN, LOW);
// TODO: direction hold delay
}
void _loop() {
}
void loop() {
// Ramp speed up:
// TODO: try exponential acceleration curve
current_direction = !current_direction;
if(current_direction){
cw();
}
else{
ccw();
}
for (freq = MIN_FREQ; freq < MAX_FREQ; freq = freq + FREQ_STEP) {
set_period(1.0 / freq * 1e6); // Convert to period in microseconds
step(); step(); step(); step(); step(); step(); step(); step();
}
// I've noticed the speed increase during this loop. Ah, because it's not having to do so much computation! Let's compute and store period in a global variable to speed it up even more.
// Run for a while at max...
// TODO: have num iterations here based on time rather than a fixed number!
for (int i = 0; i < 2000; i++) {
step(); step(); step(); step(); step(); step(); step(); step();
}
// ...and ramp it down again:
for (freq = MAX_FREQ; freq > MIN_FREQ; freq = freq - FREQ_STEP) {
set_period(1.0 / freq * 1e6); // Convert to period in microseconds
step(); step(); step(); step(); step(); step(); step(); step();
}
}
// What about variable speed
<file_sep>/Projects/2016/MIDIBots/arduino/multi_servo_test/ano/src/sketch.ino
../../multi_servo_test.ino<file_sep>/Projects/2017/SoccerBots/camera_setup.py
# <NAME>'s excellent picamera library:
from picamera.array import PiRGBArray
from picamera import PiCamera
# The OpenCV library:
import cv2
from time import sleep,time
import sys
import numpy
# Set up camera and a NumPy array wrapper suitable for transferring the image data into OpenCV
target_framerate = 20
# 0.08 s frame capture with 50 Hz target
# Hmm, at 128 x 96 the chroma subsampling is pretty bad. Can we influence the format, or do we just have to increase the resolution?
capture_res = (128,96)
#capture_res = (256,192)
# How much of the frame to crop to when doing the calibration sampling?
xfrac = 0.1
yfrac = 0.1
camera = PiCamera(resolution=capture_res, framerate=target_framerate)
camera.iso = 400
camera.shutter_speed = 30000
#camera.shutter_speed = 15000
# array wrapper:
rawCapture = PiRGBArray(camera)
params = cv2.SimpleBlobDetector_Params()
# Change thresholds
params.minThreshold = 10; # the graylevel of images
params.maxThreshold = 200;
params.filterByColor = True
params.blobColor = 255
# Filter by Area
params.filterByArea = False
params.minArea = 10000
params.filterByInertia = False
params.filterByConvexity = False
detector = cv2.SimpleBlobDetector(params)
<file_sep>/Projects/2017/RescueBot/TODO.txt
[ ] Test how frequently an Arduino sketch can read from a digital port and react.
[ ] Obtain colour sensors, test, and integrate
[ ] Range sensing (for water tower, rescue target): ultrasonic or IR?
[ ] Develop and test lifter designs
[ ] Develop a sensor "trolley" design, to keep the sensor distance and orientation consistent with the terrain. Should also provide shielding from ambient light.
[ ] Wireless communication for programming and debugging?
[ ] Test motors and drive trains (Tamiya planetary gear sets? Brushless motors? Maybe make our own brushless motor controller?!)
[ ] Implement a proportional (and possibly integral/derivative) control system? Ideally would be able to adapt turning to the curvature of the line.
[ ] Make the system adaptible to different tile surfaces and printing characteristics?
[ ] How to do high-level control? Subroutines for specialised actions for certain tiles? Include magnetometer so we can have some sense of direction?
[ ] Computer vision system??? Would need a Raspberry Pi or comparable computer onboard.
| 02835354198515fdc10f1a970ee20fc74064ed93 | [
"SQL",
"Markdown",
"Makefile",
"INI",
"Python",
"Text",
"C",
"C++",
"Shell"
] | 123 | Shell | Roboticsotago/robotics_repo | 6e597f4aac60fda3c5d3e23271205a49fa686bf2 | 02b2bfbe2edbadfac84dfbcc16dcd8192cf9f795 | |
refs/heads/master | <file_sep>namespace aqh_daily_report.Domain
{
using SharpArch.Domain.DomainModel;
public class Employee : Entity
{
public virtual string EmployeeNo { get; set; }
public virtual string Password { get; set; }
public virtual Branch Branch { get; set; }
public virtual Permission Permission { get; set; }
}
}<file_sep>using System;
namespace aqh_daily_report.Domain
{
public class ControllerActionMap : IEquatable<ControllerActionMap>
{
public ControllerActionMap(string controllerName, string actionName)
{
ControllerName = controllerName.ToLower();
ActionName = actionName.ToLower();
}
public string ControllerName { get; private set; }
public string ActionName { get; private set; }
#region IEquatable<ControllerActionMap> Members
public bool Equals(ControllerActionMap other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.ControllerName, ControllerName) && Equals(other.ActionName, ActionName);
}
#endregion
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (ControllerActionMap)) return false;
return Equals((ControllerActionMap) obj);
}
public override int GetHashCode()
{
unchecked
{
return (ControllerName.GetHashCode()*397) ^ ActionName.GetHashCode();
}
}
}
}<file_sep>using System.Web.Mvc;
using Machine.Specifications;
using Machine.Specifications.AutoMocking.Rhino;
using Machine.Specifications.Mvc;
using MvcContrib.TestHelper;
using NHibernate;
using Rhino.Mocks;
using aqh_daily_report.Domain;
using aqh_daily_report.Domain.Contracts.Tasks;
using aqh_daily_report.Web.Mvc.Controllers;
using aqh_daily_report.Web.Mvc.Controllers.ViewModels;
namespace MSpecTests.aqh_daily_report
{
[Subject(typeof (LoginController))]
public class LoginControllerSpecs : Specification<LoginController>
{
static IEmployeeTask employeeTask;
static LoginController loginController;
static LoginViewModel loginViewModel;
static ActionResult result;
static string EmployeeNo = "test";
static string Password = "<PASSWORD>";
static ICustomFormsAuthentication custom_forms_authentication;
static IFutureValue<Employee> employeeFutureValue;
Establish contact = () =>
{
{
employeeFutureValue = DependencyOf<IFutureValue<Employee>>();
employeeFutureValue.Expect(value => value.Value).Return(new Employee() { Branch = Branch.First ,Permission=Permission.Admin,Password = <PASSWORD>,EmployeeNo=EmployeeNo});
}
custom_forms_authentication = DependencyOf<ICustomFormsAuthentication>();
employeeTask = DependencyOf<IEmployeeTask>();
employeeTask.Expect(task => task.FindByEmployeeNoAndPassword(EmployeeNo, Password)).Return(employeeFutureValue);
loginController = MockRepository.GenerateMock<LoginController>(employeeTask,custom_forms_authentication);
loginViewModel = new LoginViewModel
{
EmployeeNo = EmployeeNo,
Password = <PASSWORD>
};
};
Because of = () => result = loginController.Index(loginViewModel);
It should_Login_Success = () => result.ShouldRedirectToAction<HomeController>(x => x.Index());
}
}<file_sep>using System.Web.Mvc;
namespace aqh_daily_report.Domain
{
public class CustomPermissionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controllerActionMap = new ControllerActionMap(
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
if (!HasPermission(controllerActionMap))
{
filterContext.Result = new HttpUnauthorizedResult("没有访问权限");
}
}
bool HasPermission(ControllerActionMap controllerActionMap)
{
if (DomainSession.Current.Employee == null)
return PermissionRepository.HasPermission(controllerActionMap);
return PermissionRepository.HasPermission(controllerActionMap, DomainSession.Current.Employee.Permission);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MindHarbor.ClassEnum;
using aqh_daily_report.Domain;
namespace aqh_daily_report.Infrastructure.UserType
{
[Serializable]
public class PermissionUserType : ClassEnumUserType<Permission>
{
}
}
<file_sep>using System.Collections.Generic;
using System.Collections.ObjectModel;
using MvcContrib.FluentHtml.Behaviors;
namespace aqh_daily_report.Domain
{
public static class PermissionRepository
{
static readonly IDictionary<ControllerActionMap, ICollection<Permission>> store =
new ThreadSafeDictionary<ControllerActionMap, ICollection<Permission>>();
static PermissionRepository()
{
store.Add(new ControllerActionMap("Login", "Index"),
new Collection<Permission>());
store.Add(new ControllerActionMap("Home", "Index"), new Collection<Permission>());
}
public static bool HasPermission(ControllerActionMap map, Permission permission = null)
{
if (permission == Permission.Admin)
return true;
if (!store.ContainsKey(map) || store[map].Count == 0)
return true;
return store[map].Contains(permission);
}
}
}<file_sep>using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
namespace aqh_daily_report.Infrastructure.NHibernateMaps.Conventions
{
public class HasManyToManyConvention : IHasManyToManyConvention
{
#region IHasManyToManyConvention Members
public void Apply(IManyToManyCollectionInstance instance)
{
string tablename = "tbl" + instance.EntityType.Name + "_" + instance.ChildType.Name + "_Relationships";
instance.Table(tablename);
}
#endregion
}
}<file_sep>using System.Collections.Generic;
using System.Web.Mvc;
using MvcContrib.Pagination;
using MvcContrib.UI.Grid;
using NHibernate;
using SharpArch.NHibernate.Web.Mvc;
using aqh_daily_report.Domain;
using aqh_daily_report.Domain.Contracts.Tasks;
namespace aqh_daily_report.Web.Mvc.Controllers
{
public class EmployeeController : CustomControllerBase
{
readonly IEmployeeTask EmployeeTask;
public EmployeeController(IEmployeeTask employeeTask)
{
EmployeeTask = employeeTask;
}
//
// GET: /Employee/
[Transaction]
[HttpGet]
public ActionResult Index(int? page,GridSortOptions sort)
{
ViewBag.Sort = sort;
int pageSize = 20;
int startRow = pageSize * ((page ?? 1) - 1);
IEnumerable<Employee> customers = EmployeeTask.FindAll(startRow, pageSize, sort);
IFutureValue<int> count = EmployeeTask.CountAll();
return View(new CustomPagination<Employee>(customers, page ?? 1, pageSize, count.Value));
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace aqh_daily_report.Domain
{
public interface ICustomFormsAuthentication
{
void SetAuthCookie(string userName, bool createPersistentCookie);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace aqh_daily_report.Domain
{
[CustomPermission]
public class CustomControllerBase:Controller
{
}
}
<file_sep>using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
namespace aqh_daily_report.Infrastructure.NHibernateMaps.Conventions
{
public class CustomManyToManyTableNameConvention
: ManyToManyTableNameConvention
{
protected override string GetBiDirectionalTableName(IManyToManyCollectionInspector collection,
IManyToManyCollectionInspector otherSide)
{
return "tbl" + collection.EntityType.Name + "_" + otherSide.EntityType.Name + "_R";
}
protected override string GetUniDirectionalTableName(IManyToManyCollectionInspector collection)
{
return "tbl" + collection.EntityType.Name + "_" + collection.ChildType.Name + "_R";
}
}
}<file_sep>using aqh_daily_report.Domain;
namespace aqh_daily_report.Web.Mvc.Controllers.ViewModels
{
public class EmployeeViewModel
{
public int Id { get; set; }
public string EmployeeNo { get; set; }
public string Password { get; set; }
public string BranchName { get; set; }
public string PermissionName { get; set; }
public Branch GetBranch()
{
return Branch.Parse(BranchName);
}
public Permission GetPermission()
{
return Permission.Parse(PermissionName);
}
}
}<file_sep>using System;
using MindHarbor.ClassEnum;
namespace aqh_daily_report.Domain
{
[Serializable]
public class Branch : ClassEnumGeneric<Branch>
{
public static readonly Branch First=new Branch("first");
public Branch(string name) : base(name)
{}
}
}<file_sep>using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
namespace aqh_daily_report.Infrastructure.NHibernateMaps.Conventions
{
#region Using Directives
#endregion
public class PrimaryKeyConvention : IIdConvention
{
#region IIdConvention Members
public void Apply(IIdentityInstance instance)
{
instance.Column(instance.EntityType.Name + "Id");
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using aqh_daily_report.Domain;
using aqh_daily_report.Infrastructure.UserType;
namespace aqh_daily_report.Infrastructure.NHibernateMaps.CustomerMap
{
public class EmployeeMap:IAutoMappingOverride<Employee>
{
public void Override(AutoMapping<Employee> mapping)
{
mapping.Map(x => x.Branch).CustomType<BranchUserType>();
mapping.Map(x => x.Permission).CustomType<PermissionUserType>();
}
}
}
<file_sep>using System;
using MindHarbor.ClassEnum;
namespace aqh_daily_report.Domain
{
[Serializable]
public class Permission : ClassEnumGeneric<Permission>
{
public static readonly Permission Receptionist = new Permission("Receptionist", "前台");
public static readonly Permission Consultant = new Permission("Consultant", "顾问");
public static readonly Permission Admin = new Permission("Admin", "管理员");
public Permission(string name, string desc) : base(name)
{
Desc = desc;
}
public string Desc { get; private set; }
}
}<file_sep>using System.Collections.Generic;
using MvcContrib.UI.Grid;
using NHibernate;
using SharpArch.NHibernate;
using aqh_daily_report.Domain;
using aqh_daily_report.Domain.Contracts.Tasks;
using CommonLib.QueryOver;
namespace aqh_daily_report.Infrastructure.Queries
{
public class EmployeeTask : NHibernateQuery, IEmployeeTask
{
#region IEmployeeTask Members
public IFutureValue<Employee> FindByEmployeeNoAndPassword(string employeeNo, string password)
{
return
Session.QueryOver<Employee>().Where(x => x.EmployeeNo == employeeNo && x.Password == password).FutureValue
<Employee>();
}
public IEnumerable<Employee> FindAll(int startRow, int pageSize, GridSortOptions sort)
{
return Session.QueryOver<Employee>().OrderBy(sort).Skip(startRow).Take(pageSize).Future<Employee>();
}
public IFutureValue<int> CountAll()
{
return Session.QueryOver<Employee>().Count().FutureValue<int>();
}
#endregion
}
}<file_sep>using System.Web.Mvc;
using aqh_daily_report.Domain;
namespace aqh_daily_report.Web.Mvc.Controllers
{
public class HomeController : CustomControllerBase
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
}<file_sep>using AutoMapper;
using NUnit.Framework;
using aqh_daily_report.Domain;
using aqh_daily_report.Web.Mvc.Controllers.ViewModels;
namespace aqh_daily_report.Tests
{
[TestFixture]
public class AutoMapperLearnFixture
{
[Test]
public void Flattening()
{
var employeeViewModel = new EmployeeViewModel();
employeeViewModel.EmployeeNo = "test";
employeeViewModel.Password = "<PASSWORD>";
employeeViewModel.PermissionName = Permission.Admin.Name;
employeeViewModel.BranchName = Branch.First.Name;
Mapper.CreateMap<EmployeeViewModel,Employee>();
var employee = Mapper.Map<EmployeeViewModel, Employee>(employeeViewModel);
Assert.AreEqual(employeeViewModel.EmployeeNo,employee.EmployeeNo);
Assert.AreEqual(employeeViewModel.Password,employee.Password);
Assert.AreEqual(employeeViewModel.BranchName,employee.Branch.Name);
Assert.AreEqual(employeeViewModel.PermissionName,employee.Permission.Name);
}
}
}<file_sep>using System.Web.Mvc;
using MvcContrib;
using NHibernate;
using SharpArch.NHibernate.Web.Mvc;
using aqh_daily_report.Domain;
using aqh_daily_report.Domain.Contracts.Tasks;
using aqh_daily_report.Web.Mvc.Controllers.ViewModels;
namespace aqh_daily_report.Web.Mvc.Controllers
{
public class LoginController : CustomControllerBase
{
readonly ICustomFormsAuthentication CustomFormsAuthentication;
readonly IEmployeeTask EmployeeTask;
//
// GET: /Login/
public LoginController(IEmployeeTask employeeTask, ICustomFormsAuthentication customFormsAuthentication)
{
EmployeeTask = employeeTask;
CustomFormsAuthentication = customFormsAuthentication;
}
[HttpGet]
public ActionResult Index()
{
return View();
}
//
// POST: /Login/Index
[Transaction]
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Index(LoginViewModel model)
{
if (ModelState.IsValid)
{
IFutureValue<Employee> employee = EmployeeTask.FindByEmployeeNoAndPassword(model.EmployeeNo, model.Password);
if (employee.Value != null)
{
DomainSession.Current.Employee = employee.Value;
CustomFormsAuthentication.SetAuthCookie(model.EmployeeNo, false);
return this.RedirectToAction<HomeController>(x => x.Index());
}
ModelState.AddModelError("", "登录失败!");
}
return View();
}
}
}<file_sep>using System;
using FluentNHibernate.Automapping;
using FluentNHibernate.Conventions;
using SharpArch.Domain.DomainModel;
using SharpArch.NHibernate.FluentNHibernate;
using aqh_daily_report.Domain;
using aqh_daily_report.Infrastructure.NHibernateMaps.Conventions;
namespace aqh_daily_report.Infrastructure.NHibernateMaps
{
#region Using Directives
#endregion
/// <summary>
/// Generates the automapping for the domain assembly
/// </summary>
public class AutoPersistenceModelGenerator : IAutoPersistenceModelGenerator
{
#region IAutoPersistenceModelGenerator Members
public AutoPersistenceModel Generate()
{
AutoPersistenceModel mappings = AutoMap.AssemblyOf<Employee>(new AutomappingConfiguration());
mappings.IgnoreBase<Entity>();
mappings.IgnoreBase(typeof (EntityWithTypedId<>));
mappings.Conventions.Setup(GetConventions());
mappings.UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();
return mappings;
}
#endregion
static Action<IConventionFinder> GetConventions()
{
return c =>
{
c.Add<PrimaryKeyConvention>();
c.Add<CustomForeignKeyConvention>();
c.Add<HasManyConvention>();
c.Add<TableNameConvention>();
c.Add<CustomManyToManyTableNameConvention>();
c.Add<IdGenerationConvention>();
c.Add<ForeignKeyNameConvention>();
c.Add<ReferenceConvention>();
};
}
}
}<file_sep>using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
namespace aqh_daily_report.Infrastructure.NHibernateMaps.Conventions
{
#region Using Directives
#endregion
public class HasManyConvention : IHasManyConvention
{
#region IHasManyConvention Members
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Key.Column(instance.EntityType.Name + "Id");
instance.Key.ForeignKey(instance.EntityType.Name + "_" + instance.ChildType.Name + "_FK");
instance.Cascade.AllDeleteOrphan();
instance.Inverse();
}
#endregion
}
}<file_sep>using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
namespace aqh_daily_report.Infrastructure.NHibernateMaps.Conventions
{
#region Using Directives
#endregion
public class TableNameConvention : IClassConvention
{
#region IClassConvention Members
public void Apply(IClassInstance instance)
{
instance.Table("tbl" + instance.EntityType.Name.InflectTo().Pluralized);
}
#endregion
}
}<file_sep>using System;
using MindHarbor.ClassEnum;
using aqh_daily_report.Domain;
namespace aqh_daily_report.Infrastructure.UserType
{
[Serializable]
public class BranchUserType : ClassEnumUserType<Branch>
{}
}<file_sep>using System.Collections.Generic;
using MvcContrib.UI.Grid;
using NHibernate;
namespace aqh_daily_report.Domain.Contracts.Tasks
{
public interface IEmployeeTask
{
IFutureValue<Employee> FindByEmployeeNoAndPassword(string employeeNo, string password);
IEnumerable<Employee> FindAll(int startRow,int pageSize,GridSortOptions sort);
IFutureValue<int> CountAll();
}
} | 0394e9ba04417c48b08b0c237cdc08ef80ed463f | [
"C#"
] | 25 | C# | vincentzh/aqh_daily_report | 83f351478d89efcfa5df871b1e23e39e720ae89a | 6b6204be8eba49462e1eb3773dc7f9eb37c58172 | |
refs/heads/master | <repo_name>jankney2/js306<file_sep>/script.js
console.log('connected')
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities=[]
let input=document.getElementById('input')
fetch(endpoint).then(response=>{
response.json().then(res=>{
cities.push(...res)
console.log(cities)
})
}).catch(err=>{
console.log(err)
})
function findMatches(text){
let filtered=cities.filter(el=>{
return el.city.toLowerCase().includes(text.toLowerCase()) || el.state.toLowerCase().includes(text.toLowerCase())
})
console.log(filtered)
return filtered
}
function displayMatches(arr){
const html=arr.map(el=>{
return `
<li>
${el.city}, ${el.state}
</li>
`
}).join('')
document.getElementsByTagName('ul')[0].innerHTML=html
}
input.addEventListener('keyup', (e)=>{
let inputText=document.getElementsByTagName('input')[0].value
console.log('hit', inputText)
let matches=findMatches(inputText)
displayMatches(matches)
})
| 40ff7299506cb40ce9d22bb349e6477ac051391b | [
"JavaScript"
] | 1 | JavaScript | jankney2/js306 | 49f356ca756b2b9efe03e64088aa7f39255b9ddd | 4f9256424c2ab95d7203a0b82e3e31903dc20cfe | |
refs/heads/master | <repo_name>N3Wolf/gesMDL<file_sep>/routes/lacadores.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
const Lacador = require('../models/lacador');
// List
router.get('/list', (req, res, next) => {
Lacador.getLacadorList({}, (err, lacadorList) => {
if (err) throw err;
if (!lacadorList) {
return res.json({
success: false,
msg: 'Tabela vazia'
});
} else {
return res.json({ lacadorList: lacadorList });
}
})
});
// List by Clube id
router.get('/listByClubeId', (req, res, next) => {
Lacador.getLacadorListByClubeId(req.query.idClube, (err, lacadorList) => {
if (err) throw err;
if (!lacadorList) {
return res.json({
success: false,
msg: 'Tabela vazia'
});
} else {
// console.log('lacadorList');
// console.log(lacadorList);
return res.json({ lacadorList });
}
})
});
// View
router.get('/view', (req, res, next) => {
//console.log('req.params.idLacador');
//console.log(req.query.idLacador);
Lacador.getLacadorById(req.query.idLacador, (err, lacador) => {
if (!lacador) {
return res.json({
success: false,
msg: 'Erro ao buscar o Laçador de laço desejado. Entre em contato com o suporte técnico do sistema.'
});
} else {
//console.log('lacador(routes)');
//console.log(lacador);
res.json({
lacador: lacador
});
}
})
});
// Edit
router.post('/update', (req, res, next) => {
console.log('chegou aqui');
console.log('req.body');
console.log(req.body);
Lacador.updateById(req.body, (err, callback) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao atualizar o registro do Laçador:",
erro: err
});
} else {
res.json({
success: true,
msg: "Laçador atualizado com sucesso."
});
}
});
});
//Seta o todos os laçadores de um clube como Indepentende;
router.post('/setLacadorIndependenteByClube', (req, res, next) => {
Lacador.setLacadorIndependenteByClube(req.body['idClubedelaco'], (err, callback) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao remover o vinculo entre Clube de laco e os Laçadores",
erro: err
});
} else {
res.json({
success: true,
msg: "Clubes desvinculados dos Laçadores com sucesso."
});
}
});
});
//Seta o todos os laçadores de um clube como Indepentende;
router.post('/setLacadorIndependenteById', (req, res, next) => {
Lacador.setLacadorIndependenteById(req.body['idLacador'], (err, callback) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao remover o vinculo entre Clube de laco e seus Laçadores",
erro: err
});
} else {
res.json({
success: true,
msg: "Clube desvinculado dos Laçadores com sucesso."
});
}
});
});
// Delete
router.post('/remove', (req, res, next) => {
Lacador.removeLacador(req.body.idLacador, (err, callback) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao remover o registro do Laçador."
});
} else {
res.json({
success: true,
msg: "Laçador removido do sistema com sucesso."
});
}
});
});
//Register
router.post('/add', (req, res, next) => {
let newLacador = new Lacador({
name: req.body.name,
cpf: req.body.cpf,
endereco: req.body.endereco,
email: req.body.email,
status: req.body.status,
idClube: req.body.idClube,
picture: req.body.picture ? true: null
})
//valida unique keys: CNPJ
// Lacador.getLacadorByCNPJ(newLacador, (err, federacaoEncontrada) => {
// if(err) throw err;
// if(!federacaoEncontrada){
// return res.json({success: false,msg: 'Já existe uma Federaçao com este CNPJ: '})
// }
// // else {
Lacador.addLacador(newLacador, (err, lacador) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao registrar o Laçador."
});
} else {
res.json({
success: true,
msg: "Laçador registrado com sucesso.",
id: lacador._id
});
}
});
});
module.exports = router;
<file_sep>/angular-src/src/app/classes/federacao.ts
export class Federacao {
}
<file_sep>/angular-src/src/app/theme/pages/default/services/lacadores.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LacadoresService {
lacador: any;
constructor(
private authService: AuthService,
private http: Http
) { }
getLacadores() {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/list');
//console.log('service - getlacadores()');
return this.http.get(ep, { headers: headers })
.map(res => res.json())
.map(res => res['lacadorList']) as Observable<any[]>;;
}
getLacadorById(idLacador) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/view');
//console.log('service - getlacadores()');
return this.http.get(ep, { headers: headers, params: { idLacador: idLacador } })
.map(res => res.json())
.map(res => res['lacador']) as Observable<any[]>;;;
}
getLacadorByClubeId(idClube) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/listByClubeId');
return this.http.get(ep, { headers: headers, params: { idClube: idClube } })
.map(res => res.json())
.map(res => res['lacadorList']) as Observable<any[]>;
}
addLacador(lacador) {
//return new Promise(resolve => resolve(lacador));
//console.log('passou aqui');
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/add');
return this.http.post(ep, lacador, { headers: headers })
.map(res => res.json());
}
removeLacador(idLacador) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/remove');
//console.log(3);
return this.http.post(ep, { idLacador: idLacador }, { headers: headers })
.map(res => res.json());
}
updateLacador(lacador) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/update');
return this.http.post(ep, lacador, { headers: headers })
.map(res => res.json());
}
setLacadorIndependenteByClube(idClubedelaco) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/setLacadorIndependenteByClube');
return this.http.post(ep, { idClubedelaco: idClubedelaco }, { headers: headers })
.map(res => res.json());
}
setLacadorIndependenteById(idLacador) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('lacador/setLacadorIndependenteById');
return this.http.post(ep, { idLacador: idLacador }, { headers: headers })
.map(res => res.json());
}
}
<file_sep>/angular-src/src/app/shared/appMessages.ts
import {Injectable} from '@angular/core';
@Injectable()
export class appOutputMessages {
// public static erros : any = {
// requiredField : "Este campo é obrigatório e não pode ficar em branco.",
// min1Field : "Este campo requer ao menos 1 caracter",
// min2Field : "Este campo requer ao menos 2 caracteres",
// min3Field : "Este campo requer ao menos 3 caracteres",
// min4Field : "Este campo requer ao menos 4 caracteres",
// min5Field : "Este campo requer ao menos 5 caracteres",
// min6Field : "Este campo requer ao menos 5 caracteres",
// min7Field : "Este campo requer ao menos 5 caracteres",
// min8Field : "Este campo requer ao menos 5 caracteres",
// min9Field : "Este campo requer ao menos 5 caracteres",
// min10Field : "Este campo requer ao menos 5 caracteres",
// minAllField : "Este campo requer o preenchimento de todos os caracteres",
// emailInvalid : "Este campo requer um e-mail válido."
// };
public static requiredField : "Este campo é obrigatório e não pode ficar em branco.";
public static min1Field : "Este campo requer ao menos 1 caracter";
public static min2Field : "Este campo requer ao menos 2 caracteres";
public static min3Field : "Este campo requer ao menos 3 caracteres";
public static min4Field : "Este campo requer ao menos 4 caracteres";
public static min5Field : "Este campo requer ao menos 5 caracteres";
public static min6Field : "Este campo requer ao menos 5 caracteres";
public static min8Field : "Este campo requer ao menos 5 caracteres";
public static min9Field : "Este campo requer ao menos 5 caracteres";
public static min7Field : "Este campo requer ao menos 5 caracteres";
public static min10Field : "Este campo requer ao menos 5 caracteres";
public static minAllField : "Este campo requer o preenchimento de todos os caracteres";
public static emailInvalid : "Este campo requer um e-mail válido.";
}
<file_sep>/angular-src/src/app/theme/pages/default/components/users/usersView/usersView.module.ts
import { NgModule } from '@angular/core';
//import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { LayoutModule } from '../../../../../layouts/layout.module';
import { DefaultComponent } from '../../../default.component';
import { UsersViewComponent } from './usersView.component';
import { Validators, ReactiveFormsModule } from '@angular/forms';
//import { AuthGuard } from '../../guards/auth.guard';
import { AuthService } from '../../../services/auth.service';
import { UserService } from '../../../services/user.service';
//import { SharedModule } from '../../../components/sharedModule.module';
const routes: Routes = [
{
"path": "",
"component": DefaultComponent,
"children": [
{
"path": "",
"component": UsersViewComponent
}
]
}
];
@NgModule({
imports: [
// BrowserModule,
FormsModule,
CommonModule,
RouterModule.forChild(routes),
LayoutModule
], providers: [
//FederacaoService,
AuthService,
UserService,
ReactiveFormsModule,
Validators
], exports: [
RouterModule
], declarations: [
UsersViewComponent
]
})
export class usersViewModule {
}
<file_sep>/angular-src/src/app/theme/pages/default/components/users/users.component.ts
import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';
//Depreciado
//import { ValidateService } from '../../services/validate.service';
import { UserService } from '../../services/user.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Helpers } from '../../../../../helpers';
@Component({
selector: '.m-grid__item.m-grid__item--fluid.m-wrapper',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
public objUsers: any;
public registros: number;
// @Input() isDetail: Boolean;
// @Input() paramIdClube: string;
constructor(
//Depreciado
//private validateService: ValidateService,
private usersService: UserService,
private router: Router,
private route: ActivatedRoute
) { }
ngOnInit() {
this.registros = 0;
this.usersService.getUsers().subscribe(users => {
this.registros = users.length;
this.objUsers = users;
});
}
onEditRequest(idUser) {
this.router.navigate(['/usersView', { id: idUser, isEdit: true }]);
}
onDeleteRequest(idUser, nameUser) {
if (confirm("Confirma a exclusão do Usuário \'" + nameUser + "\'?")) {
this.usersService.removeUser(idUser).subscribe(data => {
if (data.success) {
//TODO: Mensagem
alert('Registro removido com sucesso.');
location.reload();
}
})
}
}
//Ultimo bracket
}
<file_sep>/angular-src/src/app/theme/pages/default/components/usergroups/usergroups.component.ts
import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';
import { UsergroupService } from '../../services/usergroups.service';
import { UserService } from '../../services/user.service';
//Depreciado
//import { ValidateService } from '../../services/validate.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Helpers } from '../../../../../helpers';
@Component({
selector: '.m-grid__item.m-grid__item--fluid.m-wrapper',
templateUrl: './usergroups.component.html',
styleUrls: ['./usergroups.component.css']
})
export class UsergroupsComponent implements OnInit {
public objUsergroups: any;
public keys: number;
public registros: number;
@Input() isDetail: Boolean;
@Input() paramIdUsergroup: string;
constructor(
//Depreciado
//private validateService: ValidateService,
private router: Router,
private userService: UserService,
private usergroupsService: UsergroupService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.registros = 0;
if (this.paramIdUsergroup) {
// this.usergroupsService.getUsergroupByClubeId(String(this.paramIdClube)).subscribe(usergroups => {
// this.registros = usergroups.length;
// this.objUsergroups = usergroups;
// })
} else {
//busca todos os usergroups
this.usergroupsService.getUsergroups().subscribe(usergroups => {
this.registros = usergroups.length;
//let usergroupsList = Object.keys(usergroups).map(function(key) { return usergroups[key]; });
//this.objUsergroups = usergroupsList;
this.objUsergroups = usergroups;
//conta os registros
// for (var key in usergroups) {
// if (!usergroups.hasOwnProperty(key)) continue;
// var obj = usergroups[key];
// for (var prop in obj) {
// // skip loop if the property is from prototype
// this.registros++;
// if(!obj.hasOwnProperty(prop)) continue;
// }
// }
});
}
}
onEditRequest(idUsergroup) {
this.router.navigate(['/usergroupsView', { id: idUsergroup, isEdit: true }]);
}
onDeleteRequest(idUsergroup, nameUsergroup) {
if (confirm("Confirma a exclusão do laçador \'" + nameUsergroup + "\'?")) {
this.usergroupsService.removeUsergroup(idUsergroup).subscribe(data => {
if (data.success) {
//TODO: Mensagem
alert('Registro removido com sucesso.');
location.reload();
}
})
}
}
//Ultimo bracket
}
<file_sep>/angular-src/src/app/components/lacadores/lacadores.component.ts
import { Component, OnInit, Input,ViewEncapsulation } from '@angular/core';
import { FederacaoService } from '../../services/federacao.service';
import { ClubesdelacoService } from '../../services/clubesdelaco.service';
import { LacadoresService } from '../../services/lacadores.service';
//Depeciado
//import { ValidateService } from '../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
//import { ActivatedRoute } from '@angular/router';
import { Lacador } from '../../classes/lacador';
@Component({
selector: 'app-lacadores', //'.m-grid__item.m-grid__item--fluid.m-wrapper',
templateUrl: './lacadores.component.html',
styleUrls: ['./lacadores.component.css'],
encapsulation: ViewEncapsulation.None,
})
export class LacadoresComponent implements OnInit {
public objLacadores: any;
public keys: number;
public registros: number;
@Input() isDetail: Boolean;
@Input() paramIdClube: string;
constructor(
//Depeciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router,
private clubesdelacoService: ClubesdelacoService,
private lacadoresService: LacadoresService,
//private route: ActivatedRoute
) { }
ngOnInit() {
//console.log('isDetail: ' + this.isDetail);
//console.log('paramIdClube??: ' + this.paramIdClube['paramIdClube']);
this.registros = 0;
if (this.paramIdClube) {
this.lacadoresService.getLacadorByClubeId(String(this.paramIdClube)).subscribe(lacadores => {
this.registros = lacadores.length;
this.objLacadores = lacadores;
//let lacadoresList = Object.keys(lacadores).map(function(key) { return lacadores[key]; });
//this.objLacadores = lacadoresList;
})
} else {
//busca todos os lacadores
this.lacadoresService.getLacadores().subscribe(lacadores => {
this.registros = lacadores.length;
//let lacadoresList = Object.keys(lacadores).map(function(key) { return lacadores[key]; });
//this.objLacadores = lacadoresList;
this.objLacadores = lacadores;
//conta os registros
// for (var key in lacadores) {
// if (!lacadores.hasOwnProperty(key)) continue;
// var obj = lacadores[key];
// for (var prop in obj) {
// // skip loop if the property is from prototype
// this.registros++;
// if(!obj.hasOwnProperty(prop)) continue;
// }
// }
});
}
//this.federacoes.count = 1 ;// = this.federacoes.length;
}
onEditRequest(idLacador) {
this.router.navigate(['/lacadoresView', { id: idLacador, isEdit: true }]);
}
onDeleteRequest(idLacador, nameLacador) {
if (confirm("Confirma a exclusão do laçador \'" + nameLacador + "\'?")) {
this.lacadoresService.removeLacador(idLacador).subscribe(data => {
if (data.success) {
this.flashMessage.show('Registro removido com sucesso.', { cssClass: 'alert-success', timeout: 5000 });
location.reload();
//this.router.navigate(['/federacao']);
}
})
}
}
//Ultimo bracket
}
<file_sep>/angular-src/src/app/auth/_services/authentication.service.ts
import { Injectable } from "@angular/core";
import { Http, Response, Headers } from "@angular/http";
import "rxjs/add/operator/map";
import { tokenNotExpired } from 'angular2-jwt';
@Injectable()
export class AuthenticationService {
authToken: any;
user: any;
isDev: boolean;
constructor(private http: Http) {
this.isDev = true; // Change to false before deployment
}
login(email: string, password: string) {
const user = {
username: email,
password: <PASSWORD>
}
console.log('enviou para autenticar1');
this.authenticateUser(user).subscribe(data => {
let returnUser = data;
console.log('returnUser');
console.log(returnUser);
return returnUser;
});
//
// this.http.post('/api/authenticate', JSON.stringify({ email: email, password: <PASSWORD> }))
// .map((response: Response) => {
// // login successful if there's a jwt token in the response
// let user = response.json();
// if (user && user.token) {
// // store user details and jwt token in local storage to keep user logged in between page refreshes
// localStorage.setItem('currentUser', JSON.stringify(user));
// }
// });
}
registerUser(user) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let ep = this.prepEndpoint('user/register');
return this.http.post(ep, user, { headers: headers })
.map(res => res.json());
}
authenticateUser(user) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let ep = this.prepEndpoint('user/authenticate');
console.log('enviou para autenticar2');
return this.http.post(ep, user, { headers: headers })
.map(res => res.json());
}
getProfile() {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.prepEndpoint('user/view');
let user = localStorage.getItem('user');
return this.http.get(ep, { headers: headers, params: { user: user } })
.map(res => res.json());
}
storeUserData(token, user) {
localStorage.setItem('id_token', token);
localStorage.setItem('user', JSON.stringify(user));
localStorage.setItem('currentUser', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
loggedIn() {
return tokenNotExpired('id_token');
}
logout() {
this.authToken = null;
this.user = null;
localStorage.removeItem('id_token');
localStorage.removeItem('user');
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
prepEndpoint(ep) {
if (!this.isDev) {
return ep;
} else {
return 'http://localhost:3000/' + ep;
}
}
}
<file_sep>/angular-src/src/app/components/clubesdelaco/clubesdelaco.component.ts
import { Component, OnInit } from '@angular/core';
import { FederacaoService } from '../../services/federacao.service';
import { ClubesdelacoService } from '../../services/clubesdelaco.service';
//import { ValidateService } from '../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
@Component({
selector: 'app-clubesdelaco',
templateUrl: './clubesdelaco.component.html',
styleUrls: ['./clubesdelaco.component.css']
})
export class ClubesdelacoComponent implements OnInit {
public ClubesList: any;
public keys: number;
public registros: number;
constructor(
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router,
private clubesdelacoService: ClubesdelacoService
) { }
ngOnInit() {
this.clubesdelacoService.getClubesdelaco().subscribe(clubesdelaco => {
this.ClubesList = clubesdelaco;
console.log('clubesdelaco');
console.log(clubesdelaco);
this.registros = clubesdelaco.length;
// var clubesdelacoList = Object.keys(clubesdelaco).map(function(key) { return clubesdelaco[key]; });
// this.ClubesList = clubesdelacoList;
// //conta os registros
// for (var key in clubesdelaco) {
// if (!clubesdelaco.hasOwnProperty(key)) continue;
// var obj = clubesdelaco[key];
// for (var prop in obj) {
// // skip loop if the property is from prototype
// this.registros++;
// if(!obj.hasOwnProperty(prop)) continue;
// }
// }
})
//this.federacoes.count = 1 ;// = this.federacoes.length;
}
onEditRequest(idClubedelaco) {
this.router.navigate(['/clubesdelacoView', { id: idClubedelaco, isEdit: true }]);
}
onDeleteRequest(idClubedelaco, nameClubedelaco) {
if (confirm("Confirma a exclusão do clube \'" + nameClubedelaco + "\'?")) {
this.clubesdelacoService.removeClubedelaco(idClubedelaco).subscribe(data => {
if (data.success) {
location.reload();
this.flashMessage.show('Registro removido com sucesso.', { cssClass: 'alert-success', timeout: 5000 });
//this.router.navigate(['/federacao']);
}
})
}
}
//Ultimo bracket
}
<file_sep>/angular-src/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
//do metronic
import { ThemeComponent } from './theme/theme.component';
import { LayoutModule } from './theme/layouts/layout.module';
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ScriptLoaderService } from "./_services/script-loader.service";
import { ThemeRoutingModule } from "./theme/theme-routing.module";
import { AuthModule } from "./auth/auth.module";
//Componentes desenvolvidos
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { ProfileComponent } from './components/profile/profile.component';
import { SidenavComponent } from './components/sidenav/sidenav.component';
//import { FooterComponent } from './components/footer/footer.component';
import { ClubesdelacoComponent } from './components/clubesdelaco/clubesdelaco.component';
import { FederacaoComponent } from './components/federacao/federacao.component';
import { LacadoresComponent } from './components/lacadores/lacadores.component';
import { FederacaoViewComponent } from './components/federacao/federacaoView/federacaoView.component';
import { FederacaoAddComponent } from './components/federacao/federacao-add/federacao-add.component';
import { ClubesdelacoViewComponent } from './components/clubesdelaco/clubesdelacoView/clubesdelacoView.component';
//import { LacadoresViewComponent } from './components/lacadores/lacadoresView/lacadoresView.component';
//Servi�os desenvolvidos
//import { ValidateService } from './services/validate.service';
import { AuthService } from './services/auth.service';
import { FederacaoService } from './services/federacao.service';
import { ClubesdelacoService } from './services/clubesdelaco.service';
import { LacadoresService } from './services/lacadores.service';
//Guardas desenvolvidas
import { AuthGuard } from './guards/auth.guard';
//third party stuff
import { FlashMessagesModule } from 'angular2-flash-messages';
import { NgbModule, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { DatepickerConfigComponent } from './components/datepicker-config/datepicker-config.component';
import { MyNgbDateParserFormatter } from './classes/myNgbDateParserFormatter'
//import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
const appRoutes: Routes = [
// { path: '', component: HomeComponent },
// { path: 'register', component: RegisterComponent },
// { path: 'login', component: LoginComponent },
// { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
// { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
// { path: 'federacao', component: FederacaoComponent, canActivate: [AuthGuard] },
// { path: 'federacaoView', component: FederacaoViewComponent, canActivate: [AuthGuard] },
// { path: 'clubesdelaco', component: ClubesdelacoComponent, canActivate: [AuthGuard] },
// { path: 'clubesdelacoView', component: ClubesdelacoViewComponent, canActivate: [AuthGuard] },
// { path: 'lacadores', component: LacadoresComponent, canActivate: [AuthGuard] },
//{ path: 'lacadoresView', component: LacadoresViewComponent, canActivate: [AuthGuard] }
//resto das routes aqui
];
@NgModule({
declarations: [
ThemeComponent,
AppComponent,
NavbarComponent,
LoginComponent,
RegisterComponent,
HomeComponent,
DashboardComponent,
ProfileComponent,
SidenavComponent,
// FooterComponent,
ClubesdelacoComponent,
FederacaoComponent,
LacadoresComponent,
FederacaoViewComponent,
FederacaoAddComponent,
ClubesdelacoViewComponent,
//LacadoresViewComponent,
DatepickerConfigComponent
],
imports: [
LayoutModule,
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
ThemeRoutingModule,
AuthModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
RouterModule.forRoot(appRoutes),
FlashMessagesModule,
NgbModule.forRoot()
],
providers: [
ScriptLoaderService,
//ValidateService,
AuthService,
AuthGuard,
FederacaoService,
ClubesdelacoService,
LacadoresService,
{ provide: NgbDateParserFormatter, useClass: MyNgbDateParserFormatter }
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/models/lacador.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
const LacadorSchema = mongoose.Schema({
name: { type: String, required: true },
cpf: { type: String, required: true },
email: { type: String, required: true },
endereco: { type: String, required: true },
status: { type: Boolean, required: true },
picture: { type: Buffer, contentType: String},
idClube: { type: String },
flgIndepentente: { type: Boolean },
apelido: { type: String },
foneDDD1: { type: String },
fone1: { type: String },
foneDDD2: { type: String },
fone2: { type: String },
dataAssociacao: { type: Date }
//http://localhost:4200/clubesdelacoView;id=59b8d3ccc45a52357ca1cf99;isEdit=true;isDetail=true;idClube=59b8d3ccc45a52357ca1cf99
});
const Lacador = module.exports = mongoose.model('Lacador', LacadorSchema);
// Get
module.exports.getLacadorList = function(all, callback) {
Lacador.find(all, callback);
}
module.exports.getLacadorListByClubeId = function(idClube, callback) {
const query = {idClube: idClube }
Lacador.find(query, callback);
}
module.exports.getLacadorById = function(id, callback) {
const query = {
_id: id
}
Lacador.findOne(query, callback);
console.log('callback');
console.log(callback);
}
module.exports.getLacadorByName = function(name, callback) {
const query = {
name: name
}
Lacador.findOne(query, callback);
}
module.exports.getLacadorByCpf = function(cpf, callback) {
const query = {
cpf: cpf
}
Lacador.findOne(query, callback);
}
module.exports.getLacadorByEmail = function(email, callback) {
const query = {
email: email
}
Lacador.findOne(query, callback);
}
// Add
module.exports.addLacador = function(newLacador, callback) {
newLacador.save(callback);
};
//remove
module.exports.removeLacador = function(idLacador, callback) {
const query = {
_id: idLacador
}
Lacador.remove(query, callback);
}
//update
module.exports.updateById = function(lacador, callback) {
const query = {
_id: lacador._id
};
const newSet = {
$set: {
"name": lacador.name,
"email": lacador.email,
"cpf": lacador.cpf,
"endereco": lacador.endereco,
"status": lacador.status,
"picture": lacador.picture,
"idClube": lacador.idClube,
"apelido": lacador.apelido,
"foneDDD1": lacador.foneDDD1,
"fone1": lacador.fone1,
"foneDDD2": lacador.foneDDD2,
"fone2": lacador.fone2,
"dataAssociacao": lacador.dataAssociacao
}
};
console.log('lacador');
console.log(lacador);
console.log('newSet');
console.log(newSet);
Lacador.updateOne(query, newSet, callback);
}
//Torna todos os laçadores de um clube como Indepententes
module.exports.setLacadorIndependenteByClube = function(idClubedelaco, callback) {
const query = {
idClube: idClubedelaco
};
const newSet = {
$set: {
"flgIndepentente": true,
"idClube": null
}
};
// console.log('lacador');
// console.log(lacador);
// console.log('newSet');
// console.log(newSet);
if(idClubedelaco){
Lacador.update(query, newSet, callback);
}
}
//Torna um laçador Indepentente
module.exports.setLacadorIndependenteById = function(idLacador, callback) {
const query = {
_id: idLacador
};
const newSet = {
$set: {
"flgIndepentente": true,
"idClube": null
}
};
// console.log('lacador');
// console.log(lacador);
// console.log('newSet');
// console.log(newSet);
if(idClubedelaco){
Lacador.update(query, newSet, callback);
}
}
<file_sep>/routes/federacoes.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
const Federacao = require('../models/federacao');
// List
router.get('/list', (req, res, next) => {
//console.log('routes - before /list');
Federacao.getFederacaoList({}, (err, federacoesList) => {
if (err) throw err;
if (!federacoesList) {
return res.json({
success: false,
msg: 'Tabela vazia'
});
} else {
return res.json({
federacoesList: federacoesList
});
}
})
});
// View
router.get('/view', (req, res, next) => {
//console.log('req.params.idFederacao');
//console.log(req.query.idFederacao);
Federacao.getFederacaoById(req.query.idFederacao, (err, federacao) => {
if (!federacao) {
return res.json({
success: false,
msg: 'Erro ao buscar a federação desejada. Entre em contato com o suporte técnico do sistema.'
});
} else {
res.json({
federacao: federacao
});
}
})
});
// Edit
router.post('/update', (req, res, next) => {
Federacao.updateById(req.body, (err, callback) => {
if (err) {
res.json({
success: false,
msg: "Erro ao atualizar o registro da Federação:",
erro: err
});
} else {
res.json({
success: true,
msg: "Federação atualizada com sucesso."
});
}
});
});
// Delete
router.post('/remove', (req, res, next) => {
Federacao.removeFederacao(req.body.idFederacao, (err, callback) => {
if (err) {
res.json({
success: false,
msg: "Erro ao remover o registro da Federação."
});
} else {
res.json({
success: true,
msg: "Federação removida do sistema com sucesso."
});
}
});
});
//Register
router.post('/add', (req, res, next) => {
let newFederacao = new Federacao({
name: req.body.name,
razaosocial: req.body.razaosocial,
cnpj: req.body.cnpj,
status: req.body.status,
email: req.body.email,
})
//valida unique keys: CNPJ
// Federacao.getFederacaoByCNPJ(newFederacao, (err, federacaoEncontrada) => {
// if(err) throw err;
// if(!federacaoEncontrada){
// return res.json({success: false,msg: 'Já existe uma Federaçao com este CNPJ: '})
// }
// // else {
Federacao.addFederacao(newFederacao, (err, federacao) => {
if (err) {
res.json({
success: false,
msg: "Erro ao registrar a Federação."
});
} else {
res.json({
success: true,
msg: "Federação registrada com sucesso.",
id: federacao._id
});
}
});
});
module.exports = router;
<file_sep>/angular-src/src/app/components/federacao/federacaoView/federacaoView.component.ts
import { Component, OnInit } from '@angular/core';
import { FederacaoService } from '../../../services/federacao.service';
//Depeciado
//import { ValidateService } from '../../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-federacaoView',
templateUrl: './federacaoView.component.html',
styleUrls: ['./federacaoView.component.css']
})
export class FederacaoViewComponent implements OnInit {
Federacao = {
_id: String,
name: String,
razaosocial: String,
cnpj: String,
status: Boolean,
email: String
};
isView: boolean;
isInsert: boolean;
isEdit: boolean;
idRecord: any;
constructor(
//Depeciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router,
private route: ActivatedRoute
) { }
ngOnInit() {
this.route.params.subscribe((params) => {
if (params.id) { this.idRecord = params.id; }
this.isInsert = true ? params.isInsert : true;
this.isEdit = true ? params.isEdit : true;
this.isView = true ? params.isView : true;
});
if (!this.isInsert) {
this.federacaoService.getFederacaoById(this.idRecord).subscribe((result) => {
this.Federacao = result.federacao;
})
} else {
this.Federacao.name = null;
this.Federacao.razaosocial = null;
this.Federacao.status = null;
this.Federacao.cnpj = null;
this.Federacao.email = null;
}
}
onFederacaoSubmit() {
const newFederacao = {
name: this.Federacao.name,
cnpj: this.Federacao.cnpj,
razaosocial: this.Federacao.razaosocial,
status: true,//this.Federacao.status,
email: this.Federacao.email
}
// Required Fields
// Register user
if (this.isInsert) {
this.federacaoService.addFederacao(newFederacao).subscribe(data => {
if (data.success) {
//console.log(data);
this.router.navigate(['federacaoView', { id: data.id, isView: true }]);
this.flashMessage.show('Federação registrada com sucesso.', { cssClass: 'alert-success', timeout: 3000 });
} else {
this.flashMessage.show('Ocorreu um erro ao tentar inserir este registro. Favor entre em contato com o suporte técnico do sistema.', { cssClass: 'alert-danger', timeout: 3000 });
}
})
} else {
//isEdit
this.federacaoService.updateFederacao(this.Federacao).subscribe(data => {
if (data.success) {
//console.log(data);
this.router.navigate(['federacaoView', { id: this.Federacao._id, isEdit: true }]);
this.flashMessage.show('Federação atualizada com sucesso.', { cssClass: 'alert-success', timeout: 3000 });
} else {
this.flashMessage.show('Ocorreu um erro ao tentar atualizar o registro. Favor entre em contato com o suporte técnico do sistema.' + data.msg, { cssClass: 'alert-danger', timeout: 3000 });
}
})
}
}
}
<file_sep>/angular-src/src/app/theme/pages/default/components/sharedModule.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { LacadoresComponent } from "./lacadores/lacadores.component"
//import { LacadoresViewComponent } from "./lacadores/lacadoresView/lacadoresView.component"
//import { ClubesdelacoComponent } from "./clubesdelaco/clubesdelaco.component"
//import { ClubesdelacoViewComponent } from "./clubesdelaco/clubesdelacoView/clubesdelacoView.component"
@NgModule({
imports: [
CommonModule,
FormsModule
//LacadoresComponent
],
declarations: [
LacadoresComponent
// LacadoresViewComponent,
// ClubesdelacoComponent,
// ClubesdelacoViewComponent,
],
providers: [
],
exports: [
LacadoresComponent
//CommonModule,
//FormsModule
//LacadoresViewComponent,
//ClubesdelacoComponent,
//ClubesdelacoViewComponent,
]
})
export class SharedModule {}
<file_sep>/angular-src/src/app/theme/pages/default/components/federacao/federacaoView/federacaoView.component.ts
import { Component, OnInit } from '@angular/core';
import { FederacaoService } from '../../../services/federacao.service';
//Depreciado
//import { ValidateService } from '../../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { FormGroup,FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: '.m-grid__item.m-grid__item--fluid.m-wrapper',
templateUrl: './federacaoView.component.html',
styleUrls: ['./federacaoView.component.css']
})
export class FederacaoViewComponent implements OnInit {
Federacao = {
_id: String,
name: String,
razaosocial: String,
cnpj: String,
status: Boolean,
email: String
};
isView: boolean;
isInsert: boolean;
isEdit: boolean;
idRecord: any;
constructor(
//Depreciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router,
private route: ActivatedRoute
) { }
ngOnInit() {
this.route.params.subscribe((params) => {
if (params.id) { this.idRecord = params.id; }
this.isInsert = true ? params.isInsert : true;
this.isEdit = true ? params.isEdit : true;
this.isView = true ? params.isView : true;
});
if (!this.isInsert) {
this.federacaoService.getFederacaoById(this.idRecord).subscribe((result) => {
this.Federacao = result.federacao;
})
} else {
this.Federacao.name = null;
this.Federacao.razaosocial = null;
this.Federacao.status = null;
this.Federacao.cnpj = null;
this.Federacao.email = null;
}
}
onEditRequest(idFederacao) {
this.router.navigate(['/federacaoView', { id: idFederacao, isEdit: true }]);
}
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
control.controls.forEach(c => this.markFormGroupTouched(c));
}
});
}
onFederacaoSubmit(federacaoForm: FormGroup) {
this.markFormGroupTouched(federacaoForm);
if (!federacaoForm.valid) {
console.log("Form com erros!");
} else {
const newFederacao = {
name: this.Federacao.name,
cnpj: this.Federacao.cnpj,
razaosocial: this.Federacao.razaosocial,
status: true,//this.Federacao.status,
email: this.Federacao.email
}
// Required Fields
// if(!this.validateService.validateFederacao(federacao)){
// this.flashMessage.show('Para continuar é necessário preencher todos os campos', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
// // Validar o email
// if(!this.validateService.validateEmail(user.email)){
// this.flashMessage.show('Para continuar é necessário informar um e-mail válido', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
// Register user
if (this.isInsert) {
this.federacaoService.addFederacao(newFederacao).subscribe(data => {
if (data.success) {
//console.log(data);
this.router.navigate(['federacaoView', { id: data.id, isView: true }]);
//TODO: Mensagem
alert('Federação registrada com sucesso.');
} else {
//TODO: Mensagem
alert('Ocorreu um erro ao tentar inserir este registro. Favor entre em contato com o suporte técnico do sistema.' + data.msg);
}
})
} else {
//isEdit
this.federacaoService.updateFederacao(this.Federacao).subscribe(data => {
if (data.success) {
console.log(data);
alert("Registro alterado com sucesso");
this.router.navigate(['federacaoView', { id: this.Federacao._id, isEdit: true }]);
//TODO: Mensagem
//this.flashMessage.show('Federação atualizada com sucesso.', { cssClass: 'alert-success', timeout: 3000 });
} else {
//TODO: Mensagem
alert('Ocorreu um erro ao tentar atualizar o registro. Favor entre em contato com o suporte técnico do sistema: ' + data.msg);
}
})
}
}
}
}
<file_sep>/angular-src/src/app/components/clubesdelaco/clubesdelacoView/clubesdelacoView.component.ts
import { Component, OnInit } from '@angular/core';
import { FederacaoService } from '../../../services/federacao.service';
import { ClubesdelacoService } from '../../../services/clubesdelaco.service';
//Depeciado
//import { ValidateService } from '../../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { NgbDateStruct, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
//import { MyNgbDateParserFormatter } from '../../../classes/myNgbDateParserFormatter'
@Component({
selector: 'app-clubesdelacoView',
templateUrl: './clubesdelacoView.component.html',
styleUrls: ['./clubesdelacoView.component.css']
})
export class ClubesdelacoViewComponent implements OnInit {
Clubedelaco: any = {
name: String,
email: String,
sede: String,
status: Boolean,
razaoSocial: String,
cnpj: String,
sigla: String,
dataFundacao: String,
registroSETEL: String,
rua: String,
numeroSala: String,
bairro: String,
cep: String,
cidade: String,
foneDDD: String,
fone: String,
faxDDD: String,
fax: String,
nomeRepresentante: String,
cpfRepresentante: String,
rgRepresentante: String,
cargoRepresentante: String,
foneDDDRepresentante: String,
foneRepresentante: String,
atuacao: String
};
isView: boolean;
isInsert: boolean;
isEdit: boolean;
idRecord: any;
constructor(
//Depeciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router,
private route: ActivatedRoute,
private clubesdelacoService: ClubesdelacoService,
private ngbDateParserFormatter: NgbDateParserFormatter,
) { }
ngOnInit() {
this.Clubedelaco.name = '';
this.Clubedelaco.sede = '';
this.Clubedelaco.email = '';
this.Clubedelaco.status = '';
this.Clubedelaco.razaoSocial = '';
this.Clubedelaco.cnpj = '';
this.Clubedelaco.sigla = '';
this.Clubedelaco.dataFundacao = '';
this.Clubedelaco.registroSETEL = '';
this.Clubedelaco.rua = '';
this.Clubedelaco.numeroSala = '';
this.Clubedelaco.bairro = '';
this.Clubedelaco.cep = '';
this.Clubedelaco.cidade = '';
this.Clubedelaco.foneDDD = '';
this.Clubedelaco.fone = '';
this.Clubedelaco.faxDDD = '';
this.Clubedelaco.fax = '';
this.Clubedelaco.nomeRepresentante = '';
this.Clubedelaco.cpfRepresentante = '';
this.Clubedelaco.rgRepresentante = '';
this.Clubedelaco.cargoRepresentante = '';
this.Clubedelaco.foneDDDRepresentante = '';
this.Clubedelaco.foneRepresentante = '';
this.Clubedelaco.atuacao = '';
this.route.params.subscribe((params) => {
if (params.id) { this.idRecord = params.id; }
this.isInsert = true ? params.isInsert : true;
this.isEdit = true ? params.isEdit : true;
this.isView = true ? params.isView : true;
});
if (!this.isInsert) {
this.clubesdelacoService.getClubedelacoById(this.idRecord).subscribe((result) => {
this.Clubedelaco = result;
//pega a data no formato do banco de dados e monta o array do componente Datepicker
this.Clubedelaco.arrayDataFundacao = this.ngbDateParserFormatter.parse(this.Clubedelaco.dataFundacao);
})
}
}
onClubesdelacoSubmit() {
//Monta a data de fundação no formato para o banco de dados.
if (this.Clubedelaco.arrayDataFundacao) {
this.Clubedelaco.dataFundacao = new Date(this.Clubedelaco.arrayDataFundacao.year, this.Clubedelaco.arrayDataFundacao.month - 1, this.Clubedelaco.arrayDataFundacao.day);
} else {
this.Clubedelaco.dataFundacao = null
}
const newClubedelaco = {
name: this.Clubedelaco.name,
sede: this.Clubedelaco.sede,
email: this.Clubedelaco.email,
status: true, //this.Federacao.status,
razaoSocial: this.Clubedelaco.razaoSocial,
cnpj: this.Clubedelaco.cnpj,
sigla: this.Clubedelaco.sigla,
dataFundacao: this.Clubedelaco.dataFundacao,
registroSETEL: this.Clubedelaco.registroSETEL,
rua: this.Clubedelaco.rua,
numeroSala: this.Clubedelaco.numeroSala,
bairro: this.Clubedelaco.bairro,
cep: this.Clubedelaco.cep,
cidade: this.Clubedelaco.cidade,
foneDDD: this.Clubedelaco.foneDDD,
fone: this.Clubedelaco.fone,
faxDDD: this.Clubedelaco.faxDDD,
fax: this.Clubedelaco.fax,
nomeRepresentante: this.Clubedelaco.nomeRepresentante,
cpfRepresentante: this.Clubedelaco.cpfRepresentante,
rgRepresentante: this.Clubedelaco.rgRepresentante,
cargoRepresentante: this.Clubedelaco.cargoRepresentante,
foneDDDRepresentante: this.Clubedelaco.foneDDDRepresentante,
foneRepresentante: this.Clubedelaco.foneRepresentante,
atuacao: this.Clubedelaco.atuacao
}
console.log('this.Clubedelaco');
console.log(this.Clubedelaco);
// Required Fields
// Register user
if (this.isInsert) {
this.clubesdelacoService.addClubedelaco(newClubedelaco).subscribe(data => {
if (data.success) {
this.router.navigate(['clubesdelacoView', { id: data.id, isView: true }]);
this.flashMessage.show('Clube de Laço registrado com sucesso.', { cssClass: 'alert-success', timeout: 3000 });
} else {
this.flashMessage.show('Ocorreu um erro ao tentar inserir este Clube de laço. Favor entre em contato com o suporte técnico do sistema.', { cssClass: 'alert-danger', timeout: 3000 });
}
})
} else {
//isEdit
this.clubesdelacoService.updateClubedelaco(this.Clubedelaco).subscribe(data => {
if (data.success) {
this.flashMessage.show('Clube de Laço atualizado com sucesso.', { cssClass: 'alert-success', timeout: 5000 });
window.scrollTo(0, 0);
//this.router.navigate(['clubesdelacoView', { id: this.Clubedelaco._id, isEdit: true }]);
} else {
this.flashMessage.show('Ocorreu um erro ao tentar atualizar o registro. Favor entre em contato com o suporte técnico do sistema.' + data.msg, { cssClass: 'alert-danger', timeout: 3000 });
}
})
}
}
}
<file_sep>/angular-src/src/app/components/federacao/federacao-add/federacao-add.component.ts
import { Component, OnInit } from '@angular/core';
import { FederacaoService } from '../../../services/federacao.service';
//Depeciado
//import { ValidateService } from '../../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
@Component({
selector: 'app-federacao-add',
templateUrl: './federacao-add.component.html',
styleUrls: ['./federacao-add.component.css']
})
export class FederacaoAddComponent implements OnInit {
constructor(
//Depeciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router) { }
ngOnInit() {
}
};
<file_sep>/angular-src/src/app/theme/pages/default/services/clubesdelaco.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ClubesdelacoService {
clubedelaco: any;
constructor(
private authService: AuthService,
private http: Http
) { }
getClubesdelaco() {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('clubedelaco/list');
//console.log('service - getClubedelaco()');
return this.http.get(ep, { headers: headers })
.map(res => res.json())
.map(res => res['clubedelacoList']) as Observable<any[]>;
}
getClubedelacoById(idClubedelaco) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('clubedelaco/view');
console.log('service - getClubedelaco()');
console.log(idClubedelaco);
return this.http.get(ep, { headers: headers, params: { id: idClubedelaco } })
.map(res => res.json())
.map(res => res['clubedelaco']) as Observable<any[]>;
}
addClubedelaco(clubedelaco) {
//return new Promise(resolve => resolve(clubedelaco));
//console.log('passou aqui');
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('clubedelaco/add');
return this.http.post(ep, clubedelaco, { headers: headers })
.map(res => res.json());
}
removeClubedelaco(idClubedelaco) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('clubedelaco/remove');
//console.log(3);
return this.http.post(ep, { idClubedelaco: idClubedelaco }, { headers: headers })
.map(res => res.json());
}
updateClubedelaco(clubedelaco) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('clubedelaco/update');
return this.http.post(ep, clubedelaco, { headers: headers })
.map(res => res.json());
}
}
<file_sep>/angular-src/src/app/components/federacao/federacao.component.ts
import { Component, OnInit } from '@angular/core';
import { FederacaoService } from '../../services/federacao.service';
//Depeciado
//import { ValidateService } from '../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
@Component({
selector: 'app-federacao',
templateUrl: './federacao.component.html',
styleUrls: ['./federacao.component.css']
})
export class FederacaoComponent implements OnInit {
public objfed: any;
public keys: number;
public registros: number;
constructor(
//Depeciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private federacaoService: FederacaoService,
private router: Router
) { }
ngOnInit() {
this.federacaoService.getFederacoes().subscribe(federacoes => {
this.registros = 0;
var federacaoList = Object.keys(federacoes).map(function(key) { return federacoes[key]; });
this.objfed = federacaoList;
//conta os registros
for (var key in federacoes) {
if (!federacoes.hasOwnProperty(key)) continue;
var obj = federacoes[key];
for (var prop in obj) {
// skip loop if the property is from prototype
this.registros++;
if (!obj.hasOwnProperty(prop)) continue;
}
}
})
//this.federacoes.count = 1 ;// = this.federacoes.length;
}
onEditRequest(idFederacao) {
this.router.navigate(['/federacaoView', { id: idFederacao, isEdit: true }]);
}
onDeleteRequest(idFederacao, nameFederecao) {
if (confirm("Confirma a exclusão da Federação \'" + nameFederecao + "\'?")) {
this.federacaoService.removeFederacao(idFederacao).subscribe(data => {
if (data.success) {
location.reload();
this.flashMessage.show('Registro removido com sucesso.', { cssClass: 'alert-success', timeout: 5000 });
//this.router.navigate(['/federacao']);
}
})
}
}
}
<file_sep>/angular-src/src/app/auth/auth.component.ts
import { Component, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef, ViewEncapsulation } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { ScriptLoaderService } from "../_services/script-loader.service";
import { AuthenticationService } from "./_services/authentication.service";
import { AlertService } from "./_services/alert.service";
import { UserService } from "./_services/user.service";
import { AlertComponent } from "./_directives/alert.component";
import { LoginCustom } from "./_helpers/login-custom";
import { Helpers } from "../helpers";
@Component({
selector: ".m-grid.m-grid--hor.m-grid--root.m-page",
templateUrl: './templates/login-1.component.html',
encapsulation: ViewEncapsulation.None
})
export class AuthComponent implements OnInit {
model: any = {};
loading = false;
returnUrl: string;
@ViewChild('alertSignin', { read: ViewContainerRef }) alertSignin: ViewContainerRef;
@ViewChild('alertSignup', { read: ViewContainerRef }) alertSignup: ViewContainerRef;
@ViewChild('alertForgotPass', { read: ViewContainerRef }) alertForgotPass: ViewContainerRef;
constructor(private _router: Router,
private _script: ScriptLoaderService,
private _userService: UserService,
private _route: ActivatedRoute,
private _authService: AuthenticationService,
private _alertService: AlertService,
private cfr: ComponentFactoryResolver) {
}
ngOnInit() {
this.model.remember = true;
// get return url from route parameters or default to '/'
this.returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/';
this._router.navigate([this.returnUrl]);
this._script.load('body', 'assets/vendors/base/vendors.bundle.js', 'assets/demo/default/base/scripts.bundle.js')
.then(() => {
Helpers.setLoading(false);
LoginCustom.init();
});
}
signin() {
this.loading = true;
const loginCandidate = {
username: this.model.email,
password: this.<PASSWORD>
}
//chama o método de autenticação de usuário no banco.
this._authService.authenticateUser(loginCandidate).subscribe(
data => {
if (data.success) {
console.log('sucesso na autenticação');
this._authService.storeUserData(data.token, data.user); //guarda o token e o user no localstorage
this._router.navigate([this.returnUrl]);
} else {
this.showAlert('alertSignin');
this._alertService.error(data.msg);
this.loading = false;
}
})
}
signup() {
this.loading = true;
// Register user
const user = {
name: this.model.fullname,
email: this.model.email,
username: this.model.email,
password: <PASSWORD>
}
this._authService.registerUser(user).subscribe(data => {
if (data.success) {
this.showAlert('alertSignin');
this._alertService.success('Usuário registrado com sucesso. Agora você pode fazer seu login.', true);
this.loading = false;
LoginCustom.displaySignInForm();
this.model = {};
//this.flashMessage.show('Usuário registrado com sucesso. Agora você pode fazer seu login.', { cssClass: 'alert-success', timeout: 3000 });
//this.router.navigate(['/login']);
} else {
this.showAlert('alertSignup');
this._alertService.error('Ocorreu um erro ao tentar registrar seu usuário. Favor entre em contato com o suporte técnico do sistema.');
this.loading = false;
}
})
// this._userService.create(this.model)
// .subscribe(
// data => {
// this.showAlert('alertSignin');
// this._alertService.success('Thank you. To complete your registration please check your email.', true);
// this.loading = false;
// LoginCustom.displaySignInForm();
// this.model = {};
// },
// error => {
// this.showAlert('alertSignup');
// this._alertService.error(error);
// this.loading = false;
// });
}
forgotPass() {
this.loading = true;
this._userService.forgotPassword(this.model.email)
.subscribe(
data => {
this.showAlert('alertSignin');
this._alertService.success('Cool! Password recovery instruction has been sent to your email.', true);
this.loading = false;
LoginCustom.displaySignInForm();
this.model = {};
},
error => {
this.showAlert('alertForgotPass');
this._alertService.error(error);
this.loading = false;
});
}
showAlert(target) {
this[target].clear();
let factory = this.cfr.resolveComponentFactory(AlertComponent);
let ref = this[target].createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
}
<file_sep>/config/database.js
module.exports = {
database: 'mongodb://gesmdl:<EMAIL>:33104/gesmdl',
// database: 'mongodb://localhost:27017/gesMDL',
secret: 'stringsegredo'
}
<file_sep>/angular-src/src/app/theme/pages/default/services/usergroup.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UsergroupService {
usergroup: any;
constructor(
private authService: AuthService,
private http: Http
) { }
getUsergroups() {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('usergroup/list');
//console.log('service - getUsergroups()');
return this.http.get(ep, { headers: headers })
.map(res => res.json())
.map(res => res['usergroupList']) as Observable<any[]>;;
}
getUsergroupById(idUsergroup) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('usergroup/view');
//console.log('service - getUsergroups()');
return this.http.get(ep, { headers: headers, params: { idUsergroup: idUsergroup } })
.map(res => res.json())
.map(res => res['usergroup']) as Observable<any[]>;;;
}
addUsergroup(usergroup) {
//return new Promise(resolve => resolve(usergroup));
//console.log('passou aqui');
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('usergroup/add');
return this.http.post(ep, usergroup, { headers: headers })
.map(res => res.json());
}
removeUsergroup(idUsergroup) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('usergroup/remove');
//console.log(3);
return this.http.post(ep, { idUsergroup: idUsergroup }, { headers: headers })
.map(res => res.json());
}
updateUsergroup(usergroup) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('usergroup/update');
return this.http.post(ep, usergroup, { headers: headers })
.map(res => res.json());
}
}
<file_sep>/models/federacao.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
// Federacao Schema
const FederacaoSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
razaosocial: {
type: String,
required: true
},
cnpj: {
type: String,
required: true
},
status: {
type: Boolean,
required: true
}
});
const Federacao = module.exports = mongoose.model('Federacao', FederacaoSchema);
// Get
module.exports.getFederacaoList = function(all,callback){
Federacao.find(all, callback);
}
module.exports.getFederacaoById = function(id, callback){
const query = {_id: id}
Federacao.findOne(query, callback);
}
module.exports.getFederacaoByName = function(name, callback){
const query = {name: name}
Federacao.findOne(query, callback);
}
module.exports.getFederacaoByCNPJ = function(cnpj, callback){
const query = {cnpj: cnpj}
Federacao.findOne(query, callback);
}
module.exports.getFederacaoByEmail = function(email, callback){
const query = {email: email}
Federacao.findOne(query, callback);
}
// Add
module.exports.addFederacao = function(newFederacao, callback){
newFederacao.save(callback);
};
//remove
module.exports.removeFederacao = function(idFederacao,callback){
const query = {_id: idFederacao}
Federacao.remove(query, callback);
}
//update
module.exports.updateById = function(federacao,callback){
const query = {_id: federacao._id};
const sets = {
$set : {
"name": federacao.name,
"email": federacao.email,
"razaosocial": federacao.razaosocial,
"cnpj": federacao.cnpj,
"status": federacao.status
}
};
Federacao.updateOne(query, sets, callback);
}
<file_sep>/angular-src/src/app/theme/pages/default/components/lacadores/lacadoresView/lacadoresView.component.ts
import { Component, OnInit, Input, ViewChild } from '@angular/core';
//import { FederacaoService } from '../../../services/federacao.service';
import { ClubesdelacoService } from '../../../services/clubesdelaco.service';
import { LacadoresService } from '../../../services/lacadores.service';
//Depreciado
//import { ValidateService } from '../../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
//TODO: Quando 2 módulos usando ngDatepicker são abertos em sequencia, ocorre erro ao tentar carregar 2x o ngDatepicker
import { NgbDateStruct, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { FormGroup,FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
//import { uiSelect } from 'ui-select';
//import { ngSanitize } from 'angular-sanitize';
import { ActivatedRoute } from '@angular/router';
const now = new Date();
@Component({
selector: '.m-grid__item.m-grid__item--fluid.m-wrapper',
templateUrl: './lacadoresView.component.html',
styleUrls: ['./lacadoresView.component.css']
})
export class LacadoresViewComponent implements OnInit {
@ViewChild('pictureInput') fileInput;
Lacador: any = {
_id: String,
name: String,
cpf: String,
endereco: String,
email: String,
picture: Blob,
status: Boolean,
idClube: String,
nameClube: String, // não salvar no DB
flgIndepentente: Boolean,
apelido: String,
foneDDD1: String,
fone1: String,
foneDDD2: String,
fone2: String,
dataAssociacao: Date
};
isView: boolean;
isInsert: boolean;
isEdit: boolean;
idRecord: any;
@Input() requestIdClube
Clubedelaco = [];
constructor(
//Depreciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
//private federacaoService: FederacaoService,
private router: Router,
private route: ActivatedRoute,
private clubesdelacoService: ClubesdelacoService,
private lacadoresService: LacadoresService,
private ngbDateParserFormatter: NgbDateParserFormatter
) { }
ngOnInit() {
//pega todos os parametros passados pela url
this.route.params.subscribe((params) => {
if (params.id) { this.idRecord = params.id; }
this.isInsert = true ? params.isInsert : true;
this.isEdit = true ? params.isEdit : true;
this.isView = true ? params.isView : true;
});
//Se for view ou edit, busca os dados do Lacador e de todos os Clubes
if (!this.isInsert) {
//Edit ou View
this.lacadoresService.getLacadorById(this.idRecord).subscribe((result) => {
this.Lacador = result;
//pega a data no formato do banco de dados e monta o array do componente Datepicker
if (this.Lacador.dataAssociacao){
this.Lacador.arrayDataAssociacao = this.ngbDateParserFormatter.parse(this.Lacador.dataAssociacao);
}
console.log('this.Lacador');
console.log(this.Lacador);
// console.log('this.Lacador.idClube');
// console.log(this.Lacador.idClube);
if (this.isEdit) {
this.clubesdelacoService.getClubesdelaco().subscribe((clubesdelaco) => {
this.Clubedelaco = clubesdelaco;
console.log('Edit: clubesdelaco');
console.log(clubesdelaco);
});
} else {
this.clubesdelacoService.getClubedelacoById(this.Lacador.idClube).subscribe((clubeDoLacador) => {
this.Clubedelaco = clubeDoLacador;
//Se não encontrou um clube, significa que ele foi removido do sistema. Então se torna um Laçador Independente
this.Lacador.nameClube = clubeDoLacador ? clubeDoLacador['name'] : "Laçador Independente (Clube removido do sistema)";
console.log('View: clubeDoLacador');
console.log(clubeDoLacador);
//console.log(this.Lacador.nameClube);
})
}
})
} else {
//Insert
this.Lacador.name = null;
this.Lacador.cpf = null;
this.Lacador.endereco = null;
this.Lacador.email = null;
this.Lacador.picture = null;
this.Lacador.status = null;
this.Lacador.apelido = null;
this.Lacador.foneDDD1 = null;
this.Lacador.fone1 = null;
this.Lacador.foneDDD2 = null;
this.Lacador.fone2 = null;
this.Lacador.dataAssociacao = null;
if (!this.requestIdClube) {
// permite selecionar um clube
this.Lacador.idClube = null;
this.Lacador.flgIndepentente = null;
this.clubesdelacoService.getClubesdelaco().subscribe((clubesdelaco) => {
this.Clubedelaco = clubesdelaco;
console.log('this.Clubedelaco');
console.log(this.Clubedelaco);
})
} else {
//aqui a tela foi chamada para inserção em um clube específico
this.Lacador.idClube = this.requestIdClube;
this.clubesdelacoService.getClubedelacoById(this.idRecord).subscribe((result) => {
this.Clubedelaco = result;
})
}
}
console.log(this.Lacador);
}
onEditRequest(idLacador) {
this.router.navigate(['/lacadoresView', { id: idLacador, isEdit: true }]);
}
onUploadPicture() {
let fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
const formData = new FormData();
formData.append("image", fileBrowser.files[0]);
// this.projectService.upload(formData, this.project.id).subscribe(res => {
// // do stuff w/my uploaded file
// });
}
}
//toca todos os campos do form, para ativar a validação
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
control.controls.forEach(c => this.markFormGroupTouched(c));
}
});
}
onLacadoresSubmit(lacadorForm: FormGroup) {
//toca todos os campos do form, para ativar a validação
this.markFormGroupTouched(lacadorForm);
if (!lacadorForm.valid) {
console.log("Form com erros!");
} else {
//Monta a data de fundação no formato para o banco de dados.
this.Lacador.dataAssociacao = new Date(this.Lacador.arrayDataAssociacao.year, this.Lacador.arrayDataAssociacao.month - 1, this.Lacador.arrayDataAssociacao.day);
const newLacador = {
name: this.Lacador.name,
cpf: this.Lacador.cpf,
endereco: this.Lacador.endereco,
email: this.Lacador.email,
picture: this.Lacador.picture,
idClube: this.Lacador.idClube,
status: true, //this.Federacao.status,
apelido: this.Lacador.apelido,
foneDDD1: this.Lacador.foneDDD1,
fone1: this.Lacador.fone1,
foneDDD2: this.Lacador.foneDDD2,
fone2: this.Lacador.fone2,
dataAssociacao: this.Lacador.dataAssociacao
}
//console.log(newLacador);
//console.log('newLacador');
// Required Fields
// if(!this.validateService.validateFederacao(federacao)){
// this.flashMessage.show('Para continuar é necessário preencher todos os campos', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
// // Validar o email
// if(!this.validateService.validateEmail(user.email)){
// this.flashMessage.show('Para continuar é necessário informar um e-mail válido', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
console.log('newLacador');
console.log(newLacador);
if (this.isInsert) {
this.lacadoresService.addLacador(newLacador).subscribe(data => {
if (data.success) {
//console.log(data);
this.router.navigate(['lacadoresView', { id: data.id, isView: true }]);
//TODO: Mensagem
//this.flashMessage.show('Laçador registrado com sucesso.', { cssClass: 'alert-success', timeout: 3000 });
} else {
//TODO: Mensagem
//this.flashMessage.show('Ocorreu um erro ao tentar inserir este Laçador. Favor entre em contato com o suporte técnico do sistema.', { cssClass: 'alert-danger', timeout: 3000 });
}
})
} else {
//isEdit
this.lacadoresService.updateLacador(this.Lacador).subscribe(data => {
if (data.success) {
console.log(data);
//this.router.navigate(['lacadoresView', { id: this.Lacador._id, isEdit: true }]);
//TODO: Mensagem
//this.flashMessage.show('Laçador atualizado com sucesso.', { cssClass: 'alert-success', timeout: 5000 });
window.scrollTo(0, 0);
} else {
//TODO: Mensagem
//this.flashMessage.show('Ocorreu um erro ao tentar atualizar o registro. Favor entre em contato com o suporte técnico do sistema.' + data.msg, { cssClass: 'alert-danger', timeout: 5000 });
window.scrollTo(0, 0);
}
})
}
}
}
}
<file_sep>/models/usergroup.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
const UsergroupSchema = mongoose.Schema
({
name: { type: String, required: true }
situacao: { type: Boolean, required: true }
});
const Usergroup = module.exports = mongoose.model('Usergroup', UsergroupSchema);
// Get
module.exports.getUsergroupList = function(all, callback) {
Usergroup.find(all, callback);
}
module.exports.getUsergroupById = function(id, callback) {
const query = {
_id: id
}
Usergroup.findOne(query, callback);
console.log('callback');
console.log(callback);
}
// Add
module.exports.addUsergroup = function(newUsergroup, callback) {
newUsergroup.save(callback);
};
//remove
module.exports.removeUsergroup = function(idUsergroup, callback) {
const query = {
_id: idUsergroup
}
Usergroup.remove(query, callback);
}
//update
module.exports.updateById = function(usergroup, callback) {
const query = {
_id: usergroup._id
};
const newSet = {
$set: {
"name": usergroup.name,
"situacao": usergroup.situacao
}
};
console.log('usergroup');
console.log(usergroup);
console.log('newSet');
console.log(newSet);
Usergroup.updateOne(query, newSet, callback);
}
<file_sep>/angular-src/src/app/theme/pages/default/services/user.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UserService {
user: any;
constructor(
private authService: AuthService,
private http: Http
) { }
getUsers() {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('user/list');
//console.log('service - getuseres()');
return this.http.get(ep, { headers: headers })
.map(res => res.json())
.map(res => res['userList']) as Observable<any[]>;;
}
getUserById(idUser) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('user/view');
//console.log('service - getuseres()');
return this.http.get(ep, { headers: headers, params: { idUser: idUser } })
.map(res => res.json())
.map(res => res['user']) as Observable<any[]>;;;
}
getUserByUsername(idClube) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('user/viewByUsername');
return this.http.get(ep, { headers: headers, params: { idClube: idClube } })
.map(res => res.json())
.map(res => res['userList']) as Observable<any[]>;
}
addUser(user) {
//return new Promise(resolve => resolve(user));
console.log('passou aqui');
console.log(user);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('user/add');
return this.http.post(ep, user, { headers: headers })
.map(res => res.json());
}
removeUser(idUser) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('user/remove');
//console.log(3);
return this.http.post(ep, { idUser: idUser }, { headers: headers })
.map(res => res.json());
}
updateUser(user) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('user/update');
return this.http.post(ep, user, { headers: headers })
.map(res => res.json());
}
// setUserIndependenteByClube(idClubedelaco) {
// //console.log(2);
// let headers = new Headers();
// //headers.append('Authorization', this.authService.authToken);
// headers.append('Content-Type', 'application/json');
// let ep = this.authService.prepEndpoint('user/setUserIndependenteByClube');
// return this.http.post(ep, { idClubedelaco: idClubedelaco }, { headers: headers })
// .map(res => res.json());
// }
}
<file_sep>/angular-src/src/app/services/federacao.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
// let federacoes = [
// { title: 'Federação 1', isActive: true },
// { title: 'Federação 2', isActive: true },
// { title: 'Federação 3', isActive: false },
// { title: 'Federação 4', isActive: false },
// ];
@Injectable()
export class FederacaoService {
federacao: any;
constructor(
private authService: AuthService,
private http: Http
) { }
getFederacoes() {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('federacao/list');
//console.log('service - getFederacoes()');
return this.http.get(ep, { headers: headers })
.map(res => res.json());
}
getFederacaoById(idFederacao) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('federacao/view');
//console.log('service - getFederacoes()');
return this.http.get(ep, { headers: headers, params: { idFederacao: idFederacao } })
.map(res => res.json());
}
addFederacao(federacao) {
//return new Promise(resolve => resolve(federacoes));
//console.log('passou aqui');
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('federacao/add');
return this.http.post(ep, federacao, { headers: headers })
.map(res => res.json());
}
removeFederacao(idFederacao) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('federacao/remove');
//console.log(3);
return this.http.post(ep, { idFederacao: idFederacao }, { headers: headers })
.map(res => res.json());
}
updateFederacao(federacao) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('federacao/update');
return this.http.post(ep, federacao, { headers: headers })
.map(res => res.json());
}
}
<file_sep>/angular-src/src/app/theme/pages/default/services/clubesdelaco.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { ClubesdelacoService } from './clubesdelaco.service';
describe('ClubesdelacoService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ClubesdelacoService]
});
});
it('should be created', inject([ClubesdelacoService], (service: ClubesdelacoService) => {
expect(service).toBeTruthy();
}));
});
<file_sep>/routes/pages.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
const Page = require('../models/page');
// List
router.get('/list', (req, res, next) => {
Page.getPageList({}, (err, pageList) => {
if (err) throw err;
if (!pageList) {
return res.json({
success: false,
msg: 'Tabela vazia'
});
} else {
return res.json({ pageList: pageList });
}
})
});
router.get('/listByUserGroupId', (req, res, next) => {
Page.getPageByUserGroupId(req.query.idUserGroup, (err, pageList) => {
if (err) throw err;
if (!pageList) {
return res.json({
success: false,
msg: 'Tabela vazia'
});
} else {
// console.log('pageList');
// console.log(pageList);
return res.json({ pageList });
}
})
});
// View
router.get('/view', (req, res, next) => {
//console.log('req.params.idPage');
//console.log(req.query.idPage);
Page.getPageById(req.query.idPage, (err, page) => {
if (!page) {
return res.json({
success: false,
msg: 'Erro ao buscar o registro da Página desejada. Entre em contato com o suporte técnico do sistema.'
});
} else {
//console.log('Page(routes)');
//console.log(page);
res.json({
page: page
});
}
})
});
// Edit
router.post('/update', (req, res, next) => {
console.log('chegou aqui');
console.log('req.body');
console.log(req.body);
Page.updateById(req.body, (err, callback) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao atualizar o registro da Página:",
erro: err
});
} else {
res.json({
success: true,
msg: "Página atualizada com sucesso."
});
}
});
});
// Delete
router.post('/remove', (req, res, next) => {
Page.removePage(req.body.idPage, (err, callback) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao remover o registro da Página."
});
} else {
res.json({
success: true,
msg: "Página removida do sistema com sucesso."
});
}
});
});
//Register
router.post('/add', (req, res, next) => {
let newPage = new Page({
url: req.body.url,
title: req.body.title,
security: req.body.security ? true : null
})
Page.addPage(newPage, (err, page) => {
if (err) {
console.log(err);
res.json({
success: false,
msg: "Erro ao adicionar o registro de nova Página."
});
} else {
res.json({
success: true,
msg: "Página adicionada com sucesso.",
id: page._id
});
}
});
});
module.exports = router;
<file_sep>/angular-src/src/app/theme/pages/default/components/federacao/federacao-add/federacao-add.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FederacaoAddComponent } from './federacao-add.component';
describe('FederacaoAddComponent', () => {
let component: FederacaoAddComponent;
let fixture: ComponentFixture<FederacaoAddComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [FederacaoAddComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FederacaoAddComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/angular-src/src/app/theme/pages/default/components/users/usersView/usersView.component.ts
import { Component, OnInit, Input, ViewChild } from '@angular/core';
// import { appOutputMessages } from '../../../../../../shared/appmessages';
import { UserService } from '../../../services/user.service';
import { FormGroup,FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
import { ClubesdelacoService } from '../../../services/clubesdelaco.service';
//Depreciado
//import { ValidateService } from '../../../services/validate.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
const now = new Date();
@Component({
selector: '.m-grid__item.m-grid__item--fluid.m-wrapper',
templateUrl: './usersView.component.html',
styleUrls: ['./usersView.component.css']
})
export class UsersViewComponent implements OnInit {
@ViewChild('pictureInput') fileInput;
User: any = {
_id: String,
name: String,
email: String,
username: String,
password: <PASSWORD>,
status: Boolean,
picture: Blob,
cpf: String,
foneDDD1: String,
fone1: String,
dataCadastro: Date
};
isView: boolean;
isInsert: boolean;
isEdit: boolean;
idRecord: any;
//userForm: FormGroup;
constructor(
//Depreciado
//private validateService: ValidateService,
private router: Router,
private route: ActivatedRoute,
private usersService: UserService,
) { }
ngOnInit() {
//pega todos os parametros passados pela url
this.route.params.subscribe((params) => {
if (params.id) { this.idRecord = params.id; }
this.isInsert = true ? params.isInsert : true;
this.isEdit = true ? params.isEdit : true;
this.isView = true ? params.isView : true;
});
console.log('this.User');
console.log(this.User);
//Se for view ou edit, busca os dados do Usuário e de todos os Clubes
if (!this.isInsert) {
//Edit ou View
this.usersService.getUserById(this.idRecord).subscribe((result) => {
this.User = result;
//pega a data no formato do banco de dados e monta o array do componente Datepicker
// if (this.User.dataCadastro){
// this.User.arrayDataAssociacao = this.ngbDateParserFormatter.parse(this.User.dataAssociacao);
// }
console.log('this.User');
console.log(this.User);
// console.log('this.Lacador.idClube');
// console.log(this.Lacador.idClube);
})
} else {
//Insert
this.User.name = null;
this.User.email = null;
this.User.username = null;
this.User.password = <PASSWORD>;
this.User.status = null;
this.User.picture = null;
this.User.cpf = null;
this.User.foneDDD1 = null;
this.User.fone1 = null;
//this.User.dataAssociacao = now.getDate();
}
console.log(this.User);
}
onEditRequest(idUser) {
this.router.navigate(['/usersView', { id: idUser, isEdit: true }]);
}
onUploadPicture() {
let fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
const formData = new FormData();
formData.append("image", fileBrowser.files[0]);
// this.projectService.upload(formData, this.project.id).subscribe(res => {
// // do stuff w/my uploaded file
// });
}
}
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
control.controls.forEach(c => this.markFormGroupTouched(c));
}
});
}
// validateAllFormFields(formGroup: any) { //{1}
// Object.keys(formGroup.controls).forEach(field => { //{2}
// const control = formGroup.get(field); //{3}
// if (control instanceof FormControl) { //{4}
// control.markAsTouched({ onlySelf: true });
// } else if (control instanceof FormGroup) { //{5}
// this.validateAllFormFields(control); //{6}
// }
// });
// }
onUsersSubmit(userForm: FormGroup) {
this.markFormGroupTouched(userForm);
if (!userForm.valid) {
console.log("Form com erros!");
} else {
//Monta a data de fundação no formato para o banco de dados.
//this.User.dataCadastro = new Date(this.User.arrayDataAssociacao.year, this.User.arrayDataAssociacao.month - 1, this.User.arrayDataAssociacao.day);
const newUser = {
name: this.User.name,
email: this.User.email,
username: this.User.username,
password: <PASSWORD>,
//TODO: Campo status em tela
status: true,
picture: this.User.picture,
cpf: this.User.cpf,
foneDDD1: this.User.foneDDD1,
fone1: this.User.fone1,
dataCadastro: this.User.dataCadastro
}
//console.log(newLacador);
//console.log('newLacador');
// Required Fields
// if(!this.validateService.validateFederacao(federacao)){
// this.flashMessage.show('Para continuar é necessário preencher todos os campos', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
// // Validar o email
// if(!this.validateService.validateEmail(user.email)){
// this.flashMessage.show('Para continuar é necessário informar um e-mail válido', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
console.log('newUser');
console.log(newUser);
if (this.isInsert) {
this.usersService.addUser(newUser).subscribe(data => {
if (data.success) {
console.log(data);
//TODO: Mensagem
alert('Usuário registrado com sucesso.');
} else {
//TODO: Mensagem
alert('Ocorreu um erro ao tentar inserir este Laçador. Favor entre em contato com o suporte técnico do sistema.' + data.msg);
}
this.router.navigate(['usersView', { id: data.id, isView: true }]);
})
} else {
//isEdit
this.usersService.updateUser(this.User).subscribe(data => {
if (data.success) {
console.log(data);
//TODO: Mensagem
alert('Usuário atualizado com sucesso.');
window.scrollTo(0, 0);
} else {
//TODO: Mensagem
alert('Ocorreu um erro ao tentar atualizar o registro. Favor entre em contato com o suporte técnico do sistema.');
window.scrollTo(0, 0);
}
})
}
}
}
}
<file_sep>/angular-src/src/app/classes/clube-de-laco.ts
export class ClubeDeLaco {
}
<file_sep>/angular-src/src/app/theme/pages/default/components/federacao/federacao.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { LayoutModule } from '../../../../layouts/layout.module';
import { DefaultComponent } from '../../default.component';
//import { AuthGuard } from '../../guards/auth.guard';
import { AuthService } from '../../services/auth.service';
import { FederacaoService } from '../../services/federacao.service';
import { ClubesdelacoService } from '../../services/clubesdelaco.service';
import { LacadoresService } from '../../services/lacadores.service';
import { FederacaoComponent } from './federacao.component';
//import { SharedModule, SharedLacadoresComponent } from '../../components/sharedModule.module';
const routes: Routes = [
{
"path": "",
"component": DefaultComponent,
"children": [
{
"path": "",
"component": FederacaoComponent
}
]
}
];
@NgModule({
imports: [
CommonModule, RouterModule.forChild(routes), LayoutModule
], providers: [
FederacaoService,
AuthService,
ClubesdelacoService,
LacadoresService,
], exports: [
//RouterModule,
FederacaoComponent
], declarations: [
FederacaoComponent
]
})
export class federacaoModule {
}
<file_sep>/angular-src/src/app/theme/pages/default/components/federacao/federacaoView/federacaoView.module.ts
import { NgModule } from '@angular/core';
//import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { LayoutModule } from '../../../../../layouts/layout.module';
import { DefaultComponent } from '../../../default.component';
import { FederacaoViewComponent } from './federacaoView.component';
import { Validators, ReactiveFormsModule } from '@angular/forms';
//import { AuthGuard } from '../../guards/auth.guard';
import { AuthService } from '../../../services/auth.service';
//import { FederacaoService } from '../../../services/federacao.service';
import { ClubesdelacoService } from '../../../services/clubesdelaco.service';
import { LacadoresService } from '../../../services/lacadores.service';
import { FederacaoService } from '../../../services/federacao.service';
import { NgbModule, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { MyNgbDateParserFormatter } from '../../../../../../classes/myNgbDateParserFormatter';
import { DatepickerConfigComponent } from '../../datepicker-config/datepicker-config.component';
//import { SharedModule } from '../../../components/sharedModule.module';
const routes: Routes = [
{
"path": "",
"component": DefaultComponent,
"children": [
{
"path": "",
"component": FederacaoViewComponent
}
]
}
];
@NgModule({
imports: [
// BrowserModule,
FormsModule,
CommonModule,
RouterModule.forChild(routes),
LayoutModule,
NgbModule.forRoot()
], providers: [
//FederacaoService,
AuthService,
ClubesdelacoService,
LacadoresService,
FederacaoService,
{ provide: NgbDateParserFormatter, useClass: MyNgbDateParserFormatter },
ReactiveFormsModule,
Validators
], exports: [
RouterModule
], declarations: [
FederacaoViewComponent,
DatepickerConfigComponent
]
})
export class federacaoViewModule {
}
<file_sep>/angular-src/src/app/theme/pages/default/components/clubesdelaco/clubesdelacoView/clubesdelacoView.component.ts
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FederacaoService } from '../../../services/federacao.service';
import { LacadoresService } from '../../../services/lacadores.service';
import { ClubesdelacoService } from '../../../services/clubesdelaco.service';
import { LacadoresModule } from '../../lacadores/lacadores.module';
// Depreciado
// import { ValidateService } from '../../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { NgbDateStruct, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
//import { ScriptLoaderService } from '../../../../../../_services/script-loader.service';
//import { MyNgbDateParserFormatter } from '../../../classes/myNgbDateParserFormatter'
import { FormGroup,FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: '.m-grid__item.m-grid__item--fluid.m-wrapper', //'app-clubesdelacoView',
templateUrl: './clubesdelacoView.component.html',
encapsulation: ViewEncapsulation.None,
//styleUrls: ['./clubesdelacoView.component.css']
})
export class ClubesdelacoViewComponent implements OnInit {
Clubedelaco: any = {
name: String,
email: String,
sede: String,
status: Boolean,
razaoSocial: String,
cnpj: String,
sigla: String,
dataFundacao: String,
registroSETEL: String,
rua: String,
numeroSala: String,
bairro: String,
cep: String,
cidade: String,
foneDDD: String,
fone: String,
faxDDD: String,
fax: String,
nomeRepresentante: String,
cpfRepresentante: String,
rgRepresentante: String,
cargoRepresentante: String,
foneDDDRepresentante: String,
foneRepresentante: String,
atuacao: String
};
qtdLacadores: number;
public listLacadores : any[] ;
isView: boolean;
isInsert: boolean;
isEdit: boolean;
idRecord: any;
constructor(
//Depreciado
//private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private lacadoresService: LacadoresService,
private federacaoService: FederacaoService,
private router: Router,
private route: ActivatedRoute,
private clubesdelacoService: ClubesdelacoService,
private ngbDateParserFormatter: NgbDateParserFormatter,
//private _script: ScriptLoaderService
) { }
ngOnInit() {
this.Clubedelaco.name = '';
this.Clubedelaco.sede = '';
this.Clubedelaco.email = '';
this.Clubedelaco.status = '';
this.Clubedelaco.razaoSocial = '';
this.Clubedelaco.cnpj = '';
this.Clubedelaco.sigla = '';
this.Clubedelaco.dataFundacao = '';
this.Clubedelaco.registroSETEL = '';
this.Clubedelaco.rua = '';
this.Clubedelaco.numeroSala = '';
this.Clubedelaco.bairro = '';
this.Clubedelaco.cep = '';
this.Clubedelaco.cidade = '';
this.Clubedelaco.foneDDD = '';
this.Clubedelaco.fone = '';
this.Clubedelaco.faxDDD = '';
this.Clubedelaco.fax = '';
this.Clubedelaco.nomeRepresentante = '';
this.Clubedelaco.cpfRepresentante = '';
this.Clubedelaco.rgRepresentante = '';
this.Clubedelaco.cargoRepresentante = '';
this.Clubedelaco.foneDDDRepresentante = '';
this.Clubedelaco.foneRepresentante = '';
this.Clubedelaco.atuacao = '';
this.route.params.subscribe((params) => {
if (params.id) { this.idRecord = params.id; }
this.isInsert = true ? params.isInsert : true;
this.isEdit = true ? params.isEdit : true;
this.isView = true ? params.isView : true;
});
if (!this.isInsert) {
//BUSCA INFOS DO CLUBE
this.clubesdelacoService.getClubedelacoById(this.idRecord).subscribe((result) => {
this.Clubedelaco = result;
//pega a data no formato do banco de dados e monta o array do componente Datepicker
this.Clubedelaco.arrayDataFundacao = this.ngbDateParserFormatter.parse(this.Clubedelaco.dataFundacao);
})
//BUSCA OS LACADORES DO clube
this.lacadoresService.getLacadorByClubeId(this.idRecord).subscribe(result => {
//this.qtdLacadoresRegistrados = result.length;
this.listLacadores = result;
console.log('this.listLacadores');
console.log(this.listLacadores);
this.qtdLacadores = result.length;
})
}
}
onEditRequest(idClubedelaco) {
console.log('idClubedelaco');
console.log(idClubedelaco);
this.router.navigate(['/clubesdelacoView', { id: idClubedelaco, isEdit: true }]);
}
private markFormGroupTouched(formGroup: FormGroup) {
(<any>Object).values(formGroup.controls).forEach(control => {
control.markAsTouched();
if (control.controls) {
control.controls.forEach(c => this.markFormGroupTouched(c));
}
});
}
onClubesdelacoSubmit(clubesdelacoForm: FormGroup) {
this.markFormGroupTouched(clubesdelacoForm);
if (!clubesdelacoForm.valid) {
console.log("Form com erros!");
} else {
//Monta a data de fundação no formato para o banco de dados.
if (this.Clubedelaco.arrayDataFundacao) {
this.Clubedelaco.dataFundacao = new Date(this.Clubedelaco.arrayDataFundacao.year, this.Clubedelaco.arrayDataFundacao.month - 1, this.Clubedelaco.arrayDataFundacao.day);
} else {
this.Clubedelaco.dataFundacao = null
}
// Required Fields
// if(!this.validateService.validateFederacao(federacao)){
// this.flashMessage.show('Para continuar é necessário preencher todos os campos', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
// // Validar o email
// if(!this.validateService.validateEmail(user.email)){
// this.flashMessage.show('Para continuar é necessário informar um e-mail válido', {cssClass:'alert-danger', timeout:3000});
// return false;
// }
//
// Register user
if (this.isInsert) {
const newClubedelaco = {
name: this.Clubedelaco.name,
sede: this.Clubedelaco.sede,
email: this.Clubedelaco.email,
status: true, //this.Federacao.status,
razaoSocial: this.Clubedelaco.razaoSocial,
cnpj: this.Clubedelaco.cnpj,
sigla: this.Clubedelaco.sigla,
dataFundacao: this.Clubedelaco.dataFundacao,
registroSETEL: this.Clubedelaco.registroSETEL,
rua: this.Clubedelaco.rua,
numeroSala: this.Clubedelaco.numeroSala,
bairro: this.Clubedelaco.bairro,
cep: this.Clubedelaco.cep,
cidade: this.Clubedelaco.cidade,
foneDDD: this.Clubedelaco.foneDDD,
fone: this.Clubedelaco.fone,
faxDDD: this.Clubedelaco.faxDDD,
fax: this.Clubedelaco.fax,
nomeRepresentante: this.Clubedelaco.nomeRepresentante,
cpfRepresentante: this.Clubedelaco.cpfRepresentante,
rgRepresentante: this.Clubedelaco.rgRepresentante,
cargoRepresentante: this.Clubedelaco.cargoRepresentante,
foneDDDRepresentante: this.Clubedelaco.foneDDDRepresentante,
foneRepresentante: this.Clubedelaco.foneRepresentante,
atuacao: this.Clubedelaco.atuacao
}
console.log('this.Clubedelaco');
console.log(this.Clubedelaco);
this.clubesdelacoService.addClubedelaco(newClubedelaco).subscribe(data => {
if (data.success) {
this.router.navigate(['clubesdelacoView', { id: data.id, isView: true }]);
//TODO: Mensagem
alert('Clube de Laço registrado com sucesso.');
} else {
//TODO: Mensagem
alert('Ocorreu um erro ao tentar inserir este Clube de laço. Favor entre em contato com o suporte técnico do sistema.');
}
})
} else {
//isEdit
this.clubesdelacoService.updateClubedelaco(this.Clubedelaco).subscribe(data => {
if (data.success) {
//TODO: Mensagem
alert('Clube de Laço atualizado com sucesso.');
window.scrollTo(0, 0);
//this.router.navigate(['clubesdelacoView', { id: this.Clubedelaco._id, isEdit: true }]);
} else {
window.scrollTo(0, 0);
//TODO: Mensagem
alert('Ocorreu um erro ao tentar atualizar o registro. Favor entre em contato com o suporte técnico do sistema: ' + data.msg);
}
})
}
}
}
}
<file_sep>/angular-src/src/app/theme/pages/default/services/pages.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class PagesService {
page: any;
constructor(
private authService: AuthService,
private http: Http
) { }
getPages() {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('page/list');
//console.log('service - getPages()');
return this.http.get(ep, { headers: headers })
.map(res => res.json())
.map(res => res['pageList']) as Observable<any[]>;;
}
getPageById(idPage) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('page/view');
//console.log('service - getPages()');
return this.http.get(ep, { headers: headers, params: { idPage: idPage } })
.map(res => res.json())
.map(res => res['page']) as Observable<any[]>;;;
}
getPageByUserGroupId(idUserGroup) {
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('page/listByUserGroupId');
return this.http.get(ep, { headers: headers, params: { idUserGroup: idUserGroup } })
.map(res => res.json())
.map(res => res['pageList']) as Observable<any[]>;
}
addPage(page) {
//return new Promise(resolve => resolve(page));
//console.log('passou aqui');
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('page/add');
return this.http.post(ep, page, { headers: headers })
.map(res => res.json());
}
removePage(idPage) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('page/remove');
//console.log(3);
return this.http.post(ep, { idPage: idPage }, { headers: headers })
.map(res => res.json());
}
updatePage(page) {
//console.log(2);
let headers = new Headers();
//headers.append('Authorization', this.authService.authToken);
headers.append('Content-Type', 'application/json');
let ep = this.authService.prepEndpoint('page/update');
return this.http.post(ep, page, { headers: headers })
.map(res => res.json());
}
}
| 954eacb16316a1ee9c008875c64a727a437306df | [
"JavaScript",
"TypeScript"
] | 37 | JavaScript | N3Wolf/gesMDL | a6dc31f7d5580e434319f289faf8cb0cc26d382f | 81c206f4b26a430ebc36539e096fe531c8706a0d | |
refs/heads/master | <repo_name>DanielKolesnyk/The-HAM<file_sep>/Step_project_THE_HAM/Java_Script/main.js
$(document).ready(function () {
// -----------------------------------Our services
const $ourServicesButton = $('.our_ser_btn');
const $tabs = $('.our_ser_content div[data-tab]');
$ourServicesButton.on('click', function () {
const serviceTabIndex = $(this).index();
$ourServicesButton.removeClass('ser_active_btn');
$(this).addClass('ser_active_btn');
$tabs.each(function (index) {
if (index === serviceTabIndex) {
$tabs.eq(index).css({'display': 'flex'});
} else {
$tabs.eq(index).css({'display': 'none'});
}
})
});
//-----------------------------------Our Amazing
const $amazingButton = $('.amazing_btn');
let $ourAmazingWrapper = $('.amazing_wrapper figure');
$amazingButton.on('click', function () {
let selectedItem = $(this).data().btnid;
$amazingButton.removeClass('amazing_btn_active');
$(this).addClass('amazing_btn_active');
if (selectedItem !== 'All') {
$ourAmazingWrapper.not(`[data-btnID='${selectedItem}']`).css({'display': 'none'});
$(`figure[data-btnID='${selectedItem}']`).css({'display': 'flex'});
} else {
$ourAmazingWrapper.css({'display': 'flex'});
}
});
//-----------------------------------BTN LOAD
const $amazingWorkBtn = $('.amazing_btn_load');
const $loading = $('.connect');
const $secondImgBlock = $('.amazing_img_second_part figure');
const $thirdImgBlock = $('.amazing_img_third_part figure');
let amazingCounter = 0;
$amazingWorkBtn.on('click', function (event) {
setTimeout(function () {
if (amazingCounter === 0) {
$secondImgBlock.unwrap();
amazingCounter++;
$amazingWorkBtn.css({'opacity': '1'});
} else if (amazingCounter === 1) {
$thirdImgBlock.unwrap();
amazingCounter++;
$amazingWorkBtn.remove()
}
$loading.css({'display': 'none'});
}, 2000);
$loading.css({'display': 'unset'});
$amazingWorkBtn.css({'opacity': '0'});
});
//-----------------------------------What-people
$('.slider_top').slick({
asNavFor: ".slider_bot",
arrows: false,
infinite: true,
dots: false,
centerMode: true,
fade: true,
cssEase: 'linear',
draggable: false
});
$('.slider_bot').slick({
asNavFor: ".slider_top",
dots:false,
infinite: true,
slidesToShow: 3,
centerMode: true,
focusOnSelect: true,
draggable: false
});
}); | be161285231447f465c06f9b2b6e4bac9a844bc7 | [
"JavaScript"
] | 1 | JavaScript | DanielKolesnyk/The-HAM | 11657b95d24e915dc51e0af5469156854489db37 | 0d4dda3b2d144a709ddc070ca2e46880b25ec92c | |
refs/heads/main | <repo_name>DziugasMazulis/ToDO-List-REST-API<file_sep>/TO-DO_List/Models/ToDoTaskRequest.cs
using System.ComponentModel.DataAnnotations;
namespace TO_DO_List.Models.Dto
{
public class ToDoTaskRequest
{
[Required]
public string Title { get; set; }
public bool IsCompleted { get; set; }
}
}
<file_sep>/TO-DO_List/Settings/SeedDataSettings.cs
using System.Collections.Generic;
using TO_DO_List.Models.Dto;
namespace TO_DO_List.Settings
{
public class SeedDataSettings
{
public List<UserSettings> Users { get; set; }
public List<ToDoTaskSettings> ToDoTasks { get; set; }
}
}
<file_sep>/TO-DO_List/Security/AuthOperationFilter.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;
using TO_DO_List.Data;
namespace TO_DO_List.Security
{
public class AuthOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var isAuthorized = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();
if (!isAuthorized) return;
operation.Responses.TryAdd(Constants.Int401, new OpenApiResponse { Description = Constants.Unauthorized });
operation.Responses.TryAdd(Constants.Int403, new OpenApiResponse { Description = Constants.Forbidden });
var jwtbearerScheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = Constants.Bearer }
};
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[ jwtbearerScheme ] = new string [] { }
}
};
}
}
}
<file_sep>/TO-DO_List/Program.cs
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using TO_DO_List.Contracts.Services;
namespace TO_DO_List
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
SeedDatabase(host);
host.Run();
}
private static void SeedDatabase(IHost host)
{
using (var scope = host.Services.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
try
{
//not the most efficient way to clear data but hey *shrugEmoji*
var databaseService = serviceProvider.GetRequiredService<IDatabaseService>();
databaseService.EnsureDeleted();
databaseService.EnsureCreated();
databaseService.SeedRoles();
databaseService.SeedUsers();
databaseService.SeedTasks();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
<file_sep>/TO-DO_List/Data/ToDoTaskProfile.cs
using AutoMapper;
using TO_DO_List.Models;
using TO_DO_List.Models.Dto;
using TO_DO_List.ViewModels;
namespace TO_DO_List.Data
{
public class ToDoTaskProfile : Profile
{
public ToDoTaskProfile()
{
CreateMap<ToDoTask, ToDoTaskResponse>()
.ForMember(dest =>
dest.Username,
opt => opt.MapFrom(src => src.User.UserName));
CreateMap<ToDoTaskRequest, ToDoTask>()
.ForMember(dest =>
dest.User,
opt => opt.Ignore());
CreateMap<ToDoTask, ToDoTask>()
.ForMember(dest =>
dest.User,
opt => opt.Ignore());
}
}
}
<file_sep>/TO-DO_List/Repositories/ToDoTaskRepository.cs
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TO_DO_List.Contracts.Repositories;
using TO_DO_List.Data;
using TO_DO_List.Models;
namespace TO_DO_List.Repositories
{
public class ToDoTaskRepository : IToDoTaskRepository
{
private readonly ApplicationContext _applicationContext;
private readonly IMapper _mapper;
public ToDoTaskRepository(ApplicationContext applicationContext,
IMapper mapper)
{
_applicationContext = applicationContext;
_mapper = mapper;
}
public async Task<ToDoTask> AddToDoTaskAsync(ToDoTask toDoTask)
{
var result = await _applicationContext.ToDoTasks
.AddAsync(toDoTask);
await _applicationContext.SaveChangesAsync();
return result.Entity;
}
public async Task<ToDoTask> DeleteToDoTaskAsync(int toDoTaskId)
{
var result = await _applicationContext.ToDoTasks
.FirstOrDefaultAsync(t => t.ID == toDoTaskId);
if (result == null)
return result;
_applicationContext.ToDoTasks.Remove(result);
await _applicationContext.SaveChangesAsync();
return result;
}
public Task<ToDoTask> GetToDoTaskAsync(int toDoTaskId)
{
return _applicationContext.ToDoTasks
.FirstOrDefaultAsync(t => t.ID == toDoTaskId);
}
public Task<List<ToDoTask>> GetToDoTaskByUserIdAsync(string id)
{
return _applicationContext.ToDoTasks
.Where(x => x.User.Id.Equals(id))
.ToListAsync();
}
public Task<List<ToDoTask>> GetToDoTasksAsync()
{
return _applicationContext.ToDoTasks
.ToListAsync();
}
public async Task<ToDoTask> UpdateToDoTaskAsync(ToDoTask toDoTask)
{
var result = await _applicationContext.ToDoTasks
.FirstOrDefaultAsync(t => t.ID == toDoTask.ID);
if (result == null)
return result;
_mapper.Map(toDoTask, result);
await _applicationContext.SaveChangesAsync();
return result;
}
}
}
<file_sep>/TO-DO_List/Contracts/Services/IToDoTaskService.cs
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using TO_DO_List.Models.Dto;
using TO_DO_List.ViewModels;
namespace TO_DO_List.Contracts.Services
{
public interface IToDoTaskService
{
Task<IEnumerable<ToDoTaskResponse>> GetToDoTasks(ClaimsPrincipal user);
Task<ToDoTaskResponse> AddToDoTask(ClaimsPrincipal user, ToDoTaskRequest toDoTaskDto);
Task<ToDoTaskResponse> UpdateToDoTask(ClaimsPrincipal user, int id, ToDoTaskRequest toDoTask);
Task<ToDoTaskResponse> DeleteToDoTask(ClaimsPrincipal user, int id);
}
}
<file_sep>/TO-DO_List/Services/AccountService.cs
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
using TO_DO_List.Contracts.Services;
using TO_DO_List.Models;
namespace TO_DO_List.Services
{
public class AccountService : IAccountService
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IJwtService _jwtService;
public AccountService(UserManager<User> userManager,
SignInManager<User> signInManager,
IJwtService jwtService)
{
_userManager = userManager;
_signInManager = signInManager;
_jwtService = jwtService;
}
public async Task<string> Login(LoginRequest loginDto)
{
var user = await _userManager.FindByEmailAsync(loginDto.Email);
if (user == null)
return null;
var passwordCheck = await _signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false);
if (passwordCheck == null &&
!passwordCheck.Succeeded)
return null;
var roles = await _userManager.GetRolesAsync(user);
if (roles == null)
return null;
var token = _jwtService.GenerateJwt(user, roles);
if (token == null ||
token.Length <= 0)
return null;
return token;
}
public async Task<ForgotPasswordResponse> ForgotPassword(ForgotPasswordRequest forgotPassword)
{
var user = await _userManager.FindByEmailAsync(forgotPassword.Email);
if (user == null)
return null;
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
if (token == null)
return null;
var fotgotPasswordRespone = new ForgotPasswordResponse();
fotgotPasswordRespone.Email = user.Email;
fotgotPasswordRespone.Token = token;
return fotgotPasswordRespone;
}
public async Task<IdentityResult> ResetPassword(string token, string email, ResetPasswordRequest resetPasswordRequest)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
return null;
var resetPassResult = await _userManager.ResetPasswordAsync(user, token, resetPasswordRequest.Password);
return resetPassResult;
}
}
}
<file_sep>/TO-DO_List/Entities/User.cs
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
namespace TO_DO_List.Models
{
public class User : IdentityUser
{
public virtual IEnumerable<ToDoTask> ToDoTasks { get; set; }
}
}
<file_sep>/TO-DO_List/Extensions/SwaggerExtensions.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using TO_DO_List.Security;
namespace TO_DO_List.Extensions
{
public static class SwaggerExtensions
{
public static IServiceCollection AddSwag(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ToDo-List", Version = "v1" });
c.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme.",
});
c.OperationFilter<AuthOperationFilter>();
});
return services;
}
public static IApplicationBuilder UseSwag(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestService");
c.OAuthClientId("cleint-id");
c.OAuthClientSecret("client-secret");
c.OAuthRealm("client-realm");
c.OAuthAppName("OAuth-app");
c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});
return app;
}
}
}
<file_sep>/TO-DO_List/Controllers/ToDoTaskController.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TO_DO_List.Contracts.Services;
using TO_DO_List.Data;
using TO_DO_List.Models.Dto;
using TO_DO_List.ViewModels;
namespace TO_DO_List.Controllers
{
[Route("[controller]")]
[ApiController]
[Authorize]
public class ToDoTaskController : ControllerBase
{
private readonly IToDoTaskService _toDoTaskService;
public ToDoTaskController(IToDoTaskService toDoTaskService)
{
_toDoTaskService = toDoTaskService;
}
/// <summary>
/// Gets all auhtorized existing ToDo tasks.
/// </summary>
/// <returns>To admin - all ToDo tasks, to user - all user's ToDo tasks</returns>
[HttpGet("GetTasks")]
public async Task<ActionResult> GetToDoTasks()
{
try
{
var result = await _toDoTaskService.GetToDoTasks(HttpContext.User);
if (result == null)
return NotFound();
return Ok(result);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorRetrieveDatabase);
}
}
/// <summary>
/// Create a ToDo task.
/// </summary>
/// <param name="toDoTask">ToDo task request model</param>
/// <returns>A newly created ToDo task</returns>
[Authorize(Roles="user")]
[HttpPost]
public async Task<ActionResult<ToDoTaskResponse>> CreateToDoTask(ToDoTaskRequest toDoTask)
{
if (!ModelState.IsValid)
return BadRequest();
try
{
var result = await _toDoTaskService.AddToDoTask(HttpContext.User, toDoTask);
return result;
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorRetrieveDatabase);
}
}
/// <summary>
/// Updates chosed ToDo task.
/// </summary>
/// <param name="id">Chosen ToDo task's ID</param>
/// <param name="toDoTask">ToDo task's request model to be changed into containing of ToDo task's title and completion status</param>
/// <returns>Changed ToDo task</returns>
[Authorize(Roles="user")]
[HttpPut("{id:int}")]
public async Task<ActionResult<ToDoTaskResponse>> UpdateToDoTask(int id, ToDoTaskRequest toDoTask)
{
if (!ModelState.IsValid)
return BadRequest();
try
{
var result = await _toDoTaskService.UpdateToDoTask(HttpContext.User, id, toDoTask);
if (result == null)
return NotFound(string.Format(Constants.TaskNotFound, id));
return Ok(result);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorUpdateDatabase);
}
}
/// <summary>
/// Deletes a chosen ToDo task.
/// </summary>
/// <param name="id">ID of a chosen ToDo task to be deleted</param>
/// <returns>A deleted ToDo task's response model</returns>
[HttpDelete("{id:int}")]
public async Task<ActionResult<ToDoTaskResponse>> DeleteToDoTask(int id)
{
try
{
var result = await _toDoTaskService.DeleteToDoTask(HttpContext.User, id);
if (result == null)
return NotFound(string.Format(Constants.TaskNotFound, id));
return Ok(result);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorDeleteDatabase);
}
}
}
}
<file_sep>/TO-DO_List/Models/ToDoTaskResponse.cs
namespace TO_DO_List.ViewModels
{
public class ToDoTaskResponse
{
public int ID { get; set; }
public string Title { get; set; }
public bool IsCompleted { get; set; }
public string Username { get; set; }
}
}
<file_sep>/TO-DO_List/Contracts/Services/IJwtService.cs
using System.Collections.Generic;
using TO_DO_List.Models;
namespace TO_DO_List.Contracts.Services
{
public interface IJwtService
{
string GenerateJwt(User user, IList<string> roles);
}
}
<file_sep>/TO-DO_List/Controllers/AccountController.cs
using System;
using System.Threading.Tasks;
using EmailService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TO_DO_List.Contracts.Services;
using TO_DO_List.Data;
using TO_DO_List.Models;
namespace TO_DO_List.Controllers
{
[Route("[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly SignInManager<User> _signInManager;
private readonly UserManager<User> _userManager;
private readonly IJwtService _jwtService;
private readonly IEmailSender _emailSender;
private readonly IAccountService _accountService;
public AccountController(SignInManager<User> signInManager,
UserManager<User> userManager,
IJwtService jwtService,
IEmailSender emailSender,
IAccountService accountService)
{
_signInManager = signInManager;
_userManager = userManager;
_jwtService = jwtService;
_emailSender = emailSender;
_accountService = accountService;
}
/// <summary>
/// Authenticates user.
/// </summary>
/// <param name="loginRequest">A login request model containing of user email and password</param>
/// <returns>On success JWT token</returns>
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
{
if (!ModelState.IsValid)
return BadRequest();
try
{
var token = await _accountService.Login(loginRequest);
if (token == null)
return NotFound();
return Ok(token);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorRetrieveDatabase);
}
}
/// <summary>
/// Account recovery action sends password reset link to user's email
/// </summary>
/// <param name="forgotPasswordRequest">Forgot password request model containing user's email </param>
/// <returns>On success sends password recovery link to user's mail</returns>
[Authorize(Roles="user")]
[HttpPost("ForgotPassword")]
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest forgotPasswordRequest)
{
if (!ModelState.IsValid)
return BadRequest();
try
{
var forgotPasswordResponse = await _accountService.ForgotPassword(forgotPasswordRequest);
if (forgotPasswordResponse == null)
return NotFound(string.Format(Constants.UserNotFound, forgotPasswordRequest.Email));
var callback = Url.Action(nameof(ResetPassword), Constants.Account, new { token = forgotPasswordResponse.Token, email = forgotPasswordResponse.Email }, Request.Scheme);
var message = new Message(new string[] { forgotPasswordRequest.Email }, Constants.ResetPasswordToken, callback, null);
await _emailSender.SendEmailAsync(message);
return Ok(string.Format(Constants.PasswordResetLinkSent, forgotPasswordRequest.Email));
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorPasswordResetEmail);
}
}
/// <summary>
/// Changes user's password
/// </summary>
/// <param name="resetPasswordRequest">Reset password request model containing of new password and it's confirmation</param>
/// <param name="token">User's password reset token</param>
/// <param name="email">User's email</param>
/// <returns>Operation's success status</returns>
[Authorize(Roles="user")]
[HttpPost("ResetPassword")]
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest resetPasswordRequest, string token, string email)
{
if (!ModelState.IsValid ||
token == null ||
email == null)
return BadRequest(new { resetPasswordRequest, token, email });
try
{
var result = await _accountService.ResetPassword(token, email, resetPasswordRequest);
if (result == null)
return NotFound(string.Format(Constants.UserNotFound, email));
if(result.Succeeded)
return Ok(Constants.PasswordReset);
else
{
foreach (var error in result.Errors)
{
ModelState.TryAddModelError(error.Code, error.Description);
}
return StatusCode(StatusCodes.Status422UnprocessableEntity,
Constants.InvalidToken);
}
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
Constants.ErrorResetPassword);
}
}
}
}
<file_sep>/TO-DO_List/Services/ToDoTaskService.cs
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using TO_DO_List.Contracts.Repositories;
using TO_DO_List.Contracts.Services;
using TO_DO_List.Data;
using TO_DO_List.Models;
using TO_DO_List.Models.Dto;
using TO_DO_List.ViewModels;
namespace TO_DO_List.Services
{
public class ToDoTaskService : IToDoTaskService
{
private readonly UserManager<User> _userManager;
private readonly IToDoTaskRepository _toDoTaskRepository;
private readonly IMapper _mapper;
public ToDoTaskService(UserManager<User> userManager,
IToDoTaskRepository toDoTaskRepository,
IMapper mapper)
{
_userManager = userManager;
_toDoTaskRepository = toDoTaskRepository;
_mapper = mapper;
}
public async Task<IEnumerable<ToDoTaskResponse>> GetToDoTasks(ClaimsPrincipal user)
{
var currUser = await _userManager.GetUserAsync(user);
if (currUser == null)
return null;
var currUserRoles = await _userManager.GetRolesAsync(currUser);
if (currUserRoles == null)
return null;
List<ToDoTask> result = null;
if (currUserRoles.Contains(Constants.Admin))
{
result = await _toDoTaskRepository.GetToDoTasksAsync();
}
else if (currUserRoles.Contains(Constants.User))
{
result = await _toDoTaskRepository.GetToDoTaskByUserIdAsync(currUser.Id);
}
if (result == null)
return null;
var toDoTaskResponse = _mapper.Map<List<ToDoTask>, List<ToDoTaskResponse>>(result);
return toDoTaskResponse;
}
public async Task<ToDoTaskResponse> AddToDoTask(ClaimsPrincipal user, ToDoTaskRequest toDoTaskRequest)
{
var currUser = await _userManager.GetUserAsync(user);
if (currUser == null)
return null;
var toDoTask = _mapper.Map<ToDoTask>(toDoTaskRequest, opt =>
opt.AfterMap((src, dest) => dest.User = currUser));
toDoTask = await _toDoTaskRepository.AddToDoTaskAsync(toDoTask);
if (toDoTask == null)
return null;
var toDoTaskResponse = _mapper.Map<ToDoTaskResponse>(toDoTask);
return toDoTaskResponse;
}
public async Task<ToDoTaskResponse> UpdateToDoTask(ClaimsPrincipal user, int id, ToDoTaskRequest toDoTaskRequest)
{
var result = await _toDoTaskRepository.GetToDoTaskAsync(id);
if (result == null)
return null;
var currUser = await _userManager.GetUserAsync(user);
if (currUser == null ||
result.User == null ||
result.User.UserName != currUser.UserName)
return null;
var toDoTask = _mapper.Map<ToDoTask>(toDoTaskRequest, opt =>
opt.AfterMap((src, dest) => dest.ID = id));
result = await _toDoTaskRepository.UpdateToDoTaskAsync(toDoTask);
if (result == null)
return null;
var toDoTaskResponse = _mapper.Map<ToDoTaskResponse>(result);
return toDoTaskResponse;
}
public async Task<ToDoTaskResponse> DeleteToDoTask(ClaimsPrincipal user, int id)
{
var toDoTask = await _toDoTaskRepository.GetToDoTaskAsync(id);
if (toDoTask == null)
return null;
var currUser = await _userManager.GetUserAsync(user);
if (currUser == null)
return null;
var currUserRoles = await _userManager.GetRolesAsync(currUser);
if (currUserRoles == null)
return null;
if (!(toDoTask.User.UserName == currUser.UserName && currUserRoles.Contains(Constants.User)) &&
!currUserRoles.Contains(Constants.Admin))
return null;
var toDoTaskResult = await _toDoTaskRepository.DeleteToDoTaskAsync(id);
if (toDoTaskResult == null)
return null;
var toDoTaskResponse = _mapper.Map<ToDoTaskResponse>(toDoTask);
return toDoTaskResponse;
}
}
}
<file_sep>/TO-DO_List/Contracts/Repositories/IToDoTaskRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using TO_DO_List.Models;
namespace TO_DO_List.Contracts.Repositories
{
public interface IToDoTaskRepository
{
Task<ToDoTask> AddToDoTaskAsync(ToDoTask toDoTask);
Task<ToDoTask> DeleteToDoTaskAsync(int toDoTaskId);
Task<ToDoTask> GetToDoTaskAsync(int toDoTaskId);
Task<List<ToDoTask>> GetToDoTaskByUserIdAsync(string id);
Task<List<ToDoTask>> GetToDoTasksAsync();
Task<ToDoTask> UpdateToDoTaskAsync(ToDoTask toDoTask);
}
}
<file_sep>/TO-DO_List/Models/ToDoTaskSettings.cs
namespace TO_DO_List.Models.Dto
{
public class ToDoTaskSettings
{
public string Title { get; set; }
public bool IsCompleted { get; set; }
public string User { get; set; }
}
}
<file_sep>/TO-DO_List/Models/ResetPasswordRequest.cs
using System.ComponentModel.DataAnnotations;
using TO_DO_List.Data;
namespace TO_DO_List.Models
{
public class ResetPasswordRequest
{
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Compare(Constants.Password, ErrorMessage = Constants.NotMach)]
public string ConfirmPassword { get; set; }
}
}
<file_sep>/TO-DO_List/Services/DatabaseService.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using TO_DO_List.Contracts.Services;
using TO_DO_List.Data;
using TO_DO_List.Models;
using TO_DO_List.Models.Dto;
using TO_DO_List.Settings;
namespace TO_DO_List.Services
{
public class DatabaseService : IDatabaseService
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<User> _userManager;
private readonly SeedDataSettings _seedDataSettings;
private readonly ApplicationContext _applicationContext;
public DatabaseService(RoleManager<IdentityRole> roleManager,
UserManager<User> userManager,
IOptions<SeedDataSettings> seedDataSettings,
ApplicationContext applicationContext)
{
_roleManager = roleManager;
_userManager = userManager;
_seedDataSettings = seedDataSettings.Value;
_applicationContext = applicationContext;
}
/// <summary>
/// Seed roles located in program configuration.
/// </summary>
public void SeedRoles()
{
foreach(UserSettings userDto in _seedDataSettings.Users)
{
var result = _roleManager.RoleExistsAsync(userDto.Role).Result;
if (!result)
{
var role = new IdentityRole();
role.Name = userDto.Role;
var roleResult = _roleManager.
CreateAsync(role).Result;
if (!roleResult.Succeeded)
throw new System.InvalidOperationException();
}
}
}
/// <summary>
/// Seed users located in program configuration.
/// </summary>
public void SeedUsers()
{
foreach(UserSettings userDto in _seedDataSettings.Users)
{
var user = _userManager.FindByEmailAsync(userDto.Username).Result;
if (user == null)
{
user = new User();
user.UserName = userDto.Username;
user.Email = userDto.Username;
var identityUser = _userManager.CreateAsync(user, userDto.Password).Result;
if (identityUser.Succeeded)
{
_userManager.AddToRoleAsync(user, userDto.Role).Wait();
_userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, userDto.Role)).Wait();
}
else
throw new System.InvalidOperationException();
}
}
}
/// <summary>
/// Seed tasks located in program configuration.
/// </summary>
public void SeedTasks()
{
foreach (ToDoTaskSettings toDoTaskDto in _seedDataSettings.ToDoTasks)
{
var user = _userManager.FindByEmailAsync(toDoTaskDto.User).Result;
if (user != null)
{
var userRoles = _userManager.GetRolesAsync(user);
if(userRoles != null &&
!userRoles.Result.Contains(Constants.Admin))
{
ToDoTask toDoTask = new ToDoTask
{
Title = toDoTaskDto.Title,
IsCompleted = toDoTaskDto.IsCompleted,
User = user
};
_applicationContext.ToDoTasks.Add(toDoTask);
}
}
}
_applicationContext.SaveChanges();
}
/// <summary>
/// Ensure that the database for the content exists. If not then the database is created.
/// </summary>
/// <returns>True if database is created, false if it already existed.</returns>
public bool EnsureCreated() => _applicationContext.Database.EnsureCreated();
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool EnsureDeleted() => _applicationContext.Database.EnsureDeleted();
}
}
<file_sep>/TO-DO_List/Contracts/Services/IDatabaseService.cs
namespace TO_DO_List.Contracts.Services
{
public interface IDatabaseService
{
bool EnsureCreated();
bool EnsureDeleted();
void SeedRoles();
void SeedUsers();
void SeedTasks();
}
}
<file_sep>/TO-DO_List/Startup.cs
using AutoMapper;
using EmailService;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using TO_DO_List.Contracts.Repositories;
using TO_DO_List.Contracts.Services;
using TO_DO_List.Data;
using TO_DO_List.Extensions;
using TO_DO_List.Models;
using TO_DO_List.Repositories;
using TO_DO_List.Services;
using TO_DO_List.Settings;
namespace TO_DO_List
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
var emailConfig = Configuration
.GetSection(Constants.EmailConfiguration)
.Get<EmailConfiguration>();
services.AddDbContextPool<ApplicationContext>(
options => options.UseLazyLoadingProxies()
.UseMySql(Configuration.GetConnectionString(Constants.DefaultConnection)));
services.AddIdentity<User, IdentityRole>(options =>
{
options.Password.RequiredLength = 12;
options.Password.RequireDigit = false;
options.Password.RequiredUniqueChars = 1;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>();
services.Configure<DataProtectionTokenProviderOptions>(opt =>
opt.TokenLifespan = TimeSpan.FromHours(1));
services.Configure<JwtSettings>(Configuration.GetSection(Constants.Jwt));
var jwtSettings = Configuration.GetSection(Constants.Jwt).Get<JwtSettings>();
services.Configure<SeedDataSettings>(options => Configuration.GetSection(Constants.SeedData).Bind(options));
services.AddAuth(jwtSettings);
services.AddSwag();
services.AddControllers();
services.AddScoped<IJwtService, JwtService>();
services.AddScoped<IDatabaseService, DatabaseService>();
services.AddScoped<IToDoTaskRepository, ToDoTaskRepository>();
services.AddScoped<IToDoTaskService, ToDoTaskService>();
services.AddScoped<IAccountService, AccountService>();
services.AddScoped<IEmailSender, EmailSender>();
services.AddSingleton(emailConfig);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwag();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuth();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/TO-DO_List/Data/ApplicationContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using TO_DO_List.Models;
namespace TO_DO_List.Data
{
public class ApplicationContext : IdentityDbContext
{
public DbSet<ToDoTask> ToDoTasks { get; set; }
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasMany(u => u.ToDoTasks)
.WithOne(t => t.User)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
}
}
}
<file_sep>/TO-DO_List/Contracts/Services/IAccountService.cs
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
using TO_DO_List.Models;
namespace TO_DO_List.Contracts.Services
{
public interface IAccountService
{
Task<ForgotPasswordResponse> ForgotPassword(ForgotPasswordRequest forgotPassword);
Task<IdentityResult> ResetPassword(string token, string email, ResetPasswordRequest resetPasswordRequest);
Task<string> Login(LoginRequest loginDto);
}
}
<file_sep>/TO-DO_List/Data/Constants.cs
namespace TO_DO_List.Data
{
public static class Constants
{
public const string Admin = "admin";
public const string User = "user";
public const string Account = "Account";
public const string Password = "<PASSWORD>";
public const string Int401 = "401";
public const string Int403 = "403";
public const string Unauthorized = "Unauthorized";
public const string Forbidden = "Forbidden";
public const string Bearer = "bearer";
public const string Jwt = "Jwt";
public const string SeedData = "SeedData";
public const string DefaultConnection = "DefaultConnection";
public const string EmailConfiguration = "EmailConfiguration";
public const string ErrorRetrieveDatabase = "Error retrieving data from the database";
public const string ErrorUpdateDatabase = "Error updating data in database";
public const string ErrorDeleteDatabase = "Error deleting data in database";
public const string ErrorPasswordResetEmail = "Error sending password reset email";
public const string ErrorResetPassword = "<PASSWORD>";
public const string InvalidToken = "Invalid token";
public const string ResetPasswordToken = "<PASSWORD>";
public const string PasswordReset = "<PASSWORD>";
public const string NotMach = "The password and confirmation password do not match";
public const string UserNotFound = "User with email {0} not found";
public const string PasswordResetLinkSent = "Password reset link to email {0} has been sent successfully";
public const string TaskNotFound = "Task with id {0} not found";
}
}
| 92897fe3adedc6ae04ea35d780538ddf6be5613e | [
"C#"
] | 24 | C# | DziugasMazulis/ToDO-List-REST-API | 582ca093a2f8a60b33d86ae43d151b8ceca75217 | 03651afbf9e7e439a9dcf9922fc83082feab057f | |
refs/heads/master | <repo_name>leong985664/yeqingkong-api<file_sep>/controllers/contactController.js
// Return a list of all the contact
exports.list = function(req, res) {
var data = require('../data/contact.json');
res.json(data);
};
<file_sep>/controllers/conferencesController.js
// Return a list of all the conference experiences
exports.list = function(req, res) {
var data = require('../data/conferences.json');
res.json(data);
};
<file_sep>/routes/api.js
var express = require('express');
var router = express.Router();
// Require controller modules
var awardsController = require('../controllers/awardsController');
var conferencesController = require('../controllers/conferencesController');
var contactController = require('../controllers/contactController');
var coursesController = require('../controllers/coursesController');
var educationController = require('../controllers/educationController');
var publicationsController = require('../controllers/publicationsController');
var researchInterestsController = require('../controllers/researchInterestsController');
var specialtiesController = require('../controllers/specialtiesController');
var studentEvaluationsController = require('../controllers/studentEvaluationsController');
var teachingInterestsController = require('../controllers/teachingInterestsController');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/awards', awardsController.list);
router.get('/conferences', conferencesController.list);
router.get('/contact', contactController.list);
router.get('/courses', coursesController.list);
router.get('/education', educationController.list);
router.get('/publications', publicationsController.list);
router.get('/researchInterests', researchInterestsController.list);
router.get('/specialties', specialtiesController.list);
router.get('/conferences', conferencesController.list);
router.get('/studentEvaluations', studentEvaluationsController.list);
router.get('/teachingInterests', teachingInterestsController.list);
module.exports = router;
<file_sep>/controllers/educationController.js
// Return a list of all the education experiences
exports.list = function(req, res) {
var data = require('../data/education.json');
res.json(data);
};
<file_sep>/controllers/researchInterestsController.js
// Return a list of all the research interests
exports.list = function(req, res) {
var data = require('../data/researchInterests.json');
res.json(data);
};
<file_sep>/controllers/specialtiesController.js
// Return a list of all the specialties experiences
exports.list = function(req, res) {
var data = require('../data/specialties.json');
res.json(data);
};
<file_sep>/controllers/awardsController.js
// Return a list of all the awards
exports.list = function(req, res) {
var data = require('../data/awards.json');
res.json(data);
};
| 2f0dcb433ec33dfb9475f2dcc0c39a53e4c7d743 | [
"JavaScript"
] | 7 | JavaScript | leong985664/yeqingkong-api | 8353a6d0ae437e987ea8823b2ffd7ce8a5b83757 | 88ce7ebee87779bcb5db18ca1e75533c88231610 | |
refs/heads/master | <file_sep>var mongoose = require('./database');
var FuneralHome = require('../models/funeralHome');
var funeralHomes = [
{
"name": "<NAME>",
"street": "401 West Channel Islands Blvd. ",
"city": "Oxnard",
"county": "Ventura County ",
"state": "California",
"zip": 93033,
"phone": "(805) 487-4911",
"fax": "(805) 487-8970",
"fd": "FD 1104",
"basic_services_funeral_director": 1595,
"embalming": 895,
"dressing_casketing": 395,
"bathing_handling": 150,
"refrigeration": 895,
"visitation": 395,
"funeral_service": 195,
"memorial_service": 195,
"transfer_crematory": 125,
"removal": 495,
"hearse": 295,
"service_vehicle": 195,
"alternative_container": 145,
"rental_casket": 1295,
"basic_services_direct_cremation": 380,
"crematory_fee": 275,
"prayer_cards": 50,
"register_book": 80,
"urn": 295,
"casket": 1195,
"direct_cremation_total_cost": 2315,
"traditional_cremation_total_cost": 5275,
"traditional_burial_total_cost": 5785,
"location_img_url": "http://i.imgur.com/ni1lGjB.png",
"email": "<EMAIL>",
"yelpId": "conrad-carroll-mortuary-oxnard"
},
{
"name": "<NAME> ",
"street": "629 South A St.",
"city": "Oxnard",
"county": "Ventura County ",
"state": "California",
"zip": 93030,
"phone": "(805) 486-9148",
"fax": "(805) 483-4439",
"fd": "FD 1338",
"basic_services_funeral_director": 997,
"embalming": 647,
"dressing_casketing": 197,
"bathing_handling": 197,
"refrigeration": 500,
"visitation": 500,
"funeral_service": 400,
"memorial_service": null,
"transfer_crematory": null,
"removal": 397,
"hearse": 395,
"service_vehicle": 195,
"alternative_container": 75,
"rental_casket": 950,
"basic_services_direct_cremation": null,
"crematory_fee": null,
"prayer_cards": 150,
"register_book": 35,
"urn": null,
"casket": 950,
"direct_cremation_total_cost": 1200,
"traditional_cremation_total_cost": 3971.5,
"traditional_burial_total_cost": 4863,
"location_img_url": "http://i.imgur.com/1x5AwOp.png",
"email": "<EMAIL>",
"yelpId": "garcia-mortuary-oxnard"
},
{
"name": "<NAME> ",
"street": "511 North A St. ",
"city": "Oxnard",
"county": "Ventura County ",
"state": "California",
"zip": 93030,
"phone": "(805) 487-1720",
"fax": "NA",
"fd": "FD 2069",
"basic_services_funeral_director": 1095,
"embalming": 650,
"dressing_casketing": 195,
"bathing_handling": null,
"refrigeration": null,
"visitation": 400,
"funeral_service": 400,
"memorial_service": null,
"transfer_crematory": null,
"removal": 390,
"hearse": 385,
"service_vehicle": null,
"alternative_container": 60,
"rental_casket": 995,
"basic_services_direct_cremation": null,
"crematory_fee": null,
"prayer_cards": 95,
"register_book": 40,
"urn": null,
"casket": 995,
"direct_cremation_total_cost": 1200,
"traditional_cremation_total_cost": 5455,
"traditional_burial_total_cost": 4645,
"location_img_url": "http://i.imgur.com/IwpDu3A.png",
"email": "<EMAIL>",
"yelpId": "reardon-funeral-home-oxnard-2"
}
]
FuneralHome.remove({}, function(err) {
if(err) console.log(err);
FuneralHome.create(funeralHomes, function(err, savedFuneralHomes) {
if (err) {
console.log(err);
} else {
console.log("Database seeded with " + savedFuneralHomes.length + " funeral homes.");
mongoose.connection.close();
}
process.exit();
});
});
<file_sep>var mongoose = require('mongoose');
var funeralHomeSchema = new mongoose.Schema({
name: String,
street: String,
city: String,
county: String,
state: String,
zip: Number,
phone: String,
fax: String,
fd: String,
basic_services_funeral_director: Number,
embalming: Number,
dressing_casketing: Number,
bathing_handling: Number,
refrigeration: Number,
visitation: Number,
funeral_service: Number,
memorial_service: Number,
transfer_crematory: Number,
removal: Number,
hearse: Number,
service_vehicle: Number,
alternative_container: Number,
rental_casket: Number,
basic_services_direct_cremation: Number,
crematory_fee: Number,
prayer_cards: Number,
register_book: Number,
urn: Number,
casket: Number,
direct_cremation_total_cost: Number,
traditional_cremation_total_cost: Number,
traditional_burial_total_cost: Number,
location_img_url: String,
email: String,
yelpId: String
});
var funeralHome = mongoose.model('funeralHome', funeralHomeSchema);
module.exports = funeralHome;
<file_sep>var express = require('express');
var router = express.Router();
var funeralHomesCtrl = require('../controllers/funeralHomes')
/* GET home page. */
// API Documentation Landing Page
router.get('/', function(req, res, next) {
res.render('index', { title: 'Marigold' });
});
// API Routes, respond with JSON only
router.route('/api/funeralHomes')
.get(funeralHomesCtrl.index)
.post(funeralHomesCtrl.create);
router.route('/api/funeralHomes/:id')
.get(funeralHomesCtrl.show)
.patch(funeralHomesCtrl.update)
.delete(funeralHomesCtrl.destroy);
router.route('/api/email')
.post(funeralHomesCtrl.sendEmail);
router.route('/api/yelp/:id')
.get(funeralHomesCtrl.getYelp);
module.exports = router;
| c4c67d7ccd762bb3f30289e62bdc05568d11c90e | [
"JavaScript"
] | 3 | JavaScript | agonzalez27/marigold-back-end | 6412c84ded5640b1845016367d1342e2b69624bb | 66a21dc29a7fe0e3bbd9a8ccf1505efd9f8dd118 | |
refs/heads/master | <repo_name>ThanhPhat1080/react-spring-lightbox<file_sep>/src/components/ImageStage/components/Image/index.js
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { useSpring, animated, to, config } from '@react-spring/web';
import { useGesture } from 'react-use-gesture';
import {
useDoubleClick,
imageIsOutOfBounds,
getTranslateOffsetsFromScale
} from '../../utils';
/**
* Animates pinch-zoom + panning on image using spring physics
*
* @param {string} src The source URL of this image
* @param {string} alt The alt attribute for this image
* @param {boolean} isCurrentImage True if this image is currently shown in pager, otherwise false
* @param {function} setDisableDrag Function that can be called to disable dragging in the pager
*
* @see https://github.com/react-spring/react-use-gesture
* @see https://github.com/react-spring/react-spring
*/
const Image = ({ src, alt, isCurrentImage, setDisableDrag }) => {
const imageRef = useRef();
const defaultImageTransform = () => ({
scale: 1,
translateX: 0,
translateY: 0,
config: { ...config.default, precision: 0.01 }
});
/**
* Animates scale and translate offsets of Image as they change in gestures
*
* @see https://www.react-spring.io/docs/hooks/use-spring
*/
const [{ scale, translateX, translateY }, set] = useSpring(() => ({
...defaultImageTransform(),
onFrame: f => {
if (f.scale < 1 || !f.pinching) set(defaultImageTransform);
// Prevent dragging image out of viewport
if (f.scale > 1 && imageIsOutOfBounds(imageRef))
set(defaultImageTransform());
},
// Enable dragging in ImagePager if image is at the default size
onRest: f => {
if (f.scale === 1) setDisableDrag(false);
}
}));
// Reset scale of this image when dragging to new image in ImagePager
useEffect(() => {
if (!isCurrentImage) set(defaultImageTransform);
});
/**
* Update Image scale and translate offsets during pinch/pan gestures
*
* @see https://github.com/react-spring/react-use-gesture#usegesture-hook-supporting-multiple-gestures-at-once
*/
const bind = useGesture(
{
onPinch: ({
movement: [xMovement],
origin: [touchOriginX, touchOriginY],
event,
ctrlKey,
last,
cancel
}) => {
// Don't calculate new translate offsets on final frame
if (last) {
cancel();
return;
}
// Speed up pinch zoom when using mouse versus touch
const SCALE_FACTOR = ctrlKey ? 1000 : 250;
const pinchScale = scale.value + xMovement / SCALE_FACTOR;
const pinchDelta = pinchScale - scale.value;
const { clientX, clientY } = event;
// Calculate the amount of x, y translate offset needed to
// zoom-in to point as image scale grows
const [newTranslateX, newTranslateY] = getTranslateOffsetsFromScale({
imageRef,
scale: scale.value,
pinchDelta,
currentTranslate: [translateX.value, translateY.value],
// Use the [x, y] coords of mouse if a trackpad or ctrl + wheel event
// Otherwise use touch origin
touchOrigin: ctrlKey
? [clientX, clientY]
: [touchOriginX, touchOriginY]
});
// Restrict the amount of zoom between half and 3x image size
if (pinchScale < 0.5) set({ scale: 0.5, pinching: true });
else if (pinchScale > 3.0) set({ scale: 3.0, pinching: true });
else
set({
scale: pinchScale,
translateX: newTranslateX,
translateY: newTranslateY,
pinching: true
});
},
onPinchEnd: () => {
if (scale.value > 1) setDisableDrag(true);
else set(defaultImageTransform);
},
onDrag: ({
movement: [xMovement, yMovement],
pinching,
event,
cancel,
first,
memo = null
}) => {
if (event.touches && event.touches.length > 1) return;
if (pinching || scale.value <= 1) return;
// Prevent dragging image out of viewport
if (scale.value > 1 && imageIsOutOfBounds(imageRef)) cancel();
else {
if (first) {
return {
initialTranslateX: translateX.value,
initialTranslateY: translateY.value
};
}
// Translate image from dragging
set({
translateX: memo.initialTranslateX + xMovement,
translateY: memo.initialTranslateY + yMovement
});
return memo;
}
}
},
/**
* useGesture config
* @see https://github.com/react-spring/react-use-gesture#usegesture-config
*/
{
domTarget: imageRef,
event: {
passive: false
}
}
);
/**
* @see https://github.com/react-spring/react-use-gesture#adding-gestures-to-dom-nodes
*/
useEffect(bind, [bind]);
// Handle double-tap on image
useDoubleClick({
onDoubleClick: e => {
// If double-tapped while already zoomed-in, zoom out to default scale
if (scale.value !== 1) {
set(defaultImageTransform);
return;
}
// Zoom-in to origin of click on image
const { clientX: touchOriginX, clientY: touchOriginY } = e;
const pinchScale = scale.value + 1;
const pinchDelta = pinchScale - scale.value;
// Calculate the amount of x, y translate offset needed to
// zoom-in to point as image scale grows
const [newTranslateX, newTranslateY] = getTranslateOffsetsFromScale({
imageRef,
scale: scale.value,
pinchDelta,
currentTranslate: [translateX.value, translateY.value],
touchOrigin: [touchOriginX, touchOriginY]
});
// Disable dragging in pager
setDisableDrag(true);
set({
scale: pinchScale,
translateX: newTranslateX,
translateY: newTranslateY,
pinching: true
});
},
ref: imageRef,
latency: 250
});
return (
<animated.img
ref={imageRef}
className="lightbox-image"
style={{
transform: to(
[scale, translateX, translateY],
(s, x, y) => `translate(${x}px, ${y}px) scale(${s})`
),
width: 'auto',
maxHeight: '100%',
maxWidth: '100%',
...(isCurrentImage && { willChange: 'transform' })
}}
src={src}
alt={alt}
draggable="false"
onDragStart={e => {
// Disable image ghost dragging in firefox
e.preventDefault();
}}
onClick={e => {
// Don't close lighbox when clicking image
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
}}
/>
);
};
Image.propTypes = {
/* The source URL of this image */
src: PropTypes.string.isRequired,
/* The alt attribute for this image */
alt: PropTypes.string.isRequired,
/* True if this image is currently shown in pager, otherwise false */
isCurrentImage: PropTypes.bool.isRequired,
/* Function that can be called to disable dragging in the pager */
setDisableDrag: PropTypes.func.isRequired
};
export default Image;
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
## [1.1.7] - 2019-09-23
### Fixed
- Improved panning performance
- Tweaked mousewheel swiping threshold
- Upgrade to react-use-gesture v6
## [1.1.4] - 2019-08-27
### Added
- Implement mousewheel paging of images
## [1.1.3] - 2019-08-19
### Fixed
- Prevent vertical dragging from paging images
- Switch to @react-spring/web package
## [1.1.2] - 2019-08-17
### Fixed
- Properly dispose wheel event listener
## [1.1.1] - 2019-08-14
### Fixed
- Adjusted "pan out of bounds" threshold
## [1.1.0] - 2019-08-14
### Added
- Implement proper <kbd>Ctrl</kbd> + `Mousewheel` and `Trackpad Pinch` zooming
## [1.0.1] - 2019-08-7
Add testing suite and travis-ci config
## [1.0.0] - 2019-08-5
Upgrade deps and release as stable
## [0.0.3] - 2019-08-1
### Changed
- Renamed onClickNext => onNext
- Renamed onClickPrev => onPrev
## [0.0.2] - 2019-07-31
Initial Release
| f8ef7e514a7404e6259de20d4aebf788a7778a87 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ThanhPhat1080/react-spring-lightbox | 92dffa34a6e902cd8e1b89cafc93af6b78c95d80 | dc6b26419d8fc8b1be335c5ac6d4f6fd68a4d69f | |
refs/heads/master | <file_sep>Description
===========
A simple program to run an arbitrary application within a container and terminate the application when any signal is received from Docker.
The following signals will be sent to the app until it terminates:
* the signal received from Docker,
* SIGTERM
* SIGKILL
Each signal is delayed two seconds.
Usage
=====
docker-run-app [-hV] [--init-log FILE] [--] COMMAND
COMMAND - app and args to execute. app requires full path.
-- - args after this flag are reserved for COMMAND.
-h, --help - print this help message.
--init-log FILE - write docker-run-app output to FILE.
-V, --version - print version info.
Build
=====
Set up your Golang workspace.
export GOPATH=/your/go/workspace
go get github.com/boxofrox/docker-run-app
cd $GOPATH/src/github.com/boxofrox/docker-run-app
make
Make is requried to set version and build info in the binary executable.
Installation
============
Copy the binary within view of your Dockerfile.
cp $GOPATH/bin/docker-run-app /path/to/your/dockerfile/
Modify your Dockerfile to add the binary and run it. Here is an example diff:
```diff
+ ADD docker-run-app /run-app
+
- CMD ["/usr/bin/app", "-a", "-b", "-c"]
+ ENTRYPOINT ["/run-app"]
+ CMD ["--", "/usr/bin/app", "-a", "-b", "-c"]
```
The "--" are optional, but ensure that docker-run-app will not eat flags belonging to your app.
Author
======
<NAME> <<EMAIL>> (@boxofrox)
License
=======
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What the Fuck You Want
to Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
<file_sep>/*
* docker-run-app run an arbitrary command and forward signals to said command.
* Copyright (c) 2014 <NAME> <<EMAIL>> (@boxofrox)
* All Rights Reserved
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What the Fuck You Want
* to Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*
*
* Usage: docker-run-app [-h] [--init-log FILE] [--] COMMAND
*
* COMMAND - app and args to execute. app requires full path.
* -- - args after this flag are reserved for COMMAND.
* -h, --help - print this help message.
* --init-log FILE - write docker-run-app output to FILE.
* -V, --version - print version info.
*/
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path"
"strings"
"syscall"
"time"
)
var (
VERSION string
BUILD_DATE string
)
const (
SIG_TIMEOUT = time.Second * 2
)
const (
OK AppError = iota
AppStoppedWithError
CannotStartApp
FailedToKillApp
MissingArgument
InsufficientSignalError
InvalidCommand
BadFlag
)
const (
FlagFound FlagError = iota
FlagNotFound
FlagHasTooFewParams
)
type AppError int
type FlagError int
type ParamList []string
func main() {
var (
args []string
err AppError = OK
file *os.File
fileErr error
options map[string]string
)
options, args = parseFlags(os.Args[1:])
if options["init-log"] != "" {
if file, fileErr = os.OpenFile(options["init-log"], os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0664); fileErr != nil {
log.Printf("Cannot open log file (%s). Using stderr.", options["init-log"])
} else {
log.SetOutput(file)
}
}
// has command?
if len(args) == 0 {
usage()
log.Println("missing <command>. ")
err = MissingArgument
} else {
cmd := args[0]
if len(args) > 1 {
args = args[1:]
} else {
args = nil
}
err = runCommand(exec.Command(cmd, args...))
}
if file != nil {
file.Close()
}
os.Exit(int(err))
}
// eatFlag
//
// Search argument array for one flag and possibly one or more parameters.
// The flag can be one or more representations of the same flag (e.g. -h, --help).
// return the file and the remaining options in a new array.
//
func eatFlag(args []string, flags []string, paramCount int) (params ParamList, remaining []string, err FlagError) {
var (
a, b int
)
hasFlag := func(arg string) bool {
for i := range flags {
if flags[i] == arg {
return true
}
}
return false
}
if len(args) == 0 {
params, remaining, err = ParamList{}, args, FlagNotFound
return
}
remaining = make([]string, len(args))
params = ParamList{}
err = FlagNotFound
ArgLoop:
for a, b = 0, 0; a < len(args); a++ {
if "--" == args[a] {
// stop processing flags
a++
break ArgLoop
} else if hasFlag(args[a]) {
a++
availCount := len(args) - a // make sure our attempt to grab parameters does not exceeed arg array bounds.
// can we eat all the params this flag needs?
if availCount < paramCount {
params, remaining, err = ParamList{}, args, FlagHasTooFewParams
return
}
params = make(ParamList, paramCount)
for c := 0; c < availCount; c++ {
// only eat params, don't eat potential flags
if !strings.HasPrefix(args[a], "-") {
params[c] = args[a]
a++
} else {
params, remaining, err = ParamList{}, args, FlagHasTooFewParams
return
}
}
err = FlagFound
break ArgLoop
} else {
// copy unused arguments
remaining[b] = args[a]
b++
}
}
// copy remaining arguments
for ; a < len(args); a++ {
remaining[b] = args[a]
b++
}
return
}
func envOr(name string, def string) string {
if val := os.Getenv(name); val != "" {
return val
}
return def
}
func parseFlags(args []string) (options map[string]string, remaining []string) {
var (
flagErr FlagError
params ParamList
)
remaining = args
// VERSION. eat flag. exit if found.
if _, remaining, flagErr = eatFlag(remaining, []string{"-V", "--version"}, 0); flagErr == FlagFound {
version()
os.Exit(int(OK))
}
// HELP. eat flag. exit if found.
if _, remaining, flagErr = eatFlag(remaining, []string{"-h", "--help"}, 0); flagErr == FlagFound {
usage()
os.Exit(int(OK))
}
// we now have potential flags to return
options = make(map[string]string)
// INIT LOG. eat flag, 1 param. exit if error.
if params, remaining, flagErr = eatFlag(remaining, []string{"--init-log"}, 1); flagErr == FlagHasTooFewParams {
log.Println("Error: flag --init-log is missing an argument.")
usage()
os.Exit(int(BadFlag))
} else {
options["init-log"] = params.getOr(0, "")
}
return
}
func runCommand(cmd *exec.Cmd) AppError {
sigs := make(chan os.Signal, 1)
done := make(chan error, 1)
// listen for signals from docker daemon
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// run the app from goroutine, so we can monitor signals and app
// termination
go func() {
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Println("Cannot open pipe to app's stdout: ", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Println("Cannot open pipe to app's stderr: ", err)
}
err = cmd.Start()
if err != nil {
log.Fatal(err)
done <- err
return
}
log.Println("App started.")
// redirect apps's stdout/stderr to our stdout/stderr, respectively
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
err = cmd.Wait()
done <- err
}()
// monitor termination of app or signals from docker
select {
case err := <-done:
if err == nil {
log.Println("App stopped.")
return OK
} else {
log.Printf("App stopped with error (%v)", err)
return AppStoppedWithError
}
case sig := <-sigs:
log.Printf("Received signal (%v).", sig)
sigSuccess, err := stopProcess(cmd.Process, sig, syscall.SIGTERM, syscall.SIGHUP)
if err != OK {
log.Println(err)
return err
}
log.Printf("App stopped with signal (%v).\n", sigSuccess)
// did app stop with the expected signal?
switch sigSuccess {
case sig:
return OK
case syscall.SIGINT:
return OK
default:
return InsufficientSignalError
}
}
return OK
}
/** stopProcess
*
* given a process and an ordered list of signals, send the first signal and
* delay. if the process did not stop, then repeat with subsequent signals
* until the app responds, or we run out of signals.
*/
func stopProcess(p *os.Process, sigs ...os.Signal) (os.Signal, AppError) {
if len(sigs) == 0 {
if err := p.Kill(); err != nil {
log.Fatal("Failed to kill app: ", err)
}
return nil, FailedToKillApp
}
c := make(chan error, 1)
go func() {
log.Printf("Attempting to stop app with signal (%v).", sigs[0])
c <- p.Signal(sigs[0])
}()
select {
case err := <-c:
if err == nil {
return sigs[0], OK
} else {
return stopProcess(p, sigs[1:]...)
}
case _ = <-time.After(SIG_TIMEOUT):
return stopProcess(p, sigs[1:]...)
}
}
func usage() {
prog := path.Base(os.Args[0])
fmt.Printf("Usage: %s [-h] [--init-log FILE] [--] COMMAND\n", prog)
fmt.Println()
fmt.Println("Commands:")
fmt.Println()
fmt.Println(" COMMAND - app and args to execute. app requires full path.")
fmt.Println(" -- - args after this flag are reserved for COMMAND.")
fmt.Println(" -h, --help - print this help message.")
fmt.Printf(" --init-log FILE - write %s output to FILE.\n", prog)
fmt.Println(" -V, --version - print version info.")
fmt.Println()
}
func version() {
fmt.Printf("%s: version %s, build %s\n", os.Args[0], VERSION, BUILD_DATE)
fmt.Println()
}
func (err AppError) Error() string {
switch err {
case MissingArgument:
return "missing argument"
case InsufficientSignalError:
return "SIGINT insufficient to stop app"
default:
return "unknown error"
}
}
func (err FlagError) Error() string {
switch err {
case FlagFound:
return "flag found"
case FlagNotFound:
return "flag not found"
case FlagHasTooFewParams:
return "flag is missing required parameters"
default:
return "unknown error"
}
}
func (p *ParamList) getOr(index int, def string) string {
if index < 0 || index >= len(*p) {
return def
}
return (*p)[index]
}
<file_sep>.PHONY: all install build
VERSION := 0.1.0
BUILD_DATE := $(shell date -u +%Y%m%d.%H%M%S.%3N)
PKG := github.com/boxofrox/docker-run-app
LDFLAGS = -ldflags "-X main.VERSION $(VERSION) -X main.BUILD_DATE $(BUILD_DATE)"
all: install
install:
go install $(LDFLAGS) $(PKG)
build:
go build $(LDFLAGS) $(PKG)
| 4153b6a413e4684b02603911004407694993e091 | [
"Markdown",
"Go",
"Makefile"
] | 3 | Markdown | boxofrox/docker-run-app | d64ce01698f288fcda9321884ac441fc15d07742 | 62bcff82c2a6a9a626dcad553bc0e248ebaed5e2 | |
refs/heads/master | <repo_name>kiquetal/kotlin-coursera-course<file_sep>/mastermind.kt
package mastermind
data class Evaluation(val rightPosition: Int, val wrongPosition: Int)
fun evaluateGuess(secret: String, guess: String): Evaluation {
if (secret.equals(guess))
return Evaluation(4, 0);
var idx = 0;
var right = 0;
var wrong = 0;
var memo = mutableListOf<Int>();
for (c in guess) {
if (c == secret[idx++]) {
right++
memo.add(idx -1);
}
}
var newSecret:CharArray=secret.toCharArray()
var newGuess:CharArray=guess.toCharArray()
memo.map {
newSecret[it]='\u0000'
newGuess[it]='\u0000'
}
for (c in newGuess)
{
if (c!='\u0000' && newSecret.contains(c))
{
newSecret.set(newSecret.indexOf(c),'-')
}
}
for (i in newSecret)
{
if (i=='-')
wrong++
}
return Evaluation(right,wrong)
}
fun main()
{
println("veamos");
}
<file_sep>/Solutions.kt
data class Evaluation(val rightPosition:Int, val wrongPosition:Int)
fun evaluateGuess(secret: String, guess: String): Evaluation {
val rightPosition = secret.zip(guess).count {
it.first == it.second
}
val commonLetters = "ABCDEF".sumBy {
Math.min(secret.count {
it == ch
},guess.count{
it == ch
})
}
return Evaluation(rightPosition, commonLetters - rightPosition);
}
<file_sep>/testing.ws.kts
val myList= arrayListOf(113,123,123)
print(myList.count {
it >120
}>1)
val p= "kiquetal" to arrayListOf(1,2,3)
val fn= (a:String) => {
return 12
}
fn("hola")
<file_sep>/NiceString.kt
package nicestring
fun String.isNice(): Boolean {
val nList= this.toCharArray().toList()
val zipped= nList.zipWithNext()
val hasIllegal = zipped.none {
pair -> checkIllegalSubstring(pair)
}
val mininumVowels= nList.fold(0){
acc, character ->
if (character.isVowel())
acc+1
else
acc
}
val hasMinimumVowel= if (mininumVowels>=3) true else false
val hasDoubleLetter = zipped.any{pair -> isDoubleLetter(pair) }
val resultsOperations= listOf<Boolean>(hasIllegal,hasMinimumVowel,hasDoubleLetter)
val onlyTrue= resultsOperations.filter { b -> b==true }.size
return onlyTrue>=2
}
fun checkIllegalSubstring(p:Pair<Char,Char>):Boolean
{
val illegalSubstring= listOf<Pair<Char,Char>>(Pair('b','u'), Pair('b','a'), Pair('b','e'))
return illegalSubstring.any { pair -> pair==p }
}
fun Char.isVowel():Boolean {
val vowels= listOf<Char>('a','e','i','o','u')
return vowels.contains(this)
}
fun isDoubleLetter(p:Pair<Char,Char>):Boolean {
return (p.first == p.second)
}
fun main()
{
val nList= "sisxxjwlkbu".toCharArray().toList()
println(nList);
val zipped= nList.zipWithNext()
print(zipped)
val hasNoIllegal = zipped.none {
pair -> checkIllegalSubstring(pair)
}
val mininumVowels= nList.fold(0){
acc, character ->
if (character.isVowel())
acc+1
else
acc
}
val hasMinimumVowel= if (mininumVowels>=3) true else false
val hasDoubleLetter = zipped.any{pair -> isDoubleLetter(pair) }
val resultsOperations= listOf<Boolean>(hasNoIllegal,hasMinimumVowel,hasDoubleLetter)
val onlyTrue= resultsOperations.filter { b -> b==true }.size
val isNice= if (onlyTrue>=2) true else false
println("isNice"+ isNice)
}
fun checkPair(p:Pair<Char,Char>):Boolean{
println(p.first+"-"+p.second)
return false
}
<file_sep>/BoardImpl.kt
package board
import board.Direction.*
import java.util.function.Consumer
fun createSquareBoard(width: Int): SquareBoard = MyMatrix(width)
fun <T> createGameBoard(width: Int): GameBoard<T> = MyBoard<T>(width)
class MyMatrix(override val width: Int) : SquareBoard {
val myCell=Array(width) { row ->
Array(width) { col ->
Cell(row + 1, col + 1)
}
}
fun printElement() {
this.myCell.forEach { arrayOfCells ->
arrayOfCells.forEach { c->
println(c)
}
}
}
fun Array<Array<Cell>>.toMap():MutableMap<Cell,Cell> {
val m= mutableMapOf<Cell,Cell>()
this.forEach { row->
row.forEach { col ->
m[col]=col
}
}
return m;
}
private fun isValidPosition(i:Int, j:Int):Boolean {
return when {
i<1 -> false
i>width->false
j<1 ->false
j>width->false
else-> true
}
}
override fun getCellOrNull(i: Int, j: Int): Cell? {
return if (!isValidPosition(i,j))
null
else{
myCell[i-1][j-1]
}
}
override fun getCell(i: Int, j: Int): Cell {
require(isValidPosition(i, j)) { "IllegalArgumentException cell does not exist" }
return myCell[i-1][j-1]
}
override fun getAllCells(): Collection<Cell> {
val m= mutableListOf<Cell>()
this.myCell.forEach { arrayOfCells ->
arrayOfCells.forEach { cell->
m.add(cell)
}
}
return m
}
override fun getRow(i: Int, jRange: IntProgression): List<Cell> {
val m= mutableListOf<Cell>()
jRange.forEach(Consumer { t ->
if (this.isValidPosition(i,t))
m.add(this.getCell(i,t))
})
return m
}
override fun getColumn(iRange: IntProgression, j: Int): List<Cell> {
val m= mutableListOf<Cell>()
iRange.forEach(Consumer { c ->
println("check valid ${c},${j}"+this.isValidPosition(c,j))
if (this.isValidPosition(c,j)) {
m.add(this.getCell(c, j))
}
})
return m
}
override fun Cell.getNeighbour(direction: Direction): Cell? {
return when (direction)
{
Direction.UP-> getCellOrNull(this.i-1,this.j)
Direction.LEFT-> getCellOrNull(this.i,this.j-1)
Direction.DOWN-> getCellOrNull(this.i+1,this.j)
Direction.RIGHT-> getCellOrNull(this.i,this.j+1)
}
}
}
class MyBoard<T>(override val width: Int) :GameBoard<T>
{
var myMatrix= mutableMapOf<Cell,T>()
var m= arrayOfNulls<Any?>(width*width)
private var idx=0
override fun getCellOrNull(i: Int, j: Int): Cell? {
return myMatrix.filterKeys { cell -> cell == Cell(i,j) }.keys.first()
}
override fun getCell(i: Int, j: Int): Cell {
println("getCell"+i+"-"+j)
println("if emtpy"+myMatrix.isEmpty())
if (myMatrix.isEmpty()) {
return Cell(i,j)
}
return when{
myMatrix.keys.filter { c-> c.i==i && c.j==j }.size>0 -> myMatrix.keys.filter { c-> c.i==i && c.j==j }.first()
else -> Cell(i,j)
}
}
override fun getAllCells(): Collection<Cell> {
return myMatrix.keys
}
override fun getRow(i: Int, jRange: IntProgression): List<Cell> {
val myList= arrayListOf<Cell>()
jRange.forEach{ j ->
if (myMatrix.filter { entry -> entry.key == Cell(i,j) }.size>0)
myList.add(Cell(i,j))
}
return myList
}
override fun getColumn(iRange: IntProgression, j: Int): List<Cell> {
val myList= arrayListOf<Cell>()
iRange.forEach{ l ->
if (myMatrix.filter { entry -> entry.key == Cell(l,j) }.size>0)
myList.add(Cell(l,j))
}
return myList
}
override fun Cell.getNeighbour(direction: Direction): Cell? {
return when (direction)
{
Direction.UP-> getCellOrNull(this.i-1,this.j-1)
Direction.LEFT-> getCellOrNull(this.i-i,this.j)
Direction.DOWN-> getCellOrNull(this.i+1,this.j)
Direction.RIGHT-> getCellOrNull(this.i,this.j+1)
}
}
override fun get(cell: Cell): T? {
return myMatrix.get(cell)
}
override fun set(cell: Cell, value: T?) {
println("introducir"+cell + "val" + value)
if (value != null) {
myMatrix[cell] = value
m[idx++]=value
}
println(myMatrix)
}
override fun filter(predicate: (T?) -> Boolean): Collection<Cell> {
println(myMatrix)
return myMatrix.filterValues { predicate(it) }.keys
}
override fun find(predicate: (T?) -> Boolean): Cell? {
return myMatrix.filterValues { predicate(it) }.keys.first()
}
override fun any(predicate: (T?) -> Boolean): Boolean {
return m.any { predicate(it as T?) }
}
override fun all(predicate: (T?) -> Boolean): Boolean {
return m.all { predicate(it as T?) }
}
}
<file_sep>/pruebas.ws.kts
val listMap = listOf(1,2)
println(listMap)
<file_sep>/Passenger.kt
package taxipark
import java.util.HashSet
import java.util.function.BiFunction
import java.util.function.Consumer
import java.util.function.Function
/*
* Task #1. Find all the drivers who performed no trips.
*/
fun TaxiPark.findFakeDrivers(): Set<Driver> =
allDrivers.filter { driver ->
trips.none { trip ->
trip.driver == driver
}
}.toSet()
/*
* Task #2. Find all the clients who completed at least the given number of trips.
*/
fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> {
val newHashMap:HashMap<Passenger,Int> = hashMapOf();
val allPassenger:HashSet<Passenger> = hashSetOf();
val entriesMap = trips.fold(newHashMap){
acc, trip ->
val passenger=trip.passengers
passenger.forEach {
val trips = acc.getOrElse(it) { 0 }
acc.put(it, trips + 1)
allPassenger.add(it)
}
acc
}
if (minTrips<1) return allPassengers
return entriesMap.filterValues { it>=minTrips }.keys
}
/*
* Task #3. Find all the passengers, who were taken by a given driver more than once.
*/
fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> {
val newHashMap:HashMap<Passenger,ArrayList<Driver>> = hashMapOf();
// print("driver"+ driver)
val entriesMap = trips.fold(newHashMap){
acc, trip ->
val passenger=trip.passengers
val n=passenger.map {
if (acc.containsKey(it))
{
if (trip.driver.name == driver.name) {
val l = acc.get(it);
if (l != null) {
l.add(driver)
}
if (l != null) {
acc.put(it, l)
}
}
}
else
{
if (trip.driver.name == driver.name)
acc.put(it, arrayListOf(driver))
}
}
acc
}
println(entriesMap)
return entriesMap.filterValues { it.size>1}.keys
}
/*
* Task #4. Find the passengers who had a discount for majority of their trips.
*/
fun TaxiPark.findSmartPassengers(): Set<Passenger> = allPassengers.filter { p ->
trips.count { t ->
p in t.passengers && t.discount != null
} > trips.count { t ->
p in t.passengers && t.discount == null
}
}.toSet()
/*
* Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on.
* Return any period if many are the most frequent, return `null` if there're no trips.
*/
fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? {
if (trips.isEmpty())
return null
return trips.groupBy {
val start = it.duration / 10 * 10
val end = start + 9
start..end
}.maxBy { (_, group) -> group.size }?.key
}
/*
* Task #6.
* Check whether 20% of the drivers contribute 80% of the income.
*/
fun TaxiPark.checkParetoPrinciple(): Boolean {
val totalIncome = trips.sumByDouble { it.cost }
if (totalIncome.equals(0.0)) {
return false
}
val topDriversIncome =
trips.groupBy { it.driver }
.map { (_, list) ->
list.sumByDouble { it.cost }
}
.sortedDescending()
val top20 = (allDrivers.size * 0.2).toInt()
return topDriversIncome.take(top20).sum() >= totalIncome * 0.8
}
<file_sep>/rationals.kt
package rationals
import java.lang.IllegalArgumentException
import java.math.BigDecimal
import java.math.BigInteger
import java.math.MathContext
data class Rational(var numerator:BigInteger, var denominator:BigInteger)
{
init {
if (denominator.equals(0))
throw IllegalArgumentException()
if (denominator<0.toBigInteger())
{
numerator=numerator.multiply(-1.toBigInteger())
denominator=denominator.multiply(-1.toBigInteger())
}
}
operator fun plus(a: Rational): Rational {
val (numerator, denominator) = a.gcd()
val d = when (this.denominator) {
denominator -> this.denominator
else -> this.denominator.multiply(denominator)
}
return when {
d > denominator -> Rational(
this.numerator.multiply(denominator).plus(numerator.multiply(this.denominator)),
d
)
else -> Rational(this.numerator.plus(numerator), d)
}.gcd()
}
override fun toString(): String {
return if (this.denominator==1.toBigInteger())
this.numerator.toString()
else {
val calculated = this.gcd()
if (calculated.denominator==1.toBigInteger())
return calculated.numerator.toString()
return "${calculated.numerator}/${calculated.denominator}"
}
}
operator fun minus(a: Rational): Rational {
val (numerator, denominator) = a
val d = when (this.denominator) {
denominator -> this.denominator
else -> this.denominator.multiply(denominator)
}
return when {
d > denominator -> Rational(
this.numerator.multiply(denominator).minus(numerator.multiply(this.denominator)),
d
)
else -> Rational(this.numerator.plus(numerator), d)
}.gcd()
}
operator fun div(a:Rational):Rational{
val numerator= this.numerator.multiply(a.denominator)
val denominator = this.denominator.multiply(a.numerator)
return Rational(numerator,denominator).gcd()
}
operator fun times(a:Rational):Rational {
val numerator= this.numerator.multiply(a.numerator)
val denominator = this.denominator.multiply(a.denominator)
return Rational(numerator,denominator).gcd()
}
override fun equals(other: Any?): Boolean {
if (other is Rational){
val (numerator,denominator) = other.gcd()
val calculated=this.gcd()
if (numerator == calculated.numerator && denominator == calculated.denominator) {
return true
}
}
return false
}
operator fun compareTo(a:Rational): Int {
val div1= this.numerator.toDouble() / this.denominator.toDouble()
val div2=a.numerator.toDouble() / a.denominator.toDouble()
if (div1 > div2)
return 1
if (div1<div2)
return -1
return 0
}
operator fun unaryMinus():Rational {
return Rational(this.numerator.multiply(-1.toBigInteger()),this.denominator).gcd()
}
private fun gcd():Rational {
val gcd=this.numerator.gcd(this.denominator)
val numerator = this.numerator.divide(gcd)
val denominator =this.denominator.divide(gcd)
return Rational(numerator,denominator )
}
operator fun rangeTo(a:Rational):Pair<Rational,Rational>{
return Pair(this,a)
}
}
fun main() {
val half = 1 divBy 2
val third = 1 divBy 3
val sum: Rational = half + third
println(5 divBy 6 == sum)
val difference: Rational = half - third
println(1 divBy 6 == difference)
val product: Rational = half * third
println(1 divBy 6 == product)
val quotient: Rational = half / third
println(3 divBy 2 == quotient)
val negation: Rational = -half
println(-1 divBy 2 == negation)
println((2 divBy 1).toString() == "2")
println((-2 divBy 4).toString() == "-1/2")
println("117/1098".toRational().toString() == "13/122")
val twoThirds = 2 divBy 3
println(half < twoThirds)
println(half <= twoThirds)
println(half in third..twoThirds)
println(2000000000L divBy 4000000000L == 1 divBy 2)
println("912016490186296920119201192141970416029".toBigInteger() divBy
"1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2)
}
<file_sep>/extensions.kt
package rationals
import java.math.BigInteger
operator fun Pair<Rational,Rational>.contains(a:Rational):Boolean {
if (a>=this.first && a<=this.second)
return true
return false
}
infix fun Int.divBy(a:Int): Rational
{
return Rational(this.toBigInteger(),a.toBigInteger())
}
infix fun Long.divBy(a:Long): Rational
{
return Rational(BigInteger.valueOf(this),BigInteger.valueOf(a))
}
infix fun BigInteger.divBy(a:BigInteger): Rational
{
return Rational(this,a)
}
fun String.toRational(): Rational {
return if (this.length>1 && this.contains("/")) {
val (numerator, denominator) = this.split("/")
Rational(numerator.toBigInteger(), denominator.toBigInteger())
}
else
Rational(this.toBigInteger(),1.toBigInteger())
}
| 4097317dae620870cd4609580842fbde3b982b2b | [
"Kotlin"
] | 9 | Kotlin | kiquetal/kotlin-coursera-course | 04d43313977ea1e9ed64681c0d2ec5f110874c08 | ca11f5d42866f36199e06cb4d697840bff91b2a4 | |
refs/heads/main | <file_sep>#!/data/data/com.termux/files/usr/bin/bash
# Hmei7
clear
blue='\e[0;34'
cyan='\e[0;36m'
green='\e[0;34m'
okegreen='\033[92m'
lightgreen='\e[1;32m'
white='\e[1;37m'
red='\e[1;31m'
yellow='\e[1;33m'
###################################################
# CTRL C
###################################################
trap ctrl_c INT
ctrl_c() {
clear
echo -e $red"[#]> (Ctrl + C ) Detected, Trying To Exit ... "
sleep 1
echo ""
echo -e $green"[#]> Hmei7 sayang fanny "
sleep 1
echo ""
echo -e $white"[#]> Hmei7 in here!!!!! ... "
read enter
exit
}
echo -e $red"
_ _ _ _____ __
| | | |_ __ ___ ___(_)___ | / _| __ _ _ __ _ __ _ _
| |_| | '_ ` _ \ / _ \ | / / | |_ / _` | '_ \| '_ \| | | |
| _ | | | | | | __/ | / / | _| (_| | | | | | | | |_| |
|_| |_|_| |_| |_|\___|_|/_/ |_| \__,_|_| |_|_| |_|\__, |
|___/
by Hmei7, hmei7 sayang fanny
"
echo ""
echo -e $green" 01) Chat robot Hmei7"
echo -e $green" 02) Daftar Surat Alquran buat hapalan"
echo -e $green" 03) Zodiak"
echo -e $green" 04) buat hitung gaji fanny sayang"
echo -e $green" 05) buat spam aku"
echo -e $green" 06) Chat robot hmei7 2"
echo -e $white""
read -p "[root@Hmei7:~#]>" hmei7;
if [ $hmei7 = 01 ] || [ $hmei7 = 01 ]
then
clear
echo -e $green" installing robot hmei7..."
sleep 1
apt update && apt upgrade
pkg install python
pip2 install requests
pip2 install urllib
pip2 install sys
curl -O https://raw.githubusercontent.com/ramdanRm19/trash/main/robot.py
echo -e $green" Sukses!"
echo -e $green" cara pakai : python robot.py"
fi
if [ $hmei7 = 02 ] || [ $hmei7 = 02 ]
then
clear
echo -e $green" installing AL QURAN"
pkg install ruby
gem install httparty
curl -O https://raw.githubusercontent.com/ramdanRm19/trash/main/alquran.rb
echo -e $green" Sukses!"
echo -e $green" cara pakai : ruby alquran.rb"
fi
if [ $hmei7 = 03 ] || [ $hmei7 = 03 ]
then
clear
echo -e $green" Installing Zodiak "
sleep 1
apt update && apt upgrade
pkg install python
pip install os
pip install json
pip install requests
curl -O https://raw.githubusercontent.com/ramdanRm19/trash/main/zodiak.py
echo -e $green" done! "
echo -e $green" cara gunakan : python zodiak.py"
fi
if [ $hmei7 = 04 ] || [ $hmei7 = 04 ]
then
clear
echo -e $green" installing gaji"
sleep 1
pkg install ruby
curl -O https://raw.githubusercontent.com/ramdanRm19/trash/main/gaji.rb
echo -e $green"Sukses! "
echo -e $green"cara pakai : ruby gaji.rb"
fi
if [ $hmei7 = 05 ] || [ $hmei7 = 05 ]
then
clear
echo -e $green" instaling auto jailin temen"
sleep 1
pkg install python2
pip2 install requests
pip2 install json
pip2 install os
pip2 install sys
curl -O https://raw.githubusercontent.com/ramdanRm19/trash/main/spamaku.py
echo -e $green"Sukses!"
echo -e $green" cara pakai : python2 spamaku.py"
fi
if [ $hmei7 = 06 ] || [ $hmei7 = 06 ]
then
clear
echo -e $green" install chat bot hmei7 2"
sleep 1
pkg install python
pip install requests
curl -O https://raw.githubusercontent.com/ramdanRm19/trash/main/robothmei7.py
echo -e $green"Sukses!"
echo -e $green" cara pakai : python robothmei7.py"
fi
| 29b69468e5ab460aca127edb79bc99245c18cc44 | [
"Shell"
] | 1 | Shell | ramdanRm19/fanny | b0d46cbb8e428c1a058d74e1429ca2c61807effd | f49754b07e6413e1829b1bbe8b5dfbca7152a421 | |
refs/heads/master | <repo_name>tales42/AS_TP2<file_sep>/src/Exception/ApostadorRegistadoException.java
package Exception;
/**
* Created by luismp on 11/11/2018.
*/
public class ApostadorRegistadoException extends Exception {
String email;
public ApostadorRegistadoException(String email){
this.email = email;
}
public String getEmail(){
return this.email;
}
}
<file_sep>/src/Exception/SaldoInsuficienteException.java
package Exception;
/**
* Created by luismp on 11/11/2018.
*/
public class SaldoInsuficienteException extends Exception {
double quantia;
public SaldoInsuficienteException(double quantia){
this.quantia = quantia;
}
public double getQuantia(){
return this.quantia;
}
}
<file_sep>/src/GUI/GUIMainPage.java
package GUI;
import Business.AdministradorDeEventos;
import Business.Apostador;
import Business.Utilizador;
import Exception.*;
/**
* Created by luismp on 20/12/2018.
*/
public class GUIMainPage extends GUI {
/**
* Método que imprime no ecrã o menu principal
*/
private static void showMainPage() {
System.out.println("----- BET ESS -----");
if (getAtual() != null) {
System.out.println("Utilizador: " + getAtual().getNome());
}
System.out.println("1 - Efetuar Registo");
System.out.println("2 - Iniciar Sessão");
System.out.println("3 - Consultar Eventos");
System.out.println("0 - Sair");
System.out.println("-------------------");
}
/**
* Método que mostra o menu principal e mantém o handler a correr
*/
protected static void mainPageForm() {
showMainPage();
boolean handler = true;
while (handler) {
handler = mainPageHandler();
}
}
/**
* Handler do menu principal que recebe e trata os inputs do utilizador.
* Retorna false quando o utilizador pretende sair do programa, parando o ciclo e a execução do programa
* @return Booleano
*/
private static boolean mainPageHandler() {
String option = readLine();
if (option.equals("1")) {
registerForm();
showMainPage();
} else if (option.equals("2")) {
showLoginForm();
showMainPage();
} else if (option.equals("3")) {
GUIApostador.showEvents();
showMainPage();
} else if (option.equals("0")) {
terminarSessao();
saveFile();
return false;
} else {
System.out.println("Input não reconhecido.");
}
return true;
}
/**
* Método que imprime no ecrã o formulário de autenticação
*/
private static void showLoginForm() {
System.out.println("---- Iniciar Sessão ----");
System.out.println("Email:");
String email = readLine();
System.out.println("Password:");
String password = readLine();
tryLogIn(email, password);
}
/**
* Método que tenta autenticar um utilizado no sistema
* @param email
* @param password
*/
private static void tryLogIn(String email, String password) {
try {
iniciarSessao(email, password);
System.out.println("Sessão iniciada com sucesso.");
confirmarContinuar();
loggedInHandler();
} catch (PasswordIncorretaException e) {
System.out.println("Password Incorreta.");
confirmarContinuar();
} catch (UtilizadorInexistenteException e) {
System.out.println("Utilizador Inexistente.");
confirmarContinuar();
}
}
/**
* Método que imprime no ecrã o formulário de registo
*/
private static void registerForm() {
System.out.println("---- Efetuar Registo ----");
System.out.println("Insira o seu email");
String email = readLine();
System.out.println("Insira a sua password");
String password = readLine();
System.out.println("Insira o seu nome");
String nome = readLine();
tryRegistarApostador(email, password, nome);
}
/**
* Método que tenta registar um novo Apostador no sistema
* @param email
* @param password
* @param nome
*/
private static void tryRegistarApostador(String email, String password, String nome) {
try {
registarApostador(email, password, nome);
System.out.println("Utilizador registado com sucesso.");
confirmarContinuar();
} catch (ApostadorRegistadoException e) {
System.out.println("Utilizador já registado.");
confirmarContinuar();
}
}
/**
* Método que imprime a página após a autenticação do utilizador, de acordo com qual o tipo de Utilizador autenticado
* @see Utilizador
*/
protected static void loggedInScene() {
Utilizador atual = getAtual();
if (atual instanceof AdministradorDeEventos) {
adminLoggedInScene();
} else if (atual instanceof Apostador) {
apostadorLoggedInScene((Apostador) atual);
}
}
/**
* Método que imprime a página após autenticação de um administrador
* @see AdministradorDeEventos
*/
private static void adminLoggedInScene() {
System.out.println("---- Administrador -----");
System.out.println("1 - Registar Evento");
System.out.println("2 - Consultar Eventos");
System.out.println("3 - Fechar Evento");
System.out.println("0 - Sair");
System.out.println("-------------------------");
}
/**
* Método que imprime a página após autenticação de um apostador, e apresenta os seus dados no ecrã
* @param atual
* @see Apostador
*/
private static void apostadorLoggedInScene(Apostador atual) {
System.out.println("---- Apostador -----");
System.out.println("Nome: " + atual.getNome());
System.out.println("Saldo: " + atual.getSaldo());
System.out.println("Cartão: " + atual.getCartaoAssociado());
System.out.println("--------------------");
System.out.println("1 - Consultar Notificações ");
System.out.println("2 - Gerir Saldo ");
System.out.println("3 - Consultar Resultados ");
System.out.println("4 - Consultar Eventos");
System.out.println("5 - Consultar Apostas Realizadas");
System.out.println("6 - Registar Aposta");
System.out.println("0 - Sair");
System.out.println("--------------------");
}
/**
* Método que recebe e trata dos inputs da página após o login
*/
private static void loggedInHandler() {
loggedInScene();
Utilizador atual = getAtual();
boolean isLoggedIn = true;
if (atual instanceof AdministradorDeEventos) {
while (isLoggedIn) {
isLoggedIn = GUIEvento.adminLoggedInHandler();
}
} else if (atual instanceof Apostador) {
while (isLoggedIn) {
isLoggedIn = GUIApostador.apostadorLoggedInHandler();
}
}
}
}
<file_sep>/src/Business/BetESS.java
package Business;
import java.io.Serializable;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import Exception.ApostadorRegistadoException;
import Exception.PasswordIncorretaException;
import Exception.UtilizadorInexistenteException;
/**
* Created by luismp on 11/11/2018.
*/
public class BetESS implements Serializable {
private Map<Integer,Utilizador> utilizadores;
private Map<Integer, Desporto> desportos;
private Map<Integer,Equipa> equipas;
private Map<Integer,Evento> eventos;
private Utilizador atual;
/**
* Construtor Vazio de um Objeto BetESS
*/
public BetESS(){
this.utilizadores = new HashMap<>();
this.desportos = new HashMap<>();
this.equipas = new HashMap<>();
this.eventos = new HashMap<>();
this.atual = null;
}
/**
* Método que define quais os utilizadores de um sistema.
* Só é usado em casos de teste para povoar o sistema.
* @param utilizadores
*/
public void setUtilizadores(Map<Integer, Utilizador> utilizadores) {
this.utilizadores = utilizadores;
}
/**
* Setter do Utilizador atual.
* @param atual
*/
public void setAtual(Utilizador atual){
this.atual = atual;
}
/**
* Método que regista um novo Apostador no Sistema.
* Lança uma exceção caso o email utilizado já esteja registado no sistema
* @param email
* @param password
* @param nome
* @throws ApostadorRegistadoException
*/
public void registarApostador(String email, String password, String nome) throws ApostadorRegistadoException {
for(Utilizador utilizador : utilizadores.values()){
if(utilizador.getEmail().equals(email)) throw new ApostadorRegistadoException(email);
}
Apostador apostador = new Apostador(utilizadores.size()+1,email,password,nome);
utilizadores.put(apostador.getIdUtilizador(),apostador);
}
/**
* Método que tenta autentica um utilizador no sistema.
* Lança uma exceção caso a o utilizador não exista no sistema, ou caso a password esteja errada.
* @param email
* @param password
* @throws PasswordIncorretaException
* @throws UtilizadorInexistenteException
*/
public void iniciarSessao(String email, String password) throws PasswordIncorretaException, UtilizadorInexistenteException {
Utilizador atual = getUtilizador(email);
if((getUtilizador(email).getIdUtilizador() == 0)) throw new UtilizadorInexistenteException();
if(!atual.getPassword().equals(password)) throw new PasswordIncorretaException();
else setAtual(atual);
}
/**
* Método que termina a sessão do utilizador atual.
*/
public void terminarSessao(){
atual = null;
}
/**
* Método que determina qual o utilizado que possui um email passado como parâmetro
* @param email
* @return Utilizador
*/
public Utilizador getUtilizador(String email){
Utilizador ret = new Utilizador();
for(Utilizador utilizador : utilizadores.values()){
if(utilizador.getEmail().equals(email)){
ret = utilizador;
break;
}
}
return ret;
}
/**
* Getter dos Eventos do Sistema
* @return Eventos
*/
public Map<Integer,Evento> getEventos(){
return eventos;
}
/**
* Getter dos Utilizadores do sistema
* @return Utilizadores
*/
public Map<Integer,Utilizador> getUtilizadores(){
return utilizadores;
}
/**
* Getter do Utilizador atual
* @return Utilizador Atual
*/
public Utilizador getAtual(){
return atual;
}
/**
* Getter dos Desportos do sistema.
* @return Desportos
*/
public Map<Integer,Desporto> getDesportos(){
return desportos;
}
/**
* Getter das Equipas do Sistema.
* @return Equipas
*/
public Map<Integer,Equipa> getEquipas(){
return equipas;
}
/**
* Método que devolve uma coleção com os eventos que se encontram no estado aberto.
* @return Eventos Abertos
*/
public Map<Integer, Evento> getEventosAbertos(){
Map<Integer,Evento> eventosAbertos = new HashMap<>();
for(Evento e: eventos.values()){
if(e.getEstado() == 'A') eventosAbertos.put(e.getIdEvento(),e);
}
return eventosAbertos;
}
/**
* Método que regista um novo Evento no sistema.
* @param idDesporto
* @param idEquipa1
* @param idEquipa2
* @param data
* @param hora
* @param odds
* @param localizacao
*/
public void registarEvento(int idDesporto, int idEquipa1, int idEquipa2, String data, String hora, List<Double> odds, String localizacao){
Desporto desp = desportos.get(idDesporto);
Equipa eq1 = equipas.get(idEquipa1);
Equipa eq2 = equipas.get(idEquipa2);
DateTimeFormatter format = DateTimeFormatter.ofPattern("d-M-y");
LocalDate date = LocalDate.parse(data,format);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m");
LocalTime horaComeco = LocalTime.parse(hora,dtf);
Resultado vitoriaEquipa1 = new Resultado("Vitoria Equipa 1", (odds.get(0)));
Resultado empate = new Resultado("Empate",(odds.get(1)));
Resultado vitoriaEquipa2 = new Resultado("Vitoria Equipa 2",(odds.get(2)));
List<Resultado> resultados = new ArrayList<>();
resultados.add(vitoriaEquipa1);
resultados.add(empate);
resultados.add(vitoriaEquipa2);
Duration duracao = Duration.ofMinutes(90);
DetalhesEvento detalhesEvento = new DetalhesEvento(date,horaComeco,duracao,localizacao,eq1,eq2,desp);
Evento evento = new Evento(eventos.size()+1, resultados, detalhesEvento);
eventos.put(evento.getIdEvento(),evento);
}
/**
* Método que verifica se um evento está aberto.
* @param idEvento
* @return Boolean
*/
public boolean isEventoAberto(int idEvento){
return eventos.keySet().contains(idEvento);
}
/**
* Método que altera o estado de um evento
* @param idEvento
*/
public void alterarEstado(int idEvento){
eventos.get(idEvento).alterarEstado(this);
}
/**
* Método que retorna o evento associado a um identificador
* @param idEvento
* @return Evento
*/
public Evento getEvento(int idEvento){
return eventos.get(idEvento);
}
/**
* Método que retorna a designação da equipa associada a um identificador
* @param idEquipa
* @return Designação
*/
public String getDesignacaoEquipa(int idEquipa){
return equipas.get(idEquipa).getDesignacao();
}
/**
* Método utilizado para povoar o sistema, caso não exista nenhum ficheiro de dados disponível.
*/
public void initializeSystem(){
Utilizador admin = new AdministradorDeEventos(getUtilizadores().size()+1,"admin","betess","Admin");
getUtilizadores().put(admin.getIdUtilizador(),admin);
Desporto futebol = new Desporto(1,"Futebol");
desportos.put(futebol.getIdDesporto(),futebol);
Desporto basquetebol = new Desporto(2,"Basquetebol");
desportos.put(basquetebol.getIdDesporto(),basquetebol);
Equipa slb = new Equipa(1,"Sport Lisboa e Benfica");
equipas.put(slb.getIdEquipa(),slb);
Equipa fcp = new Equipa(2, "Futebol Clube do Porto");
equipas.put(fcp.getIdEquipa(),fcp);
}
}
<file_sep>/src/Business/Apostador.java
package Business;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import Exception.SaldoInsuficienteException;
/**
* Created by luismp on 10/11/2018.
*/
public class Apostador extends Utilizador {
private String cartaoAssociado;
private double saldo;
private Map<Integer,Aposta> apostas;
private List<Notificacao> notificacoes;
/**
* Construtor vazio
*/
public Apostador(){
cartaoAssociado = "";
saldo=0;
apostas = new HashMap<>();
notificacoes = new ArrayList<>();
}
/**
* Construtor parametrizado
* @param idUtilizador
* @param email
* @param password
* @param nome
*/
public Apostador(int idUtilizador, String email, String password, String nome){
super(idUtilizador,email,password,nome);
this.setCartaoAssociado(cartaoAssociado);
this.setSaldo(saldo);
this.setApostas(new HashMap<>());
this.setNotificacoes(new ArrayList<>());
}
/**
* Getter cartão associado
* @return Cartão associado
*/
public String getCartaoAssociado() {
return cartaoAssociado;
}
/**
* Setter cartão associado
* @param cartaoAssociado
*/
public void setCartaoAssociado(String cartaoAssociado) {
this.cartaoAssociado = cartaoAssociado;
}
/**
* Getter Saldo
* @return Saldo
*/
public double getSaldo() {
return saldo;
}
/**
* Setter saldo
* @param saldo
*/
public void setSaldo(double saldo) {
this.saldo = saldo;
}
/**
* Getter apostas
* @return Apostas
*/
public Map<Integer, Aposta> getApostas() {
return apostas;
}
/**
* Setter apostas
* @param apostas
*/
public void setApostas(Map<Integer, Aposta> apostas) {
this.apostas = apostas;
}
/**
* Getter notificações
* @return Notificações
*/
public List<Notificacao> getNotificacoes() {
return notificacoes;
}
/**
* Setter notificações
* @param notificacoes
*/
public void setNotificacoes(List<Notificacao> notificacoes) {
this.notificacoes = notificacoes;
}
/**
* Clone
* @return Apostador
*/
public Apostador clone(){
int idUtilizador = this.getIdUtilizador();
String email = this.getEmail();
String password = this.<PASSWORD>();
String nome = this.getNome();
return new Apostador(idUtilizador,email,password,nome);
}
/**
* Equals
* @param object
* @return Boolean
*/
public boolean equals(Object object){
if(object == this) return true;
if(object==null || object.getClass() != getClass()) return false;
Apostador apostador = (Apostador) object;
return apostador.getIdUtilizador() == getIdUtilizador();
}
/**
* toString
* @return String
*/
public String toString(){
StringBuilder string = new StringBuilder();
string
.append("----Business.Apostador----\nID : ")
.append(this.getIdUtilizador())
.append("\nEmail : ")
.append(this.getEmail())
.append("\nNome : ")
.append(this.getNome())
.append("\nCartão Associado : ")
.append(this.getCartaoAssociado())
.append("\nSaldo : ")
.append(this.getSaldo())
.append("€\n------------------\n");
return string.toString();
}
/**
* Método que deposita uma quantia em ESSCoins na conta de um Apostador
* @param quantia
*/
public void depositar(double quantia){
double novoSaldo = getSaldo() + quantia;
setSaldo(novoSaldo);
}
/**
* Método que levanta uma quantia em ESSCoins da conta de um Apostador
* Lança uma exceção caso não possua saldo suficiente
* @param quantia
* @throws SaldoInsuficienteException
*/
public void levantar(double quantia) throws SaldoInsuficienteException {
double novoSaldo = this.getSaldo() - quantia;
if(novoSaldo < 0) throw new SaldoInsuficienteException(novoSaldo);
else setSaldo(novoSaldo);
}
/**
* Método que regista uma nova Aposta
* Lança uma exceção caso o Apostador não possua saldo suficiente
* @param evento
* @param resultado
* @param quantia
* @throws SaldoInsuficienteException
*/
public void registarAposta( Evento evento, Resultado resultado, double quantia) throws SaldoInsuficienteException{
levantar(quantia);
Aposta aposta = new Aposta();
int idAposta = apostas.size()+1;
aposta.setIdAposta(idAposta);
aposta.setResultado(resultado);
aposta.setQuantia(quantia);
aposta.setGanhosPossiveis(aposta.calcularGanhos());
apostas.put(idAposta,aposta);
evento.getApostas().put(getIdUtilizador(),aposta);
}
/**
* Método que adiciona uma nova notificação no Apostador
* @param notificacao
*/
public void addNotificacao(Notificacao notificacao){
notificacoes.add(notificacao);
}
}
<file_sep>/test/Business/ApostaTest.java
package Business;
import static org.junit.Assert.*;
/**
* Created by luismp on 21/12/2018.
*/
public class ApostaTest {
@org.junit.Test
public void calcularGanhos() throws Exception {
Resultado resultadoFinal = new Resultado("Vitoria",2.5);
Aposta aposta = new Aposta(1,100,resultadoFinal);
assertEquals(aposta.calcularGanhos(), 100*2.5,0.000001);
}
}<file_sep>/test/Business/EventoTest.java
package Business;
import org.junit.Test;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by luismp on 21/12/2018.
*/
public class EventoTest {
@Test
public void alterarEstado() throws Exception {
Resultado vitoria1 = new Resultado("Vitória da Equipa 1", 2);
Resultado empate = new Resultado("Empate", 1);
Resultado vitoria2 = new Resultado("Vitória da Equipa 2", 3);
List<Resultado> resultadoList = new ArrayList<>();
resultadoList.add(vitoria1);
resultadoList.add(empate);
resultadoList.add(vitoria2);
DetalhesEvento detalhesEvento = new DetalhesEvento(LocalDate.now(),LocalTime.now(),Duration.ofMinutes(90),"estádio", new Equipa(1,"SLB"), new Equipa(2,"FCP"),new Desporto(1,"Futebol") );
Evento evento = new Evento(1,resultadoList,detalhesEvento);
Apostador apostador1 = new Apostador(1,"Tales","Tales","Tales");
apostador1.depositar(100);
apostador1.setIdUtilizador(10);
apostador1.registarAposta(evento,vitoria1,50);
Apostador apostador2 = new Apostador(2,"Bomber","Bomber","Bomber");
apostador2.depositar(100);
apostador2.setIdUtilizador(20);
apostador2.registarAposta(evento,empate,50);
Apostador apostador3 = new Apostador(3,"Gigo","Gigo","Gigo");
apostador3.depositar(100);
apostador3.setIdUtilizador(30);
apostador3.registarAposta(evento,vitoria2,50);
BetESS bet = new BetESS();
HashMap<Integer, Utilizador> utilizadorHashMap = new HashMap<>();
utilizadorHashMap.put(apostador1.getIdUtilizador(),apostador1);
utilizadorHashMap.put(apostador2.getIdUtilizador(),apostador2);
utilizadorHashMap.put(apostador3.getIdUtilizador(),apostador3);
bet.setUtilizadores(utilizadorHashMap);
evento.alterarEstado(bet);
if(evento.getResultadoFinal().getDesignacao().equals(vitoria1.getDesignacao())){
assertEquals(150,apostador1.getSaldo(),0.0000001);
}
else if(evento.getResultadoFinal().getDesignacao().equals(empate.getDesignacao())){
assertEquals(100,apostador2.getSaldo(),0.0000001);
}
else if(evento.getResultadoFinal().getDesignacao().equals(vitoria2.getDesignacao())){
assertEquals(200,apostador3.getSaldo(),0.0000001);
}
assertEquals(1,apostador1.getNotificacoes().size(),0.0000001);
assertEquals(1,apostador2.getNotificacoes().size(),0.0000001);
assertEquals(1,apostador3.getNotificacoes().size(),0.0000001);
}
}<file_sep>/src/Business/Notificacao.java
package Business;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* Created by luismp on 10/11/2018.
*/
public class Notificacao implements Serializable {
private LocalDateTime data;
private String texto;
/**
* Construtor Vazio de uma Notificação
*/
public Notificacao(){
this.data = LocalDateTime.now();
this.texto="";
}
/**
* Getter da Data de uma Notificação
* @return Data
*/
public LocalDateTime getData() {
return data;
}
/**
* Getter do Texto de uma Notificação
* @return Texto
*/
public String getTexto() {
return texto;
}
/**
* Setter do texto de uma Notificação
* @param texto
*/
public void setTexto(String texto) {
this.texto = texto;
}
/**
* Método clone()
* @return
*/
public Notificacao clone(){
Notificacao notificacao = new Notificacao();
notificacao.setTexto(texto);
return notificacao;
}
/**
* toString
* @return String
*/
public String toString(){
StringBuilder string = new StringBuilder();
string
.append("----Notificação----\nTimestamp : ")
.append(this.getData())
.append("\n")
.append(this.getTexto())
.append("\n-------------------\n");
return string.toString();
}
}
<file_sep>/src/GUI/GUISaldo.java
package GUI;
import Business.Apostador;
import Business.BetESS;
import Exception.*;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Created by luismp on 20/12/2018.
*/
public class GUISaldo extends GUI {
/**
* Método que imprime no ecrã o menu de gestão do Saldo de um Apostador
*/
protected static void gerirSaldoScene() {
System.out.println("--- Gerir Saldo ---");
System.out.println("1 - Associar Cartão");
System.out.println("2 - Depositar Dinheiro");
System.out.println("3 - Levantar Dinheiro");
System.out.println("0 - Sair");
System.out.println("-------------------");
}
/**
* Método que recebe e trata os inputs relativos ao menu de gestão de saldo
*/
protected static void gerirSaldoHandler() {
while (true) {
String opcao = readLine();
if (opcao.equals("1")) {
associarCartao();
confirmarContinuar();
gerirSaldoScene();
} else if (opcao.equals("2")) {
depositarDinheiro();
confirmarContinuar();
gerirSaldoScene();
} else if (opcao.equals("3")) {
levantarDinheiro();
confirmarContinuar();
gerirSaldoScene();
} else if (opcao.equals("0")) {
break;
} else {
System.out.println("Input não reconhecido");
confirmarContinuar();
gerirSaldoScene();
}
}
}
/**
* Método que permite um Apostador associar um cartão ao sistema
*/
private static void associarCartao() {
Apostador atual = (Apostador) getAtual();
System.out.println("Insira o número do cartão, do tipo dddd-dddd-dddd-dddd");
try {
String novoCartao = validarCartao();
atual.setCartaoAssociado(novoCartao);
} catch (Exception e) {
System.out.println("Cartão inválido");
confirmarContinuar();
return;
}
}
/**
* Método que valida o cartão inserido baseado na forma
* @return Cartão
*/
private static String validarCartao() {
Scanner scanner = new Scanner(System.in);
Pattern mb = Pattern.compile("[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}");
return scanner.next(mb);
}
/**
* Método que permite ao Apostador depositar dinheiro no sistema
*/
private static void depositarDinheiro() {
Apostador atual = (Apostador) getAtual();
System.out.println("Qual a quantia que quer depositar?");
String quantia = readLine();
if (isDouble(quantia)) {
double qt = Double.parseDouble(quantia);
atual.depositar(qt);
confirmarContinuar();
} else {
System.out.println("Valor inválido");
confirmarContinuar();
return;
}
}
/**
* Método que permite ao Apostador levantar dinheiro do sistema
*/
private static void levantarDinheiro() {
Apostador atual = (Apostador) getAtual();
System.out.println("Qual a quantia que quer levantar?");
String quantia = readLine();
if (isDouble(quantia)) {
double qt = Double.parseDouble(quantia);
try {
atual.levantar(qt);
confirmarContinuar();
} catch (SaldoInsuficienteException e) {
System.out.println("Impossível levantar essa quantia");
confirmarContinuar();
return;
}
}
}
}
<file_sep>/src/GUI/GUIApostador.java
package GUI;
import Business.Aposta;
import Business.Apostador;
import Business.Evento;
import Business.Notificacao;
import Business.Resultado;
import Exception.SaldoInsuficienteException;
/**
* Created by luismp on 20/12/2018.
*/
public class GUIApostador extends GUI{
/**
* Método que recebe e trata os inputs da página após o login de um apostador
* @return
*/
protected static boolean apostadorLoggedInHandler() {
String opcao = readLine();
if (opcao.equals("1")) {
showNotificacoes();
confirmarContinuar();
GUIMainPage.loggedInScene();
} else if (opcao.equals("2")) {
GUISaldo.gerirSaldoScene();
GUISaldo.gerirSaldoHandler();
confirmarContinuar();
GUIMainPage.loggedInScene();
} else if (opcao.equals("3")) {
showResultados();
confirmarContinuar();
GUIMainPage.loggedInScene();
} else if (opcao.equals("4")) {
showEvents();
confirmarContinuar();
GUIMainPage.loggedInScene();
} else if (opcao.equals("5")) {
showApostas();
confirmarContinuar();
GUIMainPage.loggedInScene();
} else if (opcao.equals("6")) {
novaApostaForm();
confirmarContinuar();
GUIMainPage.loggedInScene();
} else if (opcao.equals("0")) {
terminarSessao();
return false;
} else {
System.out.println("Input não reconhecido");
confirmarContinuar();
GUIMainPage.loggedInScene();
}
return true;
}
/**
* Método que apresenta o formulário para registar uma nova Aposta
* @see Aposta
*/
private static void novaApostaForm() {
Apostador atual = (Apostador) getAtual();
System.out.println("---- Registar Nova Aposta ----");
System.out.println("Indique em qual evento quer apostar");
int idEvento = escolherIDEvento();
if(idEvento == -1) {
return;
}
Evento evento = getEvento(idEvento);
printDetalhesEvento(evento);
int idResultado = escolherResultado();
Resultado resultado = evento.getResultado(idResultado);
double quantia;
quantia = escolherQuantia();
tryRegistarAposta(atual, evento, resultado, quantia);
}
/**
* Método que imprime no ecrã os detalhes de um evento
* @param evento
* @see Evento
*/
private static void printDetalhesEvento(Evento evento) {
System.out.println(evento);
System.out.println("Indique qual o resultado que pretende apostar:\n" +
"0 - Vitória de " + evento.getDesignacaoEquipa(1) + "- odd : " + evento.getResultado(0).getOdd() + "\n" +
"1 - Empate - odd : " + evento.getResultado(1).getOdd() + "\n" +
"2 - Vitória de " + evento.getDesignacaoEquipa(2) + "- odd : " + evento.getResultado(2).getOdd() + "\n");
}
/**
* Método que tenta registar uma nova Aposta no sistema
* @param atual
* @param evento
* @param resultado
* @param quantia
* @see Aposta
*/
private static void tryRegistarAposta(Apostador atual, Evento evento, Resultado resultado, double quantia) {
try {
atual.registarAposta(evento, resultado, quantia);
} catch (SaldoInsuficienteException e) {
System.out.println("Saldo insuficiente. Aposta não registada");
return;
}
}
/**
* Método que permite ao Apostador selecionar qual a quantia a apostar
* @return Quantia
*/
private static double escolherQuantia() {
System.out.println("Qual a quantia que quer apostar?");
double quantia;
while (true) {
String qt = readLine();
if (!isDouble(qt)) {
System.out.println("Quantia inválida. Insira uma nova quantia");
} else {
quantia = Double.parseDouble(qt);
break;
}
}
return quantia;
}
/**
* Método que permite ao Apostador selecionar qual o Resultado em que quer apostar
* @return Resultado
*/
private static int escolherResultado() {
int idResultado = 0;
while (true) {
String idres = readLine();
if (idres.equals("0")) {
idResultado = 0;
break;
} else if (idres.equals("1")) {
idResultado = 1;
break;
} else if (idres.equals("2")) {
idResultado = 2;
break;
} else {
System.out.println("Resultado inválido. Insira um resultado válido");
}
}
return idResultado;
}
/**
* Método que permite ao Apsotador selecionar qual o identificador do evento em que quer apostar
* @return ID Evento
*/
private static int escolherIDEvento() {
int idEvento = 0;
while (true) {
String idev = readLine();
if (isInteger(idev)) {
idEvento = Integer.parseInt(idev);
if (isEventoAberto(idEvento)) break;
else {
System.out.println("Evento não disponível");
idEvento = -1;
break;
}
} else {
System.out.println("Input não reconhecido");
idEvento = -1;
break;
}
}
return idEvento;
}
/**
* Método que imprime todos os resultados no ecrã
*/
private static void showResultados() {
System.out.println("---- Resultados ----");
for (Evento e : getEventos().values()) {
if (e.getEstado() == 'F') {
System.out.println(e.toString());
}
}
System.out.println("--------------------");
}
/**
* Método que imprime no ecrã todas as Apostas que um Apostador registou
*/
private static void showApostas() {
Apostador atual = (Apostador) getAtual();
System.out.println("---- Apostas Realizadas ----");
if (atual.getApostas().size() == 0) {
System.out.println("Não há apostas");
} else {
for (Aposta a : atual.getApostas().values()) {
System.out.println(a.toString());
}
}
System.out.println("----------------------------");
}
/**
* Método que imprime no ecrã todas as Notificações enviadas a um Apostador
*/
private static void showNotificacoes() {
Apostador atual = (Apostador) getAtual();
System.out.println("---- Notificações ----");
if (atual.getNotificacoes().size() == 0) {
System.out.println("Não há notificações");
} else {
for (Notificacao n : atual.getNotificacoes()) {
System.out.println(n.toString());
}
}
System.out.println("---------------------");
}
}
<file_sep>/README.md
# AS_TP2
Arquiteturas de Software - TP2- Refactoring
<file_sep>/src/Business/Resultado.java
package Business;
import java.io.Serializable;
/**
* Created by luismp on 11/11/2018.
*/
public class Resultado implements Serializable {
public String designacao;
public double odd;
/**
* Construtor Vazio de um Resultado
*/
public Resultado(){
this.designacao = "";
this.odd = 0;
}
/**
* Construtor parametrizado de um Resultado
* @param designacao
* @param odd
*/
public Resultado(String designacao, double odd){
this.designacao = designacao;
this.odd = odd;
}
/**
* Getter da Designação de um Resultado
* @return Designação
*/
public String getDesignacao() {
return designacao;
}
/**
* Getter da Odd de um Resultado
* @return Odd
*/
public double getOdd() {
return odd;
}
/**
* Método equals
* @param object
* @return Boolean
*/
public boolean equals(Object object){
if(object == this) return true;
if(object==null || object.getClass() != this.getClass()) return false;
Resultado resultado = (Resultado) object;
return resultado.getDesignacao().equals(this.getDesignacao()) && resultado.getOdd() == this.getOdd();
}
/**
* toString
* @return String
*/
public String toString(){
StringBuilder string = new StringBuilder();
string
.append("----Resultado----\nOdd : ")
.append(this.getOdd())
.append("\n")
.append(this.getDesignacao())
.append("\n-----------------\n");
return string.toString();
}
}
| ee5d52348c8e4885b6f2c28a05dcfdc1d562f99f | [
"Markdown",
"Java"
] | 12 | Java | tales42/AS_TP2 | 74ead8193de48eb071006241fddb15a00aa8fade | b9f9326c08c52126c5ff1d7aa9d183ac36e2f912 | |
refs/heads/master | <file_sep>using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace IntroToMEF
{
/// <summary>
/// Tutorial : Developing Modular Applications with MEF
/// URL : https://blogs.msmvps.com/bsonnino/2013/08/31/developing-modular-applications-with-mef/
/// </summary>
class Program
{
static void Main(string[] args)
{
// Now we need to tell that our parts are not only in the current assembly,
// but they can also be found in the current folder.For that we must compose
// two catalogs: one for the current assembly(for the imported parts) and
// another for the folder (for the exported parts).We will use an AggregateCatalog
// to compose both catalogs
var catalog = new AggregateCatalog(
new AssemblyCatalog(Assembly.GetExecutingAssembly()),
new DirectoryCatalog("."));
// created the container that composes the parts after the menu is created
var container = new CompositionContainer(catalog);
var menu = new Menu();
container.ComposeParts(menu);
// When the menu.OptionList() method is called, the module’s title is listed
menu.OptionList();
Console.ReadLine();
}
}
}
<file_sep>using IntroToMEF.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace IntroToMEF
{
/// <summary>
/// In order to match the parts, we must say
/// that the imported part is also of the IModule type
/// </summary>
public class Menu
{
[ImportMany]
private IEnumerable<IModule> _modules;
/// <summary>
/// List all the modules.
/// </summary>
public void OptionList()
{
// iterate over all the modules that we find
foreach (var module in _modules)
{
// write to console
Console.WriteLine(module.Title);
}
}
}
}
<file_sep>using IntroToMEF.Interfaces;
using System.ComponentModel.Composition;
namespace IntroToMEF.Modules
{
/// <summary>
/// Our class will implement this interface (IModule) and the export
/// will tell that we are exporting the IModule interface
/// </summary>
[Export(typeof(IModule))]
public class Customer : IModule
{
public Customer()
{
Title = "Customers";
}
public string Title { get; set; }
}
}
<file_sep>using IntroToMEF.Interfaces;
using System.ComponentModel.Composition;
namespace IntroToMEF.Modules
{
/// <summary>
/// Our class will implement this interface (IModule) and the export
/// will tell that we are exporting the IModule interface
/// </summary>
[Export(typeof(IModule))]
public class Product : IModule
{
public Product()
{
Title = "Products";
}
public string Title { get; set; }
}
}
| 74113e84a9d85da9a724c47221de804eb470b42c | [
"C#"
] | 4 | C# | goose-za/IntroToMEF | 4d080b3f8996c60a79916cfebf927adbd410d07a | 7a8473925a9744194d5640cb87842f0fb34d2aba | |
refs/heads/master | <file_sep>package com.hqyj.dinner.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
/**
* <p> 分页<p>
*
* @Author : long
* @Date : 2020-10-26 14:24
**/
@Data
public class Page {
//页码
// @Transient
@TableField(exist = false)
private Integer page;
//每页显示的行数
// @Transient
@TableField(exist = false)
private Integer rows;
}
<file_sep>package com.hqyj.dinner.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.dinner.entity.OrderDetail;
import com.hqyj.dinner.entity.Tables;
import com.hqyj.dinner.service.OrderDetailService;
import com.hqyj.dinner.service.TablesService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 前端控制器
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Controller
@RequestMapping("orderDetail")
public class OrderDetailController {
@Resource
OrderDetailService orderDetailService;
@Resource
private TablesService tablesService;
@RequestMapping("/orderTable")
public String orderTable() {
return "order_manage/orderTable";
}
@RequestMapping("orderPage")
public String orderPage() {
return "order_manage/order_display";
}
//预定一个餐桌
@RequestMapping("/order")
@ResponseBody
public HashMap<String, Object> order(Tables tables) {
HashMap<String, Object> map = new HashMap<>();
QueryWrapper<Tables> queryWrapper = new QueryWrapper<>();
tables.setStatus(0);
queryWrapper.eq("id", tables.getId());
if (tablesService.update(tables, queryWrapper)) {
map.put("info", "预定成功");
} else {
map.put("info", "预定失败");
}
return map;
}
//翻台
@RequestMapping("/cancel")
@ResponseBody
public HashMap<String, Object> cancel(Tables tables) {
HashMap<String, Object> map = new HashMap<>();
QueryWrapper<Tables> queryWrapper = new QueryWrapper<>();
tables.setStatus(1);
queryWrapper.eq("id", tables.getId());
if (tablesService.update(tables, queryWrapper)) {
map.put("info", "翻台成功");
} else {
map.put("info", "翻台失败");
}
return map;
}
//订餐按钮
@RequestMapping("/orderDinner")
@ResponseBody
public Map<String, Integer> orderDinner(Tables tables) {
HashMap<String, Integer> map = new HashMap<>();
map.put("tableId", tables.getId());
map.put("tableStatus", tables.getStatus());
return map;
}
//去到点菜页面
@RequestMapping("/menu/{tableId}&{tableStatus}")
public ModelAndView menu(@PathVariable("tableId") Integer tableId, @PathVariable("tableStatus") Integer tableStatus, ModelAndView mv) {
Tables tables = new Tables();
tables.setId(tableId);
tables.setStatus(tableStatus);
System.out.println(tables + "****************");
/* HashMap<String,Object> map = new HashMap<>();
map.put("tables",tables);*/
mv.addObject("tables", tables);
mv.setViewName("order_manage/menu");
return mv;
}
//添加一个菜
@RequestMapping("/addCar")
@ResponseBody
public HashMap<String, Object> addCar(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("table_id", orderDetail.getTableId());
queryWrapper.eq("food_id", orderDetail.getFoodId());
queryWrapper.eq("status", 0);
if (orderDetailService.getOne(queryWrapper) != null) {
UpdateWrapper<OrderDetail> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("food_count", orderDetail.getFoodCount());
boolean update = orderDetailService.update(orderDetail, queryWrapper);
if (update) {
map.put("info", "加入成功");
} else {
map.put("info", "加入失败");
}
return map;
}
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String orderNo = dateFormat.format(date);
System.out.println(orderDetail.getTableId() + "++++++++++++++++++++++++++++++++++++");
orderDetail.setStatus(0);//0是没下单
orderDetail.setPay(0);//0没付钱
orderDetail.setOrderNo(orderNo);
int i = orderDetailService.add(orderDetail);
if (i > 0) {
map.put("info", "加入成功");
} else {
map.put("info", "加入失败");
}
return map;
}
//取消加入的菜
@RequestMapping("/cancel2")
@ResponseBody
public HashMap<String, Object> cancel(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
int result = orderDetailService.delete(orderDetail);
if (result > 0) {
map.put("info", "取消成功");
} else {
map.put("info", "取消失败");
}
return map;
}
//下单
@RequestMapping("/confirm")
@ResponseBody
public HashMap<String, Object> confirm(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
List<OrderDetail> orderDetailList = orderDetailService.select(orderDetail);
UpdateWrapper<OrderDetail> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("status", 1);
if (orderDetailList != null) {
for (OrderDetail orderDetail2 : orderDetailList) {
orderDetail2.setStatus(1);
orderDetailService.update(updateWrapper);
}
map.put("data", orderDetailList);
map.put("info", "下单成功");
return map;
}
map.put("info", "下单失败!如有疑问请询问服务员!");
return map;
}
//详情及结算
@RequestMapping("/search/{tableId}")
public ModelAndView eachTableOrder(@PathVariable("tableId") Integer tableId, ModelAndView modelAndView) {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setTableId(tableId);
modelAndView.addObject("orderDetail", orderDetail);
modelAndView.setViewName("order_manage/eachTableOrder");
return modelAndView;
}
//查看点的菜
@RequestMapping("/findOrder")
@ResponseBody
public HashMap<String, Object> findOrder(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
List<OrderDetail> orderDetailList = orderDetailService.selectTableOrder(orderDetail.getTableId());
map.put("data", orderDetailList);
return map;
}
//计算价格
@RequestMapping("/count")
@ResponseBody
public HashMap<String, Object> count(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
double pay = 0.0;
// double pay2 = 0.0;
List<OrderDetail> orderDetailList = orderDetailService.selectTableOrder(orderDetail.getTableId());
for (OrderDetail detail : orderDetailList) {
Double price = detail.getPrice();
Integer num = detail.getFoodCount();
pay = price * num + pay;
//System.out.println(pay);
}
/*for (OrderDetail detail : orderDetailList) {
Double price = detail.getVipPrice();
Integer num = detail.getFoodCount();
pay2 = price * num + pay2;
//System.out.println(pay);
}*/
map.put("data", pay);
// map.put("data2", pay2);
return map;
}
//付钱
@RequestMapping("/pay")
@ResponseBody
public HashMap<String, Object> pay(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
UpdateWrapper<OrderDetail> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("pay", 1);
//找到对应餐桌且上了菜的
List<OrderDetail> orderDetailList = orderDetailService.selectNotPay(orderDetail.getTableId());
if (orderDetailList.size() != 0) {
for (OrderDetail detail : orderDetailList) {
orderDetailService.update(detail);
}
map.put("data", "支付成功");
return map;
}
map.put("data", "订单尚未完成");
return map;
}
//商家出菜页面
@RequestMapping("/chucai")
public String chucai() {
return "order_manage/chucai";
}
@RequestMapping("/cai")
@ResponseBody
public HashMap<String, Object> cai(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
List<OrderDetail> orderDetailList = orderDetailService.selectNotMake(orderDetail);
map.put("data", orderDetailList);
return map;
}
@RequestMapping("/make")
@ResponseBody
public HashMap<String, Object> make(OrderDetail orderDetail) {
HashMap<String, Object> map = new HashMap<>();
//找出数据
List<OrderDetail> one = orderDetailService.selectOntMakeFood(orderDetail);
if (one.size() >= 1) {
//修改数据
int update = orderDetailService.update2(orderDetail);
if (update > 0) {
map.put("info", "成功");
return map;
}
map.put("info", "操作失败!");
return map;
}
map.put("info", "操作失败!");
return map;
}
@ResponseBody
@RequestMapping("findAllOrder")
public HashMap<String, Object> findAllOrder(OrderDetail order) {
HashMap<String, Object> map = new HashMap<>();
PageHelper.startPage(order.getPage(), order.getRows());
List<OrderDetail> orderDetails = orderDetailService.findAll();
PageInfo<OrderDetail> pageInfo = new PageInfo<>(orderDetails);
map.put("total", pageInfo.getTotal());
map.put("pages", pageInfo.getPages());
map.put("endPage", pageInfo.getNavigateLastPage());
map.put("curPage", order.getPage());
map.put("data", pageInfo.getList());
return map;
}
@ResponseBody
@RequestMapping("del")
public HashMap<String, Object> del(OrderDetail order) {
HashMap<String, Object> map = new HashMap<>();
final boolean result = orderDetailService.removeById(order.getId());
if (result) {
map.put("info", "删除成功");
} else {
map.put("info", "删除失败");
}
return map;
}
}
<file_sep>package com.hqyj.dinner.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class FoodType extends Page implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 菜系ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 菜系名称
*/
private String typeName;
/**
* 状态,0:下架 1:上架
*/
private Integer status;
}
<file_sep>package com.hqyj.dinner.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hqyj.dinner.entity.OrderDetail;
import com.hqyj.dinner.mapper.OrderDetailMapper;
import com.hqyj.dinner.service.OrderDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements OrderDetailService {
@Resource
OrderDetailMapper orderDetailMapper;
@Override
public List<OrderDetail> findAll() {
return orderDetailMapper.selectList(null);
}
@Override
public int add(OrderDetail orderDetail) {
return orderDetailMapper.insert(orderDetail);
}
@Override
public int delete(OrderDetail orderDetail) {
QueryWrapper wrapper=new QueryWrapper();
wrapper.eq("food_id",orderDetail.getFoodId());
return orderDetailMapper.delete(wrapper);
}
@Override
public int update(OrderDetail orderDetail) {
QueryWrapper wrapper=new QueryWrapper();
wrapper.eq("status",2);
wrapper.eq("table_id",orderDetail.getTableId());
orderDetail.setPay(1);
return orderDetailMapper.update(orderDetail,wrapper);
}
@Override
public List<OrderDetail> select(OrderDetail orderDetail) {
QueryWrapper wrapper=new QueryWrapper();
wrapper.eq("table_id",orderDetail.getTableId());
wrapper.eq("status",0);
return orderDetailMapper.selectList(wrapper);
}
@Override
public List<OrderDetail> selectTableOrder(Integer tableId) {
QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("table_id",tableId);
queryWrapper.in("status",1,2);
queryWrapper.eq("pay",0);
return orderDetailMapper.selectList(queryWrapper);
}
@Override
public List<OrderDetail> selectNotPay(Integer tableId) {
QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("table_id",tableId);
queryWrapper.eq("status",2);
queryWrapper.eq("pay",0);
return orderDetailMapper.selectList(queryWrapper);
}
@Override
public List<OrderDetail> selectNotMake(OrderDetail orderDetail) {
QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("status",1);
queryWrapper.eq("pay",0);
return orderDetailMapper.selectList(queryWrapper);
}
@Override
public List<OrderDetail> selectOntMakeFood(OrderDetail orderDetail) {
QueryWrapper<OrderDetail> queryWrapper =new QueryWrapper<>();
queryWrapper.eq("food_id",orderDetail.getFoodId());
queryWrapper.eq("status",1);
queryWrapper.eq("pay",0);
return orderDetailMapper.selectList(queryWrapper);
}
@Override
public int update2(OrderDetail orderDetail) {
UpdateWrapper<OrderDetail> updateWrapper = new UpdateWrapper();
updateWrapper.eq("id",orderDetail.getId());
updateWrapper.set("status",2);
return orderDetailMapper.update(orderDetail,updateWrapper);
}
}
<file_sep>package com.hqyj.dinner.mapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.dinner.entity.Food;
import com.hqyj.dinner.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author Luo
* @since 2020-10-19
*/
public interface UserMapper extends BaseMapper<User> {
List<String> selectRole(String userName);
}
<file_sep>package com.hqyj.dinner.controller;
import com.hqyj.dinner.entity.FoodType;
import com.hqyj.dinner.service.FoodTypeService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@RestController
@RequestMapping("foodType")
public class FoodTypeController {
@Resource
FoodTypeService foodTypeService;
@RequestMapping("/findAll")
public HashMap<String,Object> findAll(){
List<FoodType> foodTypeList = foodTypeService.findAll();
HashMap<String,Object> map = new HashMap<>();
map.put("data",foodTypeList);
return map;
}
@RequestMapping("/add")
public HashMap<String,Object> add(FoodType foodType) {
HashMap<String,Object> map = new HashMap<>();
int result = foodTypeService.add(foodType);
if(result>0) {
map.put("info","新增成功");
return map;
}else {
map.put("info","新增失败");
return map;
}
}
@RequestMapping("/update")
public HashMap<String,Object> update(FoodType foodType) {
HashMap<String, Object> map = new HashMap<>();
int result = foodTypeService.update(foodType);
if(result>0) {
map.put("info","修改成功");
return map;
}else {
map.put("info","修改失败");
return map;
}
}
@RequestMapping("/del")
public HashMap<String,Object> del(FoodType foodType) {
HashMap<String, Object> map = new HashMap<>();
int result = foodTypeService.delete(foodType);
if(result>0) {
map.put("info","删除成功");
return map;
}else {
map.put("info","删除失败");
return map;
}
}
@RequestMapping("/select")
public HashMap<String,Object> select(FoodType foodType){
HashMap<String, Object> map = new HashMap<>();
List<FoodType> foodTypeList = foodTypeService.select(foodType);
map.put("data",foodTypeList);
return map;
}
}
<file_sep>package com.hqyj.dinner.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.dinner.entity.FoodType;
import com.hqyj.dinner.mapper.FoodTypeMapper;
import com.hqyj.dinner.service.FoodTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Service
public class FoodTypeServiceImpl extends ServiceImpl<FoodTypeMapper, FoodType> implements FoodTypeService {
@Resource
FoodTypeMapper foodTypeMapper;
@Override
public List<FoodType> findAll() {
return foodTypeMapper.selectList(null);
}
@Override
public int add(FoodType foodType) {
return foodTypeMapper.insert(foodType);
}
@Override
public int update(FoodType foodType) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("id",foodType.getId());
return foodTypeMapper.update(foodType,queryWrapper);
}
@Override
public int delete(FoodType foodType) {
QueryWrapper<FoodType> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id",foodType.getId());
return foodTypeMapper.delete(queryWrapper);
}
@Override
public List<FoodType> select(FoodType foodType) {
QueryWrapper<FoodType> queryWrapper = new QueryWrapper<>();
if(foodType.getId()!=null){
queryWrapper.eq("id",foodType.getId());
}
if(foodType.getTypeName()!=null){
queryWrapper.like("type_name",foodType.getTypeName());
}
return foodTypeMapper.selectList(queryWrapper);
}
}
<file_sep>package com.hqyj.dinner.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
/**
* Program: dinner
* Description:
* Author: Luo
* Date: 2020-10-23 19:49
*/
@SpringBootTest
class FoodControllerTest {
@Autowired
FoodController foodController;
@Test
void test(){
final HashMap<String, Object> map = foodController.queryMenuFood(1, 5);
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}<file_sep>package com.hqyj.dinner.service;
import com.hqyj.dinner.entity.OrderDetail;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author Luo
* @since 2020-10-19
*/
public interface OrderDetailService extends IService<OrderDetail> {
List<OrderDetail> findAll();
int add(OrderDetail orderDetail );
int delete(OrderDetail orderDetail);
int update(OrderDetail orderDetail);
List<OrderDetail> select(OrderDetail orderDetail);
List<OrderDetail> selectTableOrder(Integer tableId);
List<OrderDetail> selectNotPay(Integer tableId);
List<OrderDetail> selectNotMake(OrderDetail orderDetail);
List<OrderDetail> selectOntMakeFood(OrderDetail orderDetail);
int update2(OrderDetail orderDetail);
}
<file_sep>package com.hqyj.dinner.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hqyj.dinner.entity.Role;
import com.hqyj.dinner.entity.User;
import com.hqyj.dinner.mapper.RoleMapper;
import com.hqyj.dinner.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
@Autowired
RoleMapper roleMapper;
@Override
public List<Role> queryAllRole() {
return roleMapper.selectList(null);
}
@Override
public int add(Role role) {
return roleMapper.insert(role);
}
@Override
public int delete(Role role) {
UpdateWrapper<Role> wrapper = new UpdateWrapper<>();
wrapper.eq("id",role.getId());
wrapper.set("status",0);
return roleMapper.update(role,wrapper);
}
@Override
public List<Role> select(Role role) {
QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
if (role.getId()!=null){
queryWrapper.eq("id",role.getId());
}
if (!role.getRoleName().isEmpty()){
queryWrapper.like("role_name",role.getRoleName());
}
if (role.getStatus()!=null){
queryWrapper.eq("status",role.getStatus());
}
return roleMapper.selectList(queryWrapper);
}
@Override
public int modify(Role role) {
QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id",role.getId());
return roleMapper.update(role,queryWrapper);
}
}
<file_sep>package com.hqyj.dinner.shrio;
import com.hqyj.dinner.entity.User;
import com.hqyj.dinner.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Program: dinner
* Description: Realm授权、认证
* Author: Luo
* Date: 2020-10-20 00:20
*/
public class MyAuthorizingRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取当前登录的用户信息
Subject subject = SecurityUtils.getSubject();
String userName = (String) subject.getPrincipal();
//根据用户名查询用户拥有的权限或者角色
List<String> list = userService.selectRole(userName);
//创建shiro授权对象
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//给用户赋予角色
simpleAuthorizationInfo.addRoles(list);
return simpleAuthorizationInfo;
}
/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获取登录用户的凭证
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//获取用户名
String userName = (String) token.getPrincipal();
//查询数据库,获取用户对象
User user_db = userService.selectUserByUserName(userName);
//判断用户是否存在
if (user_db != null) {
//创建用户凭证 ,这个对象会把数据库查询出来的用户信息和登录的用户信息进行比对
return new SimpleAuthenticationInfo(userName, user_db.getPwd(), new Md5Hash(userName), this.getName());
}
return null;
}
}
<file_sep>package com.hqyj.dinner.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.beans.Transient;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Food extends Page implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 菜品ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 菜品名称
*/
private String foodName;
/**
* 菜品名称
*/
@TableField(exist = false)
private String typeName;
/**
* 菜系id
*/
private Integer typeId;
/**
* 价格
*/
private Double price;
/**
* vip价格
*/
private Double vipPrice;
/**
* 菜品图片url
*/
private String imgUrl;
/**
* 菜品描述
*/
private String description;
/**
* 状态,0:下架,1:上架
*/
private Integer status;
/**
* 备用
*/
private String zhanWei;
}
<file_sep>package com.hqyj.dinner.util;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Component;
/**
* md5 密码加密工具类
*/
@Component
public class MdFive {
/**
*
* @param password 密码
* @param saltValue 盐值
* @return md5加密后的密码
*/
public String encrypt(String password,String saltValue){
//创建MD5算法对象
Object salt = new Md5Hash(saltValue);
//SimpleHash(算法名称,要加密的密码,盐值,加密次数)
Object result = new SimpleHash("MD5", password, salt, 1024);
return result.toString();
}
}
<file_sep>package com.hqyj.dinner.mapper;
import com.hqyj.dinner.entity.UserRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author Luo
* @since 2020-10-19
*/
public interface UserRoleMapper extends BaseMapper<UserRole> {
}
<file_sep>package com.hqyj.dinner.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.dinner.entity.Tables;
import com.hqyj.dinner.entity.User;
import com.hqyj.dinner.entity.Role;
import com.hqyj.dinner.entity.User;
import com.hqyj.dinner.service.RoleService;
import com.hqyj.dinner.service.UserService;
import com.hqyj.dinner.util.MdFive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Autowired
MdFive mdFive;
/**
* 进入用户管理
*/
@RequestMapping("/userPage")
public String userPage() {
return "sys_manage/user";
}
/**
* 查询所有用户
*/
@ResponseBody
@RequestMapping("queryAllUser")
public HashMap<String, Object> queryAllUser(User user) {
HashMap<String, Object> map = new HashMap<>();
//1 设置分页参数:页码和条数
PageHelper.startPage(user.getPage(), user.getRows());
//2 查询结果集合
List<User> userList = userService.queryAllUser();
// 3 创建分页对象
PageInfo<User> pageInfo = new PageInfo<>(userList);
List<User> listResult = pageInfo.getList();
map.put("total", pageInfo.getTotal());
map.put("pages", pageInfo.getPages());
map.put("endPage", pageInfo.getNavigateLastPage());
map.put("curPage", user.getPage());
map.put("data", listResult);
return map;
}
@RequestMapping("/add")
@ResponseBody
public HashMap<String, Object> add(User user) {
HashMap<String, Object> map = new HashMap<>();
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("user_name", user.getUserName());
final List<User> userList = userService.list(wrapper);
if (user.getUserName().isEmpty() || user.getPwd().isEmpty()) {
map.put("info", "用户名和密码不能为空!");
} else if (userList.isEmpty()) {
user.setPwd(<PASSWORD>.<PASSWORD>(user.getPwd(), user.getUserName()));
int result = userService.add(user);
if (result > 0) {
map.put("info", "新增成功");
} else {
map.put("info", "新增失败!");
}
} else {
map.put("info", "用户已存在!");
}
return map;
}
@RequestMapping("/update")
@ResponseBody
public HashMap<String, Object> update(User user) {
HashMap<String, Object> map = new HashMap<>();
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("user_name", user.getUserName());
User user_db = userService.getOne(wrapper);
String userPwd = user.getPwd();
if (user.getUserName().isEmpty() || user.getPwd().isEmpty()) {
map.put("info", "用户名和密码不能为空!");
} else if (user_db != null) {
if (userPwd.equals(user_db.getPwd())) {
int result = userService.modify(user);
if (result > 0) {
map.put("info", "修改成功");
} else {
map.put("info", "修改失败!");
}
} else {
user.setPwd(mdFive.encrypt(userPwd, user.getUserName()));
int result = userService.modify(user);
if (result > 0) {
map.put("info", "修改成功");
} else {
map.put("info", "修改失败!");
}
}
}else {
user.setPwd(mdFive.encrypt(userPwd, user.getUserName()));
int result = userService.modify(user);
if (result > 0) {
map.put("info", "修改成功");
} else {
map.put("info", "修改失败!");
}
}
return map;
}
@RequestMapping("/del")
@ResponseBody
public HashMap<String, Object> del(User user) {
HashMap<String, Object> map = new HashMap<>();
int result = userService.delete(user);
if (result > 0) {
map.put("info", "删除成功");
} else {
map.put("info", "删除失败");
}
return map;
}
@RequestMapping("/select")
@ResponseBody
public HashMap<String, Object> select(User user) {
HashMap<String, Object> map = new HashMap<>();
if (user.getUserName().isEmpty() && user.getName().isEmpty() &&
user.getStatus() == null && user.getRoleId() == null &&
user.getTelNum().isEmpty()) {
map.put("info", "请输入信息以查询");
} else {
//1 设置分页参数:页码和条数
PageHelper.startPage(user.getPage(), user.getRows());
//2 查询结果集合
List<User> userList = userService.select(user);
// 3 创建分页对象
PageInfo<User> pageInfo = new PageInfo<>(userList);
map.put("total", pageInfo.getTotal());
map.put("pages", pageInfo.getPages());
map.put("endPage", pageInfo.getNavigateLastPage());
map.put("curPage", user.getPage());
if (pageInfo.getList().isEmpty()) {
map.put("info", "没有此条记录,请添加!");
} else {
map.put("data", pageInfo.getList());
map.put("info", "查询成功");
}
}
return map;
}
@ResponseBody
@RequestMapping("/fpRole")
public HashMap<String, Object> fpRole(User user) {
HashMap<String, Object> map = new HashMap<>();
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("id", user.getId());
wrapper.set("role_id", user.getRoleId());
if (userService.update(wrapper)) {
map.put("info", "分配成功");
} else {
map.put("info", "分配失败");
}
return map;
}
@RequestMapping("/backUser")
@ResponseBody
public HashMap<String, Object> backUser(User user) {
HashMap<String, Object> map = new HashMap<>();
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("id", user.getId());
wrapper.set("status", 1);
if (userService.update(wrapper)) {
map.put("info", "恢复成功");
} else {
map.put("info", "恢复失败!");
}
return map;
}
}
<file_sep>package com.hqyj.dinner.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class OrderDetail extends Page implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 订单详情ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 订单编号
*/
private String orderNo;
/**
* 所属订单ID
*/
//private Integer orderId;
/**
* 菜名ID
*/
private Integer foodId;
/**
* 订餐数量
*/
private Integer foodCount;
/**
* 状态,0:删除,1:正常
*/
private Integer tableId;
private Integer status;
private Double vipPrice;
private Double price;
/**
* 备用
*/
private Integer pay;
}
<file_sep>package com.hqyj.dinner.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.dinner.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author Luo
* @since 2020-10-19
*/
public interface UserService extends IService<User> {
User selectUserByUserName(String userName);
List<User> queryAllUser();
int add(User user);
int modify(User user);
int delete(User user);
List<User> select(User user);
List<String> selectRole(String userName);
}
<file_sep>package com.hqyj.dinner.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hqyj.dinner.entity.Food;
import com.hqyj.dinner.entity.Tables;
import com.hqyj.dinner.entity.User;
import com.hqyj.dinner.mapper.RoleMapper;
import com.hqyj.dinner.mapper.UserMapper;
import com.hqyj.dinner.mapper.UserRoleMapper;
import com.hqyj.dinner.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.dinner.util.MdFive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author Luo
* @since 2020-10-19
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
UserMapper userMapper;
@Override
public User selectUserByUserName(String userName) {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("user_name",userName);
return userMapper.selectOne(wrapper);
}
@Override
public List<User> queryAllUser() {
return userMapper.selectList(null);
}
//增
@Override
public int add(User user) {
return userMapper.insert(user);
}
//改
@Override
public int modify(User user) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id",user.getId());
return userMapper.update(user,queryWrapper);
}
//删
@Override
public int delete(User user) {
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("id",user.getId());
wrapper.set("status",0);
return userMapper.update(user,wrapper);
}
//查
@Override
public List<User> select(User user) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (!user.getUserName().isEmpty()) {
queryWrapper.like("user_name", user.getUserName());
}
if (!user.getName().isEmpty()) {
queryWrapper.like("name", user.getName());
}
if (user.getStatus() != null) {
queryWrapper.eq("status", user.getStatus());
}
if (user.getRoleId() != null) {
queryWrapper.eq("role_id", user.getRoleId());
}
if (!user.getTelNum().isEmpty()) {
queryWrapper.like("tel_num", user.getTelNum());
}
return userMapper.selectList(queryWrapper);
}
@Override
public List<String> selectRole(String userName) {
return userMapper.selectRole(userName);
}
}
| 4eab261a82f543536b54ed97b60b0712cd4ff003 | [
"Java"
] | 18 | Java | Mirror-song/dinner | 3b951e6f2d493ec4f3ce006021296688c04f0d36 | fa64fcf6dc6df57ee5a337365a1ca8c6d1d289ab | |
refs/heads/master | <repo_name>tivonY/Demo<file_sep>/test/src/main/java/com/tivon/server/aop4/TestMain4.java
package com.tivon.server.aop4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.tivon.server.aop2.IUserDao;
public class TestMain4 {
// <!-- 定义被代理者 -->
// <bean id="userDao" class="com.tivon.server.aop.UserDao"></bean>
// <bean id="myAspect" class="com.tivon.server.aop3.LoginHelper"></bean>
//
// <aop:config>
// <aop:pointcut id="loginHelpers" expression="execution(* *.login(..))" />
// <aop:aspect ref="myAspect">
// <aop:before pointcut-ref="loginHelpers" method="beforeLogin" />
// <aop:after pointcut-ref="loginHelpers" method="afterLogin" />
// </aop:aspect>
// </aop:config>
public static void main(String[] args) {
ApplicationContext appCtx = new FileSystemXmlApplicationContext("application.xml");
IUserDao userDao = (IUserDao) appCtx.getBean("userDao");
userDao.login();
}
}
<file_sep>/test/src/main/java/com/tivon/server/ioc3/PhoneCall.java
package com.tivon.server.ioc3;
public interface PhoneCall {
public void responseCall(String mess);
}
<file_sep>/test/src/main/java/com/tivon/server/ioc2/User.java
package com.tivon.server.ioc2;
public class User {
public void testResponseCall() {
PhoneCall call = new AndroidPhone();
call.responseCall(" i am android phone");
}
}
<file_sep>/test/src/main/java/com/tivon/server/aop/Test.java
package com.tivon.server.aop;
public class Test {
// AOP 资料:
// http://blog.csdn.net/h_xiao_x/article/details/72774496
// https://www.jianshu.com/p/f51bdde15191
// https://www.cnblogs.com/gaopeng527/p/5290997.html
}
<file_sep>/test/src/main/java/com/tivon/server/ioc3/Director.java
package com.tivon.server.ioc3;
public class Director {
public void direct() {
PhoneCall phoneCall = new AndroidPhone();
User user = new User();
//①调用属性Setter方法注入
user.setPhoneCall(phoneCall);
user.responseCall();
}
}
<file_sep>/test/src/main/java/com/tivon/server/test/SampleController.java
package com.tivon.server.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
@RequestMapping(value = "/greeting")
public ModelAndView test(ModelAndView mv) {
mv.setViewName("/fragments");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
@RequestMapping(value = "/main")
public ModelAndView main(ModelAndView mv) {
mv.setViewName("/view/main");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
@RequestMapping(value = "/login")
public ModelAndView login(ModelAndView mv) {
mv.setViewName("/view/login.html");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
<file_sep>/test/src/main/java/com/tivon/server/ioc/User.java
package com.tivon.server.ioc;
public class User {
public void testResponseCall() {
AndroidPhone phone = new AndroidPhone();
phone.responseCall(" i am android phone");
}
}
<file_sep>/test/src/main/java/com/tivon/server/ioc4/Test.java
package com.tivon.server.ioc4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// http://www.importnew.com/14751.html
// <!--IOC ①实现类实例化-->
// <bean id="geli" class="com.tivon.server.ioc4.LiuDeHua"/>
// <!--②通过geli-ref建立依赖关系-->
// <bean id="moAttack" class="com.tivon.server.ioc4.MoAttack">
// <property name="geli" ref="geli"/>
// </bean>
ApplicationContext appCtx = new FileSystemXmlApplicationContext("application.xml");
User user = (User) appCtx.getBean("moAttack");
user.responseCall();
}
}
<file_sep>/test/src/main/java/com/tivon/server/sql/SqlMain.java
package com.tivon.server.sql;
public class SqlMain {
public static void main(String[] args) {
//sql server
//uuid : newid();
//1.修改表字段:ALTER TABLE t_user ALTER COLUMN upass VARCHAR(255);
//2.datetime and datetime2 : datetime2精确度高;
//3.datetimeoffset - 时区
//4. timestamp 是二进制数字,它表明数据库中数据修改发生的相对顺序;最初是为了支持 SQL Server 恢复算法
}
}
<file_sep>/test/src/main/java/com/tivon/server/aop2/TestMain2.java
package com.tivon.server.aop2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestMain2 {
//
//
// <!-- 定义被代理者 -->
//<!-- <bean id="userDao" class="com.tivon.server.aop.UserDao"></bean> -->
//
// <!-- 定义通知内容,也就是切入点执行前后需要做的事情 -->
// <!-- <bean id="loginHelper" class="com.tivon.server.aop.LoginHelper"></bean> -->
//
// <!-- 定义切入点位置 -->
// <!-- <bean id="loginPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
// <property name="pattern" value=".*login"></property>
// </bean> -->
//
// <!-- 使切入点与通知相关联,完成切面配置 -->
// <!-- <bean id="loginHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
// <property name="advice" ref="loginHelper"></property>
// <property name="pointcut" ref="loginPointcut"></property>
// </bean> -->
//
// <!-- 设置代理 -->
// <!-- <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
// 代理的对象,有睡觉能力
// <property name="target" ref="userDao"></property>
// 使用切面
// <property name="interceptorNames" value="loginHelperAdvisor"></property>
// 代理接口,睡觉接口
// <property name="proxyInterfaces" value="com.tivon.server.aop.IUserDao"></property>
// </bean> -->
//
//https://blog.csdn.net/zhangliangzi/article/details/52334964
public static void main(String[] args) {
//AOP : Aspect Oriented Program
//aspectjweaver
//aspectjrt
//spring-aop
//如果是web项目,则使用注释的代码加载配置文件,这里是一般的Java项目,所以使用下面的方式
ApplicationContext appCtx = new FileSystemXmlApplicationContext("application.xml");
IUserDao userDao = (IUserDao)appCtx.getBean("proxy");
userDao.login();
}
}
| 7615d384e76a0cd5982f3b263f068fba0c2eedb6 | [
"Java"
] | 10 | Java | tivonY/Demo | b049d050809aa2d66312352fbe2b1199a13ef191 | 3131e0169a10c2c192ac5ba243da9009b6918aab | |
refs/heads/master | <repo_name>wagmarcel/oisp-sdk-go<file_sep>/cmd/test_api.go
package main
import (
"fmt"
"os"
"github.com/oisp-sdk-go/pkg/oispapi"
)
func main() {
username := os.Getenv("OISP_USERNAME")
password := os.Getenv("OISP_PASSWORD")
url := os.Getenv("OISP_URL")
api, err := oispapi.NewOispAPIFromUser(username, password, url)
if err != nil {
fmt.Println("Error while trying to get token", err)
}
fmt.Println("Received token ", api)
api, err = oispapi.NewOispAPIFromToken(api.GetToken(), url)
if err != nil {
fmt.Println("Error while trying to get token", err)
}
fmt.Println("Received token ", api)
devices, err := api.GetDevices()
if err != nil {
fmt.Println("Error while trying to get devices", err)
}
fmt.Println("Retrieved devices: ", devices)
device := oispapi.Device{
DeviceID: "11-22-33-44-55-66",
Name: "MyGoDevice",
Tags: []string{"hello", "world"},
GatewayID: "mygogateway",
}
err = api.CreateDevice(&device)
if err != nil {
fmt.Println("Error while creating device:", err)
} else {
fmt.Println("Device created successfully")
}
newdevice, err := api.GetDevice(device.DeviceID)
if err != nil {
fmt.Println("Error while retrieving device: ", err)
}
fmt.Println("Device retrieved: ", newdevice)
updateDevice := oispapi.Device{
DeviceID: device.DeviceID,
Name: "MyGoDevice2",
Tags: []string{"hello2", "world2"},
GatewayID: "mygogateway2",
}
err = api.UpdateDevice(&updateDevice)
if err != nil {
fmt.Println("Error while updating device:", err)
} else {
fmt.Println("Device updated successfully")
}
err = api.DeleteDevice(device.DeviceID)
if err != nil {
fmt.Println("Error deleting device:", err)
} else {
fmt.Println("Device deleted successfully")
}
}
<file_sep>/pkg/oispapi/auth.go
package oispapi
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
type getTokenRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type getTokenResponse struct {
Token string `json:"token"`
}
type getAuthTokenInfoResponse struct {
Payload struct {
UserID string `json:"sub"`
Accounts []Account `json:"accounts"`
} `json:"payload"`
}
const getTokenPath = "/v1/api/auth/token"
const getAuthTokenInfoPath = "/v1/api/auth/tokenInfo"
//GetUserToken is creating the user token from username and password
//Caution: Should not be used for long term services! The token is only valid
//for limited time (e.g. 1h)
func (o *Oispapi) getUserToken(username string, password string) error {
body := &getTokenRequest{Username: username, Password: <PASSWORD>}
jsonValue, _ := json.Marshal(body)
response, err := http.Post(o.url+getTokenPath, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
return err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode != 200 {
return errors.New(string(responseData))
}
responseObject := getTokenResponse{}
json.Unmarshal(responseData, &responseObject)
o.token = responseObject.Token
return nil
}
//getAuthTokenInfo is retrieving the details of a token
func (o *Oispapi) getAuthTokenInfo() error {
client := &http.Client{}
req, _ := http.NewRequest("GET", o.url+getAuthTokenInfoPath, nil)
setHeaders(req, o.token)
response, err := client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode != 200 {
return errors.New(string(responseData))
}
responseObject := getAuthTokenInfoResponse{}
json.Unmarshal(responseData, &responseObject)
o.accounts = responseObject.Payload.Accounts
o.userID = responseObject.Payload.UserID
return nil
}
<file_sep>/pkg/oispapi/devices.go
package oispapi
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
const getDevicesPath = "/v1/api/accounts/{accountId}/devices"
const getOneDevicePath = "/v1/api/accounts/{accountId}/devices/{deviceId}"
//GetDevices is retrieving the list of devices of active account
func (o *Oispapi) GetDevices() (*[]Device, error) {
client := &http.Client{}
replacements := map[string]string{"accountId": o.accounts[o.activAccount].ID}
url := makeURL(o.url, getDevicesPath, replacements)
req, _ := http.NewRequest("GET", url, nil)
setHeaders(req, o.token)
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, errors.New(string(responseData))
}
responseObject := []Device{}
json.Unmarshal(responseData, &responseObject)
return &responseObject, nil
}
//CreateDevice is creating a new device
func (o *Oispapi) CreateDevice(device *Device) error {
client := &http.Client{}
replacements := map[string]string{"accountId": o.accounts[o.activAccount].ID}
url := makeURL(o.url, getDevicesPath, replacements)
jsonBody, _ := json.Marshal(device)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
setHeaders(req, o.token)
response, err := client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode != 201 {
return errors.New(string(responseData))
}
responseObject := []Device{}
json.Unmarshal(responseData, &responseObject)
return nil
}
//GetDevice is retrieving the list of devices of active account
func (o *Oispapi) GetDevice(deviceID string) (*Device, error) {
client := &http.Client{}
replacements := map[string]string{
"accountId": o.accounts[o.activAccount].ID,
"deviceId": deviceID,
}
url := makeURL(o.url, getOneDevicePath, replacements)
req, _ := http.NewRequest("GET", url, nil)
setHeaders(req, o.token)
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, errors.New(string(responseData))
}
responseObject := Device{}
json.Unmarshal(responseData, &responseObject)
return &responseObject, nil
}
//UpdateDevice is updating a new device
func (o *Oispapi) UpdateDevice(device *Device) error {
client := &http.Client{}
replacements := map[string]string{"accountId": o.accounts[o.activAccount].ID,
"deviceId": device.DeviceID,
}
url := makeURL(o.url, getOneDevicePath, replacements)
updatedDevice := Device(*device)
updatedDevice.DeviceID = ""
jsonBody, _ := json.Marshal(updatedDevice)
req, _ := http.NewRequest("PUT", url, bytes.NewBuffer(jsonBody))
setHeaders(req, o.token)
response, err := client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode != 200 {
return errors.New(string(responseData))
}
responseObject := []Device{}
json.Unmarshal(responseData, &responseObject)
return nil
}
//DeleteDevice is deleting a device
func (o *Oispapi) DeleteDevice(deviceID string) error {
client := &http.Client{}
replacements := map[string]string{
"accountId": o.accounts[o.activAccount].ID,
"deviceId": deviceID,
}
url := makeURL(o.url, getOneDevicePath, replacements)
req, _ := http.NewRequest("DELETE", url, nil)
setHeaders(req, o.token)
response, err := client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode != 204 {
return errors.New(string(responseData))
}
return nil
}
<file_sep>/pkg/oispapi/oispapi.go
package oispapi
import (
"net/http"
"regexp"
)
// Oispapi is managing an API session
type Oispapi struct {
token string
url string
accounts []Account
userID string
activAccount int
}
// Account contains the detail of one account
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
}
// Device contains the device details
type Device struct {
DeviceID string `json:"deviceId,omitempty"`
Name string `json:"name,omitempty"`
GatewayID string `json:"gatewayId,omitempty"`
DomainID string `json:"domainId,omitempty"`
Status string `json:"status,omitempty"`
Created int64 `json:"created,omitempty"`
Attributes map[string]string `json:"attributes,omitempty"`
Tags []string `json:"tags,omitempty"`
Components []Component `json:"components,omitempty"`
Contact string `json:"contact,omitempty"`
Loc []float64 `json:"loc,omitempty"`
Description string `json:"desription,omitempty"`
}
// Component reprecents a single device component
type Component struct {
CID string `json:"cid"`
Name string `json:"name"`
ComponentTypeID string `json:"componentTypeId"`
Type string `json:"type"`
ComponentType ComponentType `json:"componentType"`
}
// ComponentType describe the details of a component type
type ComponentType struct {
CTID string `json:"_id"`
ID string `json:"id"`
DomainID string `json:"domainID"`
Dimension string `json:"dimension"`
Default string `json:"default"`
Display string `json:"display"`
Format string `json:"format"`
Measureunit string `json:"measureunit"`
Version string `json:"version"`
Type string `json:"type"`
DataType string `json:"dataType"`
Min string `json:"min"`
Max string `json:"max"`
}
func setHeaders(req *http.Request, token string) {
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
}
// NewOispAPIFromToken is initiating the Oispapi struct from a user token
func NewOispAPIFromToken(token string, url string) (*Oispapi, error) {
o := &Oispapi{
token: token,
url: url,
}
err := o.getAuthTokenInfo()
if err != nil {
return nil, err
}
return o, nil
}
// NewOispAPIFromUser is initiating the Oispapi struct from username/password
func NewOispAPIFromUser(username string, password string, url string) (*Oispapi, error) {
o := &Oispapi{
url: url,
}
err := o.getUserToken(username, password)
if err != nil {
return nil, err
}
err = o.getAuthTokenInfo()
if err != nil {
return nil, err
}
return o, nil
}
func makeURL(url string, path string, replacements map[string]string) string {
replaced := path
for k, v := range replacements {
re := regexp.MustCompile(`(\{` + k + `\})`)
replaced = re.ReplaceAllString(replaced, v)
}
return url + replaced
}
// GetToken returns the access token value
func (o *Oispapi) GetToken() string {
return o.token
}
| 89398cf03aa2738f4323373f0dba48c5c6c3831b | [
"Go"
] | 4 | Go | wagmarcel/oisp-sdk-go | bd8de961654a90e65421ad5a0524fc949333f123 | 8a864ddc4849bcbc5f397f31730de8f7b03113dd | |
refs/heads/main | <file_sep>N = input()
sizeN = len(N)
minval = int(N) - 9*sizeN if int(N) - 9*sizeN >= 0 else 0
maxval = int(N) + 1
for num in range(minval, maxval):
listNum = list(map(int, str(num)))
if int(N) == num + sum(listNum):
print(num)
break
elif int(N) == num:
print(0)<file_sep>N = int(input())
numbers = []
for i in range(N):
numbers.append(int(input()))
for i in range(N-1):
for j in range(i, N):
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
for num in numbers:
print(num)
<file_sep>import math
T = int(input())
case = []
for i in range(T):
case.append(input().split())
for idx in case:
x1, y1, r1, x2, y2, r2 = map(int, idx)
dist = math.sqrt(pow((x2-x1),2)+pow((y2-y1),2))
r = [r1, r2, dist]
mr = max(r)
r.remove(mr)
if dist==0 and r1==r2:
print("-1")
elif dist==r1+r2 or mr==sum(r):
print("1")
elif mr > sum(r):
print("0")
else:
print("2") <file_sep>n = int(input())
words = []
for i in range(0, n):
words.append(input())
count = n
for word in words:
for i in range(0, len(word)-1):
if word[i] == word[i+1]:
pass
else:
if word[i] in word[(i+1):]:
count -= 1
break
print(count)<file_sep>import math
T = int(input())
xy = []
for i in range(T):
x, y = map(int, input().split())
xy.append((x,y))
for xx, yy in xy:
count = 0
dist = yy - xx
sq = round(math.sqrt(dist))
if sq*sq < dist <= sq*sq + sq:
count = 2*sq
else:
count = 2*sq - 1
print(count)
'''
20 12344321 4^2+4 8 4.xxx
25 123454321 5^2 9 5
30 1234554321 5^2+5 10(2i) 5.xxx
36 12345654321 6^6 11(2i-1) 6
'''<file_sep>import sys
sys.setrecursionlimit(100000)
needed = 0
def calMoney(price, count):
global needed
needed += price*count
if count > 0:
return calMoney(price, count-1)
else:
return needed
def solution(price, money, count):
rest = money - calMoney(price, count)
answer = -1*rest if rest<0 else 0
return answer<file_sep>from itertools import combinations
N, M = map(int, input().split())
cards = list(map(int, input().split()))
cmb = list(combinations(cards, 3))
s = []
for idx in cmb:
s.append(M-sum(idx))
minval = 100001
minarg = -1
for idx, value in enumerate(s):
if 0 <= value < minval:
minval = value
minarg = idx
print(sum(cmb[minarg]))<file_sep>def Fibonacci(k):
if k > 2:
return Fibonacci(k-1) + Fibonacci(k-2)
elif k==1 or k==2:
return 1
else:
return 0
n = int(input())
print(Fibonacci(n))<file_sep>A, B, V = map(int, input().split())
day=0
step = A - B
h = V - A
if h%step == 0:
day = h // step +1
else:
day = h // step +2
print(day) | f670f54ad0a412c0985cb2d8dfcab461fd829e95 | [
"Python"
] | 9 | Python | kwang4372/ProblemSolving | 4d0a42cb545759a627bf295c64799dfa39092ad7 | b4b763ad9e51ba8981535fa8d7e155af6c188ab4 | |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TagsService {
private tags = [
'All',
'Web',
'Database',
'API',
'Fullstack',
'DevOps',
'Operating Systems',
'Embedded Systems',
'Machine Learning',
'Game Development',
'Cloud Computing',
'Programming Languages'
];;
constructor() { }
async getTags(): Promise<string[]> {
return this.tags;
}
}
<file_sep>export const environment = {
production: true,
BASE_API_URL: 'https://api-m5xbm75jva-uc.a.run.app'
};
<file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Project } from '../types/project';
@Injectable({
providedIn: 'root'
})
export class ProjectsService {
constructor(private http: HttpClient) { }
async searchProjects(query: string, tags: string[]) {
}
async getProjects(): Promise<Project[]> {
return await this.http.get<Project[]>(`${environment.BASE_API_URL}/projects`).toPromise();
}
async getProject(id: string): Promise<Project> {
return await this.http.get<Project>(`${environment.BASE_API_URL}/projects/${id}`).toPromise();
}
async createProject(project: Project): Promise<void> {
await this.http.post(`${environment.BASE_API_URL}/projects`, project, { withCredentials: true }).toPromise();
}
async updateProject(id: string, project: Partial<Project>) {
await this.http.patch(`${environment.BASE_API_URL}/projects/${id}`, project, { withCredentials: true }).toPromise();
}
async deleteProject(id: string) {
await this.http.delete(`${environment.BASE_API_URL}/projects/${id}`).toPromise();
}
async getAuthorProjects(authId: string): Promise<Project[]> {
return await this.http.get<Project[]>(`${environment.BASE_API_URL}/users/${authId}/projects`).toPromise();
}
}
<file_sep>import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
constructor(@Inject(DOCUMENT) private document: Document) { }
ngOnInit(): void {
console.log(environment.BASE_API_URL);
}
login() {
this.document.location.href = environment.BASE_API_URL + '/google';
}
}
<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { environment } from 'src/environments/environment';
import { User } from '../types/user';
export const COOKIE = 'hackhub';
@Injectable({
providedIn: 'root'
})
export class UserService {
private _user: { id: string, name: string, email: string, profileURL: string } = null;
constructor(private http: HttpClient, private cookieService: CookieService) { }
async getUser(id: string): Promise<User> {
return await this.http.get<User>(`${environment.BASE_API_URL}/users/${id}`).toPromise();
}
async getUsers(): Promise<User[]> {
return await this.http.get<User[]>(`${environment.BASE_API_URL}/users`).toPromise();
}
async updateUser(id: string, updates: Partial<User>) {
await this.http.patch(`${environment.BASE_API_URL}/users/${id}`, updates).toPromise()
}
async deleteUser(id: string) {
await this.http.delete(`${environment.BASE_API_URL}/users/${id}`).toPromise();
}
async user() {
if (!this._user) {
this._user = await this.http.get<any>(`${environment.BASE_API_URL}/users/token`, { withCredentials: true }).toPromise();
}
return this._user;
}
getCookie() {
if (this.cookieService.check(COOKIE)) {
return this.cookieService.get(COOKIE);
} else {
throw new Error('User is not logged in!');
}
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ProjectsService } from 'src/app/services/projects.service';
import { UserService } from 'src/app/services/user.service';
import { Project } from 'src/app/types/project';
@Component({
selector: 'app-project-popup',
templateUrl: './project-popup.component.html',
styleUrls: ['./project-popup.component.scss']
})
export class ProjectPopupComponent implements OnInit {
mode: string;
model: Project = {
authorID: '',
name: '',
description: '',
repositoryURL: null
}
constructor(private projectsService: ProjectsService, private userService: UserService, private dialogRef: MatDialogRef<ProjectPopupComponent>, @Inject(MAT_DIALOG_DATA) data) {
this.mode = data.mode;
if (this.mode === 'update') {
this.model = data.params;
}
}
ngOnInit(): void {
}
async submit() {
switch(this.mode) {
case 'create':
const user = (await this.userService.user()).id;
this.model.authorID = user;
await this.projectsService.createProject(this.model);
break;
case 'update':
await this.projectsService.updateProject(this.model._id, this.model);
break;
}
this.cancel();
}
cancel() {
this.dialogRef.close();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { TagsService } from 'src/app/services/tags.service';
@Component({
selector: 'app-searchbar',
templateUrl: './searchbar.component.html',
styleUrls: ['./searchbar.component.scss']
})
export class SearchbarComponent implements OnInit {
tags: string[] = [];
constructor(private tagsService: TagsService) { }
async ngOnInit(): Promise<void> {
this.tags = await this.tagsService.getTags();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ProjectsService } from '../services/projects.service';
import { UserService } from '../services/user.service';
import { Project } from '../types/project';
import { ProjectPopupComponent } from './project-popup/project-popup.component';
@Component({
selector: 'app-author-dashboard',
templateUrl: './author-dashboard.component.html',
styleUrls: ['./author-dashboard.component.scss']
})
export class AuthorDashboardComponent implements OnInit {
projects: Project[] = [];
constructor(private projectService: ProjectsService, private userService: UserService, private dialog: MatDialog) { }
async ngOnInit(): Promise<void> {
await this.detectChange();
}
async openCreateProjectPopup() {
const dialogRef = this.dialog.open(ProjectPopupComponent, {
data: { mode: 'create' }
});
await dialogRef.afterClosed().toPromise()
await this.detectChange();
}
async detectChange() {
const user = (await this.userService.user()).id;
this.projects = await this.projectService.getAuthorProjects(user);
}
}
<file_sep>FROM nginx:alpine
COPY /dist/hackhub-client /usr/share/nginx/html
EXPOSE 80<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ProjectsService } from 'src/app/services/projects.service';
@Component({
selector: 'app-delete-confirm',
templateUrl: './delete-confirm.component.html',
styleUrls: ['./delete-confirm.component.scss']
})
export class DeleteConfirmComponent implements OnInit {
mode: string;
id: string;
constructor(private projectsService: ProjectsService, private dialogRef: MatDialogRef<DeleteConfirmComponent>, @Inject(MAT_DIALOG_DATA) data) {
this.mode = data.mode;
this.id = data.params
}
ngOnInit(): void {
}
async submit() {
await this.projectsService.deleteProject(this.id);
this.cancel();
}
cancel() {
this.dialogRef.close();
}
}
<file_sep>import { Tag } from './tags';
export class Project {
_id?: string;
authorID: string;
name: string;
description: string;
repositoryURL?: string;
tags?: Tag[];
}<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ProjectPopupComponent } from './author-dashboard/project-popup/project-popup.component';
import { MatDialogModule } from "@angular/material/dialog";
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './shared/navbar/navbar.component';
import { SearchbarComponent } from './shared/searchbar/searchbar.component';
import { ProjectsComponent } from './projects/projects.component';
import { ProjectCardComponent } from './shared/project-card/project-card.component';
import { ProjectDetailsComponent } from './project-details/project-details.component';
import { AuthorDashboardComponent } from './author-dashboard/author-dashboard.component';
import { ProjectTileComponent } from './author-dashboard/project-tile/project-tile.component';
import { FormsModule } from '@angular/forms';
import { DeleteConfirmComponent } from './author-dashboard/delete-confirm/delete-confirm.component';
import { CookieService } from 'ngx-cookie-service';
import { AuthInterceptor } from './services/auth.intercepter';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
SearchbarComponent,
ProjectsComponent,
ProjectCardComponent,
ProjectDetailsComponent,
AuthorDashboardComponent,
ProjectTileComponent,
ProjectPopupComponent,
DeleteConfirmComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatDialogModule,
FormsModule,
HttpClientModule,
],
providers: [
CookieService,
{
provide : HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi : true,
},
],
bootstrap: [AppComponent],
entryComponents: [ProjectPopupComponent, DeleteConfirmComponent]
})
export class AppModule { }
<file_sep>export const environment = {
production: true,
BASE_API_URL: 'https://api-staging-m5xbm75jva-uc.a.run.app'
};<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ProjectsService } from '../services/projects.service';
import { UserService } from '../services/user.service';
import { Project } from '../types/project';
import { User } from '../types/user';
@Component({
selector: 'app-project-details',
templateUrl: './project-details.component.html',
styleUrls: ['./project-details.component.scss']
})
export class ProjectDetailsComponent implements OnInit {
project: Project;
author: User;
constructor(private route: ActivatedRoute, private projectService: ProjectsService, private userService: UserService) { }
async ngOnInit(): Promise<void> {
const id = this.route.snapshot.paramMap.get('id');
this.project = await this.projectService.getProject(id);
this.author = await this.userService.getUser(this.project.authorID);
}
}
<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Project } from 'src/app/types/project';
import { DeleteConfirmComponent } from '../delete-confirm/delete-confirm.component';
import { ProjectPopupComponent } from '../project-popup/project-popup.component';
@Component({
selector: 'app-project-tile',
templateUrl: './project-tile.component.html',
styleUrls: ['./project-tile.component.scss']
})
export class ProjectTileComponent implements OnInit {
@Input() project: Project;
@Output() detectChange = new EventEmitter<boolean>();
constructor(private dialog: MatDialog) { }
ngOnInit(): void {
}
async updateProject() {
const dialogRef = this.dialog.open(ProjectPopupComponent, {
data: { mode: 'update', params: this.project }
});
await dialogRef.afterClosed().toPromise();
this.detectChange.emit(true);
}
async deleteProject() {
const dialogRef = this.dialog.open(DeleteConfirmComponent, {
data: { mode: 'project', params: this.project._id }
});
await dialogRef.afterClosed().toPromise();
this.detectChange.emit(true);
}
}
| 1538d3241dbf53d47e1b8628d84314f3db0632df | [
"TypeScript",
"Dockerfile"
] | 15 | TypeScript | EVogel1999/hackhub-client | 5e961eda1bea2d859aa1e48505d9fe8c1f1d52a0 | f7500b7297456febecc4331da7f572f976959fd9 | |
refs/heads/working | <file_sep>// generated on <%= date %> using <%= name %> <%= version %>
const gulp = require('gulp');
const gulpLoadPlugins = require('gulp-load-plugins');
const browserSync = require('browser-sync').create();
const del = require('del');
const inlineCss = require('gulp-inline-css');
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
gulp.task('html', () => {
return gulp.src('app/*.html')
.pipe($.useref({searchPath: ['app', '.']}))
.pipe(inlineCss())
.pipe(gulp.dest('dist'));
});
gulp.task('images', () => {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling
svgoPlugins: [{cleanupIDs: false}]
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('extras', () => {
return gulp.src([
'app/*.*',
'!app/*.html'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', del.bind(null, ['dist']));
gulp.task('serve', () => {
browserSync.init({
notify: false,
port: 9000,
server: {
baseDir: ['app']
}
});
gulp.watch([
'app/*.html',
'app/images/**/*'
]).on('change', reload);
});
gulp.task('serve:dist', () => {
browserSync.init({
notify: false,
port: 9000,
server: {
baseDir: ['dist']
}
});
});
gulp.task('build', ['html', 'images', 'extras'], () => {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], () => {
gulp.start('build');
});
<file_sep># Email generator [![Build Status](https://secure.travis-ci.org/jeffreysbrother/generator-ninthlink-email.svg?branch=working)](http://travis-ci.org/jeffreysbrother/generator-ninthlink-email)
> [Yeoman](http://yeoman.io) generator that scaffolds out an HTML email using [gulp](http://gulpjs.com/) for the build process
## Generator Features
Please see our [gulpfile](app/templates/gulpfile.js) for up to date information on what we support.
* gulp-inline-css
* Built-in preview server with BrowserSync
* Awesome image optimization
* The gulpfile makes use of [ES2015 features](https://babeljs.io/docs/learn-es2015/) by using [Babel](https://babeljs.io)
*For more information on what this generator can do for you, take a look at the [gulp plugins](app/templates/_package.json) used in our `package.json`.*
## Template Features
1. table-based, modular HTML email optimized for Gmail App and iOS Apple Mail App
2. no media queries; container width of 600px
3. use of rems and ems so that each module can be resized independently
4. thoroughly-documented, tested, and validated code
5. CSS fix for superscript HTML entities (®) -- line-height distortion is anticipated and eliminated
6. Includes an HTML snippet that fixes Gmail's attempt to automatically resize fonts. A discussion of this can be found [here](http://freshinbox.com/blog/gmail-on-ios-increases-font-size-on-some-emails/). The code is included just before the closing body tag.
7. added `display:table-cell;` to all images nested within links, in order to make sure that the link doesn't extend beyond the image. This has the effect of making the layout more balanced since links extending beyond the image borders was similar to adding padding to one side of the image.
## Getting Started
- Install dependencies: `npm install --global yo gulp-cli bower`
- Install the generator: `npm install --global generator-ninthlink-email`
- Run `yo ninthlink-email` to scaffold your webapp
- Run `gulp serve` to preview and watch for changes
- Run `gulp` to build your webapp for production
- Run `gulp serve:dist` to preview the production build
## License
[BSD license](http://opensource.org/licenses/bsd-license.php)
<file_sep>'use strict';
const Generator = require('yeoman-generator');
const yosay = require('yosay');
const chalk = require('chalk');
const mkdirp = require('mkdirp');
const _s = require('underscore.string');
module.exports = class extends Generator {
constructor(args, opts) {
super(args, opts);
// generators.Base.apply(this, arguments);
this.option('babel', {
desc: 'Use Babel',
type: Boolean,
defaults: false
});
}
initializing() {
this.pkg = require('../package.json');
}
prompting() {
this.log(yosay('You wanna make a damn email? Well, that\'s SWELL.'));
var prompts = [{
type: 'confirm',
name: 'includeAddress',
message: 'Include an address section below the footer?',
default: true
}];
return this.prompt(prompts).then(function (answers) {
var features = answers.features;
function hasFeature(feat) {
return features && features.indexOf(feat) !== -1;
};
// manually deal with the response, get back and store the results.
// we change a bit this way of doing to automatically do this in the self.prompt() method.
this.includeAddress = answers.includeAddress;
}.bind(this));
}
writing() {
this._gulpfile();
this._packageJSON();
this._bower();
this._babel();
this._git();
this._editorConfig();
this._html();
this._misc();
}
_gulpfile() {
this.fs.copyTpl(
this.templatePath('gulpfile.js'),
this.destinationPath('gulpfile.js'),
{
date: (new Date).toISOString().split('T')[0],
name: this.pkg.name,
version: this.pkg.version,
includeBabel: this.options['babel']
}
);
}
_packageJSON() {
this.fs.copyTpl(
this.templatePath('_package.json'),
this.destinationPath('package.json'),
{
includeBabel: this.options['babel']
}
);
}
// if the bower.json file is not created, Yeoman will complain
_bower() {
var bowerJson = {
name: 'html-email',
private: true,
dependencies: {}
};
this.fs.writeJSON('bower.json', bowerJson);
}
_babel() {
this.fs.copy(
this.templatePath('babelrc'),
this.destinationPath('.babelrc')
);
}
_git() {
this.fs.copy(
this.templatePath('gitignore'),
this.destinationPath('.gitignore'));
this.fs.copy(
this.templatePath('gitattributes'),
this.destinationPath('.gitattributes'));
}
_editorConfig() {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
}
_html() {
this.fs.copyTpl(
this.templatePath('index.html'),
this.destinationPath('app/index.html'),
{
appname: this.appname,
includeAddress: this.includeAddress
}
);
}
_misc() {
mkdirp('app/images');
}
install() {
this.installDependencies({
skipInstall: this.options['skip-install']
});
}
end() {
var howToInstall =
'\nAfter running ' +
chalk.yellow.bold('npm install') +
', inject your' +
'\nfront end dependencies by running ' +
chalk.yellow.bold('gulp wiredep') +
'.';
if (this.options['skip-install']) {
this.log(howToInstall);
return;
}
}
}
| 3723068195b0339891706295c28f878dd182c90d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jeffreysbrother/generator-ninthlink-email | 85b21cb7c2cf12e403a87da029392f85b2760656 | f16307edb60cb80814b5a55eda689f9132cef267 | |
refs/heads/master | <repo_name>jserranochen/Asignacion-1-2led<file_sep>/Tarea 1/Tarea 1/main.c
/*
* Tarea 1.c
*
* Created: 06/11/2020 1:06:47 p. m.
* Author : Josue
*/
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
DDRB |= (1<<PORTB4);
DDRB |= (1<<PORTB6);
DDRA &= ~(1<<PORTA2);
PORTB = (0 << PORTB4);
PORTB = (0 << PORTB6);
PORTA = (1<<PORTA2);
while (1)
{
if (PINA & (1<<PORTA2))
{
PORTB|=(1<<PORTB6);
_delay_ms(1000);
PORTB &=~(1<<PORTB4);
_delay_ms(1000);
}
else
{
PORTB &=~(1<<PORTB6);
_delay_ms(1000);
PORTB|=(1<<PORTB4);
_delay_ms(1000);
}
}
} | df2ea6c4af94efe128f9414e75024f7d026cf3d0 | [
"C"
] | 1 | C | jserranochen/Asignacion-1-2led | a2fbc84dcbfc8feb06a864286ac8a317be339404 | a7fd63ef6449a0e81d645b6d4165eb4e6064117c | |
refs/heads/master | <file_sep>package edu.javacourse.register.business;
// класс, исполняющий бизнес-логику
// Вызывается классом MarriageController, вызывает MarriageDao
import edu.javacourse.register.dao.MarriageDao;
import edu.javacourse.register.dao.PersonDao;
import edu.javacourse.register.domain.MarriageCertificate;
import edu.javacourse.register.domain.Person;
import edu.javacourse.register.domain.PersonFemale;
import edu.javacourse.register.domain.PersonMale;
import edu.javacourse.register.view.MarriageRequest;
import edu.javacourse.register.view.MarriageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
@Service("marriageService") //(специализация @Component) обычно используется если класс предостовляет какой-то бизнес-функционал
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) // область видимости бинов (singleton или prototype)
public class MarriageManager {
private static final Logger LOGGER = LoggerFactory.getLogger(MarriageManager.class);
// при запуске MarriageManager, создается MarriageDao и PersonDao (оба в одном экземпляре)
@Autowired // механизм автоматического связывания бинов
private MarriageDao marriageDao;
@Autowired // механизм автоматического связывания бинов
private PersonDao personDao;
// с помощью данных, пришедших в request, необходимо проверить, зарегистрирован ли брак
@Transactional // Определение области действия одной транзакции БД (метод findMarriageCertificate)
public MarriageResponse findMarriageCertificate(MarriageRequest request) {
LOGGER.info("findMarriageCertificate called");
// добавление 3 персон
personDao.addPerson(getPerson(1));
personDao.addPerson(getPerson(2));
// получение свидетельства о браке
MarriageCertificate mc = getMarriageCertificate();
// сохранить полученное свидетельство о браке
marriageDao.saveAndFlush(mc);
// найти все сертификаты
// marriageDao.findAll();
// найти сертификаты по Id
// marriageDao.findById(1L);
// поиск по номеру, используя findByNumber
List<MarriageCertificate> list = marriageDao.findByNumber("12345");
// показать на экране, с помощью лямбда
list.forEach(m -> LOGGER.info("MC:{}", m.getMarriageCertificateId()));
LOGGER.info("----------------");
// поиск по номеру, используя findByNum
List<MarriageCertificate> list2 = marriageDao.findByNum("98765");
list2.forEach(m -> LOGGER.info("MC:{}", m.getMarriageCertificateId()));
LOGGER.info("----------------");
// поиск по номеру, используя findSomething
List<MarriageCertificate> list3 = marriageDao.findSomething("01928");
list3.forEach(m -> LOGGER.info("MC:{}", m.getMarriageCertificateId()));
return new MarriageResponse();
}
// создание MarriageCertificate
private MarriageCertificate getMarriageCertificate() {
MarriageCertificate mc = new MarriageCertificate();
mc.setIssueDate(LocalDate.now());
mc.setNumber("98765");
mc.setActive(true);
// нужно найти всех персон
List<Person> persons = personDao.findPersons();
for(Person person : persons) {
if (person instanceof PersonMale) {
mc.setHusband((PersonMale)person);
} else {
mc.setWife((PersonFemale)person);
}
}
return mc;
}
// создание новой персоны
private Person getPerson(int sex) {
Person m = sex == 1 ? new PersonMale() : new PersonFemale();
m.setFirstName("1_" + sex);
m.setLastName("2_" + sex);
m.setPatronymic("3_" + sex);
m.setDateOfBirth(LocalDate.of(1991, 3, 12));
return m;
}
}
<file_sep>package edu.javacourse.register.dao;
// класс, который вызывает EntityManager (класс, который работает непостредственно с БД)
import edu.javacourse.register.domain.MarriageCertificate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository // класс - хранилие данных (при использовании Spring Data)
// JpaRepository принимает два класса: сущность, с которой MarriageDao будет работать (MarriageCertificate)
// и тип идентификатора, который используется в dao (Long)
public interface MarriageDao extends JpaRepository<MarriageCertificate, Long> {
// Spring Data сгенерирует выдачу, по правилам именования метода,
// номер содержит какую-то подстроку
List<MarriageCertificate> findByNumber(String number);
// findByNum объявлен как NamedQuery, обращение к запросу в другом месте
// в аннотации @Param указывается имя параметра из именованного запроса
List<MarriageCertificate> findByNum(@Param("number") String number);
// у метода имеется только Query, необходимо написать запрос
@Query("SELECT mc FROM MarriageCertificate mc WHERE mc.number = :number")
List<MarriageCertificate> findSomething(@Param("number") String number);
// private static final Logger LOGGER = LoggerFactory.getLogger(MarriageCertificate.class);
//
// private EntityManager entityManager;
// // пример инициализации какого-то поля
// @Value("${test.value}") // установка значения поля, используя property файл
// private String test;
//
// public void setTest(String test) {
// this.test = test;
// }
//
// public MarriageCertificate findMarriageCertificate(MarriageRequest request){
// LOGGER.info("findMarriageCertificate called:{}", test);
//
// return null;
// }
}
<file_sep>package edu.javacourse.register;
import edu.javacourse.register.rest.MarriageController;
import edu.javacourse.register.view.MarriageRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Starter {
public static void main(String[] args) {
// создание контекста
// интерфейс верхнего уровня ApplicationContext
// принимает на вход список файлов с описанием контекста
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"springContext.xml"}
);
// // получение бина, с указанием конкретного класса
// MarriageController controller = context.getBean(MarriageController.class);
//// MarriageController controller = context.getBean("controller", MarriageController.class);
// // передача реквеста (пока пустой)
// controller.findMarriageCertificate(new MarriageRequest());
}
}
<file_sep>package edu.javacourse.register.config;
import edu.javacourse.register.dao.PersonDao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration // класс - источник определения бинов (аналог конфигурации в xml)
// необходимо прописать property файл, для его загрузки. Обычно в Configuration классе
@PropertySource(value = {"classpath:/register.properties"})
public class MarriageConfig {
@Bean // метод создает, настраивает и инициализирует новый объект, управляемый Spring IoC контейнером
public PersonDao buildPersonDao(){
System.out.println("PersonDao is created");
return new PersonDao();
}
}
<file_sep>package edu.javacourse.register.dao;
// класс, для того, чтобы вытащить список персон
import edu.javacourse.register.domain.Person;
import javax.persistence.*;
import java.util.List;
public class PersonDao {
// необходимо создать Entity Manager
@PersistenceContext // автоматическое связывание менеджера сущностей с бином (прописано в springContext.xml)
private EntityManager entityManager;
// получение списка персон
public List<Person> findPersons() {
// будет возвращен список объектов класса Person (используется язык JPAQL/HQL)
// named query (именованные запросы), экономия времени на компиляцию
Query query = entityManager.createNamedQuery("Person.findPersons");
return query.getResultList();
}
// добавление персоны в БД
public Long addPerson(Person person){
// // получение транзакции
// EntityTransaction tr = entityManager.getTransaction();
// // начало транзакции
// tr.begin();
// try{
// сохраняем персону в БД
entityManager.persist(person);
// запись сохраненных данных непосредственно в БД
entityManager.flush();
// // завершение транзакции
// tr.commit();
// } catch (Exception ex) {
// // отмена транзакции
// tr.rollback();
// throw new RuntimeException(ex);
// }
// возвращается Id персоны
return person.getPersonId();
}
}
| bf43bc81fd3b72eaac7b8e5298b1fe3be24325d6 | [
"Java"
] | 5 | Java | cisleithania/register-office | 727c3f54d22c13153a5f6d2b406344038cf6bebd | d124f7eb36d1695a741a1ea5386570407d9ed58a | |
refs/heads/main | <repo_name>pedroantonioresendefogaca/DesafioGoDev<file_sep>/run.py
from pessoa import Pessoa
from espacos import Espacos
from salas import Salas
pessoa = Pessoa()
espacos = Espacos()
salas = Salas()
while True:
try:
interface = int(input('!!!DESAFIO GODEV!!!\nInsira a operação que gostaria de realizar\n1 - Cadastro de pessoas\n2 - Consulta de pessoas\n3 - Cadastro de salas\n4 - Consulta de salas\n5 - Cadastro de espaços de café\n6 - Consulta de espaços de café\n7 - Sair\nInsira a operação desejada: '))
if interface == 1:
pessoa.cadastro_pessoas()
elif interface == 2:
pessoa.consultar_pessoas()
elif interface == 3:
salas.cadastro_salas()
elif interface == 4:
salas.consulta_salas()
elif interface == 5:
espacos.cadastro_espaços_de_café()
elif interface == 6:
espacos.consulta_espaços_de_café()
elif interface == 7:
print('Obrigado por utilizar o sistema!')
break
except ValueError:
print('Insira uma operação válida')
<file_sep>/espacos.py
class Espacos:
def __init__(self):
self.__dict_espaços_de_café = {}
def cadastro_espaços_de_café(self):
dict_espaços_de_café = self.__dict_espaços_de_café
nome_espaços = input('Nome do espaço: ')
lotação_espaços = input('Lotação do espaço: ')
dict_espaços_de_café[nome_espaços] = lotação_espaços
return dict_espaços_de_café
def consulta_espaços_de_café(self):
dict_espaços_de_café = self.__dict_espaços_de_café
print('A seguir você irá ver uma relação de cada espaço de café pela ordem de: Seu nome e lotação')
print(dict_espaços_de_café)
def consulta_espaços_de_café_cadastro_pessoa(self):
dict_espaços_de_café = self.__dict_espaços_de_café
return dict_espaços_de_café<file_sep>/salas.py
class Salas:
def __init__(self):
self.__dict_salas = {}
def cadastro_salas(self):
dict_salas = self.__dict_salas
nome_salas = input('Nome da sala: ')
lotação_salas = input('Lotação da sala: ')
dict_salas[nome_salas] = lotação_salas
return dict_salas
def consulta_salas(self):
dict_salas = self.__dict_salas
print('A seguir você irá ver uma relação de cada sala pela ordem de: Seu nome e lotação')
print(dict_salas)
def consulta_salas_cadastro_pessoa(self):
dict_salas = self.__dict_salas
return dict_salas<file_sep>/README.md
# DesafioGoDev
Python version: 3.7.5
Para executar, basta rodar o arquivo run.py<file_sep>/pessoa.py
from salas import Salas
from espacos import Espacos
class Pessoa:
def __init__(self):
self.__dict_pessoas = {}
self.__salas = Salas()
self.__espacos = Espacos()
def cadastro_pessoas(self):
dict_pessoas = self.__dict_pessoas
salas = self.__salas
espacos = self.__espacos
nome_pessoas = input('Nome: ')
sobrenome_pessoas = input('Sobrenome: ')
primeira_sala_pessoas = input(f'Primeira sala (entre {salas.consulta_salas_cadastro_pessoa()}): ')
if primeira_sala_pessoas == None:
print('Insira uma sala válida')
elif primeira_sala_pessoas not in salas.consulta_salas_cadastro_pessoa():
print('Insira uma sala válida')
else:
pass
segunda_sala_pessoas = input(f'Segunda sala (entre {salas.consulta_salas_cadastro_pessoa()}): ')
if segunda_sala_pessoas == None:
print('Insira uma sala válida')
elif segunda_sala_pessoas not in salas.consulta_salas_cadastro_pessoa():
print('Insira uma sala válida')
elif segunda_sala_pessoas == primeira_sala_pessoas:
print('Insira uma sala que não tenha sido selecionada')
else:
pass
espaço_pessoas = input(f'Espaço (entre {espacos.consulta_espaços_de_café_cadastro_pessoa()}): ')
if espaço_pessoas == None:
print('Insira um espaço válido')
elif espaço_pessoas not in espacos.consulta_espaços_de_café_cadastro_pessoa():
print('Insira um espaço válido')
else:
pass
dict_pessoas[nome_pessoas] = sobrenome_pessoas, primeira_sala_pessoas, segunda_sala_pessoas, espaço_pessoas
return dict_pessoas
def consultar_pessoas(self):
dict_pessoas = self.__dict_pessoas
print('A seguir você irá ver uma relação de cada pessoa pela ordem de: Seu nome, sobrenome, primeira e segunda sala que realizará a prova, e o espaço de café designado.')
print(dict_pessoas)
| 2a5c3641c7a57768caa9433e4c758c6cd2e5987e | [
"Markdown",
"Python"
] | 5 | Python | pedroantonioresendefogaca/DesafioGoDev | 105d6077f91523cb1e21cfeda9df91bf316d24c7 | cfb2cc1f02062762e505092ffab03e913c5f2775 | |
refs/heads/master | <file_sep>##Affordable Phone Purchase
* Write a program to calculate the total price of your phone purchase. You will keep purchasing phones (hint: loop!) until you run out of money in your bank account. You'll also buy accessories for each phone as long as your purchase amount is below your mental spending threshold.
* After you've calculated your purchase amount, add in the tax, then print out the calculated purchase amount, properly formatted.
* Finally, check the amount against your bank account balance to see if you can afford it or not.
* You should set up some constants for the "tax rate," "phone price," "accessory price," and "spending threshold," as well as a variable for your "bank account balance.""
* You should define functions for calculating the tax and for formatting the price with a "$" and rounding to two decimal places.
**This is a practice taken from <NAME>'s "You Don't Know JS"<file_sep>var SPENDING_LIMIT = 500;
var SALES_TAX = 0.09;
var PHONE = 120;
var ACCESSORY = 20;
var available_funds = 1000.01;
var cost = 0;
function totalCost(cost) {
return "$" + cost.toFixed(2);
}
// purchase of phones while funds are still avail
while (cost < available_funds) {
cost = cost + PHONE;
// if there are funds to buy accessories
if (cost < SPENDING_LIMIT) {
cost = cost + ACCESSORY;
}
}
function calculateTax(cost) {
return cost * SALES_TAX;
}
// need to incorporate sales tax
cost = cost + calculateTax(cost);
console.log(
"Your purchase: " + totalCost(cost)
);
// checks if the phone is affordable; enough money in avaialable funds
if (cost > available_funds) {
console.log(
"You do not have enough funds."
);
}
| 74f8300d3e390ffda2ca88596880e4fce8a6fd51 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | amyhliao/JS-practice | 84a3d102bc4a7273e50600037f18e3a1bf975d2a | 62cd60f38bd306b1970cc0aa34fd6918acd086fc | |
refs/heads/master | <repo_name>tusharuiit/2013_2014_VirtualPhysics<file_sep>/README.md
# 2013_2014_VirtualPhysics
I solved programming assignments in object-oriented, declarative language Modelica and applied it for computer simulation. I
modelled electrical and mechanical systems to model a car. I used extensive modeling libraries. I created my own mechanical
modeling library. I developed a real-time simulation of an electric vehicle, in the Modelica programming language.
<file_sep>/Exercise2/exercise2ml.py
#!/usr/bin/env python3
# Author <NAME> (c) 2011
from math import *
#Setting the parameters
MS = 250.0 #mass of the motocycle [kg]
MP = 70.0 #mass of the swing [kg]
R = 2.5 #Radius of the swing [m]
G = -9.81 #Gravity acceleration
phi0 = 1.25 #Initial elongation [rad]
h = 0.001 #time-step of forward Euler integration [s]
tStop = 5 #stop time [s]
#Setting the initial values
s = 0
v = 0
phi = phi0
w = 0
time = 0
#open file for ouput
fh = open("out.dat","w")
#perform time-integration
while time < tStop:
fz = MP*R*w*w;
a = (sin(phi)*fz-cos(phi)*sin(phi)*MP*G)/(MS+MP*(1-cos(phi)*cos(phi)));
z = (sin(phi)*G - cos(phi)*a)/R;
dv_dt = a
ds_dt = v
dw_dt = z
dphi_dt = w
v += h*dv_dt
s += h*ds_dt
w += h*dw_dt
phi += h*dphi_dt
time += h
print(time,"\t",v,"\t",w,fh)
print("See out.dat for simulation result")
fh.close()
| d05f7a7a9438b1cdaacdcff52964d8ca7a80f413 | [
"Markdown",
"Python"
] | 2 | Markdown | tusharuiit/2013_2014_VirtualPhysics | f7eb78ac3fdc80a1e86ca5afe19645eae88cd47d | c8c0e86a81d78cecebae8ca8c44474710c3b2b15 | |
refs/heads/master | <file_sep>import facebook
USER_TOKEN = "<KEY>"
APP_ID = ""
APP_SECRET = "<KEY>"
graph = facebook.GraphAPI(access_token=USER_TOKEN, version="3.0")
print(graph)
graph.put_object(parent_object='597998914309186', connection_name='feed', message='Hello, world')<file_sep><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/addons/p5.dom.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="/s/p5speech-m3lc.js"></script>
<srcipt src="/s/Queue.js"></script>
<script>
// eventually add to environment variables:
AUTOMATION_URL = "https://n8up.herokuapp.com/webhook/1/webhook/listen";
SENTENCE_ID = "block-yui_3_17_2_1_1593335120037_4492";
IMAGE_ID = "block-yui_3_17_2_1_1593243056431_3681";
TWEET_CHAR_LIMIT = 280;
var myRec = new p5.SpeechRec();
myRec.continuous = false;
// changes the header with the text in the argument
function changeText(newText)
{
completeText = newText;
$(document).ready(function(){
$("#" + SENTENCE_ID).find("h3")
.text(completeText);
});
setTimeout(clearText, 3*1000);
}
// removes text in the header
function clearText()
{
$(document).ready(function(){
$("#" + SENTENCE_ID).find("h3")
.text("");
});
}
// sends text to automation in n8n
// content needs to be plain text to avoids preflight CORS
function sendText(text)
{
$.ajax({
type: 'POST',
url: AUTOMATION_URL,
data: text,
contentType: "text/plain",
success: function(result) {
console.log("Received: ", result);
},
headers: {
Accept: "application/json; charset=utf-8",
}
})
}
// starts mic again for new recording
function restartMic() {
console.log("Starting mic again");
myRec.start();
}
// callback for when recording is done
function showResult()
{
if(myRec.resultValue==false)
return;
if(myRec.resultString.length > TWEET_CHAR_LIMIT) {
changeText("You said too much!");
}
else {
sendText(myRec.resultString);
changeText(myRec.resultString);
}
}
// changes cursor when hovering over image
function changeImage()
{
img = document.getElementById(IMAGE_ID).getElementsByTagName("img");
// cursor is hosted in google drive
img[0].style.cursor = "url('https://drive.google.com/uc?export=view&id=1hDk7a0P7pDODQuAsYKpH8KIx8J8ii_01'), auto";
}
function setup()
{
// NOT NEEDED:
// graphics stuff
// createCanvas(800, 400);
// background(255, 255, 255);
// fill(0, 0, 0, 255);
// textSize(32);
// textAlign(CENTER);
// text("say something", width/2, height/2);
// change style of img block
changeImage();
// set callback to restart mic
document.getElementById(IMAGE_ID).onclick = restartMic;
myRec.onResult = showResult;
}
</script>
| 251421ff96d2932ef07e756b89fb87f2dcf5feed | [
"JavaScript",
"Python"
] | 2 | Python | saisani/InstantTweet | 6e822540b50b35019b5534fa3c9742e7260df789 | 8fa75adaa86d4fa42f6b248115cbe8b81998af33 | |
refs/heads/master | <file_sep><?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'vendor/autoload.php';
//require_once 'src/InstagramScraper.php';
use InstagramScraper\Instagram;
//const MAIN_URL = "https://www.instagram.com",
//LOGIN_URL = "https://www.instagram.com/accounts/login/ajax/";
////echo 'Hello </br>';
////$response = Request::get(MAIN_URL);
//$response = Request::get(MAIN_URL);
//
//$cookie = $response->headers['Set-Cookie'];
//$cookie[0] = explode(';', $cookie[0])[0] ;
//$cookie[1] = explode(';', $cookie[1])[0] ;
//$cookie[2] = explode(';', $cookie[2])[0] ;
//$h = '';
//$crfs = '';
//foreach ($cookie as $c) {
// if (strpos($c, 'sessionid') !== false) {
// continue;
// }
// if (strpos($c, 'csrf') !== false) {
// $crfs = explode('=',$c)[1];
// }
//
// $h = $h . $c . ';';
//}
//
////echo $crfs;
//$headers = ['cookie' => $h, 'referer' => 'https://www.instagram.com/', 'x-csrftoken' => $crfs];
//$response = Request::post(LOGIN_URL, $headers, ['username' => 'debugposter8', 'password' => '<PASSWORD>']);
//echo json_encode($response);
//echo Media::getIdFromCode('z-arAqi4DP') . '<br/>';
//echo Media::getCodeFromId('936303077400215759_123123');
//echo Media::getLinkFromId('936303077400215759_123123');
//echo shorten(936303077400215759);
//echo json_encode($instagram->getMediaById('936303077400215759_123123123'));
$instagram = Instagram::withCredentials('PASTE_LOGIN', 'PASTE_PASSWORD');
$instagram->login();
echo __DIR__;
//echo json_encode($instagram->getTopMediasByTagName('hello'));<file_sep><?php
namespace InstagramScraper\Model;
class Location
{
public $id;
public $name;
public $lat;
public $lng;
function __construct()
{
}
public static function makeLocation($locationArray)
{
$location = new Location();
$location->id = $locationArray['id'];
$location->name = $locationArray['name'];
$location->lat = $locationArray['lat'];
$location->lng = $locationArray['lng'];
return $location;
}
} | 51b2ccf7511cb1b4427b13e6d5412f759d91001d | [
"PHP"
] | 2 | PHP | perminder-klair/instagram-php-scraper | b1ae4f9ea06266e64a1be81a1b188212dc254ef9 | 9973c42e7228e90d8d6de85dde8b3c59bddefb7b | |
refs/heads/master | <file_sep>package controller.page;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import common.ActorUtil;
import facade.actor.ArticleFacadeActor;
import facade.message.ArticleFacadeFindAllRequest;
import facade.message.ArticleFacadeFindAllResponse;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import javax.inject.Singleton;
import play.api.inject.Injector;
import play.mvc.Controller;
import play.mvc.Result;
import view.html.home;
@Singleton
public class HomeController extends Controller {
private final ActorRef articleFacadeActor;
@Inject
public HomeController(ActorSystem actorSystem, Injector injector) {
articleFacadeActor = actorSystem.actorOf(ActorUtil.props(ArticleFacadeActor.class, injector));
}
public CompletionStage<Result> renderHomePage() {
CompletionStage<ArticleFacadeFindAllResponse> futureResponse = ActorUtil.ask(articleFacadeActor, new ArticleFacadeFindAllRequest());
return futureResponse.thenApply(response -> ok(home.render(response.getDtos())));
}
}
<file_sep>package dao.message;
public class ArticleDaoFindAllRequest {
}
<file_sep>package dao.message;
import model.ArticleModel;
import java.util.Collection;
public class ArticleDaoFindAllResponse {
private final Collection<ArticleModel> models;
public ArticleDaoFindAllResponse(Collection<ArticleModel> models) {
this.models = models;
}
public Collection<ArticleModel> getModels() {
return models;
}
}
<file_sep>package dao.message;
import model.ArticleModel;
public class ArticleDaoUpdateRequest {
private final ArticleModel model;
public ArticleDaoUpdateRequest(ArticleModel model) {
this.model = model;
}
public ArticleModel getModel() {
return model;
}
}
<file_sep>package service.message;
import model.ArticleModel;
import java.util.Collection;
public class ArticleServiceFindAllResponse {
private final Collection<ArticleModel> models;
public ArticleServiceFindAllResponse(Collection<ArticleModel> models) {
this.models = models;
}
public Collection<ArticleModel> getModels() {
return models;
}
}
<file_sep>package facade.converter;
import common.BiConverter;
import dto.ArticleDto;
import model.ArticleModel;
import javax.inject.Singleton;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
@Singleton
public class ArticleModelDtoBiConverter extends BiConverter<ArticleModel, ArticleDto> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT);
@Override
public ArticleDto forth(ArticleModel item) {
ArticleDto dto = new ArticleDto();
dto.setId(item.getId());
dto.setTitle(item.getTitle());
dto.setDescription(item.getDescription());
dto.setDate(FORMATTER.format(item.getDate()));
dto.setContent(item.getContent());
return dto;
}
@Override
public ArticleModel back(ArticleDto item) {
return new ArticleModel(item.getId(), item.getTitle(), item.getDescription(), LocalDateTime.now(), item.getContent());
}
}
<file_sep>package controller.common;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import common.ActorUtil;
import common.Converter;
import controller.form.ArticleForm;
import dto.ArticleDto;
import facade.actor.ArticleFacadeActor;
import facade.message.ArticleFacadeCreateRequest;
import facade.message.ArticleFacadeDeleteRequest;
import facade.message.ArticleFacadeUpdateRequest;
import javax.inject.Inject;
import javax.inject.Singleton;
import play.api.inject.Injector;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
@Singleton
public class ArticleController extends Controller {
@Inject
private FormFactory formFactory;
@Inject
private Converter<ArticleForm, ArticleDto> articleFormConverter;
private final ActorRef articleFacadeActor;
@Inject
public ArticleController(ActorSystem actorSystem, Injector injector) {
articleFacadeActor = actorSystem.actorOf(ActorUtil.props(ArticleFacadeActor.class, injector));
}
@Security.Authenticated
public Result handleUpdateArticle(String id) {
Form<ArticleForm> form = formFactory.form(ArticleForm.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest();
} else {
ArticleDto dto = articleFormConverter.forth(form.get());
dto.setId(id);
articleFacadeActor.tell(new ArticleFacadeUpdateRequest(dto), articleFacadeActor);
return ok();
}
}
@Security.Authenticated
public Result handleCreateArticle() {
Form<ArticleForm> form = formFactory.form(ArticleForm.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest();
} else {
articleFacadeActor.tell(new ArticleFacadeCreateRequest(articleFormConverter.forth(form.get())), articleFacadeActor);
return ok();
}
}
@Security.Authenticated
public Result handleDeleteArticle(String id) {
articleFacadeActor.tell(new ArticleFacadeDeleteRequest(id), articleFacadeActor);
return ok();
}
}
<file_sep>package dao.message;
import model.UserModel;
public class UserDaoFindResponse {
private final UserModel model;
public UserDaoFindResponse(UserModel model) {
this.model = model;
}
public UserModel getModel() {
return model;
}
}
<file_sep>docstoreonly=true
docstore.url=http://127.0.0.1:9200
docstore.active=true
docstore.generateMapping=false
docstore.dropCreate=false
docstore.create=true<file_sep>import * as PR from 'google-code-prettify/bin/prettify.min.js';
const BROWSER_UNSUPPORTED_METHODS: Array<String> = ["PUT", "DELETE"];
function sendRequest(method: string, url: string, data: any): void {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send(data);
}
function handleUnsupportedFormMethods(): void {
let forms = document.getElementsByTagName("form");
for (let i = 0; i < forms.length; i++) {
let form = forms[i];
let method = form.getAttribute("method");
if (BROWSER_UNSUPPORTED_METHODS.indexOf(method) != -1) {
form.onsubmit = (event: Event) => {
event.preventDefault();
sendRequest(method, form.action, new FormData(form));
}
}
}
}
window.onload = () => {
PR.prettyPrint();
handleUnsupportedFormMethods();
};<file_sep>package common;
import akka.util.Timeout;
import scala.concurrent.duration.Duration;
import java.util.concurrent.TimeUnit;
public final class ActorConstant {
public static final Timeout MAX_PATTERN_ASK_TIMEOUT = Timeout.apply(Duration.apply(30, TimeUnit.SECONDS));
private ActorConstant() {}
}
<file_sep>package dao;
import model.ArticleModel;
import java.util.List;
public interface ArticleDao {
List<ArticleModel> findAll();
ArticleModel find(String id);
void create(ArticleModel model);
void update(ArticleModel model);
void delete(String id);
}
<file_sep>package dao.message;
import model.ArticleModel;
public class ArticleDaoCreateRequest {
private final ArticleModel model;
public ArticleDaoCreateRequest(ArticleModel model) {
this.model = model;
}
public ArticleModel getModel() {
return model;
}
}
<file_sep>package service;
import javax.inject.Singleton;
@Singleton
public class ArticleService {
}
<file_sep>package dao.actor;
import akka.actor.AbstractActor;
import akka.japi.pf.ReceiveBuilder;
import dao.ArticleDao;
import dao.message.ArticleDaoCreateRequest;
import dao.message.ArticleDaoDeleteRequest;
import dao.message.ArticleDaoFindAllRequest;
import dao.message.ArticleDaoFindAllResponse;
import dao.message.ArticleDaoFindRequest;
import dao.message.ArticleDaoFindResponse;
import dao.message.ArticleDaoUpdateRequest;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ArticleDaoActor extends AbstractActor {
private static final Logger LOGGER = LoggerFactory.getLogger(ArticleDaoActor.class);
private final ArticleDao articleDao;
@Inject
public ArticleDaoActor(ArticleDao articleDao) {
this.articleDao = articleDao;
receive(
ReceiveBuilder
.match(ArticleDaoFindAllRequest.class, this::findAll)
.match(ArticleDaoFindRequest.class, this::find)
.match(ArticleDaoCreateRequest.class, this::add)
.match(ArticleDaoUpdateRequest.class, this::update)
.match(ArticleDaoDeleteRequest.class, this::delete)
.matchAny(message -> LOGGER.warn("Received unknown message: {}", message))
.build()
);
}
private void findAll(ArticleDaoFindAllRequest ignored) {
sender().tell(new ArticleDaoFindAllResponse(articleDao.findAll()), self());
}
private void find(ArticleDaoFindRequest message) {
sender().tell(new ArticleDaoFindResponse(articleDao.find(message.getId())), self());
}
private void add(ArticleDaoCreateRequest message) {
articleDao.create(message.getModel());
}
private void update(ArticleDaoUpdateRequest message) {
articleDao.update(message.getModel());
}
private void delete(ArticleDaoDeleteRequest message) {
articleDao.delete(message.getId());
}
}
<file_sep>package controller.page;
import play.mvc.Controller;
import play.mvc.Result;
import view.admin.html.login;
public class LoginController extends Controller {
public Result renderLoginPage() {
return ok(login.render());
}
}
<file_sep># Notes
Simple note manager<file_sep>package common;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
public final class ConcurrencyUtil {
private ConcurrencyUtil() {}
public static <R> R blocked(CompletionStage<R> stage) {
try {
return stage.toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
}
<file_sep>package dao.ebean;
import dao.ArticleDao;
import io.ebean.Ebean;
import java.util.List;
import javax.inject.Singleton;
import model.ArticleModel;
@Singleton
public class ArticleEbeanDao implements ArticleDao {
@Override
public List<ArticleModel> findAll() {
return Ebean.find(ArticleModel.class)
.findList();
}
@Override
public ArticleModel find(String id) {
return Ebean.find(ArticleModel.class)
.setId(id)
.findUnique();
}
@Override
public void create(ArticleModel model) {
Ebean.save(model);
}
@Override
public void update(ArticleModel model) {
Ebean.update(model);
}
@Override
public void delete(String id) {
Ebean.delete(find(id));
}
}
<file_sep>package service.actor;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.PatternsCS;
import common.ActorUtil;
import dao.actor.UserDaoActor;
import dao.message.UserDaoFindRequest;
import dao.message.UserDaoFindResponse;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.api.inject.Injector;
import service.UserService;
import service.message.UserServiceAuthRequest;
import service.message.UserServiceAuthResponse;
public class UserServiceActor extends AbstractActor {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceActor.class);
private final UserService service;
private final ActorRef UserDaoActor;
@Inject
public UserServiceActor(Injector injector, UserService service) {
this.service = service;
UserDaoActor = context().actorOf(ActorUtil.props(UserDaoActor.class, injector));
receive(
ReceiveBuilder
.match(UserServiceAuthRequest.class, this::authenticate)
.matchAny(message -> LOGGER.warn("Received unknown message: {}", message))
.build()
);
}
private void authenticate(UserServiceAuthRequest message) {
CompletionStage<UserDaoFindResponse> future = ActorUtil.ask(UserDaoActor, new UserDaoFindRequest(message.getModel().getUsername()));
PatternsCS.pipe(
future.thenApply(result -> new UserServiceAuthResponse(service.authenticate(result.getModel(), message.getModel()))),
context().dispatcher()
).to(sender(), self());
}
}
<file_sep>package facade;
import common.BiConverter;
import dto.ArticleDto;
import java.util.Collection;
import javax.inject.Inject;
import javax.inject.Singleton;
import model.ArticleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class ArticleFacade {
private static final Logger LOGGER = LoggerFactory.getLogger(ArticleFacade.class);
@Inject
private BiConverter<ArticleModel, ArticleDto> converter;
public ArticleModel convertBack(ArticleDto dto) {
ArticleModel model = converter.back(dto);
LOGGER.debug("Dto={} has been converted to model={}", dto, model);
return model;
}
public ArticleDto convertForth(ArticleModel model) {
ArticleDto dto = converter.forth(model);
LOGGER.debug("Model={} has been converted to dto={}", model, dto);
return dto;
}
public Collection<ArticleDto> convertForth(Collection<ArticleModel> models) {
Collection<ArticleDto> dtos = converter.forth(models);
LOGGER.debug("Models={} has been converted to dtos={}", models, dtos);
return dtos;
}
}
<file_sep>package common;
import java.util.Collection;
import java.util.stream.Collectors;
public abstract class Converter<F, T> {
public abstract T forth(F item);
public Collection<T> forth(Collection<F> items) {
return items.stream().map(this::forth).collect(Collectors.toList());
}
}
<file_sep>package service.message;
public class ArticleServiceFindAllRequest {
}
| 57f673f81fb82d362aa7500748c82abbf8a8ac35 | [
"Markdown",
"Java",
"TypeScript",
"INI"
] | 23 | Java | yakky-hub/notes | 4859b31d59be152d52394ee7b004503c1191bf5b | 11961465d352375356920f84c0d2d4f722029326 | |
refs/heads/master | <file_sep># Cambridge_Email
Email pdfs to all Cambridge students.
<file_sep>import yagmail
import openpyxl
'''import datetime
x = datetime.datetime.now()
log = x.strftime('%d')+x.strftime('%m')+x.strftime('%Y')+'.txt'
open(log, 'w+')
import PyPDF2
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
max_page = pdf_reader.numPages
for i in range(1, 3):
pdf_writer = PyPDF2.PdfFileWriter()
page = pdf_reader.getPage(i)
page_string = page.extractText()
idStart = int(page_string.find('Number'))+8
idNumber = page_string[idStart: idStart+4]
newPdf = idNumber+'.pdf'
pdf_writer.addPage(page)
pdf_idNumber = open(newPdf, 'wb')
pdf_writer.write(pdf_idNumber)
pdf_idNumber.close()
pdf_file.close()'''
yag = yagmail.SMTP("<EMAIL>", "Openfire1")
body = "For those who have lost the Cambridge log-in details, please see attached."
students = openpyxl.load_workbook('Camb11.xlsx')
max_value = students['Sheet1'].max_row
for row in range(2, max_value+1):
school_ID_cell = 'B' + str(row)
school_ID = students['Sheet1'][school_ID_cell].value
address = str(school_ID)+'@burnside.school.nz'
cambridge_ID_cell = 'C' + str(row)
cambridge_ID = students['Sheet1'][cambridge_ID_cell].value
filename = str(cambridge_ID)+'.pdf'
print(school_ID, school_ID_cell, address, filename)
yag.send(
to=address,
subject="Cambridge Results: Your log-in and password",
contents=body,
attachments=filename,
)
| 61d7b137509aef762e7b0113ffa5ea8c7347134b | [
"Markdown",
"Python"
] | 2 | Markdown | timpsch/Cambridge_Email | 4449e1e9d1da77f860b6bd9c476e15afb26348f7 | d8b19ec64b5b2a9e380edf107eb4e687be6a5a5f | |
refs/heads/master | <repo_name>YoumingZheng/Animal-Shelter_JAVA-Project_NetBeans<file_sep>/FinalProject/FinalProject/src/userinterface/VolunteerWorkArea/AssignJPanel.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 userinterface.VolunteerWorkArea;
import Business.EcoSystem;
import Business.Enterprise.AnimalShelterEnterprise;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.InspectionOrganization;
import Business.Organization.Organization;
import Business.Person.Volunteer;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.AdoptionWorkRequest;
import Business.WorkQueue.InspectionWorkRequest;
import Business.WorkQueue.WorkRequest;
import java.awt.CardLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
/**
*
* @author brandonz
*/
public class AssignJPanel extends javax.swing.JPanel {
/**
* Creates new form AssignJPanel
*/
private JPanel userProcessContainer;
private EcoSystem business;
private UserAccount userAccount;
private Organization organization;
private Enterprise enterprise;
private Network netWork;
private EcoSystem system;
private InspectionOrganization inspectionOrganization;
public AssignJPanel(JPanel userProcessContainer,UserAccount userAccount, Organization organization, Enterprise enterprise, Network network,EcoSystem system) {
initComponents();
this.userProcessContainer = userProcessContainer;
this.system = system;
this.userAccount = userAccount;
this.organization = organization;
this.enterprise = enterprise;
this.netWork = network;
populateTable1();
}
/**
* 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() {
refreshJButton = new javax.swing.JButton();
assignJButton = new javax.swing.JButton();
processJButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
zipTxt = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
jTable4 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
refreshJButton.setText("Search");
refreshJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshJButtonActionPerformed(evt);
}
});
add(refreshJButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(211, 51, -1, -1));
assignJButton.setText("Assign to me");
assignJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
assignJButtonActionPerformed(evt);
}
});
add(assignJButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 277, -1, -1));
processJButton.setText("Process");
processJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
processJButtonActionPerformed(evt);
}
});
add(processJButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 573, 137, -1));
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"<NAME>", "Address", "Species", "Breed", "Gender", "Color"
}
) {
boolean[] canEdit = new boolean [] {
false, true, false, true, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane3.setViewportView(jTable3);
add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 83, 816, 176));
add(zipTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(78, 52, 115, -1));
jLabel3.setText("Zip");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 55, -1, -1));
jTable4.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer Name", "Address", "Species", "Breed", "Gender", "Color"
}
) {
boolean[] canEdit = new boolean [] {
false, true, false, true, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane4.setViewportView(jTable4);
add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 354, 816, 201));
jButton1.setText("Back");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(49, 629, -1, -1));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setText("Assign Inspection");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void refreshJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshJButtonActionPerformed
populateTable();
}//GEN-LAST:event_refreshJButtonActionPerformed
public void populateTable() {
DefaultTableModel model = (DefaultTableModel) jTable3.getModel();
model.setRowCount(0);
/*if(zipTxt.getText().equals("") || zipTxt.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "please type zip");
}*/
if(zipTxt.getText().equals("") || zipTxt.getText().isEmpty()){
for(InspectionWorkRequest isp : enterprise.getInspectionWorkQueue().getWorkRequestList()){
if(isp.getStatus().equalsIgnoreCase("Sent")){
Object[] row = new Object[6];
row[0] = isp;
row[1] = isp.getCustomer().getAddress();
row[2] = isp.getAnimal().getSpecies();
row[3] = isp.getAnimal().getBreed();
row[4] = isp.getAnimal().getGender();
row[5] = isp.getAnimal().getColor();
model.addRow(row);
}
}
}else{
for(InspectionWorkRequest isp : enterprise.getInspectionWorkQueue().getWorkRequestList()){
if(isp.getCustomer().getZipCode().equals(zipTxt.getText()) && isp.getStatus().equalsIgnoreCase("Sent")){
Object[] row = new Object[6];
row[0] = isp;
row[1] = isp.getCustomer().getAddress();
row[2] = isp.getAnimal().getSpecies();
row[3] = isp.getAnimal().getBreed();
row[4] = isp.getAnimal().getGender();
row[5] = isp.getAnimal().getColor();
model.addRow(row);
}
}
}
/*for (Network network : business.getNetworkList()) {
for (Enterprise enterprise : network.getEnterpriseDirectory().getEnterpriseList()) {
if(enterprise instanceof AnimalShelterEnterprise){
//if(ase.getZipCode().equals(enterprise))
for(Organization o: enterprise.getOrganizationDirectory().getOrganizationList())
if(o instanceof InspectionOrganization)
for (WorkRequest request : inspectionOrganization.getWorkQueueReceived().getWorkRequestList()) {
Object[] row = new Object[6];
row[0] = request.getAnimal().getID();
row[1] = request.getAnimal().getSpecies();
row[2] = request.getAnimal().getBreed();
row[3] = request.getAnimal().getGender();
row[4] = request.getAnimal().getColor();
row[5] = request.getAnimal().getAge();
}
}
}
}*/
}
public void populateTable1() {
DefaultTableModel model = (DefaultTableModel) jTable4.getModel();
model.setRowCount(0);
for(InspectionWorkRequest iwr:userAccount.getInspectionWorkQueue().getWorkRequestList()){
Object[] row = new Object[6];
row[0] = iwr;
row[1] = iwr.getCustomer().getAddress();
row[2] = iwr.getAnimal().getSpecies();
row[3] = iwr.getAnimal().getBreed();
row[4] = iwr.getAnimal().getGender();
row[5] = iwr.getAnimal().getColor();
model.addRow(row);
}
/*
for (InspectionWorkRequest iwr : list){
Object[] row = new Object[6];
row[0] =iwr;
row[1] = iwr.getCustomer().getAddress();
row[3] = iwr.getAnimal().getSpecies();
row[4] = iwr.getAnimal().getBreed();
row[5] = iwr.getAnimal().getColor();
if(!iwr.getStatus().equals("Generated")){
row[6] =df.format(iwr.getLastTimeCheckDate()) ;
}else
row[6] = "Just Generated";
model.addRow(row);
}
*/
}
private void assignJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_assignJButtonActionPerformed
int selectedRow = jTable3.getSelectedRow();
if (selectedRow >= 0) {
InspectionWorkRequest request = (InspectionWorkRequest) jTable3.getValueAt(selectedRow, 0);
request.setStatus("Assigned");
request.setVolunteer((Volunteer) userAccount.getPerson());
enterprise.getInspectionWorkQueue().getWorkRequestList().remove(request);
userAccount.getInspectionWorkQueue().getWorkRequestList().add(request);
//populateTable1(request);
populateTable1();
populateTable();
} else {
JOptionPane.showMessageDialog(null, "Choose a row to assign.");
}
}//GEN-LAST:event_assignJButtonActionPerformed
private void processJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processJButtonActionPerformed
int selectedRow = jTable4.getSelectedRow();
if (selectedRow >= 0) {
InspectionWorkRequest request = (InspectionWorkRequest) jTable4.getValueAt(selectedRow, 0);
GradeJPanel g = new GradeJPanel(userProcessContainer,userAccount,request);
userProcessContainer.add("g",g);
CardLayout cardLayout = (CardLayout)userProcessContainer.getLayout();
cardLayout.show(userProcessContainer,"g");
} else {
JOptionPane.showMessageDialog(null, "Choose a row to process.");
}
// int selectedRow = workRequestJTable.getSelectedRow();
//
// if (selectedRow >= 0) {
// InspectionWorkRequest request = (InspectionWorkRequest) workRequestJTable.getValueAt(selectedRow, 0);
//
// request.setStatus("Processing");
//
// ProcessWorkRequestJPanel processWorkRequestJPanel = new ProcessWorkRequestJPanel(userProcessContainer, request);
// userProcessContainer.add("processWorkRequestJPanel", processWorkRequestJPanel);
// CardLayout layout = (CardLayout) userProcessContainer.getLayout();
// layout.next(userProcessContainer);
//
// } else {
// JOptionPane.showMessageDialog(null, "Please select a request message to process.");
// return;
// }
}//GEN-LAST:event_processJButtonActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton assignJButton;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTable jTable3;
private javax.swing.JTable jTable4;
private javax.swing.JButton processJButton;
private javax.swing.JButton refreshJButton;
private javax.swing.JTextField zipTxt;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Interface/InspectionManager/InspectionManagerWorkArea.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 Interface.InspectionManager;
import Business.EcoSystem;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* @author <NAME>
*/
public class InspectionManagerWorkArea extends javax.swing.JPanel {
/**
* Creates new form InspectionManagerWorkArea
*/
JPanel userProcessContainer;
UserAccount userAccount;
Organization organization;
Enterprise enterprise;
Network network;
EcoSystem system;
public InspectionManagerWorkArea(JPanel userProcessContainer, UserAccount account, Organization organization, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=account;
this.organization=organization;
this.enterprise=enterprise;
this.network=network;
this.system=system;
}
/**
* 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() {
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("Select and Send Inspection Work Request");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(251, 101, -1, -1));
jButton3.setText("Analysis");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(251, 284, 271, -1));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setText("Inspection Manager");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
SelectInspectionWorkRequest siwr = new SelectInspectionWorkRequest(userProcessContainer, userAccount, organization, enterprise, network, system);
userProcessContainer.add("SelectInspectionWorkRequest", siwr);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
Analysis analysis = new Analysis(userProcessContainer, userAccount, organization, enterprise, network, system);
userProcessContainer.add("Analysis", analysis);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_jButton3ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Business/WorkQueue/LostAnimalWorkRequest.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 Business.WorkQueue;
import Business.Person.Customer;
import javax.swing.ImageIcon;
/**
*
* @author <NAME>
*/
public class LostAnimalWorkRequest extends WorkRequest{
private String Result;
private Customer lostCustomer;
private boolean validId;
private boolean vaccineHistory;
private boolean receipt;
private ImageIcon icon;
private String picturepath;
public String getPicturepath() {
return picturepath;
}
public void setPicturepath(String picturepath) {
this.picturepath = picturepath;
}
public ImageIcon getIcon() {
return icon;
}
public void setIcon(ImageIcon icon) {
this.icon = icon;
}
public String getResult() {
return Result;
}
public void setResult(String Result) {
this.Result = Result;
}
public Customer getLostCustomer() {
return lostCustomer;
}
public void setLostCustomer(Customer lostCustomer) {
this.lostCustomer = lostCustomer;
}
public boolean isValidId() {
return validId;
}
public void setValidId(boolean validId) {
this.validId = validId;
}
public boolean isVaccineHistory() {
return vaccineHistory;
}
public void setVaccineHistory(boolean vaccineHistory) {
this.vaccineHistory = vaccineHistory;
}
public boolean isReceipt() {
return receipt;
}
public void setReceipt(boolean receipt) {
this.receipt = receipt;
}
@Override
public String toString() {
return lostCustomer.getName();
}
}
<file_sep>/FinalProject/FinalProject/src/Business/WorkQueue/InspectionWorkRequest.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 Business.WorkQueue;
import Business.Person.Customer;
import Business.Person.Volunteer;
import java.util.Date;
/**
*
* @author brandonz
*/
public class InspectionWorkRequest extends WorkRequest{
private String Result;
private Date lastTimeCheckDate;
private Customer customer;
private String firstInspection;
private String secondInspection;
private String thirdInspection;
private Volunteer volunteer;
public InspectionWorkRequest(){
super();
lastTimeCheckDate=this.getRequestDate();
}
public Volunteer getVolunteer() {
return volunteer;
}
public void setVolunteer(Volunteer volunteer) {
this.volunteer = volunteer;
}
public String getResult() {
return Result;
}
public void setResult(String Result) {
this.Result = Result;
}
public Date getLastTimeCheckDate() {
return lastTimeCheckDate;
}
public void setLastTimeCheckDate(Date lastTimeCheckDate) {
this.lastTimeCheckDate = lastTimeCheckDate;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getFirstInspection() {
return firstInspection;
}
public void setFirstInspection(String firstInspection) {
this.firstInspection = firstInspection;
}
public String getSecondInspection() {
return secondInspection;
}
public void setSecondInspection(String secondInspection) {
this.secondInspection = secondInspection;
}
public String getThirdInspection() {
return thirdInspection;
}
public void setThirdInspection(String thirdInspection) {
this.thirdInspection = thirdInspection;
}
public boolean nextTimeCheck(double i){
long day=(((new Date(lastTimeCheckDate.getTime()+(long)30*24*60*60*1000)).getTime())-(lastTimeCheckDate.getTime()))/(24*60*60*1000);
if(true) // day<=i
return true;
else
return false;
}
@Override
public String toString() {
return customer.getName();
}
}
<file_sep>/FinalProject/FinalProject/src/userinterface/VolunteerWorkArea/VolunteerWorkArea.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 userinterface.VolunteerWorkArea;
import Business.EcoSystem;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.InspectionOrganization;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* @author brandonz
*/
public class VolunteerWorkArea extends javax.swing.JPanel {
/**
* Creates new form VolunteerWorkArea
*/
JPanel userProcessContainer;
UserAccount userAccount;
Organization organization;
Enterprise enterprise;
Network network;
EcoSystem system;
public VolunteerWorkArea(JPanel userProcessContainer, UserAccount account, Organization organization, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=account;
this.organization=organization;
this.enterprise=enterprise;
this.network=network;
this.system=system;
}
/**
* 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() {
btnAssign = new javax.swing.JButton();
btnFeedback = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btnAssign.setText("Assign");
btnAssign.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAssignActionPerformed(evt);
}
});
add(btnAssign, new org.netbeans.lib.awtextra.AbsoluteConstraints(169, 124, 129, -1));
btnFeedback.setText("Feedback");
btnFeedback.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFeedbackActionPerformed(evt);
}
});
add(btnFeedback, new org.netbeans.lib.awtextra.AbsoluteConstraints(169, 203, 129, -1));
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel2.setText("Volunteer Work Area");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void btnAssignActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAssignActionPerformed
AssignJPanel muajp = new AssignJPanel(userProcessContainer, userAccount, organization, enterprise, network, system);
userProcessContainer.add("AssignJPanel", muajp);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);// TODO add your handling code here:
}//GEN-LAST:event_btnAssignActionPerformed
private void btnFeedbackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFeedbackActionPerformed
// FeedbackJPanel muajp = new FeedbackJPanel(userProcessContainer, system, userAccount, (InspectionOrganization)organization);
// userProcessContainer.add("FeedbackJPanel", muajp);
//
// CardLayout layout = (CardLayout) userProcessContainer.getLayout();
// layout.next(userProcessContainer); // TODO add your handling code here:
}//GEN-LAST:event_btnFeedbackActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAssign;
private javax.swing.JButton btnFeedback;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Interface/InspectionManager/SelectInspectionWorkRequest.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 Interface.InspectionManager;
import Business.EcoSystem;
import Business.Enterprise.CustomerAndVolunteerEnterprise;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.InspectionWorkRequest;
import java.awt.CardLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
/**
*
* @author <NAME>
*/
public class SelectInspectionWorkRequest extends javax.swing.JPanel {
/**
* Creates new form SendInspectionWorkRequest
*/
JPanel userProcessContainer;
UserAccount userAccount;
Organization organization;
Enterprise enterprise;
Network network;
EcoSystem system;
ArrayList<InspectionWorkRequest> upperList=new ArrayList<InspectionWorkRequest>();
ArrayList<InspectionWorkRequest> lowerList=new ArrayList<InspectionWorkRequest>();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
SelectInspectionWorkRequest(JPanel userProcessContainer, UserAccount userAccount, Organization organization, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=userAccount;
this.organization=organization;
this.enterprise=enterprise;
this.network=network;
this.system=system;
populateComboBox();
}
public void populateComboBox(){
jComboBox1.removeAllItems();
double a=5;
double b=10;
double c=15;
double d=25;
jComboBox1.addItem(a);
jComboBox1.addItem(b);
jComboBox1.addItem(c);
jComboBox1.addItem(d);
}
public void populateUpperTable(ArrayList<InspectionWorkRequest> list){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
for (InspectionWorkRequest iwr : list){
Object[] row = new Object[6];
row[0] =iwr;
row[1] = iwr.getCustomer().getAddress();
row[2] = iwr.getAnimal().getSpecies();
row[3] = iwr.getAnimal().getBreed();
row[4] = iwr.getAnimal().getColor();
if(!iwr.getStatus().equals("Generated")){
row[5] =df.format(iwr.getLastTimeCheckDate()) ;
}else
row[5] = "Just Generated";
model.addRow(row);
}
}
public void populateLowerTable(ArrayList<InspectionWorkRequest> list){
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.setRowCount(0);
for (InspectionWorkRequest iwr : list){
Object[] row = new Object[6];
row[0] =iwr;
row[1] = iwr.getCustomer().getAddress();
row[2] = iwr.getAnimal().getID();
row[3] = iwr.getVolunteer()==null ? "Unassigned" : iwr.getVolunteer().getName();
row[4] = df.format(new Date(iwr.getLastTimeCheckDate().getTime()+(long)30*24*60*60*1000));
row[5] = iwr.getStatus();
model.addRow(row);
}
}
/**
* 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() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jComboBox1 = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
txtEmail = new javax.swing.JTextField();
txtName = new javax.swing.JTextField();
txtID = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtVAddress = new javax.swing.JTextField();
txtVEmail = new javax.swing.JTextField();
txtVName = new javax.swing.JTextField();
txtVID = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
txtBreed = new javax.swing.JTextField();
txtColor = new javax.swing.JTextField();
txtSpecies = new javax.swing.JTextField();
txtAID = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jLabel17 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Adopter Name", "Address", "Animal Species", "Breed", "Color", "Last Check Time"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
jTable1.getColumnModel().getColumn(4).setResizable(false);
jTable1.getColumnModel().getColumn(5).setResizable(false);
}
add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 83, 906, 199));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 52, -1, -1));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel1.setText("days from next Inspection");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(81, 52, -1, -1));
jButton1.setText("Send single Request to Volunteers");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(689, 289, -1, -1));
jButton2.setText("Send all on the list to Volunteers");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 289, -1, -1));
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Adopter Name", "Address", "Animal ID", "Volunteer Name", "Supposed Check Time", "Status"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(jTable2);
add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 397, 906, 215));
jButton3.setText("Check out");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 365, -1, -1));
jButton4.setText("See Details");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(821, 619, -1, -1));
jLabel2.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jLabel2.setText("Customer:");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 657, -1, -1));
jLabel3.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jLabel3.setText("Volunteer:");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(331, 657, -1, -1));
jLabel4.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jLabel4.setText("Animal:");
add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(632, 657, -1, -1));
jLabel5.setText("Name:");
add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 707, -1, -1));
jLabel6.setText("ID:");
add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 747, -1, -1));
jLabel7.setText("Email:");
add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 827, -1, -1));
jLabel8.setText("Address:");
add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 787, -1, -1));
txtAddress.setEditable(false);
txtAddress.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtAddressActionPerformed(evt);
}
});
add(txtAddress, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 784, 188, -1));
txtEmail.setEditable(false);
txtEmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtEmailActionPerformed(evt);
}
});
add(txtEmail, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 824, 188, -1));
txtName.setEditable(false);
txtName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNameActionPerformed(evt);
}
});
add(txtName, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 704, 188, -1));
txtID.setEditable(false);
txtID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIDActionPerformed(evt);
}
});
add(txtID, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 744, 188, -1));
jLabel9.setText("Email:");
add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(331, 827, -1, -1));
jLabel10.setText("Address:");
add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(331, 787, -1, -1));
txtVAddress.setEditable(false);
txtVAddress.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtVAddressActionPerformed(evt);
}
});
add(txtVAddress, new org.netbeans.lib.awtextra.AbsoluteConstraints(387, 784, 188, -1));
txtVEmail.setEditable(false);
txtVEmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtVEmailActionPerformed(evt);
}
});
add(txtVEmail, new org.netbeans.lib.awtextra.AbsoluteConstraints(387, 824, 188, -1));
txtVName.setEditable(false);
txtVName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtVNameActionPerformed(evt);
}
});
add(txtVName, new org.netbeans.lib.awtextra.AbsoluteConstraints(387, 704, 188, -1));
txtVID.setEditable(false);
txtVID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtVIDActionPerformed(evt);
}
});
add(txtVID, new org.netbeans.lib.awtextra.AbsoluteConstraints(387, 744, 188, -1));
jLabel11.setText("Name:");
add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(331, 707, -1, -1));
jLabel12.setText("ID:");
add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(331, 747, -1, -1));
jLabel13.setText("Color:");
add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(632, 827, -1, -1));
jLabel14.setText("Breed:");
add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(632, 787, -1, -1));
txtBreed.setEditable(false);
txtBreed.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtBreedActionPerformed(evt);
}
});
add(txtBreed, new org.netbeans.lib.awtextra.AbsoluteConstraints(686, 784, 188, -1));
txtColor.setEditable(false);
txtColor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtColorActionPerformed(evt);
}
});
add(txtColor, new org.netbeans.lib.awtextra.AbsoluteConstraints(686, 824, 188, -1));
txtSpecies.setEditable(false);
txtSpecies.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSpeciesActionPerformed(evt);
}
});
add(txtSpecies, new org.netbeans.lib.awtextra.AbsoluteConstraints(686, 704, 188, -1));
txtAID.setEditable(false);
txtAID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtAIDActionPerformed(evt);
}
});
add(txtAID, new org.netbeans.lib.awtextra.AbsoluteConstraints(686, 744, 188, -1));
jLabel15.setText("Species:");
add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(632, 707, -1, -1));
jLabel16.setText("ID:");
add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(632, 747, -1, -1));
buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("All Requests Sent");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
add(jRadioButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 365, -1, -1));
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText("Requests Assigned");
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
add(jRadioButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(148, 365, -1, -1));
buttonGroup1.add(jRadioButton3);
jRadioButton3.setText("Requests Unassigned");
jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton3ActionPerformed(evt);
}
});
add(jRadioButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(287, 365, -1, -1));
jButton6.setText("Check out");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(298, 51, -1, -1));
jButton7.setText("Back");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 853, -1, -1));
jLabel17.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel17.setText("Inspection Work Request");
add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void txtAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAddressActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtAddressActionPerformed
private void txtEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEmailActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtEmailActionPerformed
private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNameActionPerformed
private void txtIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIDActionPerformed
private void txtVAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtVAddressActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtVAddressActionPerformed
private void txtVEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtVEmailActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtVEmailActionPerformed
private void txtVNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtVNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtVNameActionPerformed
private void txtVIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtVIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtVIDActionPerformed
private void txtBreedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBreedActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtBreedActionPerformed
private void txtColorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtColorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtColorActionPerformed
private void txtSpeciesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSpeciesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSpeciesActionPerformed
private void txtAIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtAIDActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
int selectedRow = jTable1.getSelectedRow();
if (selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row first!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
InspectionWorkRequest iwr=(InspectionWorkRequest)jTable1.getValueAt(selectedRow, 0);
for(Enterprise en:network.getEnterpriseDirectory().getEnterpriseList()){
if(en instanceof CustomerAndVolunteerEnterprise){
en.getInspectionWorkQueue().getWorkRequestList().add(iwr);
iwr.setStatus("Sent");
iwr.setSender(userAccount);
break;
}
}
upperList.remove(iwr);
populateUpperTable(upperList);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
for(Enterprise en:network.getEnterpriseDirectory().getEnterpriseList()){
if(en instanceof CustomerAndVolunteerEnterprise){
for(InspectionWorkRequest iwr:upperList){
en.getInspectionWorkQueue().getWorkRequestList().add(iwr);
iwr.setStatus("Sent");
iwr.setSender(userAccount);
}
}
}
upperList.clear();
populateUpperTable(upperList);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
populateLowerTable(lowerList);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
int selectedRow = jTable2.getSelectedRow();
if (selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row first!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
InspectionWorkRequest iwr=(InspectionWorkRequest)jTable2.getValueAt(selectedRow, 0);
txtName.setText(iwr.getCustomer().getName());
txtID.setText(String.valueOf(iwr.getCustomer().getId()));
txtAddress.setText(iwr.getCustomer().getAddress());
txtEmail.setText(iwr.getCustomer().getEmail());
if(iwr.getStatus().equals("Assigned")){
txtVName.setText(iwr.getVolunteer().getName());
txtVID.setText(String.valueOf(iwr.getVolunteer().getId()));
txtVAddress.setText(iwr.getVolunteer().getAddress());
txtVEmail.setText(iwr.getVolunteer().getEmail());
}else if(iwr.getStatus().equals("Sent")){
txtVName.setText("Volunteer Unassigned");
txtVID.setText("Volunteer Unassigned");
txtVAddress.setText("Volunteer Unassigned");
txtVEmail.setText("Volunteer Unassigned");
}
txtSpecies.setText(iwr.getAnimal().getSpecies());
txtAID.setText(String.valueOf(iwr.getAnimal().getID()));
txtBreed.setText(iwr.getAnimal().getBreed());
txtColor.setText(iwr.getAnimal().getColor());
}//GEN-LAST:event_jButton4ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
// TODO add your handling code here:
lowerList.clear();
if(jRadioButton1.isSelected()){
for(InspectionWorkRequest iwr:organization.getInspectionWorkQueue().getWorkRequestList()){
if(iwr.getStatus().equalsIgnoreCase("Sent") || iwr.getStatus().equalsIgnoreCase("Assigned")){
lowerList.add(iwr);
}
}
}
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
// TODO add your handling code here:
lowerList.clear();
if(jRadioButton2.isSelected()){
for(InspectionWorkRequest iwr:organization.getInspectionWorkQueue().getWorkRequestList()){
if(iwr.getStatus().equalsIgnoreCase("Assigned")){
lowerList.add(iwr);
}
}
}
}//GEN-LAST:event_jRadioButton2ActionPerformed
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed
// TODO add your handling code here:
lowerList.clear();
if(jRadioButton3.isSelected()){
for(InspectionWorkRequest iwr:organization.getInspectionWorkQueue().getWorkRequestList()){
if(iwr.getStatus().equalsIgnoreCase("Sent")){
lowerList.add(iwr);
}
}
}
}//GEN-LAST:event_jRadioButton3ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
// TODO add your handling code here:
upperList.clear();
double i=(Double)jComboBox1.getSelectedItem();
for(InspectionWorkRequest iwr:organization.getInspectionWorkQueue().getWorkRequestList()){
if(iwr.getStatus().equalsIgnoreCase("Generated") || iwr.getStatus().equalsIgnoreCase("Completed")){
if(iwr.nextTimeCheck(i)){
upperList.add(iwr);
}
}
}
populateUpperTable(upperList);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
// TODO add your handling code here:
}//GEN-LAST:event_jButton7ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField txtAID;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtBreed;
private javax.swing.JTextField txtColor;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtSpecies;
private javax.swing.JTextField txtVAddress;
private javax.swing.JTextField txtVEmail;
private javax.swing.JTextField txtVID;
private javax.swing.JTextField txtVName;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Interface/InventoryManager/ManageAnimalInventory.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 Interface.InventoryManager;
import Business.Animal.Animal;
import Business.EcoSystem;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Image;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import java.io.File;
/**
*
* @author <NAME>
*/
public class ManageAnimalInventory extends javax.swing.JPanel {
/**
* Creates new form ManageAnimalInventory
*/
JPanel userProcessContainer;
UserAccount userAccount;
Organization organization;
Enterprise enterprise;
Network network;
EcoSystem system;
ImageIcon icon;
String picturepath=null;
ManageAnimalInventory(JPanel userProcessContainer, UserAccount userAccount, Organization organization, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=userAccount;
this.organization=organization;
this.enterprise=enterprise;
this.network=network;
this.system=system;
populateTable();
}
public void populateTable(){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
if(enterprise.getAnimalDirectory()!=null){
for (Animal animal : enterprise.getAnimalDirectory().getAnimalDirectory()){
Object[] row = new Object[5];
row[0] = animal;
row[1] = animal.getSpecies();
row[2]=animal.getBreed();
row[3]=animal.getColor();
row[4]=animal.getAge();
model.addRow(row);
}
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtGender = new javax.swing.JTextField();
txtAge = new javax.swing.JTextField();
txtColor = new javax.swing.JTextField();
txtBreed = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
backJButton = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
txtSpecies = new javax.swing.JTextField();
jlPhoto = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Species", "Breed", "Color", "Age"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 60, 917, 255));
jLabel1.setText("Breed:");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(116, 396, -1, -1));
jLabel2.setText("Gender:");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(108, 431, -1, -1));
jLabel3.setText("Color:");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(119, 471, -1, -1));
jLabel4.setText("Age:");
add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(127, 506, -1, -1));
add(txtGender, new org.netbeans.lib.awtextra.AbsoluteConstraints(172, 428, 170, -1));
add(txtAge, new org.netbeans.lib.awtextra.AbsoluteConstraints(172, 503, 170, -1));
add(txtColor, new org.netbeans.lib.awtextra.AbsoluteConstraints(172, 468, 170, -1));
add(txtBreed, new org.netbeans.lib.awtextra.AbsoluteConstraints(172, 393, 170, -1));
jButton1.setText("Create");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(271, 560, -1, -1));
backJButton.setText("<< Back");
backJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backJButtonActionPerformed(evt);
}
});
add(backJButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(94, 560, -1, -1));
jLabel5.setText("Species:");
add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(105, 356, -1, -1));
add(txtSpecies, new org.netbeans.lib.awtextra.AbsoluteConstraints(172, 353, 170, -1));
jlPhoto.setText(" Upload photo here");
add(jlPhoto, new org.netbeans.lib.awtextra.AbsoluteConstraints(611, 353, 189, 165));
jButton2.setText("Upload");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(672, 531, -1, -1));
jButton3.setText("Bar Chart");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(761, 531, -1, -1));
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel6.setText("Manage Inventory");
add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
Animal an=enterprise.getAnimalDirectory().newAnimal();
//an.setIcon(icon);
an.setPicturepath(picturepath);
an.setSpecies(txtSpecies.getText());
an.setBreed(txtBreed.getText());
an.setColor(txtColor.getText());
an.setGender(txtGender.getText());
an.setAge(txtAge.getText());
populateTable();
}//GEN-LAST:event_jButton1ActionPerformed
private void backJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backJButtonActionPerformed
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_backJButtonActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
/*JFileChooser imgc = new JFileChooser();
imgc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int i = imgc.showOpenDialog(null);
String path;
path = imgc.getSelectedFile().getAbsolutePath();
if(i== imgc.APPROVE_OPTION){
String name = imgc.getSelectedFile().getName();
System.out.println("path:"+path+"; name:"+name);
}else{
System.out.println("no document");
}
icon = new ImageIcon(Image.class.getResource(String.valueOf(path)));//ImageIcon(path);
icon.setImage(icon.getImage().getScaledInstance(150,150,Image.SCALE_DEFAULT));
jlPhoto.setIcon(icon);*/
/*JFileChooser imgc = new JFileChooser();
imgc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int i = imgc.showOpenDialog(null);
String path;
path = imgc.getSelectedFile().getAbsolutePath();
if(i== imgc.APPROVE_OPTION){
String name = imgc.getSelectedFile().getName();
System.out.println("path:"+path+"; name:"+name);
}else{
System.out.println("no document");
}
icon = new ImageIcon(path);
icon.setImage(icon.getImage().getScaledInstance(150,150,Image.SCALE_DEFAULT));
jlPhoto.setIcon(icon);*/
picturepath = null;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
File pic = jfc.getSelectedFile();
if (pic!=null&&pic.getAbsolutePath().endsWith(".jpg")){
picturepath = pic.getAbsolutePath();
ImageIcon imageIcon = new ImageIcon(picturepath);
Image image = imageIcon.getImage();
Image smallImage = image.getScaledInstance(169,169,Image.SCALE_FAST);
ImageIcon smallIcon = new ImageIcon(smallImage);
jlPhoto.setIcon(smallIcon);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
int dog = 0;
int cat = 0;
for(Animal an:enterprise.getAnimalDirectory().getAnimalDirectory()){
if(an.getSpecies().equals("dog")){
dog++;
}
if(an.getSpecies().equals("cat")){
cat++;
}
}
dataset.setValue(dog, "1", "Dog");
dataset.setValue(cat, "2", "Cat");
JFreeChart chart = ChartFactory.createBarChart("Animal Variety", "Animals Species", "Amount", dataset, PlotOrientation.VERTICAL, false, true, false);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLACK);
ChartFrame frame = new ChartFrame("Bar Chart for Animals", chart);
frame.setVisible(true);
frame.setSize(450,350);
}//GEN-LAST:event_jButton3ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backJButton;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
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.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JLabel jlPhoto;
private javax.swing.JTextField txtAge;
private javax.swing.JTextField txtBreed;
private javax.swing.JTextField txtColor;
private javax.swing.JTextField txtGender;
private javax.swing.JTextField txtSpecies;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Interface/CertificationManager/CertificationManagerWorkArea.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 Interface.CertificationManager;
import Business.EcoSystem;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import Interface.InventoryManager.ManageAnimalInventory;
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* @author <NAME>
*/
public class CertificationManagerWorkArea extends javax.swing.JPanel {
/**
* Creates new form CertificationManagerWorkArea
*/
JPanel userProcessContainer;
UserAccount userAccount;
Organization organization;
Enterprise enterprise;
Network network;
EcoSystem system;
public CertificationManagerWorkArea(JPanel userProcessContainer, UserAccount account, Organization organization, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=account;
this.organization=organization;
this.enterprise=enterprise;
this.network=network;
this.system=system;
txtEnterprise.setText(enterprise.getName());
}
/**
* 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() {
jLabel2 = new javax.swing.JLabel();
txtEnterprise = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel2.setText("Enterprise:");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 60, -1, -1));
txtEnterprise.setEditable(false);
add(txtEnterprise, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 62, 194, -1));
jButton1.setText("Recive Appilication Work Request");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 102, -1, -1));
jButton2.setText("Recive Lost Pet Work Request");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 145, -1, -1));
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel3.setText("Certification Manager");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
ReciveAdoptionWorkRequest ma = new ReciveAdoptionWorkRequest(userProcessContainer, userAccount, organization, enterprise, network, system);
userProcessContainer.add("ManageAnimalInventory", ma);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
ReciveLostAnimalWorkRequest mlp = new ReciveLostAnimalWorkRequest(userProcessContainer, userAccount, organization, enterprise, network, system);
userProcessContainer.add("ManageAnimalInventory", mlp);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_jButton2ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField txtEnterprise;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Interface/CustomerRole/FosterCareAnnounce.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 Interface.CustomerRole;
import Business.Animal.Animal;
import Business.EcoSystem;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.AdoptionWorkRequest;
import Business.WorkQueue.FostCareWorkRequest;
import Business.WorkQueue.InspectionWorkRequest;
import java.awt.CardLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
/**
*
* @author brandonz
*/
public class FosterCareAnnounce extends javax.swing.JPanel {
/**
* Creates new form FosterCareAnnounce
*/
private JPanel userProcessContainer;
private EcoSystem system;
private UserAccount userAccount;
private Enterprise enterprise;
private Network netWork;
private Animal an;
public FosterCareAnnounce(JPanel userProcessContainer,UserAccount userAccount, Enterprise enterprise, Network network,EcoSystem system) {
initComponents();
this.userProcessContainer = userProcessContainer;
this.system = system;
this.userAccount = userAccount;
this.enterprise = enterprise;
this.netWork = network;
display();
}
/**
* 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() {
jLabel8 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel4 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
txtBreed2 = new javax.swing.JTextField();
txtColor = new javax.swing.JTextField();
txtGender = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
txtSpecies = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
txtAge = new javax.swing.JTextField();
txtDay = new javax.swing.JTextField();
txtHabit = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtPhone = new javax.swing.JTextField();
jLabel20 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtMessage = new javax.swing.JTextField();
backJButton = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();
jLabel8.setText("jLabel8");
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("Announce");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(846, 670, -1, -1));
jLabel3.setText("My Animal");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 101, -1, -1));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Name", "Species", "Breed", "Color", "Age"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 124, 960, 255));
jLabel4.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jLabel4.setText("Animal Information:");
add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 449, -1, -1));
jLabel13.setText("Color:");
add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 616, -1, -1));
jLabel14.setText("Breed:");
add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 576, -1, -1));
txtBreed2.setEditable(false);
txtBreed2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtBreed2ActionPerformed(evt);
}
});
add(txtBreed2, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 573, 188, -1));
txtColor.setEditable(false);
txtColor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtColorActionPerformed(evt);
}
});
add(txtColor, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 613, 188, -1));
txtGender.setEditable(false);
txtGender.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtGenderActionPerformed(evt);
}
});
add(txtGender, new org.netbeans.lib.awtextra.AbsoluteConstraints(63, 533, 188, -1));
jLabel15.setText("Species:");
add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 499, -1, -1));
jButton2.setText("Import Animal Information");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 397, -1, -1));
jLabel5.setText("Gender:");
add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 536, -1, -1));
txtSpecies.setEditable(false);
txtSpecies.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSpeciesActionPerformed(evt);
}
});
add(txtSpecies, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 496, 188, -1));
jLabel16.setText("Age:");
add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 656, -1, -1));
txtAge.setEditable(false);
txtAge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtAgeActionPerformed(evt);
}
});
add(txtAge, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 653, 188, -1));
txtDay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDayActionPerformed(evt);
}
});
add(txtDay, new org.netbeans.lib.awtextra.AbsoluteConstraints(748, 569, 92, -1));
txtHabit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtHabitActionPerformed(evt);
}
});
add(txtHabit, new org.netbeans.lib.awtextra.AbsoluteConstraints(747, 529, 188, -1));
jLabel17.setText("Phone:");
add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(703, 495, -1, -1));
jLabel6.setText("Pet Habit:");
add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(686, 532, -1, -1));
jLabel7.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jLabel7.setText("My Information:");
add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(578, 445, -1, -1));
txtPhone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPhoneActionPerformed(evt);
}
});
add(txtPhone, new org.netbeans.lib.awtextra.AbsoluteConstraints(748, 492, 188, -1));
jLabel20.setText("Help me for how many days:");
add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(578, 572, -1, -1));
jLabel2.setText("Message:");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(688, 607, -1, -1));
txtMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtMessageActionPerformed(evt);
}
});
add(txtMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints(748, 604, 188, -1));
backJButton.setText("<<Back");
backJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backJButtonActionPerformed(evt);
}
});
add(backJButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 693, -1, -1));
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel9.setText("Foster Care Announce");
add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
int selectedRow = jTable1.getSelectedRow();
if (selectedRow >= 0) {
FostCareWorkRequest frequest = new FostCareWorkRequest();
InspectionWorkRequest irequest = (InspectionWorkRequest) jTable1.getValueAt(selectedRow, 0);
frequest.setAnimal(irequest.getAnimal());
frequest.setCustomer(irequest.getCustomer());
frequest.setDayCount(txtDay.getText());
frequest.setPhone(txtPhone.getText());
frequest.setHabit(txtHabit.getText());
frequest.setMessage(txtMessage.getText());
frequest.setStatus("Sent");
frequest.setResult("");
enterprise.getFosterCareWorkQueue().getWorkRequestList().add(frequest);
JOptionPane.showMessageDialog(null, "Request Posted");
//userAccount.getFosterCareWorkQueue().getWorkRequestList().add(frequest);
} else {
JOptionPane.showMessageDialog(null, "Choose a row to announce.");
}
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void txtBreed2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBreed2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtBreed2ActionPerformed
private void txtColorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtColorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtColorActionPerformed
private void txtGenderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtGenderActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtGenderActionPerformed
private void txtSpeciesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSpeciesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSpeciesActionPerformed
private void txtAgeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAgeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtAgeActionPerformed
private void txtDayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDayActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDayActionPerformed
private void txtHabitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHabitActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtHabitActionPerformed
private void txtPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPhoneActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPhoneActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
int selectedRow = jTable1.getSelectedRow();
if (selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row first!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
InspectionWorkRequest inspectionWorkRequest=(InspectionWorkRequest)jTable1.getValueAt(selectedRow, 0);
Animal animal=inspectionWorkRequest.getAnimal();
txtSpecies.setText(animal.getSpecies());
txtGender.setText(animal.getGender());
txtBreed2.setText(animal.getBreed());
txtColor.setText(animal.getColor());
txtAge.setText(animal.getAge());
}//GEN-LAST:event_jButton2ActionPerformed
private void txtMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMessageActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtMessageActionPerformed
private void backJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backJButtonActionPerformed
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_backJButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backJButton;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtAge;
private javax.swing.JTextField txtBreed2;
private javax.swing.JTextField txtColor;
private javax.swing.JTextField txtDay;
private javax.swing.JTextField txtGender;
private javax.swing.JTextField txtHabit;
private javax.swing.JTextField txtMessage;
private javax.swing.JTextField txtPhone;
private javax.swing.JTextField txtSpecies;
// End of variables declaration//GEN-END:variables
private void display() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
for(InspectionWorkRequest inspectionWorkRequest: userAccount.getInspectionWorkQueue().getWorkRequestList()){
Object[] row = new Object[5];
Animal animal=inspectionWorkRequest.getAnimal();
row[0] = inspectionWorkRequest;
row[1] = animal.getSpecies();
row[2]=animal.getBreed();
row[3]=animal.getColor();
row[4]=animal.getAge();
model.addRow(row);
}
}
}
<file_sep>/FinalProject/FinalProject/src/Business/Person/CustomerList.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 Business.Person;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
*
* @author <NAME>
*/
public class CustomerList {
private ArrayList<Customer> customerList;
public ArrayList<Customer> getCustomerList() {
return customerList;
}
public CustomerList(){
customerList=new ArrayList<Customer>();
}
public Customer newCustomer(String name){
Customer customer=new Customer();
customer.setName(name);
customerList.add(customer);
return customer;
}
}
<file_sep>/README.md
# Animal-Shelter_JAVA-Project_NetBeans
JAVA application to standardize and automated the process of animal adoption, including searching, applying (adoption/lost), transportation, certification, inspection
<file_sep>/FinalProject/FinalProject/src/Interface/Register.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 Interface;
import Business.EcoSystem;
import Business.Enterprise.CustomerAndVolunteerEnterprise;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Person.Customer;
import Business.Person.Volunteer;
import Business.Role.CustomerRole;
import Business.Role.VolunteerRole;
import Business.UserAccount.UserAccount;
import java.awt.CardLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author <NAME>
*/
public class Register extends javax.swing.JPanel {
/**
* Creates new form Register
*/
JPanel userProcessContainer;
EcoSystem system;
CustomerAndVolunteerEnterprise cve;
Register(JPanel container, EcoSystem system) {
initComponents();
this.system=system;
this.userProcessContainer=container;
pouplateComoBox();
}
private void pouplateComoBox(){
jcbNetwork.removeAllItems();
for(Network network:system.getNetworkList()){
jcbNetwork.addItem(network);
}
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
txtEmail = new javax.swing.JTextField();
txtAddress = new javax.swing.JTextField();
txtZipCode = new javax.swing.JTextField();
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
jcbNetwork = new javax.swing.JComboBox();
jLabel1.setText("Name:");
jLabel2.setText("Email:");
jLabel3.setText("Address:");
jLabel4.setText("Zip Code:");
jLabel5.setText("User Name:");
jLabel6.setText("Password:");
jLabel7.setFont(new java.awt.Font("Tahoma", 3, 24)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 102, 255));
jLabel7.setText("Register now for adorable animals and a happier life!");
jButton1.setText("Be a Volunteer");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Be an Adopter");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel8.setText("NetWork:");
jcbNetwork.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(146, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(147, 147, 147)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
.addComponent(txtName)
.addComponent(txtEmail)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(txtZipCode, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(132, 132, 132)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addComponent(jLabel5)
.addComponent(jLabel8))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
.addComponent(txtUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
.addComponent(jcbNetwork, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2))
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 650, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(115, 115, 115))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(99, 99, 99)
.addComponent(jLabel7)
.addGap(55, 55, 55)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtZipCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jcbNetwork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(8, 8, 8))
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(166, 166, 166))
);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
Network net=(Network)jcbNetwork.getSelectedItem();
for(Enterprise ent:net.getEnterpriseDirectory().getEnterpriseList()){
if(ent instanceof CustomerAndVolunteerEnterprise){
String name=txtName.getText();
Volunteer vol=((CustomerAndVolunteerEnterprise) ent).getVolunteerList().newVolunteer(name);
vol.setEmail(txtEmail.getText());
vol.setAddress(txtAddress.getText());
vol.setZipCode(txtZipCode.getText());
UserAccount ua=ent.getUserAccountDirectory().createUserAccount(txtUserName.getText(), txtPassword.getText(), vol, new VolunteerRole());
vol.setUserAccount(ua);
break;
}
}
JOptionPane.showMessageDialog(null, "You are now a registed volunteer at: "+net.getName());
userProcessContainer.removeAll();
JPanel blankJP = new JPanel();
userProcessContainer.add("blank", blankJP);
CardLayout crdLyt = (CardLayout) userProcessContainer.getLayout();
crdLyt.next(userProcessContainer);
//jButton1.setEnabled(false);
//jButton2.setEnabled(false);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
Network net=(Network)jcbNetwork.getSelectedItem();
for(Enterprise ent:net.getEnterpriseDirectory().getEnterpriseList()){
if(ent instanceof CustomerAndVolunteerEnterprise){
String name=txtName.getText();
Customer Cus=((CustomerAndVolunteerEnterprise) ent).getCustomerList().newCustomer(name);
Cus.setEmail(txtEmail.getText());
Cus.setAddress(txtAddress.getText());
Cus.setZipCode(txtZipCode.getText());
UserAccount ua=ent.getUserAccountDirectory().createUserAccount(txtUserName.getText(), txtPassword.getText(), Cus, new CustomerRole());
Cus.setUserAccount(ua);
}
}
JOptionPane.showMessageDialog(null, "You are now a registed Customer at: "+net.getName());
userProcessContainer.removeAll();
JPanel blankJP = new JPanel();
userProcessContainer.add("blank", blankJP);
CardLayout crdLyt = (CardLayout) userProcessContainer.getLayout();
crdLyt.next(userProcessContainer);
//dB4OUtil.storeSystem(system);
/*jButton1.setEnabled(false);
jButton2.setEnabled(false);*/
}//GEN-LAST:event_jButton2ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
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.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JComboBox jcbNetwork;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
private javax.swing.JTextField txtZipCode;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Business/WorkQueue/InventoryWorkRequest.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Business.WorkQueue;
import Business.Enterprise.Enterprise;
/**
*
* @author raunak
*/
public class InventoryWorkRequest extends WorkRequest{
private Enterprise enterpriseSend;
private Enterprise enterpriseReceive;
public Enterprise getEnterpriseSend() {
return enterpriseSend;
}
public void setEnterpriseSend(Enterprise enterpriseSend) {
this.enterpriseSend = enterpriseSend;
}
public Enterprise getEnterpriseReceive() {
return enterpriseReceive;
}
public void setEnterpriseReceive(Enterprise enterpriseReceive) {
this.enterpriseReceive = enterpriseReceive;
}
@Override
public String toString() {
return enterpriseReceive.getName();
}
}
<file_sep>/FinalProject/FinalProject/src/userinterface/VolunteerWorkArea/GradeJPanel.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 userinterface.VolunteerWorkArea;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.InspectionWorkRequest;
import java.awt.CardLayout;
import java.awt.Component;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author brandonz
*/
public class GradeJPanel extends javax.swing.JPanel {
/**
* Creates new form GradeJPanel
*/
JPanel userProcessContainer;
UserAccount useraccount;
InspectionWorkRequest isp;
int grade;
String s=new String();
public GradeJPanel(JPanel userProcessContainer, UserAccount useraccount, InspectionWorkRequest isp ) {
initComponents();
this.userProcessContainer = userProcessContainer;
this.useraccount = useraccount;
this.isp = isp;
grade = 0;
}
/**
* 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() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup4 = new javax.swing.ButtonGroup();
buttonGroup5 = new javax.swing.ButtonGroup();
buttonGroup6 = new javax.swing.ButtonGroup();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jRadioButton4 = new javax.swing.JRadioButton();
jRadioButton5 = new javax.swing.JRadioButton();
jRadioButton6 = new javax.swing.JRadioButton();
jLabel4 = new javax.swing.JLabel();
jRadioButton7 = new javax.swing.JRadioButton();
jRadioButton8 = new javax.swing.JRadioButton();
jRadioButton9 = new javax.swing.JRadioButton();
jLabel5 = new javax.swing.JLabel();
jRadioButton10 = new javax.swing.JRadioButton();
jRadioButton11 = new javax.swing.JRadioButton();
jRadioButton12 = new javax.swing.JRadioButton();
jLabel6 = new javax.swing.JLabel();
jRadioButton13 = new javax.swing.JRadioButton();
jRadioButton14 = new javax.swing.JRadioButton();
jRadioButton15 = new javax.swing.JRadioButton();
jLabel7 = new javax.swing.JLabel();
jRadioButton16 = new javax.swing.JRadioButton();
jRadioButton17 = new javax.swing.JRadioButton();
jRadioButton18 = new javax.swing.JRadioButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
txtGrade = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("Good");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText("Fair");
buttonGroup1.add(jRadioButton3);
jRadioButton3.setText("Bad");
jLabel2.setText("Status");
jLabel3.setText("Relationship between customer and pet");
buttonGroup6.add(jRadioButton4);
jRadioButton4.setText("Good");
jRadioButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton4ActionPerformed(evt);
}
});
buttonGroup6.add(jRadioButton5);
jRadioButton5.setText("Fair");
buttonGroup6.add(jRadioButton6);
jRadioButton6.setText("Bad");
jLabel4.setText("Living condition");
buttonGroup2.add(jRadioButton7);
jRadioButton7.setText("Good");
buttonGroup2.add(jRadioButton8);
jRadioButton8.setText("Fair");
buttonGroup2.add(jRadioButton9);
jRadioButton9.setText("Bad");
jLabel5.setText("Space");
buttonGroup3.add(jRadioButton10);
jRadioButton10.setText("Good");
buttonGroup3.add(jRadioButton11);
jRadioButton11.setText("Fair");
buttonGroup3.add(jRadioButton12);
jRadioButton12.setText("Bad");
jLabel6.setText("Food");
buttonGroup4.add(jRadioButton13);
jRadioButton13.setText("Good");
buttonGroup4.add(jRadioButton14);
jRadioButton14.setText("Fair");
buttonGroup4.add(jRadioButton15);
jRadioButton15.setText("Bad");
jLabel7.setText("Pet supplies");
buttonGroup5.add(jRadioButton16);
jRadioButton16.setText("Good");
buttonGroup5.add(jRadioButton17);
jRadioButton17.setText("Fair");
buttonGroup5.add(jRadioButton18);
jRadioButton18.setText("Bad");
jButton1.setText("Confirm");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Back");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
txtGrade.setEditable(false);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel8.setText("Grade Inspection");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(135, 135, 135))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addGap(36, 36, 36)
.addComponent(jRadioButton2)
.addGap(28, 28, 28)
.addComponent(jRadioButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton7)
.addGap(36, 36, 36)
.addComponent(jRadioButton8)
.addGap(28, 28, 28)
.addComponent(jRadioButton9))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton10)
.addGap(36, 36, 36)
.addComponent(jRadioButton11)
.addGap(28, 28, 28)
.addComponent(jRadioButton12))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton13)
.addGap(36, 36, 36)
.addComponent(jRadioButton14)
.addGap(18, 18, 18)
.addComponent(jRadioButton15))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton16)
.addGap(46, 46, 46)
.addComponent(jRadioButton17)
.addGap(18, 18, 18)
.addComponent(jRadioButton18))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton4)
.addGap(36, 36, 36)
.addComponent(jRadioButton5)
.addGap(28, 28, 28)
.addComponent(jRadioButton6))))
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jButton2)
.addGap(142, 142, 142)
.addComponent(txtGrade, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel8)))
.addGap(215, 215, 215))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(jLabel8)
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jRadioButton1)
.addComponent(jRadioButton2)
.addComponent(jRadioButton3))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jRadioButton7)
.addComponent(jRadioButton8)
.addComponent(jRadioButton9))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel5))
.addComponent(jRadioButton10)
.addComponent(jRadioButton11)
.addComponent(jRadioButton12))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel6))
.addComponent(jRadioButton13)
.addComponent(jRadioButton14)
.addComponent(jRadioButton15))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jRadioButton16)
.addComponent(jRadioButton17)
.addComponent(jRadioButton18))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton4)
.addComponent(jLabel3))
.addComponent(jRadioButton5)
.addComponent(jRadioButton6))
.addGap(83, 83, 83)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(txtGrade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton1)))
);
}// </editor-fold>//GEN-END:initComponents
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(jRadioButton1.isSelected() == false && jRadioButton2.isSelected() == false && jRadioButton3.isSelected() == false){
JOptionPane.showMessageDialog(null, "answer the first question");
return;
}
if(jRadioButton7.isSelected() == false && jRadioButton8.isSelected() == false && jRadioButton9.isSelected() == false){
JOptionPane.showMessageDialog(null, "answer the second question");
return;
}
if(jRadioButton10.isSelected() == false && jRadioButton11.isSelected() == false && jRadioButton12.isSelected() == false){
JOptionPane.showMessageDialog(null, "answer the third question");
return;
}
if(jRadioButton13.isSelected() == false && jRadioButton14.isSelected() == false && jRadioButton15.isSelected() == false){
JOptionPane.showMessageDialog(null, "answer the forth question");
return;
}
if(jRadioButton16.isSelected() == false && jRadioButton17.isSelected() == false && jRadioButton18.isSelected() == false){
JOptionPane.showMessageDialog(null, "answer the fifth question");
return;
}
if(jRadioButton4.isSelected() == false && jRadioButton5.isSelected() == false && jRadioButton6.isSelected() == false){
JOptionPane.showMessageDialog(null, "answer the sixth question");
return;
}
grade = 0;
s=null;
if(jRadioButton1.isSelected()) {
grade = grade +3;
}
if(jRadioButton2.isSelected()) {
grade = grade +2;
}
if(jRadioButton3.isSelected()){
grade = grade +1;
}
if(jRadioButton7.isSelected()) {
grade = grade +3;
}
if(jRadioButton8.isSelected()) {
grade = grade +2;
}
if(jRadioButton9.isSelected()){
grade = grade +1;
}
if(jRadioButton10.isSelected()) {
grade = grade +3;
}
if(jRadioButton11.isSelected()) {
grade = grade +2;
}
if(jRadioButton12.isSelected()){
grade = grade +1;
}
if(jRadioButton13.isSelected()) {
grade = grade +3;
}
if(jRadioButton14.isSelected()) {
grade = grade +2;
}
if(jRadioButton15.isSelected()){
grade = grade +1;
}
if(jRadioButton16.isSelected()) {
grade = grade +3;
}
if(jRadioButton17.isSelected()) {
grade = grade +2;
}
if(jRadioButton18.isSelected()){
grade = grade +1;
}
if(jRadioButton4.isSelected()) {
grade = grade +3;
}
if(jRadioButton5.isSelected()) {
grade = grade +2;
}
if(jRadioButton6.isSelected()){
grade = grade +1;
}
Date date = new Date();
//isp.setGrade(grade);
isp.setLastTimeCheckDate(date);
isp.setStatus("Completed");
if(grade<=7){
s="C";
}else if(grade>7 && grade<=14){
s="B";
}else if(grade>14 && grade<=18){
s="A";
}
if(isp.getFirstInspection()==null){
isp.setFirstInspection(s);
}else if(isp.getSecondInspection()==null){
isp.setSecondInspection(s);
}else if(isp.getThirdInspection()==null){
isp.setThirdInspection(s);
}
useraccount.getInspectionWorkQueue().getWorkRequestList().remove(isp);
txtGrade.setText(s);
JOptionPane.showMessageDialog(null, "Grade Completed");
jButton1.setEnabled(false);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
/*userProcessContainer.remove(this);
CardLayout cardLayout = (CardLayout)userProcessContainer.getLayout();
cardLayout.show(userProcessContainer,"AssignJPanel"); */
userProcessContainer.remove(this);
Component[] componentArray = userProcessContainer.getComponents();
Component component = componentArray[componentArray.length - 1];
AssignJPanel assignJPanel = (AssignJPanel) component;
assignJPanel.populateTable1();
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton4ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.ButtonGroup buttonGroup4;
private javax.swing.ButtonGroup buttonGroup5;
private javax.swing.ButtonGroup buttonGroup6;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton10;
private javax.swing.JRadioButton jRadioButton11;
private javax.swing.JRadioButton jRadioButton12;
private javax.swing.JRadioButton jRadioButton13;
private javax.swing.JRadioButton jRadioButton14;
private javax.swing.JRadioButton jRadioButton15;
private javax.swing.JRadioButton jRadioButton16;
private javax.swing.JRadioButton jRadioButton17;
private javax.swing.JRadioButton jRadioButton18;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JRadioButton jRadioButton5;
private javax.swing.JRadioButton jRadioButton6;
private javax.swing.JRadioButton jRadioButton7;
private javax.swing.JRadioButton jRadioButton8;
private javax.swing.JRadioButton jRadioButton9;
private javax.swing.JTextField txtGrade;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Interface/InventoryManager/SendWorkRequest.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 Interface.InventoryManager;
import Business.Animal.Animal;
import Business.EcoSystem;
import Business.Enterprise.AnimalShelterEnterprise;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.InventoryWorkRequest;
import Business.WorkQueue.WorkRequest;
import java.awt.CardLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
/**
*
* @author <NAME>
*/
public class SendWorkRequest extends javax.swing.JPanel {
/**
* Creates new form SendWorkRequest
*/
JPanel userProcessContainer;
UserAccount userAccount;
Organization organization;
Enterprise enterprise;
Network network;
EcoSystem system;
SendWorkRequest(JPanel userProcessContainer, UserAccount userAccount, Organization organization, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=userAccount;
this.organization=organization;
this.enterprise=enterprise;
this.network=network;
this.system=system;
populateJcbEnterprise();
populateHistory();
populateCustomerRequest();
}
public void populateTable(Enterprise enterprise){
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.setRowCount(0);
if(enterprise.getAnimalDirectory()!=null){
for (Animal animal : enterprise.getAnimalDirectory().getAnimalDirectory()){
Object[] row = new Object[5];
row[0] = animal;
row[1] = animal.getBreed();
row[2]=animal.getGender();
row[3]=animal.getColor();
row[4]=animal.getAge();
model.addRow(row);
}
}
}
public void populateHistory(){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
for (WorkRequest wr : enterprise.getWorkQueueSent().getWorkRequestList()){
InventoryWorkRequest inwr=(InventoryWorkRequest)wr;
Object[] row = new Object[6];
row[0] = inwr;
row[1] = inwr.getSender();
row[2]=inwr.getAnimal();
row[3]=inwr.getAnimal().getBreed();
row[4]=inwr.getMessage();
row[5]=inwr.getStatus();
model.addRow(row);
}
}
public void populateCustomerRequest(){
DefaultTableModel model = (DefaultTableModel) jTable3.getModel();
model.setRowCount(0);
for (WorkRequest wr : organization.getWorkQueueReceived().getWorkRequestList()){
InventoryWorkRequest inwr=(InventoryWorkRequest)wr;
Object[] row = new Object[6];
row[0] = inwr;
row[1] = inwr.getSender();
row[2]=inwr.getAnimal();
row[3]=inwr.getAnimal().getBreed();
row[4]=inwr.getMessage();
row[5]=inwr.getStatus();
model.addRow(row);
}
}
public void populateJcbEnterprise(){
jcbEnterprise.removeAllItems();
for(Enterprise en:network.getEnterpriseDirectory().getEnterpriseList()){
if(en instanceof AnimalShelterEnterprise){
jcbEnterprise.addItem(en);
}
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
jcbEnterprise = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jButton2 = new javax.swing.JButton();
txtMessage = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
backJButton = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Shelter", "Sender", "Animal ID", "Breed", "Message", "Status"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
jTable1.getColumnModel().getColumn(4).setResizable(false);
jTable1.getColumnModel().getColumn(5).setResizable(false);
}
add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 738, 655, 208));
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel2.setText("Enterprise:");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 86, -1, -1));
jcbEnterprise.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbEnterprise.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcbEnterpriseActionPerformed(evt);
}
});
add(jcbEnterprise, new org.netbeans.lib.awtextra.AbsoluteConstraints(257, 86, 174, -1));
jButton1.setText("Cancle");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(705, 964, 89, 37));
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Breed", "Gender", "Color", "Age"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(jTable2);
add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 129, 655, 208));
jButton2.setText("Send");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(705, 355, 89, 37));
add(txtMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints(409, 362, 286, -1));
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel3.setText("History:");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 709, -1, -1));
jLabel1.setText("Add Message:");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(323, 365, -1, -1));
backJButton.setText("<< Back");
backJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backJButtonActionPerformed(evt);
}
});
add(backJButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 976, -1, -1));
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel4.setText("Customer Request:");
add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 399, -1, -1));
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Shelter", "Sender", "Animal ID", "Breed", "Message", "Status"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane3.setViewportView(jTable3);
if (jTable3.getColumnModel().getColumnCount() > 0) {
jTable3.getColumnModel().getColumn(0).setResizable(false);
jTable3.getColumnModel().getColumn(1).setResizable(false);
jTable3.getColumnModel().getColumn(2).setResizable(false);
jTable3.getColumnModel().getColumn(3).setResizable(false);
jTable3.getColumnModel().getColumn(4).setResizable(false);
jTable3.getColumnModel().getColumn(5).setResizable(false);
}
add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(139, 428, 655, 208));
jButton3.setText("Send");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(705, 654, 89, 37));
jButton4.setText("Reject");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(598, 654, 89, 37));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel5.setText("Send Work Request");
add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void jcbEnterpriseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbEnterpriseActionPerformed
// TODO add your handling code here:
Enterprise ent=(Enterprise)jcbEnterprise.getSelectedItem();
if(ent!=null){
populateTable(ent);
}
}//GEN-LAST:event_jcbEnterpriseActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
/*
int selectedRow = workRequestJTable.getSelectedRow();
if (selectedRow < 0){
return;
}
LabTestWorkRequest request = (LabTestWorkRequest)workRequestJTable.getValueAt(selectedRow, 0);
JOptionPane.showMessageDialog(null, "No Person Found!","Warining",JOptionPane.WARNING_MESSAGE);
*/
int selectedRow=jTable2.getSelectedRow();
if(selectedRow<0){
JOptionPane.showMessageDialog(null, "Please Select a Row First!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
Enterprise en=(Enterprise)jcbEnterprise.getSelectedItem();
if(en==enterprise){
JOptionPane.showMessageDialog(null, "Wrong Enterprise!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
Animal an=(Animal)jTable2.getValueAt(selectedRow, 0);
InventoryWorkRequest iwr=new InventoryWorkRequest();
iwr.setAnimal(an);
iwr.setEnterpriseSend(enterprise);
iwr.setEnterpriseReceive(en);
iwr.setSender(userAccount);
iwr.setStatus("sent");
String message=txtMessage.getText();
try{
iwr.setMessage(message);
}catch(Exception e){
iwr.setMessage(enterprise.getName()+" "+"Sent You an Request");
}
enterprise.getWorkQueueSent().getWorkRequestList().add(iwr);
en.getWorkQueueReceived().getWorkRequestList().add(iwr);
populateHistory();
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
int selectedRow=jTable1.getSelectedRow();
if(selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row first!");
return;
}
InventoryWorkRequest ii=(InventoryWorkRequest)jTable1.getValueAt(selectedRow, 0);
int dialogResult=JOptionPane.showConfirmDialog(null, "Are You Sure to Withdraw the Request?", "Waring",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
enterprise.getWorkQueueSent().getWorkRequestList().remove(ii);
ii.getEnterpriseReceive().getWorkQueueReceived().getWorkRequestList().remove(ii);
JOptionPane.showMessageDialog(null, "Work Request Cancled Successfully!");
}
populateHistory();
}//GEN-LAST:event_jButton1ActionPerformed
private void backJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backJButtonActionPerformed
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_backJButtonActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
int selectedRow = jTable3.getSelectedRow();
if (selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row first!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
InventoryWorkRequest iwr=(InventoryWorkRequest)jTable3.getValueAt(selectedRow, 0);
enterprise.getWorkQueueSent().getWorkRequestList().add(iwr);
iwr.getEnterpriseReceive().getWorkQueueReceived().getWorkRequestList().add(iwr);
iwr.setStatus("Approved");
organization.getWorkQueueReceived().getWorkRequestList().remove(iwr);
populateHistory();
populateCustomerRequest();
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
int selectedRow = jTable3.getSelectedRow();
if (selectedRow < 0){
JOptionPane.showMessageDialog(null, "Please select a row first!","Warining",JOptionPane.WARNING_MESSAGE);
return;
}
InventoryWorkRequest iwr=(InventoryWorkRequest)jTable3.getValueAt(selectedRow, 0);
iwr.setStatus("Rejected");
organization.getWorkQueueReceived().getWorkRequestList().remove(iwr);
populateCustomerRequest();
}//GEN-LAST:event_jButton4ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backJButton;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
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.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTable jTable3;
private javax.swing.JComboBox jcbEnterprise;
private javax.swing.JTextField txtMessage;
// End of variables declaration//GEN-END:variables
}
<file_sep>/FinalProject/FinalProject/src/Business/Organization/Organization.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Business.Organization;
import Business.Animal.AnimalDirectory;
import Business.Person.CustomerList;
import Business.Person.Staff;
import Business.Person.VolunteerList;
import Business.Role.Role;
import Business.UserAccount.UserAccountDirectory;
import Business.WorkQueue.AdoptionWorkQueue;
import Business.WorkQueue.FosterCareWorkQueue;
import Business.WorkQueue.InspectionWorkQueue;
import Business.WorkQueue.LostAnimalWorkQueue;
import Business.WorkQueue.WorkQueue;
import java.util.ArrayList;
/**
*
* @author raunak
*/
public abstract class Organization {
private String name;
private WorkQueue workQueueSent;
private WorkQueue workQueueReceived;
private AdoptionWorkQueue adoptionWorkQueue;
private LostAnimalWorkQueue lostAnimalWorkQueue;
private InspectionWorkQueue inspectionWorkQueue;
private FosterCareWorkQueue fosterCareWorkQueue;
private UserAccountDirectory userAccountDirectory;
private AnimalDirectory animalDirectory;
private Staff staff;
private int organizationID;
private static int counter;
private String ZipCode;
private String Address;
public enum Type{
Admin("Admin Organization"),
Inventory("Animal inventory center"),
Certification("Certification Organization"),
Inspection("InspectionOrganization");
private String value;
private Type(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public Organization(String name) {
this.name = name;
workQueueSent = new WorkQueue();
workQueueReceived = new WorkQueue();
adoptionWorkQueue=new AdoptionWorkQueue();
lostAnimalWorkQueue=new LostAnimalWorkQueue();
inspectionWorkQueue = new InspectionWorkQueue();
fosterCareWorkQueue = new FosterCareWorkQueue();
animalDirectory=new AnimalDirectory();
staff=new Staff();
userAccountDirectory = new UserAccountDirectory();
organizationID = counter;
++counter;
}
public AdoptionWorkQueue getAdoptionWorkQueue() {
return adoptionWorkQueue;
}
public LostAnimalWorkQueue getLostAnimalWorkQueue() {
return lostAnimalWorkQueue;
}
public FosterCareWorkQueue getFosterCareWorkQueue() {
return fosterCareWorkQueue;
}
public void setFosterCareWorkQueue(FosterCareWorkQueue fosterCareWorkQueue) {
this.fosterCareWorkQueue = fosterCareWorkQueue;
}
public String getZipCode() {
return ZipCode;
}
public void setZipCode(String ZipCode) {
this.ZipCode = ZipCode;
}
public String getAddress() {
return Address;
}
public void setAddress(String Address) {
this.Address = Address;
}
public abstract ArrayList<Role> getSupportedRole();
public UserAccountDirectory getUserAccountDirectory() {
return userAccountDirectory;
}
public int getOrganizationID() {
return organizationID;
}
public Staff getStaff() {
return staff;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
public WorkQueue getWorkQueueSent() {
return workQueueSent;
}
public void setWorkQueueSent(WorkQueue workQueueSent) {
this.workQueueSent = workQueueSent;
}
public WorkQueue getWorkQueueReceived() {
return workQueueReceived;
}
public void setWorkQueueReceived(WorkQueue workQueueReceived) {
this.workQueueReceived = workQueueReceived;
}
public AnimalDirectory getAnimalDirectory() {
return animalDirectory;
}
public InspectionWorkQueue getInspectionWorkQueue() {
return inspectionWorkQueue;
}
public void setInspectionWorkQueue(InspectionWorkQueue inspectionWorkQueue) {
this.inspectionWorkQueue = inspectionWorkQueue;
}
}
<file_sep>/FinalProject/FinalProject/src/Interface/CustomerRole/CustomerRoleWorkArea.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 Interface.CustomerRole;
import Business.Animal.Animal;
import Business.EcoSystem;
import Business.Enterprise.Enterprise;
import Business.Network.Network;
import Business.Organization.Organization;
import Business.UserAccount.UserAccount;
import Business.WorkQueue.AdoptionWorkRequest;
import Business.WorkQueue.InspectionWorkRequest;
import Interface.InventoryManager.ManageAnimalInventory;
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* @author <NAME>
*/
public class CustomerRoleWorkArea extends javax.swing.JPanel {
/** Creates new form CustomerRoleWorkArea */
JPanel userProcessContainer;
UserAccount userAccount;
Enterprise enterprise;
Network network;
EcoSystem system;
public CustomerRoleWorkArea(JPanel userProcessContainer, UserAccount account, Enterprise enterprise, Network network, EcoSystem system) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.userAccount=account;
this.enterprise=enterprise;
this.network=network;
this.system=system;
}
/** 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() {
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("Search for Adoption");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(294, 152, 179, -1));
jButton3.setText("Find a Lost Animal");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(294, 212, 179, -1));
jButton4.setText("Need foster care");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(294, 272, 179, -1));
jButton5.setText("Help others to foster care");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(294, 338, -1, -1));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setText("Customer Work Area");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
SearchForAdoption sfa = new SearchForAdoption(userProcessContainer, userAccount, enterprise, network, system);
userProcessContainer.add("SearchForAdoption", sfa);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
ReportJPanel reportJPanel = new ReportJPanel(userProcessContainer, userAccount, enterprise, network, system);
userProcessContainer.add("reportJPanel", reportJPanel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
/*ReportALostAnimal rla = new ReportALostAnimal(userProcessContainer, userAccount, enterprise, network, system);
userProcessContainer.add("ReportALostAnimal", rla);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);*/
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
FosterCareAnnounce fosterCareAnnounce = new FosterCareAnnounce( userProcessContainer, userAccount, enterprise, network, system);
userProcessContainer.add("fosterCareAnnounce", fosterCareAnnounce);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
// TODO add your handling code here:
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
HelpToFosterCare helpToFosterCare = new HelpToFosterCare(userProcessContainer, userAccount, enterprise, network, system);
userProcessContainer.add("helpToFosterCarel", helpToFosterCare);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
// TODO add your handling code here:
}//GEN-LAST:event_jButton5ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| ae696524b0757a3515d02d57d4c48f5c6f9630f6 | [
"Markdown",
"Java"
] | 17 | Java | YoumingZheng/Animal-Shelter_JAVA-Project_NetBeans | b452c69c327922e55f99c879116ca77c5f748dbf | 926b6d6c79f0ffd2c2c6268f11dee2eda4cc9bda | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VehicleSpawner : MonoBehaviour
{
public GameObject vehiclePrefab;
public Transform vehicleContains;
public int vehiclesToSpawn;
public Coroutine cor;
void Start()
{
cor = StartCoroutine(SpawnCar());
}
IEnumerator SpawnCar()
{
if (cor == null)
{
int count = 0;
while (count < vehiclesToSpawn)
{
GameObject newVehicle = Instantiate(vehiclePrefab, vehicleContains);
Transform child = transform.GetChild(Random.Range(0, transform.childCount - 1));
newVehicle.GetComponent<WaypointNavigator>().currentWaypoint = child.GetComponent<Waypoint>();
newVehicle.transform.position = child.position;
yield return new WaitForSeconds(1.5f);
count++;
}
cor = null;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterNavigationController : MonoBehaviour
{
public Transform mTransform;
public Vector3 destination;
public float stopDistance = .5f;
public float movementSpeed = 1f;
public float rotationSpeed = 120f;
public bool reachedDestination = false;
[HideInInspector] public Vector3 lastPosition;
[Header("Sensors")]
public float sensorLength = 15f;
public Vector3 frontSensorPosition;
public float frontSideSensorPosition;
public float frontSensorAngle;
private bool avoiding = false;
float avoidMultiplier = 0;
Vector3 sensorStartPos;
void Update()
{
CheckSensor();
if (transform.position != destination)
{
Vector3 destinationDirection = destination - transform.position;
destinationDirection.y = 0;
float destinationDistance = destinationDirection.magnitude;
if (!avoiding)
{
if (destinationDistance >= stopDistance)
{
reachedDestination = false;
Quaternion targetRotation = Quaternion.LookRotation(destinationDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
else
{
reachedDestination = true;
}
}
else
{
if (destinationDistance >= stopDistance)
{
reachedDestination = false;
Quaternion targetRotation = Quaternion.LookRotation(destinationDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
transform.Translate(Vector3.forward * avoidMultiplier * movementSpeed * Time.deltaTime);
}
else
{
reachedDestination = true;
}
}
}
}
public void SetDestination(Vector3 destination)
{
this.destination = destination;
reachedDestination = false;
}
public void CheckSensor()
{
RaycastHit hit;
sensorStartPos = mTransform.position;
sensorStartPos += mTransform.forward * frontSensorPosition.z;
sensorStartPos += mTransform.up * frontSensorPosition.y;
avoidMultiplier = 0;
avoiding = false;
//front center
if (Physics.Raycast(sensorStartPos, mTransform.forward, out hit, sensorLength))
{
if (!hit.collider.CompareTag("Road") && hit.collider.CompareTag("Car"))
{
Debug.DrawLine(sensorStartPos, hit.point);
avoiding = true;
}
}
//front right sensor
sensorStartPos += transform.right * frontSideSensorPosition;
if (Physics.Raycast(sensorStartPos, transform.forward, out hit, sensorLength))
{
if (!hit.collider.CompareTag("Road") && hit.collider.CompareTag("Car"))
{
Debug.DrawLine(sensorStartPos, hit.point, Color.red);
avoidMultiplier -= 1f;
avoiding = true;
}
}
//front right angle sensor
else if (Physics.Raycast(sensorStartPos, Quaternion.AngleAxis(frontSensorAngle, transform.up) * transform.forward, out hit, sensorLength))
{
if (!hit.collider.CompareTag("Road") && hit.collider.CompareTag("Car"))
{
Debug.DrawLine(sensorStartPos, hit.point, Color.blue);
avoidMultiplier -= 0.5f;
avoiding = true;
}
}
//front left sensor
sensorStartPos -= transform.right * frontSideSensorPosition * 2;
if (Physics.Raycast(sensorStartPos, transform.forward, out hit, sensorLength))
{
if (!hit.collider.CompareTag("Road") && hit.collider.CompareTag("Car"))
{
Debug.DrawLine(sensorStartPos, hit.point, Color.red);
avoidMultiplier += 1f;
avoiding = true;
}
}
//front left angle sensor
else if (Physics.Raycast(sensorStartPos, Quaternion.AngleAxis(-frontSensorAngle, transform.up) * transform.forward, out hit, sensorLength))
{
if (!hit.collider.CompareTag("Road") && hit.collider.CompareTag("Car"))
{
Debug.DrawLine(sensorStartPos, hit.point, Color.blue);
avoidMultiplier += 0.5f;
avoiding = true;
}
}
}
}
<file_sep>using UnityEngine;
public class RayTest : MonoBehaviour
{
[Header("Sensors")]
public float sensorLength = 5f;
//public Vector3 frontSensorPosition;
public Transform mtransform;
private void FixedUpdate()
{
CheckSensor();
}
public void CheckSensor()
{
RaycastHit hit;
Vector3 sensorStartPos = mtransform.position;
if (Physics.Raycast(sensorStartPos, mtransform.forward, out hit, sensorLength))
{
}
Debug.DrawLine(sensorStartPos, hit.point);
}
}
| f4d08e7b7f12b010a1a23435546ec55d3242a590 | [
"C#"
] | 3 | C# | NurYilmaz34/TrafficAI | dcc47906823d9f5cf1fade4a42b0a05cfbf13cf1 | f1ba08fa18329bfb1dfbee0cf65a27d65d24ffef | |
refs/heads/main | <repo_name>jesuscardenascastro/Practica01Grupo08<file_sep>/selectionSortppc/SelectionSortPlusPlus.cpp
// heapSortV2.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
// heapSort.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include <stdio.h>
#include <iostream>
#include <chrono>
#include <fstream>
#include <string>
#include <windows.h>
#include <limits.h>
#include <tchar.h>
using namespace std;
using namespace std::chrono;
float t0, t1;
void swap(long int* a, long int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void selectionSort( int arr[], int n)
{
long int i, j, midx;
for (i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
midx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[midx])
midx = j;
// Swap the found minimum element
// with the first element
swap(arr[midx], arr[i]);
}
}
string getCurrentDir() {
char buff[MAX_PATH];
GetModuleFileName( NULL, buff, MAX_PATH );
string::size_type position = string( buff ).find_last_of( "\\/" );
return string( buff ).substr( 0, position);
}
int main()
{
int arr2[] = { 100,200,300,400,500,600,700,800,900,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,20000,30000,40000,50000,60000,70000,80000,90000,100000 };
int n = sizeof(arr2) / sizeof(arr2[0]);
string str1 = "";
for (int i = 0; i < n; i++) {
int num = arr2[i];
int* arr = nullptr;
arr = new int[num];
//ifstream file("E:\\2021\\UNSA\\Semestre I\\Algoritmos\\Practica\\Trabajo en equipo\\Practica01Grupo08\\Luis\\data\\archivo" + to_string(num) + ".txt");
ifstream file(getCurrentDir() +"\\data\\archivo" + to_string(num) + ".txt");
if (file.is_open())
{
for (int i = 0; i < num; ++i)
{
file >> arr[i];
}
file.close();
}
cout << num << endl;
auto t0 = high_resolution_clock::now();
selectionSort(arr, num);
auto t1 = high_resolution_clock::now();
/* Getting number of milliseconds as an integer. */
auto ms_int = duration_cast<milliseconds>(t1 - t0);
/* Getting number of milliseconds as a double. */
duration<double, std::milli> ms_double = t1 - t0;
str1 = str1 + to_string(num) + "," + to_string(ms_double.count()) + "\n";
}
ofstream MyFile(getCurrentDir() +"\\SelectionSortC.txt");
MyFile << str1 << endl;
MyFile.close();
return 0;
}
<file_sep>/graficos.py
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter, StrMethodFormatter
def main():
#Generate Bubble Sort
resBubbleSortC = np.loadtxt("./ResBubbleSortCPlusPlus.txt", dtype='f')
resBubbleSortPy = np.loadtxt("./ResBubbleSortPython.txt", dtype='f')
ax = plt.subplot(1,2,1)
# plt.subplot(1, 2, 1)
# ax.title('Bubble Sort')
ax.plot(resBubbleSortC[:,0],resBubbleSortC[:,1], color='green', linewidth=2.0, linestyle='-', label='C++')
ax.plot(resBubbleSortPy[:,0],resBubbleSortPy[:,1], color='orange', linewidth=2.0, linestyle='-', label='Python')
ax.yaxis.set_major_formatter(StrMethodFormatter('{x:,}'))
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:,}'))
plt.title('Bubble Sort')
plt.xlabel('Data')
plt.ylabel('Miliseconds')
plt.legend(loc='upper left')
#Generate Counting Sort
resCountSortC = np.loadtxt("./ResCountingSortCPlusPlus.txt", dtype='f')
resCountSortPy = np.loadtxt("./ResCountingSortPython.txt", dtype='f')
ax2 = plt.subplot(1, 2, 2)
plt.title('Counting Sort')
ax2.plot(resCountSortC[:,0],resCountSortC[:,1], color='green', linewidth=2.0, linestyle='-', label='C++ ')
ax2.plot(resCountSortPy[:,0],resCountSortPy[:,1], color='orange', linewidth=2.0, linestyle='-', label='Python')
ax2.yaxis.set_major_formatter(StrMethodFormatter('{x:,}'))
ax2.xaxis.set_major_formatter(StrMethodFormatter('{x:,}'))
plt.xlabel('Data')
plt.ylabel('Miliseconds')
plt.legend(loc='upper left')
plt.show()
main() | cea7c75cea9e9c5dbe0f18d5255f9a8abedab642 | [
"Python",
"C++"
] | 2 | C++ | jesuscardenascastro/Practica01Grupo08 | 86208ce1f907572a85485031049e506dde33948e | f96d10c389a1653c8af77748b6c390c6c925e25f | |
refs/heads/master | <file_sep>Rails.application.routes.draw do
devise_for :users
root to: 'pages#home'
resources :users, only: [ :show, :index ]
post 'users/:id/friendships', to: 'friendships#create', as: :user_friendships_create
resources :challenges, only: [ :new, :create, :index, :show ] do
resources :challenge_users, only: [ :new, :create ]
resources :goals, only: [ :new, :create ]
end
delete 'friendships/:id', to: 'friendships#destroy', as: :friendships_destroy
patch 'friendships/:id', to: 'friendships#update', as: :friendships_update
resources :friendships, only: [ :index ]
patch 'challenge_users/:id', to: 'challenge_users#update'
post 'goals/:id/progress_entries', to: 'progress_entries#create'
resources :user_goals do
patch :plus_one
end
get "memories", to: "memories#index"
end
<file_sep>class UserGoalsController < ApplicationController
def plus_one
@user_goal = UserGoal.find(params[:user_goal_id])
@user_goal.current_amount += 1
@user_goal.save!
@challenge = @user_goal.goal.challenge
redirect_to challenge_path(@challenge, anchor: "container-#{@user_goal.goal.id}")
end
end
<file_sep>class Challenge < ApplicationRecord
belongs_to :user
has_many :challenge_users
has_many :users, through: :challenge_users
has_many :goals
has_many :user_goals, through: :goals
validates :name, presence: true
validates :end_date, presence: true
validates :start_date, presence: true
def day_of_challenge
(Date.today - self.start_date).to_i
end
def challenge_duration
(self.end_date - self.start_date).to_i
end
def days_left
(self.end_date - Date.today).to_i
end
end
<file_sep>class UserGoal < ApplicationRecord
belongs_to :user
belongs_to :goal
has_many :steps
# finds ACTUAL amount for specific user and specific goal
# scope :user_amount_of_day, ->(goal, user) { where(user: user, goal: goal)[0].current_amount }
def delta_to_target
self.current_amount - self.goal.goal_for_the_day
end
def delta_to_team_average
self.current_amount - self.goal.team_average
end
end
<file_sep>class Goal < ApplicationRecord
belongs_to :challenge
has_many :user_goals
has_many :steps, through: :user_goals
has_many :users, through: :user_goals
validates :name, presence: true
validates :target_amount, presence: true
validates :unit, presence: true
# validates :goal_type, presence: true
enum goal_type: [:min_amount, :max_amount]
def team_average
all_amounts = self.user_goals.map{|x| x[:current_amount]}
team_average = all_amounts.inject(&:+).to_f / all_amounts.size
return team_average
end
def min_max_nice
self.goal_type == "min_amount" ? "min" : "max"
end
def amount_per_day
(self.target_amount.to_f / self.challenge.challenge_duration.to_f)
end
def goal_for_the_day
self.amount_per_day * self.challenge.day_of_challenge
end
end
<file_sep>class GoalsController < ApplicationController
def new
@challenge = Challenge.find(params[:challenge_id])
@goals = @challenge.goals
@goal = Goal.new
end
def create
@challenge = Challenge.find(params[:challenge_id])
@goals = @challenge.goals
@goal = Goal.new(goal_params)
@goal.challenge = @challenge
if @goal.save
# UserGoal.create(user: user, goal: goal, current_amount: amount)
@challenge.users.each do |user|
UserGoal.find_or_create_by(goal: @goal, user: user)
end
redirect_to challenge_path(@challenge)
else
render :new
end
end
private
def goal_params
params.require(:goal).permit(:name, :target_amount, :unit)
end
end
<file_sep>class Step < ApplicationRecord
belongs_to :user_goal
end
<file_sep>class UsersController < ApplicationController
def index
@friendships = Friendship.where("asker_id = ? or receiver_id = ?", current_user.id, current_user.id)
@friends = []
@friendships.each do |friendship|
if friendship.receiver_id == current_user.id
@friends << friendship.asker
else
@friends << friendship.receiver
end
end
if params[:query].present?
@users = User.where("first_name ILIKE ?", "%#{params[:query]}%")
else
@users = []
end
@users -= @friends
end
end
<file_sep>class ChallengeUsersController < ApplicationController
def new
@challenge = Challenge.find(params[:challenge_id])
@challenge_users = @challenge.challenge_users
@challenge_user = ChallengeUser.new
@friendships_unsorted = Friendship.where(asker_id: current_user.id) + Friendship.where(receiver_id: current_user.id)
@friendships = @friendships_unsorted.select { |friendship| friendship.accepted? }
@friends_unsorted = []
@friendships.each do |friendship|
@friends_unsorted << User.find(friendship.asker_id)
@friends_unsorted << User.find(friendship.receiver_id)
end
@friends = @friends_unsorted.uniq.reject { |friend| friend.id == current_user.id }
end
def create
@challenge = Challenge.find(params[:challenge_id])
@challenge_users = @challenge.challenge_users
@challenge_users_names = @challenge_users.map {|user| user.user.first_name}
@challenge_user = ChallengeUser.new(challenge_user_params)
@challenge_user.challenge = @challenge
if @challenge_user.save && !@challenge_users_names.include?(@challenge_user.user.first_name)
@challenge.goals.each do |goal|
UserGoal.create(user_id: @challenge_user.user_id, goal_id: goal.id, current_amount: 0)
end
redirect_to challenge_path(@challenge)
end
end
private
def challenge_user_params
params.require(:challenge_user).permit(:user_id)
end
end
<file_sep>class FriendshipsController < ApplicationController
def index
@friendships = Friendship.where("asker_id = ? or receiver_id = ?", current_user.id, current_user.id)
@friends = []
@friends_pending = []
@friends_accepting = []
@friendships.each do |friendship|
if friendship.status != "pending"
if friendship.receiver_id == current_user.id
@friends << friendship.asker
else
@friends << friendship.receiver
end
else
if friendship.asker_id == current_user.id
@friends_pending << friendship.receiver
else
@friends_accepting << friendship.asker
end
end
end
end
def create
friendship = Friendship.new
friendship.asker = current_user
user = User.find(params[:id])
friendship.receiver = user
friendship.status = 0
friendship.save!
redirect_to friendships_path
end
def update
@friendships = Friendship.where("asker_id = ? and receiver_id = ? or asker_id = ? and receiver_id = ?", current_user.id, params[:id], params[:id], current_user.id)
@friendships.each do |friendship|
friendship.update(:status => 1)
end
redirect_to friendships_path
end
def destroy
@friendships = Friendship.where("asker_id = ? and receiver_id = ? or asker_id = ? and receiver_id = ?", current_user.id, params[:id], params[:id], current_user.id)
@friendships.each do |friendship|
friendship.destroy
end
redirect_to friendships_path
end
end
<file_sep>class AddDefaultValueUserGoal < ActiveRecord::Migration[6.0]
def change
change_column :user_goals, :current_amount, :integer, default: 0
end
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'date'
UserGoal.destroy_all
Goal.destroy_all
ChallengeUser.destroy_all
Challenge.destroy_all
Friendship.destroy_all
User.destroy_all
puts "** Let's create some users for my2022 **"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1617603749/da22yjwdbfkl4uq8cqvy.jpg')
jonas = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Jonas", last_name: "Hagedorn")
jonas.photo.attach(io: file, filename: 'jonas.jpg', content_type: 'image/jpg')
jonas.save!
puts "#{jonas.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1617604976/nuur2wmzwub7k9xcgd5f.jpg')
caterina = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Caterina", last_name: "Biffis")
caterina.photo.attach(io: file, filename: 'caterina.jpg', content_type: 'image/jpg')
caterina.save!
puts "#{caterina.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1617972092/txqoasjgslma5y22gfdu.jpg')
silke = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Silke", last_name: "Guthrie")
silke.photo.attach(io: file, filename: 'silke.jpg', content_type: 'image/jpg')
silke.save!
puts "#{silke.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1617954179/ojiticlbou6iocwbqeje.jpg')
seb = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Sebastian", last_name: "Strube")
seb.photo.attach(io: file, filename: 'seb.jpg', content_type: 'image/jpg')
seb.save!
puts "#{seb.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1596118942/yvkorthmlicxnuag0szm.jpg')
max = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Max", last_name: "Keller")
max.photo.attach(io: file, filename: 'max.jpg', content_type: 'image/jpg')
max.save!
puts "#{max.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1601461074/xrbi2mzjyawsdisknhdd.jpg')
santi = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Santi", last_name: "Sanchez")
santi.photo.attach(io: file, filename: 'santi.jpg', content_type: 'image/jpg')
santi.save!
puts "#{santi.first_name} was created. What a great user!"
file = URI.open('https://avatars.githubusercontent.com/u/37805251?v=4')
val = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Valerie", last_name: "Schraauwers")
val.photo.attach(io: file, filename: 'val.jpg', content_type: 'image/jpg')
val.save!
puts "#{val.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1617958938/yniyzgmayab38bubnpjb.jpg')
dave = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "David", last_name: "Klören
")
dave.photo.attach(io: file, filename: 'dave.jpg', content_type: 'image/jpg')
dave.save!
puts "#{dave.first_name} was created. What a great user!"
file = URI.open('https://res.cloudinary.com/wagon/image/upload/c_fill,g_face,h_200,w_200/v1617870772/pllppuncxqixjiwdavjr.jpg')
soto = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Soto", last_name: "Dimitriu")
soto.photo.attach(io: file, filename: 'soto.jpg', content_type: 'image/jpg')
soto.save!
puts "#{soto.first_name} was created. What a great user!"
file = URI.open('https://avatars.githubusercontent.com/u/80338339?v=4')
marnie = User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Marnie", last_name: "Nyenhuis")
marnie.photo.attach(io: file, filename: 'marnie.jpg', content_type: 'image/jpg')
marnie.save!
puts "#{marnie.first_name} was created. What a great user!"
puts "** #{User.count} beautiful users created! They will love the app! **"
puts ""
puts "Lets make some friendships"
friendship1 = Friendship.new(asker_id: jonas.id, receiver_id: seb.id, status: 1)
friendship1.save!
friendship1 = Friendship.new(asker_id: jonas.id, receiver_id: caterina.id, status: 1)
friendship1.save!
friendship1 = Friendship.new(asker_id: jonas.id, receiver_id: silke.id, status: 1)
friendship1.save!
friendship1 = Friendship.new(asker_id: jonas.id, receiver_id: marnie.id, status: 1)
friendship1.save!
puts ""
puts "** Now let's build a challenge **"
challenge1 = Challenge.new(name: "Surviving the bootcamp", description: "Let's not destroy our bodies tooo much while coding the whole day", start_date: "12.04.2021", end_date: "13.06.2021", user: jonas)
challenge1.save!
puts "The challenge with the fancy name << #{challenge1.name} >> was created by #{challenge1.user.first_name}. It starts at #{challenge1.start_date} and ends at #{challenge1.end_date}."
puts ""
puts "** Let's see, which friends will be joining #{challenge1.user.first_name} for the challenge ***"
ChallengeUser.create(challenge: challenge1, user: jonas)
ChallengeUser.create(challenge: challenge1, user: seb)
ChallengeUser.create(challenge: challenge1, user: silke)
ChallengeUser.create(challenge: challenge1, user: caterina)
puts ""
puts "** Now let's add some GOALS to the challenge << #{challenge1.name} >>**"
goal1 = Goal.new(challenge: challenge1, name: "Flashcard Practice", target_amount: 36, unit: "days", goal_type: :min_amount)
goal1.save!
puts "The goal << #{goal1.name} (#{goal1.goal_type} #{goal1.target_amount} #{goal1.unit}) >> was added to the challenge."
# add minmax
goal2 = Goal.new(challenge: challenge1, name: "Do sports", target_amount: 27, unit: "Sport Sessions", goal_type: :min_amount)
goal2.save!
puts "The goal << #{goal2.name} (#{goal2.goal_type} #{goal2.target_amount} #{goal2.unit}) >> was added to the challenge."
goal3 = Goal.new(challenge: challenge1, name: "Meet new people", target_amount: 32, unit: "new Person", goal_type: :min_amount)
goal3.save!
puts "The goal << #{goal3.name} (#{goal3.goal_type} #{goal3.target_amount} #{goal3.unit}) >> was added to the challenge."
goal4 = Goal.new(challenge: challenge1, name: "Rock the demo day", target_amount: 1, unit: "Demo Day rocked", goal_type: :min_amount)
goal4.save!
puts "The goal << #{goal4.name} (#{goal4.goal_type} #{goal4.target_amount} #{goal4.unit}) >> was added to the challenge."
puts ""
puts "*** Now let's see, how everyone is performing... ***"
UserGoal.create(user: jonas, goal: goal1, current_amount: 37)
UserGoal.create(user: seb, goal: goal1, current_amount: 20)
UserGoal.create(user: silke, goal: goal1, current_amount: 32)
UserGoal.create(user: caterina, goal: goal1, current_amount: 25)
UserGoal.create(user: jonas, goal: goal2, current_amount: 20)
UserGoal.create(user: seb, goal: goal2, current_amount: 12)
UserGoal.create(user: silke, goal: goal2, current_amount: 33)
UserGoal.create(user: caterina, goal: goal2, current_amount: 37)
UserGoal.create(user: jonas, goal: goal3, current_amount: 15)
UserGoal.create(user: seb, goal: goal3, current_amount: 45)
UserGoal.create(user: silke, goal: goal3, current_amount: 35)
UserGoal.create(user: caterina, goal: goal3, current_amount: 25)
UserGoal.create(user: jonas, goal: goal4, current_amount: 0)
UserGoal.create(user: seb, goal: goal4, current_amount: 1)
UserGoal.create(user: silke, goal: goal4, current_amount: 1)
UserGoal.create(user: caterina, goal: goal4, current_amount: 1)
puts "/// USER PROGRESS TO BE ADDED ///"
puts "** Now let's build a 2nd challenge **"
challenge2 = Challenge.create(name: "Life after bootcamp", description: "Let's make sure to keep crushing what we have learned", start_date: "11.06.2021", end_date: "09.09.2021", user: jonas)
challenge2.save!
ChallengeUser.create(challenge: challenge2, user: jonas)
ChallengeUser.create(challenge: challenge2, user: marnie)
goal21 = Goal.new(challenge: challenge2, name: "Revise Lectures", target_amount: 25, unit: "Lectures", goal_type: :min_amount)
goal21.save!
puts "The goal << #{goal21.name} (#{goal21.goal_type} #{goal2.target_amount} #{goal21.unit}) >> was added to the challenge."
goal22 = Goal.new(challenge: challenge2, name: "Play CSS Codewars", target_amount: 50, unit: "Hours", goal_type: :min_amount)
goal22.save!
puts "The goal << #{goal22.name} (#{goal22.goal_type} #{goal2.target_amount} #{goal22.unit}) >> was added to the challenge."
puts "*** Now let's see, how everyone is performing... ***"
UserGoal.create(user: jonas, goal: goal21, current_amount: 0)
UserGoal.create(user: jonas, goal: goal22, current_amount: 0)
UserGoal.create(user: marnie, goal: goal21, current_amount: 0)
UserGoal.create(user: marnie, goal: goal22, current_amount: 0)
<file_sep>class Friendship < ApplicationRecord
belongs_to :asker, class_name: "User"
belongs_to :receiver, class_name: "User"
enum status: [:pending, :accepted, :declined]
end
<file_sep>class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :user_goals
has_many :challenge_users
has_many :challenges, through: :challenge_users
has_many :goals, through: :user_goals
has_many :friendships_as_asker, class_name: "Friendship", foreign_key: :asker_id
has_many :friendships_as_receiver, class_name: "Friendship", foreign_key: :receiver_id
validates :first_name, presence: true
validates :last_name, presence: true
has_one_attached :photo
def full_name
"#{first_name} #{last_name}"
end
end
<file_sep>require 'date'
class ChallengesController < ApplicationController
def new
@challenge = Challenge.new
end
def create
@challenge = Challenge.new(challenge_params)
@challenge.user = current_user
if @challenge.save
ChallengeUser.create(challenge: @challenge, user: current_user) # accepted: true)
redirect_to challenge_path(@challenge)
else
render :new
end
end
def index
@challenge_users = ChallengeUser.where(user: current_user)
end
def show
@challenge = Challenge.find(params[:id])
@users = @challenge.users
@goals = @challenge.goals
end
private
def challenge_params
params.require(:challenge). permit(:name, :start_date, :end_date)
end
end
<file_sep>class AddStartDateToChallenge < ActiveRecord::Migration[6.0]
def change
add_column :challenges, :start_date, :date
end
end
| 2a0aaa4ff2a62b64be3a79803ea7fa49c000d9d6 | [
"Ruby"
] | 16 | Ruby | sebstrfra/my2022 | 5a3eae2913ad291ca61ce52f9f8e63ab032513b8 | 4216067a162716ea434aac7f1e1c1da69976959b | |
refs/heads/master | <repo_name>jiahao0428/hadoop-spark-cluster<file_sep>/bootstrap.sql
CREATE DATABASE metastore;
USE metastore;
SOURCE /usr/local/hive/scripts/metastore/upgrade/mysql/hive-schema-0.14.0.mysql.sql;
CREATE USER 'hiveuser'@'%' IDENTIFIED BY 'hivepassword';
GRANT all on *.* to 'hiveuser'@localhost identified by 'hive<PASSWORD>';
flush privileges;
<file_sep>/README.md
# Apache Hadoop/Yarn 2.7.1 cluster Docker image
This project is actually a clone from https://github.com/sfedyakov/hadoop-271-cluster with some small usability enhancements and some to let the image work in Docker Machine/Compose Swarm clusters and use Spark. The essence of the latter enhancements is to copy entries from /etc/hosts to nodes across the cluster, because Docker Compose has some bugs with DNS and host aliases.
# Build the image
Before you build, please download the following: Oracle Java and Apache Hadoop.
# Limitations
Please be aware of the following
- You have to download each installing packages (hadoop, spark, hive)
- Exactly one Namenode is allowed
- /etc/hosts are synchronized continuously every 60 seconds. So if you add more nodes during cluster run, new nodes may not be visible to existing ones for about a minute. Hope, Docker will fix their Compose DNS issues!
<file_sep>/Dockerfile
# Creates pseudo distributed hadoop 2.7.1
#
# sudo docker build -t yarn_cluster .
FROM sequenceiq/pam:centos-6.5
MAINTAINER <NAME> <EMAIL>
USER root
# install dev tools
RUN yum -y update && \
yum install -y centos-release-SCL && \
yum install -y python27 && \
yum install -y curl which tar sudo openssh-server openssh-clients rsync | true && \
yum update -y libselinux | true && \
yum install dnsmasq -y && \
yum reinstall cracklib-dicts -y && \
echo source /etc/bashrc > /root/.bash_profile && \
echo user=root >> /etc/dnsmasq.conf && \
echo bogus-priv >> /etc/dnsmasq.conf && \
echo interface=eth0 >> /etc/dnsmasq.conf && \
echo no-dhcp-interface=eth0 >> /etc/dnsmasq.conf
# passwordless ssh
RUN ssh-keygen -q -N "" -t dsa -f /etc/ssh/ssh_host_dsa_key && \
ssh-keygen -q -N "" -t rsa -f /etc/ssh/ssh_host_rsa_key && \
ssh-keygen -q -N "" -t rsa -f /root/.ssh/id_rsa && \
cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys
# java
ADD jdk-8u73-linux-x64.rpm /tmp/
RUN rpm -i /tmp/jdk-8u73-linux-x64.rpm && \
rm /tmp/jdk-8u73-linux-x64.rpm
# hadoop
ADD hadoop-2.7.1.tar.gz /usr/local/
RUN cd /usr/local && ln -s ./hadoop-2.7.1 hadoop && \
rm /usr/local/hadoop/lib/native/*
# sbt
RUN curl https://bintray.com/sbt/rpm/rpm | tee /etc/yum.repos.d/bintray-sbt-rpm.repo
RUN yum install -y sbt
# git
RUN yum install -y git
# maven
RUN yum install -y wget
RUN wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
RUN sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
RUN yum install -y apache-maven
# pip
RUN rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
RUN yum groupinstall -y development
RUN yum install -y zlib-dev openssl-devel sqlite-devel bzip2-devel
ADD Python-2.7.6.tar.xz /usr/local/
RUN cd /usr/local/Python-2.7.6 && ./configure --prefix=/usr/local
RUN cd /usr/local/Python-2.7.6 && make
RUN cd /usr/local/Python-2.7.6 && make altinstall
ENV PATH=/usr/local/Python-2.7.6:$PATH
#RUN yum install -y python-devel
ADD get-pip.py /
RUN cd / && python get-pip.py
RUN pip install requests
RUN pip install numpy
RUN pip install cython
RUN pip install pandas
# Zeppline
RUN git clone https://github.com/apache/incubator-zeppelin.git
RUN mv incubator-zeppelin /usr/local/zeppelin
RUN cd /usr/local/zeppelin && mvn install -DskipTests -Drat.skip=true
# fixing the libhadoop.so like a boss
ADD hadoop-native-64-2.7.0.tar /usr/local/hadoop/lib/native/
ENV HADOOP_PREFIX=/usr/local/hadoop \
HADOOP_COMMON_HOME=/usr/local/hadoop \
HADOOP_HDFS_HOME=/usr/local/hadoop \
HADOOP_MAPRED_HOME=/usr/local/hadoop \
HADOOP_YARN_HOME=/usr/local/hadoop \
HADOOP_CONF_DIR=/usr/local/hadoop/etc/hadoop \
YARN_CONF_DIR=$HADOOP_PREFIX/etc/hadoop \
JAVA_HOME=/usr/java/default \
SPARK_HOME=/usr/local/spark \
SPARK_YARN_QUEUE=dev \
SCALA_HOME=/usr/local/scala \
ELASTICSEARCH_HOME=/usr/local/elasticsearch \
KIBANA_HOME=/usr/local/kibana \
TERM=xterm \
HIVE_HOME=/usr/local/hive
ENV PATH=$PATH:$JAVA_HOME/bin:$HADOOP_HDFS_HOME/bin:$SPARK_HOME/bin:$SPARK_HOME/sbin:$HIVE_HOME/bin:$SCALA_HOME/bin:$ELASTICSEARCH_HOME/bin:$KIBANA_HOME/bin:.
ENV PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/build:$PYTHONPATH
#ENV alias elasticsearch='elasticsearch -Des.insecure.allow.root=true'
# hive
ADD apache-hive-2.0.1-bin.tar.gz /usr/local/
RUN cd /usr/local && ln -s ./apache-hive-2.0.1-bin hive
ADD hive-site.xml /usr/local/hive/conf/
RUN cd /usr/local/hive/conf && cp hive-env.sh.template hive-env.sh
# mysql
RUN yum install -y mysql-server
RUN yum install -y mysql-connector-java
RUN cp /usr/share/java/mysql-connector-java.jar /usr/local/hive/lib/
ADD bootstrap.sql /usr/local/hive/
RUN sed -i '/^export JAVA_HOME/ s:.*:export JAVA_HOME=/usr/java/default\nexport HADOOP_PREFIX=/usr/local/hadoop\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh && \
sed -i '/^export HADOOP_CONF_DIR/ s:.*:export HADOOP_CONF_DIR=/usr/local/hadoop/etc/hadoop/:' $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh && \
mkdir $HADOOP_PREFIX/input && \
cp $HADOOP_PREFIX/etc/hadoop/*.xml $HADOOP_PREFIX/input
# pseudo distributed
ADD core-site.xml $HADOOP_PREFIX/etc/hadoop/core-site.xml
#RUN sed s/HOSTNAME/localhost/ /usr/local/hadoop/etc/hadoop/core-site.xml.template > /usr/local/hadoop/etc/hadoop/core-site.xml
ADD hdfs-site.xml $HADOOP_PREFIX/etc/hadoop/hdfs-site.xml
ADD mapred-site.xml $HADOOP_PREFIX/etc/hadoop/mapred-site.xml
ADD yarn-site.xml $HADOOP_PREFIX/etc/hadoop/yarn-site.xml
RUN $HADOOP_PREFIX/bin/hdfs namenode -format
ADD ssh_config /root/.ssh/config
RUN chmod 600 /root/.ssh/config && \
chown root:root /root/.ssh/config
ADD bootstrap.sh /etc/bootstrap.sh
RUN chown root:root /etc/bootstrap.sh && \
chmod 700 /etc/bootstrap.sh
ENV BOOTSTRAP /etc/bootstrap.sh
# workingaround docker.io build error
RUN ls -la /usr/local/hadoop/etc/hadoop/*-env.sh && \
chmod +x /usr/local/hadoop/etc/hadoop/*-env.sh && \
ls -la /usr/local/hadoop/etc/hadoop/*-env.sh
# fix the 254 error code
RUN sed -i "/^[^#]*UsePAM/ s/.*/#&/" /etc/ssh/sshd_config && \
echo "UsePAM no" >> /etc/ssh/sshd_config && \
echo "Port 2122" >> /etc/ssh/sshd_config
#Spark
ADD spark-1.6.1-bin-hadoop2.6.tgz /usr/local
ADD scala-2.10.4.tgz /usr/local
RUN cd /usr/local && ln -s ./spark-1.6.1-bin-hadoop2.6 spark && \
cd /usr/local && ln -s ./scala-2.10.4 scala
ADD hive-site.xml /usr/local/spark/conf/
#Elasticsearch
#ADD elasticsearch-2.2.1.tar.gz /usr/local
#RUN cd /usr/local && ln -s ./elasticsearch-2.2.1 elasticsearch
#kibana
#ADD kibana-4.4.2-linux-x64.tar.gz /usr/local
#RUN cd /usr/local && ln -s ./kibana-4.4.2-linux-x64 kibana
CMD ["/etc/bootstrap.sh", "-d"]
# Hdfs ports
EXPOSE 50010 50020 50070 50075 50090 19888 8030 8031 8032 8033 8040 8042 8080 8088 49707 2122
# Mapred ports
#EXPOSE 19888
#Yarn ports
#EXPOSE 8030 8031 8032 8033 8040 8042 8088
#Other ports
#EXPOSE 49707 2122
# ElasticSearch Port
#EXPOSE 9200
| ba2521b84ddf53108436ca85aa305dc897482f96 | [
"Markdown",
"SQL",
"Dockerfile"
] | 3 | SQL | jiahao0428/hadoop-spark-cluster | 990f53794a4c69a75372c8319a6f047ec70ff63b | a73ab45923164f00530a190fe553c14a9fdcadbd | |
refs/heads/main | <repo_name>meinert/pythonprojecttemplate<file_sep>/mypackage/mymodule.py
from datetime import datetime, timedelta
# Firebase guide
# https://morioh.com/p/a593f973aff0
class MyClass():
def __init__(self, input):
self.input = input
# set Write or replace data to a defined path, like messages/users/<username>
# update Update some of the keys for a defined path without replacing all of the data
# push Add to a list of data in the database. Every time you push a new node onto a list, your database generates a unique key, like messages/users/<unique-user-id>/<username>
# transaction Use transactions when working with complex data that could be corrupted by concurrent updates
class MySecondClass():
def __init__(self, input):
self.input = input<file_sep>/mypackage/dataModels/constants.py
class ValueTypes:
FIRSTCONSTANT = 'first'
SECONDCONSTANT = 'second'
<file_sep>/mypackage/__init__.py
from .core import hmm
from .mymodule import *
<file_sep>/mypackage/mysecondmodule.py
from mypackage.dataModels import datamodel, constants
import json
class OtherClass():
def __init__(self, input):
self.input = input
<file_sep>/module.py
from mypackage import mymodule
from mypackage.dataModels import datamodel, constants
type = constants.ProductTypes.LIGGEUNDERLAG
classInstance = mymodule.MyClass('xxx')<file_sep>/mypackage/dataModels/datamodel.py
from dataclasses import dataclass, asdict, astuple, fields
import datetime
@dataclass
class DefaultProduct:
ean: int = None
brand: str = None
price: float = None
priceScore: float = None
productUrl: str = None
productName: str = None
stock: str = None
freight: float = -1
productId: str = None
updated: datetime = None
store: str = None
category: str = None
deliveryTime: str = None
imageUrl: str = None
eanValid: bool = None
totalScore: int = None
status: str = None
key: str = None
productLink: str = None
@dataclass
class DimensionProduct:
height: float = None
length: float = None
width: float = None
weight: float = None
heightScore: float = None
lengthScore: float = None
widthScore: float = None
weightScore: float = None
@dataclass
class DimensionPackedProduct:
packHeight: float = None
packWidth: float = None
packLength: float = None
packShape: str = None
packVolume: float = None
packHeightScore: float = None
packWidthScore: float = None
packVolumeScore: float = None
def __init__(self, pack_height=None, pack_width=None, pack_shape=None, pack_length=None):
self.packHeight = pack_height
self.packWidth = pack_width
self.packLength = pack_length
self.packShape = pack_shape
self.packVolume = self.calculate_pack_vol()
def calculate_pack_vol(self):
if self.packShape == 'Cylinder':
return pi * self.packWidth/2 * self.packWidth/2 * self.packHeight / 1000 # pi * radius^2 * height converted to Liter
elif self.packShape == 'Box':
return self.packLength * self.packWidth * self.packHeight / 1000
@dataclass
class Liggeunderlag(DefaultProduct, DimensionProduct, DimensionPackedProduct):
rvalue: float = None
rvalueScore: float = None
type: str = None # TODO: rename to subclass
def __iter__(self):
return iter(astuple(self))
def to_dict(data):
return asdict(data)
def dict_to_dataclass(dict_to_cast, data_class):
if data_class == 'liggeunderlag':
try:
return Liggeunderlag(**dict_to_cast[1])
except Exception:
return Liggeunderlag(**dict_to_cast)
else:
print('Product type: {} not supported yet'.format(data_class))
return None
<file_sep>/README.md
# pythonprojecttemplate
Template for a basic python project
| 9cdc0145a28a953ef62fbb24e04ac0216f387b6b | [
"Markdown",
"Python"
] | 7 | Python | meinert/pythonprojecttemplate | c368b2d3de2f64afdcf9eb79c9d982d9b037c711 | 8417aac44d81f5c1f994f5613ce7b184620b7665 | |
refs/heads/master | <repo_name>click2tman/slmdinc.org<file_sep>/docroot/modules/custom/ocms_accessibility/src/Form/AccessibilityConfigForm.php
<?php
namespace Drupal\ocms_accessibility\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* A configuration form for custom accessibility settings.
*/
class AccessibilityConfigForm extends ConfigFormBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* {@inheritdoc}
*/
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($config_factory);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ocms_accessibility_config_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$config = $this->config('ocms_accessibility.settings');
$content_type_options = [];
$content_types = $this->entityTypeManager
->getStorage('node_type')
->loadMultiple();
// Content type machine/name.
foreach ($content_types as $content) {
$content_type_options[$content->get('type')] = $content->get('name');
}
// Content type options.
$form['content_types'] = [
'#type' => 'checkboxes',
'#options' => $content_type_options,
'#title' => $this->t('Content types to apply accessibility check on submit:'),
'#default_value' => $config->get('content_types'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configFactory->getEditable('ocms_accessibility.settings')
->set('content_types', $form_state->getValue('content_types'))
->save();
parent::submitForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['ocms_accessibility.settings'];
}
}
<file_sep>/docroot/modules/custom/ocms_accessibility/js/check_compliance.js
/**
* @file
* Force ckeditor plugin a11ychecker to be called on form submit.
*/
(function ($, Drupal, proxyAlert) {
// Number of checker submissions via main form submit.
var submit_form_checking = 0;
// Alert proxy to suppress no-issue alert on submit.
window.alert = function() {
var a11ychecker_valid_msg = 'does not contain any accessibility issues';
// Suppress alert & decrement # of editors being checked.
if (submit_form_checking > 0 && arguments[0].indexOf(a11ychecker_valid_msg)) {
submit_form_checking -= 1;
return;
}
return proxyAlert.apply(this, arguments);
};
Drupal.behaviors.accessibilityFormValidation = {
attach:function (context, settings) {
// Submit button.
$('.submit-with-accessibility-checker', context).once("form_submit").each(function () {
$(this).click(function(e) {
if (!checkCompliant(this)) {
e.preventDefault();
}
});
});
function checkCompliant(button) {
// No checker button found or manually checked so continue submit.
var manually_checked = $("#edit-field-confirm-508-value").is(':checked');
var no_checker_button = $('.cke_button__a11ychecker').length == 0;
if (manually_checked || no_checker_button) {
return true;
}
// Run a11ychecker.
submit_form_checking = $('.cke_button__a11ychecker').length;
if (navigator.appVersion.indexOf('Edge') > -1) {
$('.cke_button__a11ychecker').mouseup();
} else {
$('.cke_button__a11ychecker').click();
}
// Check if balloon dialog with warnings appear, otherwise continue.
setTimeout(function() {
if ($('.cke_balloon').prop('style')['display'] !== 'none') {
return false;
}
else {
$(button).unbind(event).click();
}
}, 2000);
}
}
};
})(jQuery, Drupal, window.alert);
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerLoggingInterface.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Core\Logger\RfcLogLevel;
/**
* Defines an interface for the Link logging services.
*/
interface PupLinkcheckerLoggingInterface {
/**
* Logs a system message based on configured security level.
*
* @param $type
* The category to which this message belongs. Can be any string, but the
* general practice is to use the name of the module calling watchdog().
* @param $message
* The message to store in the log. Keep $message translatable
* by not concatenating dynamic values into it! Variables in the
* message should be added by using placeholder strings alongside
* the variables argument to declare the value of the placeholders.
* See t() for documentation on how $message and $variables interact.
* @param $variables
* Array of variables to replace in the message on display or
* NULL if message is already translated or not possible to
* translate.
* @param $severity
* The severity of the message; one of the following values as defined in
* @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
* - RfcLogLevel::EMERGENCY: Emergency, system is unusable.
* - RfcLogLevel::ALERT: Alert, action must be taken immediately.
* - RfcLogLevel::CRITICAL: Critical conditions.
* - RfcLogLevel::ERROR: Error conditions.
* - RfcLogLevel::WARNING: Warning conditions.
* - RfcLogLevel::NOTICE: (default) Normal but significant conditions.
* - RfcLogLevel::INFO: Informational messages.
* - RfcLogLevel::DEBUG: Debug-level messages.
* @param $link
* A link to associate with the message.
*
* @see watchdog_severity_levels()
* @see watchdog()
*/
public function logMessage($type, $message, $variables = array(), $severity = RfcLogLevel::NOTICE, $link = NULL);
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerFilteringService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Core\Config\ConfigFactoryInterface;
/**
* Implements the PupLinkcheckerFilteringInterface.
*/
class PupLinkcheckerFilteringService implements PupLinkcheckerFilteringInterface {
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs the OCMS Linkchecker Filtering Service object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public function checkMarkup($text, $formatId = NULL, $langcode = '') {
$config = $this->configFactory->get('ocms_linkchecker.settings');
$skipFilters = array_keys(array_filter($config->get('extract.filter.blacklist')));
return check_markup($text, $formatId, $langcode, $skipFilters);
}
}
<file_sep>/docroot/themes/custom/ocms_corporate/js/init/isotope-masonry-init.js
jQuery(document).ready(function($) {
//Masonry Layout
$(".grid-masonry-container").fadeIn("slow");
$(".grid-masonry-container").imagesLoaded(function() {
$(".grid-masonry-container").isotope({
itemSelector: ".masonry-grid-item",
layoutMode: "masonry"
});
$(".grid-masonry-container").isotope("layout");
});
//Masonry Layout Style 2
$(".grid-masonry-container-style-2").fadeIn("slow");
$(".grid-masonry-container-style-2").imagesLoaded(function() {
$(".grid-masonry-container-style-2").isotope({
itemSelector: ".masonry-grid-item",
layoutMode: "fitRows"
});
$(".grid-masonry-container-style-2").isotope("layout");
});
});
<file_sep>/docroot/themes/custom/ocms_corporate/js/init/flexslider-in-page-init.js
jQuery(document).ready(function($) {
$(window).load(function() {
if ($("#in-page-images-slider.flexslider").length>0) {
$("#in-page-images-slider.flexslider").fadeIn("slow");
$("#in-page-images-slider.flexslider").flexslider({
animation: drupalSettings.ocms_corporate.flexsliderInPageInit.inPageSliderEffect, // Select your animation type, "fade" or "slide"
prevText: "",
nextText: "",
pauseOnAction: false,
useCSS: false,
slideshow: false,
});
};
});
});
<file_sep>/docroot/themes/custom/ocms_cart/js/init/owl-carousel-brands-init.js
(function ($, Drupal, drupalSettings) {
Drupal.behaviors.mtOwlCarouselBrands = {
attach: function (context, settings) {
$(context).find('.mt-carousel-brands').once('mtowlCarouselBrandsInit').each(function() {
$(this).owlCarousel({
items: 2,
responsive:{
0:{
items:2,
},
480:{
items:2,
},
768:{
items:3,
},
992:{
items:4,
},
1200:{
items:5,
},
1680:{
items:5,
}
},
autoplay: drupalSettings.ocms_cart.owlCarouselBrandsInit.owlBrandsAutoPlay,
autoplayTimeout: drupalSettings.ocms_cart.owlCarouselBrandsInit.owlBrandsEffectTime,
nav: true,
dots: false,
loop: true,
navText: false
});
});
}
};
})(jQuery, Drupal, drupalSettings);
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerMaintenanceService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
/**
* Implements the PupLinkcheckerMaintenanceInterface.
*/
class PupLinkcheckerMaintenanceService implements PupLinkcheckerMaintenanceInterface {
use StringTranslationTrait;
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Drupal's queue service.
*
* @var \Drupal\Core\Queue\QueueFactory
*/
protected $queueFactory;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs the OCMS Linkchecker Maintenance Service object.
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
* The OCMS Linkchecker Utility Service.
* @param \Drupal\Core\Database\Connection
* The database connection
* @param \Drupal\Core\Queue\QueueInterface
* The Queue service
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
*/
public function __construct(PupLinkcheckerUtilityInterface $ocms_linkchecker_utility, Connection $database, QueueFactory $queue_factory, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation) {
$this->utilityService = $ocms_linkchecker_utility;
$this->connection = $database;
$this->queueFactory = $queue_factory;
$this->configFactory = $config_factory;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public function deleteUnreferencedLinks() {
$linkchecker_entity = $this->connection->select('ocms_linkchecker_entity', 'le')
->distinct()
->fields('le', array('lid'));
$this->connection->delete('ocms_linkchecker_link')
->condition('lid', $linkchecker_entity, 'NOT IN')
->execute();
}
/**
* {@inheritdoc}
*/
public function deleteUnscannedNodeLinks() {
$nodeTypes = $this->utilityService->scanNodeTypes();
if (!empty($nodeTypes)) {
$subquery1 = $this->connection->select('node', 'n')
->fields('n', array('nid'))
->condition('n.type', $nodeTypes, 'NOT IN');
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_id', $subquery1, 'IN')
->condition('entity_type', 'node')
->execute();
// @todo: Remove comments link references from table.
}
else {
// No active node types. Remove all items from table.
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_type', 'node')
->execute();
// @todo Remove comments link references from table.
}
}
/**
* {@inheritdoc}
*/
public function checkLinks() {
$config = $this->configFactory->get('ocms_linkchecker.settings');
$links = $this->connection->query('SELECT lid
FROM {ocms_linkchecker_link}
WHERE last_checked < :nextCheck
AND status = :checkLink
ORDER BY last_checked, lid ASC
', array(
':nextCheck' => REQUEST_TIME - $config->get('check.interval'),
':checkLink' => 1
));
$this->queueFactory->get('ocms_linkchecker_check_links')->createQueue();
$queue = $this->queueFactory->get('ocms_linkchecker_check_links');
foreach ($links as $link) {
// We will always add the item to the queue. The QueueWorker will double
// check whether the item is being processed again too soon on account of
// an older item that had not made it through a previous cron run. It
// could be too expensive to check all the items in the queue to see if
// we should skip adding this.
$queue->createItem($link->lid);
}
}
/**
* {@inheritdoc}
*/
public function scanNodeType($nodeType) {
$this->queueFactory->get('ocms_linkchecker_scan_node')->createQueue();
$queue = $this->queueFactory->get('ocms_linkchecker_scan_node');
$results = $this->connection->select('node', 'n')
->fields('n', array('nid'))
->condition('n.type', $nodeType)
->execute();
foreach ($results as $result) {
$queue->createItem($result->nid);
}
\Drupal::logger('ocms_linkchecker')
->notice($this->t('All nodes of type: :nodeType will be scanned for links.', array(':nodeType' => $nodeType)));
}
/**
* {@inheritdoc}
*/
public function removeNodeType($nodeType) {
$subquery1 = $this->connection->select('node', 'n')
->fields('n', array('nid'))
->condition('n.type', $nodeType);
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_id', $subquery1, 'IN')
->condition('entity_type', 'node')
->execute();
\Drupal::logger('ocms_linkchecker')
->notice($this->t('Removed link references for node type: :nodeType.', array(':nodeType' => $nodeType)));
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerMaintenanceInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link maintenance services.
*/
interface PupLinkcheckerMaintenanceInterface {
/**
* Deletes all links without a reference.
*
* This is triggered via cron.
*
* For speed reasons and check results we keep the links for some time
* as they may be reused by other new content.
*/
public function deleteUnreferencedLinks();
/**
* Deletes links to node types that are no longer scanned.
*
* This is triggered via cron.
*/
public function deleteUnscannedNodeLinks();
/**
* Checks links and processes the response code appropriately.
*
* This is triggered via cron.
*/
public function checkLinks();
/**
* Scans all nodes of a given node type for links.
*
* This is triggered by a node type being set to scan for links.
*
* @param string $nodeType
* The machine name for the node
*/
public function scanNodeType($nodeType);
/**
* Removes all link references for nodes of a given type.
*
* This is triggered by a node type being set to not scan for links.
*
* @param string $nodeType
* The machine name for the node
*/
public function removeNodeType($nodeType);
}
<file_sep>/docroot/modules/custom/ocms_universal_assets/src/EventSubscriber/RemoveXFrameOptionsSubscriber.php
<?php
namespace Drupal\ocms_universal_assets\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Removes the X-Frame-Options to allow iframe embedding.
*/
class RemoveXFrameOptionsSubscriber implements EventSubscriberInterface {
/**
* Update response headers based on path.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* Response event.
*/
public function updateResponseHeaders(FilterResponseEvent $event) {
$response = $event->getResponse();
$path = $_SERVER['REQUEST_URI'];
if (strpos($path, '/assets/universal') === 0) {
$response->headers->remove('X-Frame-Options');
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET');
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = array('updateResponseHeaders', -10);
return $events;
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerAccessInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link access services.
*/
interface PupLinkcheckerAccessInterface {
/**
* Returns block Ids with a link the current user is allowed to view.
*
* @param object $link
* An object representing the link to check.
*
* @return array
* An array of block IDs that contain the provided link and that the
* current user is allowed to view.
*/
public function accessBlockIds($link);
/**
* Returns comment Ids with a link the current user is allowed to view.
*
* @param object $link
* An object representing the link to check.
* @param object $commentAuthorAccount
* (optional) If a user account object is provided, the returned comments
* will additionally be restricted to only those owned by this account.
* Otherwise, comments owned by any user account may be returned.
*
* @return array
* An array of comment IDs that contain the provided link and that the
* current user is allowed to view.
*/
public function accessCommentIds($link, $commentAuthorAccount = NULL);
/**
* Determines if the current user has access to view a link.
*
* Link URLs can contain private information (for example, usernames and
* passwords). So this module should only display links to a user if the link
* already appears in at least one place on the site where the user would
* otherwise have access to see it.
*
* @param object $link
* An object representing the link to check.
*
* @return array
*/
public function accessLink($link);
/**
* Returns node Ids with a link the current user may be allowed to view.
*
* Important note: For performance reasons, this function is not always
* guaranteed to return the exact list of node IDs that the current user is
* allowed to view. It will, however, always return an empty array if the user
* does not have access to view *any* such nodes, thereby meeting the security
* goals of _linkchecker_link_access() and other places that call it.
*
* In the case where a user has access to some of the nodes that contain the
* link, this function may return some node IDs that the user does not have
* access to. Therefore, use caution with its results.
*
* @param object $link
* An object representing the link to check.
* @param object $nodeAuthorAccount
* (optional) If a user account object is provided, the returned nodes will
* additionally be restricted to only those owned by this account.
* Otherwise, nodes owned by any user account may be returned.
*
* @return array
* An array of node IDs that contain the provided link and that the current
* user may be allowed to view.
*/
public function accessNodeIds($link, $nodeAuthorAccount = NULL);
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerParsingService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Implements the PupLinkcheckerParsingInterface.
*/
class PupLinkcheckerParsingService implements PupLinkcheckerParsingInterface {
/**
* OCMS Linkchecker Filtering Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerFilteringInterface
*/
protected $filteringService;
/**
* Drupal's entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface;
*/
protected $entityFieldManager;
/**
* Constructs the OCMS Linkchecker Parsing Service object.
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerFilteringInterface $ocms_linkchecker_filtering_service
* The OCMS Linkchecker Filtering Service.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface
* The entity field manager
*/
public function __construct(PupLinkcheckerFilteringInterface $ocms_linkchecker_filtering_service, EntityFieldManagerInterface $entity_field_manager) {
$this->filteringService = $ocms_linkchecker_filtering_service;
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public function parseFields($entityType, $bundleName, $entity, $returnFieldNames = FALSE) {
global $base_url;
$textItems = array();
$textItemsByField = array();
// Create settings for _filter_url() function.
$filter = new \stdClass();
$filter->settings['filter_url_length'] = 72;
// Collect the fields from this entity_type and bundle.
foreach ($this->entityFieldManager->getFieldDefinitions($entityType, $bundleName) as $fieldName => $instance) {
$field = FieldStorageConfig::loadByName($entityType, $fieldName);
if (isset($field)) {
$type = $field->get('type');
}
else {
$type = '';
}
switch ($type) {
// Core fields.
case 'text_with_summary':
$fieldValues = $entity->get($fieldName)->getValue();
foreach ($fieldValues as $item) {
$item += array(
'format' => NULL,
'summary' => '',
'value' => '',
);
$languageCode = $entity->language()->getId();
$textItems[] = $textItemsByField[$fieldName][] = $this->filteringService->checkMarkup($item['value'], $item['format'], $languageCode, TRUE);
$textItems[] = $textItemsByField[$fieldName][] = $this->filteringService->checkMarkup($item['summary'], $item['format'], $languageCode, TRUE);
}
break;
// Core fields.
case 'text':
case 'text_long':
$fieldValues = $entity->get($fieldName)->getValue();
foreach ($fieldValues as $item) {
$item += array(
'format' => NULL,
'value' => '',
);
$languageCode = $entity->language()->getId();
$textItems[] = $textItemsByField[$fieldName][] = $this->filteringService->checkMarkup($item['value'], $item['format'], $languageCode, TRUE);
}
break;
case 'link':
$fieldValues = $entity->get($fieldName)->getValue();
foreach ($fieldValues as $item) {
$item += array(
'title' => '',
);
$languageCode = $entity->language()->getId();
$options = UrlHelper::parse($item['uri']);
// Force this to look like an external URL so that ::fromUri won't
// change it from how it's entered.
if (!UrlHelper::isExternal($options['path'])) {
$options['path'] = $base_url . str_replace(['entity:', 'internal:'], ['/', ''], $item['uri']);
}
$url = Url::fromUri($options['path'], $options);
$textItems[] = $textItemsByField[$fieldName][] = Link::fromTextAndUrl($item['title'], $url)->toString();
}
break;
}
}
return ($returnFieldNames) ? $textItemsByField : $textItems;
}
/**
* {@inheritdoc}
*/
public function getAbsoluteUrl($url) {
// Parse the URL and make sure we can handle the schema.
$uri = @parse_url($url);
if ($uri == FALSE) {
return NULL;
}
if (!isset($uri['scheme'])) {
return NULL;
}
// Break if the schema is not supported.
if (!in_array($uri['scheme'], array('http', 'https'))) {
return NULL;
}
$scheme = $uri['scheme'] . '://';
$user = isset($uri['user']) ? $uri['user'] . ($uri['pass'] ? ':' . $uri['pass'] : '') . '@' : '';
$port = isset($uri['port']) ? $uri['port'] : 80;
$host = $uri['host'] . ($port != 80 ? ':' . $port : '');
// Glue the URL variables.
$absoluteUrl = $scheme . $user . $host . '/';
return $absoluteUrl;
}
}
<file_sep>/docroot/modules/custom/ocms_viewfiles/src/Form/PagerForm.php
<?php
namespace Drupal\ocms_viewfiles\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configures taxonomy used for breadcrumb settings for this site.
*/
class PagerForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ocms_viewfiles_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'ocms_taxonomy_breadcrumb.configuration',
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$first_image=file_create_url(drupal_get_path('module', 'ocms_viewfiles') . '/css/first.png');
$prev_image=file_create_url(drupal_get_path('module', 'ocms_viewfiles') . '/css/prev.png');
$next_image=file_create_url(drupal_get_path('module', 'ocms_viewfiles') . '/css/next.png');
$last_image=file_create_url(drupal_get_path('module', 'ocms_viewfiles') . '/css/last.png');
$form['text']['#markup'] ='<img src="'.$first_image.'" class="first"/><img src="'.$prev_image.'" class="prev"/>';
$page_terms=array("25"=>"25","50"=>"50", "100"=>"100");
$form['pagedisplay'] = array(
'#required'=> FALSE,
'#type' => 'textfield',
'#attributes' => array('class' => array('pagedisplay'), 'readonly' => 'readonly','size' => 6),
);
$form['text2']['#markup'] ='<img src="'.$next_image.'" class="next"/><img src="'.$last_image.'" class="last"/>';
$form['amount'] = [
'#type' => 'select',
'#attributes' => array('class' => array('pagesize'),'width'=>'4px'),
'#multiple' => false,
'#options' => $page_terms,
'#default_value' => '50',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
//dsm ("The value on submit is ". $values['ocms_taxonomy_breadcrumb']);
$this->config('ocms_taxonomy_breadcrumb.configuration')
->set('breadcrumb_taxonomy', $values['ocms_taxonomy_breadcrumb'])
->save();
parent::submitForm($form, $form_state);
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerUtilityInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link utility services.
*/
interface PupLinkcheckerUtilityInterface {
/**
* Defines the list of allowed response codes for form input validation.
*
* @param int $code
* A numeric response code.
*
* @return boolean
* TRUE if the status code is valid, otherwise FALSE.
*/
public function isValidResponseCode($responseCode);
/**
* Checks if this entity is the default revision (published).
*
* @param object $entity
* The entity object, e.g., $node.
*
* @return bool
* TRUE if the entity is the default revision, FALSE otherwise.
*/
public function isDefaultrevision($entity);
/**
* Returns all the values of one-dimensional and multidimensional arrays.
*
* @return array
* Returns all the values from the input array and indexes the array numerically.
*/
public function recurseArrayValues(array $array);
/**
* Determines if the link status should be checked or not.
*
* This checks against reserved URLS, user-selected excluded URLs and
* the protocol.
*
* @return boolean
* Whether to be checked
*/
public function shouldCheckLink($url);
/**
* Checks if the link is an internal URL or not.
*
* @param object $link
* Link object.
*
* @return bool
* TRUE if link is internal, otherwise FALSE.
*/
public function isInternalUrl(&$link);
/**
* Returns information from database about a block.
*
* @param int $bid
* ID of the block to get information for.
*
* @return object
* Associative object of information stored in the database for this block.
* Object keys:
* - module: 'block' as the source of the custom blocks data.
* - delta: Block ID.
* - info: Block description.
* - body['value']: Block contents.
* - body['format']: Filter ID of the filter format for the body.
*/
public function getBlock($bid);
/**
* Returns all content type enabled with link checking.
*
* @return array
* An array of node type names, keyed by the type.
*/
public function scanNodeTypes();
/**
* Returns all content type enabled with comment link checking.
*
* @return array
* An array of node type names, keyed by the type.
*/
public function scanCommentTypes();
/**
* Impersonates another user, see http://drupal.org/node/287292#comment-3162350.
*
* Each time this function is called, the active user is saved and $new_user
* becomes the active user. Multiple calls to this function can be nested,
* and session saving will be disabled until all impersonation attempts have
* been reverted using linkchecker_revert_user().
*
* @param int|object $new_user
* User to impersonate, either a UID or a user object.
*
* @return object
* Current user object.
*
* @see linkchecker_revert_user()
*/
public function impersonateUser($newUser = NULL);
/**
* Reverts to the previous user after impersonating.
*
* @return object
* Current user.
*
* @see linkchecker_impersonate_user()
*/
public function revertUser();
/**
* Load a link object
*
* @param int $lid
* The link id
*
* @return object $link
* The fully loaded link object
*/
public function loadLink($lid);
/**
* Update a link.
*
* The user sets the values on the Edit link settings form.
*
* @param object $link
* The fully loaded link object
*/
public function updateLink($link);
/**
* Load an entity object
*
* @param string $entityType
* The entity type
* @param int $id
* The entity id
*
* @return object $entity
* The fully loaded entity object
*/
public function loadEntity($entityType, $id);
}
<file_sep>/docroot/modules/custom/ocms_media_access/src/MediaAccessPermissions.php
<?php
namespace Drupal\ocms_media_access;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\media_entity\Entity\MediaBundle;
/**
* Provides granular permissions for media entity types.
*/
class MediaAccessPermissions {
use StringTranslationTrait;
/**
* Returns an array of media type permissions.
*
* @return array
* The media type permissions.
*
* @see \Drupal\user\PermissionHandlerInterface::getPermissions()
*/
public function mediaTypePermissions() {
$perms = array();
// Generate permissions for all media types.
foreach (MediaBundle::loadMultiple() as $type) {
$perms += $this->buildPermissions($type);
}
return $perms;
}
/**
* Returns a list of media permissions for a given media type.
*
* @param \Drupal\media_entity\Entity\MediaBundle $type
* The media type.
*
* @return array
* An associative array of permission names and descriptions.
*/
protected function buildPermissions(MediaBundle $type) {
$type_id = $type->id();
$type_params = ['%type_name' => $type->label()];
return [
"create $type_id media" => [
'title' => $this->t('%type_name: Create new media', $type_params),
],
"edit any $type_id media" => [
'title' => $this->t('%type_name: Edit any media', $type_params),
],
"edit own $type_id media" => [
'title' => $this->t('%type_name: Edit own media', $type_params),
],
"delete any $type_id media" => [
'title' => $this->t('%type_name: Delete any media', $type_params),
],
"delete own $type_id media" => [
'title' => $this->t('%type_name: Delete own media', $type_params),
],
];
}
}
<file_sep>/docroot/themes/custom/ocms_base/js/global-assets.js
/**
* @file
* For loading external assets such as header and footer.
*/
$(function() {
// The base path to the asset pages.
var baseAssetOrigin = _IRS.baseAssetOrigin;
// The base path used in replacing relative paths.
var baseDomain = _IRS.baseDomain;
// Assets to prepend.
var prependAssets = _IRS.prependAssets;
var includeStyles = _IRS.includeStyles;
// Available assets.
var globalAssets = {
header: {
assetPath: baseAssetOrigin + '/assets/universal/header',
assetElement: '#navbar'
},
footer: {
assetPath: baseAssetOrigin + '/assets/universal/footer',
assetElement: 'footer'
}
};
var stylePaths = [
'/themes/custom/ocms_base/css/style.min.css',
'/core/modules/system/css/components/hidden.module.css'
];
var scriptPaths = [
// Scripts array to append.
];
// Include scripts and stylesheets.
if (includeStyles) {
// Stylesheets.
for (var i = 0; i < stylePaths.length; i++) {
var styleElement = document.createElement('link');
styleElement.type = 'text/css';
styleElement.rel = 'stylesheet';
styleElement.href = baseAssetOrigin + stylePaths[i];
$('head').append(styleElement);
}
// Scripts.
for (var j = 0; j < scriptPaths.length; j++) {
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = baseAssetOrigin + scriptPaths[j];
$('head').append(scriptElement);
}
}
// Prepend assets.
Object.keys(prependAssets).forEach(function(asset) {
if (globalAssets[asset]) {
$.ajax({
url: globalAssets[asset].assetPath
})
.done(function(content) {
var element = $(content).filter(globalAssets[asset].assetElement);
$(prependAssets[asset]).prepend(element);
$(globalAssets[asset].assetElement + ' a[href^="/"]').attr('href', addBaseDomain);
$(globalAssets[asset].assetElement + ' img[src^="/"]').attr('src', addBaseDomain);
});
}
});
// Add base domain to relative paths.
function addBaseDomain(_idx, oldHref) {
return oldHref.replace(/^\//, baseDomain + '/');
}
});
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerHttpService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use GuzzleHttp\Exception\TransferException;
/**
* Implements the PupLinkcheckerHttpInterface.
*/
class PupLinkcheckerHttpService implements PupLinkcheckerHttpInterface {
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* The HTTP client with which to test the links.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs the OCMS Linkchecker Http Service object.
*
* @param \Drupal\Core\Database\Connection
* The database connection
* @param \GuzzleHttp\ClientInterface $http_client
* A Guzzle client object.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
*/
public function __construct(Connection $database, ClientInterface $http_client, ConfigFactoryInterface $config_factory) {
$this->connection = $database;
$this->httpClient = $http_client;
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public function checkLink($link) {
$url = $link->url;
try {
if ($link->method == 'GET') {
$response = $this->httpClient
->get($url);
}
else {
$response = $this->httpClient
->head($url);
}
}
catch (BadResponseException $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There was a bad response exception caught.';
\Drupal::logger('ocms_linkchecker')->notice('A bad response exception was caught for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
catch (ClientException $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There was a client exception caught.';
\Drupal::logger('ocms_linkchecker')->notice('A client exception was caught for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
catch (ConnectException $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There was a connection exception caught.';
\Drupal::logger('ocms_linkchecker')->notice('A connection exception was caught for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
catch (RequestException $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There was a request exception caught.';
\Drupal::logger('ocms_linkchecker')->notice('A request exception was caught for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
catch (ServerException $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There was a server exception caught.';
\Drupal::logger('ocms_linkchecker')->notice('A server exception was caught for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
catch (TooManyRedirectsException $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There were too many redirects.';
\Drupal::logger('ocms_linkchecker')->notice('There were too many redirects for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
catch (\Exception $exception) {
$response = $exception->getResponse();
$code = '400';
$error = 'There was an unexpected exception caught.';
\Drupal::logger('ocms_linkchecker')->notice('An unexpected exception was caught for @url.', array('@url' => $url));
watchdog_exception('ocms_linkchecker', $exception);
}
if (!empty($response)) {
$code = $response->getStatusCode();
$error = $response->getReasonPhrase();
}
$config = $this->configFactory->get('ocms_linkchecker.settings');
$ignoreResponseCodes = preg_split('/(\r\n?|\n)/', $config->get('error.ignore_response_codes'));
if (in_array($code, $ignoreResponseCodes)) {
$failIncrement = -1 * $link->fail_count;
}
else {
$failIncrement = 1;
}
$this->connection->update('ocms_linkchecker_link')
->condition('lid', $link->lid)
->fields(array(
'code' => $code,
'error' => $error,
'fail_count' => 0,
'last_checked' => time(),
))
->expression('fail_count',
'fail_count + :failIncrement',
array(':failIncrement' => $failIncrement))
->execute();
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerBatchInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link batch services.
*/
interface PupLinkcheckerBatchInterface {
// @todo: I really don't know yet whether I'm going to create a service or
// if I'm using some type of "batch workers" as <NAME> suggested.
// Drupal 8 still has the Batch API
// @see: https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8.3.x
// http://tylerfrankenstein.com/code/drupal-8-batch-example
// http://valuebound.com/resources/blog/batch-process-drupal-8
// http://www.accessadvertising.co.uk/blog/2016/07/smack-my-batch-batch-processing-drupal-8
// https://mr.alexfinnarn.com/article/bettering-batch-api
}
<file_sep>/docroot/modules/custom/ocms_viewfiles/js/ocms_viewfiles.js
(function($) {
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
$("#myTable").tablesorter();
if($('#pager').length >0 ){
$("#myTable").tablesorterPager({container: $("#pager")});
}
}
};
})(jQuery);
<file_sep>/docroot/modules/custom/ocms_files/src/Controller/OcmsOcmsController.php
<?php
namespace Drupal\irspup\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\irspup\Utility\DescriptionTemplateTrait;
/**
* Simple controller class used to test the DescriptionTemplateTrait.
*/
class IrsPupController extends ControllerBase {
use DescriptionTemplateTrait;
/**
* {@inheritdoc}
*
* We override this so we can see some substitutions.
*/
protected function getModuleName()
{
return 'irspup';
}
/**
* This is the old non-twig version reporting out.
*
*
*/
// public function showModuleInfo() {
// return array(
// '#type' => 'markup',
// '#markup' => '<h2>IRS OCMS Modules</h2>
// <div id="block-seven-content" data-block-plugin-id="system_main_block" class="block block-system block-system-main-block">
// <ul class="admin-list">'
// .'<li><a href="/admin/config/irspup/irs_file_operations"><span class="label">Static File Operations</span><div class="description">Make the most recent version of a file always retain its original filename.</div></a></li>'
// .'<li><a href="/admin/config/irspup/irs_sfbu"><span class="label">SFBU</span><div class="description">Static File Bulk Upload Automatically.</div></a></li>
// <li><a href="/admin/config/irspup/irs_customjs"><span class="label">Custom JS</span><div class="description">A module to demonstrate how to insert Javascript.</div></a></li>
// </ul></div>
// </div>
// </div>'
// );
// }
}<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerExtractionService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Implements the PupLinkcheckerExtractionInterface.
*/
class PupLinkcheckerExtractionService implements PupLinkcheckerExtractionInterface {
/**
* OCMS Linkchecker Parsing Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerParsingInterface
*/
protected $parsingService;
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* Drupal's language manager service.
*
* @var \Drupal\Core\Language\LanguageManagerInterface;
*/
protected $languageManager;
/**
* The current request.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs the OCMS Linkchecker Extraction Service object.
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerParsingInterface $ocms_linkchecker_parsing
* The OCMS Linkchecker Parsing Service.
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface $ocms_linkchecker_utility
* The OCMS Linkchecker Utility Service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
*/
public function __construct(PupLinkcheckerParsingInterface $ocms_linkchecker_parsing, PupLinkcheckerUtilityInterface $ocms_linkchecker_utility, LanguageManagerInterface $language_manager, RequestStack $request_stack, ConfigFactoryInterface $config_factory) {
$this->parsingService = $ocms_linkchecker_parsing;
$this->utilityService = $ocms_linkchecker_utility;
$this->languageManager = $language_manager;
$this->request = $request_stack->getCurrentRequest();
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public function extractContentLinks($text, $contentPath) {
global $base_root;
$isHttps = $this->request->isSecure();
$config = $this->configFactory->get('ocms_linkchecker.settings');
$htmlDom = Html::load($text);
$urls = array();
// Finds all hyperlinks in the content.
if ($config->get('extract.from_a') == 1) {
$links = $htmlDom->getElementsByTagName('a');
foreach ($links as $link) {
$urls[] = $link->getAttribute('href');
}
$links = $htmlDom->getElementsByTagName('area');
foreach ($links as $link) {
$urls[] = $link->getAttribute('href');
}
}
// Finds all audio links in the content.
if ($config->get('extract.from_audio') == 1) {
$audios = $htmlDom->getElementsByTagName('audio');
foreach ($audios as $audio) {
$urls[] = $audio->getAttribute('src');
// Finds source tags with links in the audio tag.
$sources = $audio->getElementsByTagName('source');
foreach ($sources as $source) {
$urls[] = $source->getAttribute('src');
}
// Finds track tags with links in the audio tag.
$tracks = $audio->getElementsByTagName('track');
foreach ($tracks as $track) {
$urls[] = $track->getAttribute('src');
}
}
}
// Finds embed tags with links in the content.
if ($config->get('extract.from_embed') == 1) {
$embeds = $htmlDom->getElementsByTagName('embed');
foreach ($embeds as $embed) {
$urls[] = $embed->getAttribute('src');
$urls[] = $embed->getAttribute('pluginurl');
$urls[] = $embed->getAttribute('pluginspage');
}
}
// Finds iframe tags with links in the content.
if ($config->get('extract.from_iframe') == 1) {
$iframes = $htmlDom->getElementsByTagName('iframe');
foreach ($iframes as $iframe) {
$urls[] = $iframe->getAttribute('src');
}
}
// Finds img tags with links in the content.
if ($config->get('extract.from_img') == 1) {
$imgs = $htmlDom->getElementsByTagName('img');
foreach ($imgs as $img) {
$urls[] = $img->getAttribute('src');
$urls[] = $img->getAttribute('longdesc');
}
}
// Finds object/param tags with links in the content.
if ($config->get('extract.from_object') == 1) {
$objects = $htmlDom->getElementsByTagName('object');
foreach ($objects as $object) {
$urls[] = $object->getAttribute('data');
$urls[] = $object->getAttribute('codebase');
// Finds param tags with links in the object tag.
$params = $object->getElementsByTagName('param');
foreach ($params as $param) {
// @todo
// - Try to extract links in unkown "flashvars" values
// (e.g., file=http://, data=http://).
$names = array('archive', 'filename', 'href', 'movie', 'src', 'url');
if ($param->hasAttribute('name') && in_array($param->getAttribute('name'), $names)) {
$urls[] = $param->getAttribute('value');
}
$srcs = array('movie');
if ($param->hasAttribute('src') && in_array($param->getAttribute('src'), $srcs)) {
$urls[] = $param->getAttribute('value');
}
}
}
}
// Finds video tags with links in the content.
if ($config->get('extract.from_video') == 1) {
$videos = $htmlDom->getElementsByTagName('video');
foreach ($videos as $video) {
$urls[] = $video->getAttribute('poster');
$urls[] = $video->getAttribute('src');
// Finds source tags with links in the video tag.
$sources = $video->getElementsByTagName('source');
foreach ($sources as $source) {
$urls[] = $source->getAttribute('src');
}
// Finds track tags with links in the audio tag.
$tracks = $video->getElementsByTagName('track');
foreach ($tracks as $track) {
$urls[] = $track->getAttribute('src');
}
}
}
// Remove empty values.
$urls = array_filter($urls);
// Remove duplicate urls.
$urls = array_unique($urls);
// What type of links should be checked?
$linkcheckerCheckLinkTypes = $config->get('general.check_link_types');
$links = array();
foreach ($urls as $url) {
// Decode HTML links into plain text links.
// DOMDocument->loadHTML does not provide the RAW url from code. All html
// entities are already decoded.
// @todo: Try to find a way to get the raw value.
$urlDecoded = $url;
// Prefix protocol relative urls with a protocol to allow link checking.
if (preg_match('!^//!', $urlDecoded)) {
$httpProtocol = $isHttps ? 'https' : 'http';
$urlDecoded = $httpProtocol . ':' . $urlDecoded;
}
// FIXME: #1149596 HACK - Encode spaces in URLs, so validation equals TRUE and link gets added.
$urlEncoded = str_replace(' ', '%20', $urlDecoded);
// Full qualified URLs.
if ($linkcheckerCheckLinkTypes != 2 && UrlHelper::isValid($urlEncoded, TRUE)) {
// Add to Array and change HTML links into plain text links.
$links[$urlDecoded][] = $url;
}
// Skip mailto:, javascript:, etc.
elseif (preg_match('/^\w[\w.+]*:/', $urlDecoded)) {
continue;
}
// Local URLs. $linkchecker_check_links_types = 0 or 2
elseif ($linkcheckerCheckLinkTypes != 1 && UrlHelper::isValid($urlEncoded, FALSE)) {
// Get full qualified url with base path of content.
$absoluteContentPath = $this->parsingService->getAbsoluteUrl($contentPath);
// Absolute local URLs need to start with [/].
if (preg_match('!^/!', $urlDecoded)) {
// Add to Array and change HTML encoded links into plain text links.
$links[$base_root . $urlDecoded][] = $url;
}
// Anchors and URL parameters like "#foo" and "?foo=bar".
elseif (!empty($contentPath) && preg_match('!^[?#]!', $urlDecoded)) {
// Add to Array and change HTML encoded links into plain text links.
$links[$contentPath . $urlDecoded][] = $url;
}
// Relative URLs like "./foo/bar" and "../foo/bar".
elseif (!empty($absoluteContentPath) && preg_match('!^\.{1,2}/!', $urlDecoded)) {
// Build the URI without hostname before the URI is normalized and
// dot-segments will be removed. The hostname is added back after the
// normalization has completed to prevent hostname removal by the regex.
// This logic intentionally does not implement all the rules definied in
// RFC 3986, section 5.2.4 to show broken links and over-dot-segmented
// URIs; e.g., http://example.com/../../foo/bar.
// For more information, see http://drupal.org/node/832388.
$path = substr_replace($absoluteContentPath . $urlDecoded, '', 0, strlen($base_root));
// Remove './' segments where possible.
$path = str_replace('/./', '/', $path);
// Remove '../' segments where possible. Loop until all segments are
// removed. Taken over from _drupal_build_css_path() in common.inc.
$last = '';
while ($path != $last) {
$last = $path;
$path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
}
// Glue the hostname and path to full-qualified URI.
$links[$base_root . $path][] = $url;
}
// Relative URLs like "test.png".
elseif (!empty($absoluteContentPath) && preg_match('!^[^/]!', $urlDecoded)) {
$links[$absoluteContentPath . $urlDecoded][] = $url;
}
else {
// @todo Are there more special cases the module need to handle?
}
}
}
return $links;
}
/**
* {@inheritdoc}
*/
public function extractNodeLinks($node, $returnFieldNames = FALSE) {
$filter = new \stdClass();
$filter->settings['filter_url_length'] = 72;
// Create array of node fields to scan.
$textItems = array();
$textItemsByField = array();
// Add fields typically not used for urls to the bottom. This way a link may
// found earlier while looping over $textItemsByField below.
$textItemsByField = array_merge($textItemsByField, $this->parsingService->parseFields('node', $node->bundle(), $node, TRUE));
// @see: https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/_filter_url/8.3.x
$textItemsByField['title'][] = _filter_url($node->getTitle(), $filter);
$textItems = $this->utilityService->recurseArrayValues($textItemsByField);
// Get the absolute node path for extraction of relative links.
if ($node->language()) {
$path = $node->toUrl('canonical', ['absolute' => true, 'language' => $node->language()])->toString();
}
else {
$path = $node->toUrl('canonical', ['absolute' => true])->toString();
}
// Extract all links in a node.
$links = $this->extractContentLinks(implode(' ', $textItems), $path);
// Return either the array of links, or an array of field names containing
// each link, depending on what was requested.
if (!$returnFieldNames) {
return $links;
}
else {
$fieldNames = array();
foreach ($textItemsByField as $fieldName => $items) {
foreach ($items as $item) {
foreach ($links as $uri => $link) {
// We only need to do a quick check here to see if the URL appears
// anywhere in the text; if so, that means users with access to this
// field will be able to see the URL (and any private data such as
// passwords contained in it). This is sufficient for the purposes of
// _linkchecker_link_node_ids(), where this information is used.
foreach ($link as $originalLink) {
if (strpos($item, $originalLink) !== FALSE) {
$fieldNames[$uri][$fieldName] = $fieldName;
}
// URLs in $links have been auto-decoded by DOMDocument->loadHTML
// and does not provide the RAW url with html special chars.
// NOTE: htmlspecialchars() is 30% slower than str_replace().
elseif (strpos($item, str_replace('&', '&', $originalLink)) !== FALSE) {
$fieldNames[$uri][$fieldName] = $fieldName;
}
}
}
}
}
return $fieldNames;
}
}
/**
* {@inheritdoc}
*/
public function extractCommentLinks($comment, $returnFieldNames = FALSE) {
}
/**
* {@inheritdoc}
*/
public function extractBlockLinks($block, $returnFieldNames = FALSE) {
}
}
<file_sep>/docroot/modules/custom/ocms_universal_assets/js/iframe_send_height.js
/**
* @file
* Send parent of iframe the updated height.
*/
(function ($) {
Drupal.behaviors.iframeSendHeight = {
attach:function (context, settings) {
var pymChild = new pym.Child();
// Delay update height to resolve cut-off footer.
setTimeout(function() {
pymChild.sendHeight();
}, 400);
// Update child height on click for dom updates like expanded content.
$(document, context).click(function() {
setTimeout(function() {
pymChild.sendHeight();
}, 400);
});
}
};
})(jQuery);
<file_sep>/docroot/modules/custom/ocms_linkchecker/ocms_linkchecker.views.inc
<?php
/**
* @file
* Provide views data for ocms_linkchecker.module.
*/
/**
* Implements hook_views_data().
*/
function ocms_linkchecker_views_data() {
$data = [];
$data['ocms_linkchecker_link']['table']['group'] = t('OCMS Linkchecker Link Table');
$data['ocms_linkchecker_link']['table']['base'] = [
'field' => 'lid',
'title' => t('OCMS Linkchecker Link Table'),
'help' => t('The Link table contains all the information for each link that will be checked'),
];
$data['ocms_linkchecker_link']['lid'] = [
'title' => t('Link ID'),
'help' => t('A unique ID that is incremented automatically when a row is created'),
'field' => [
'id' => 'numeric',
],
'argument' => [
'id' => 'numeric',
],
'filter' => [
'id' => 'numeric',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_link']['url'] = [
'title' => t('URL'),
'help' => t('The fully qualified URL to check'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_link']['method'] = [
'title' => t('Method'),
'help' => t('The method to check links (HEAD, GET)'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_link']['code'] = [
'title' => t('Code'),
'help' => t('The HTTP status code returned when checking the link'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_link']['error'] = [
'title' => t('Error'),
'help' => t('The message returned from the server when checking the link'),
'field' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_link']['fail_count'] = [
'title' => t('Fail Count'),
'help' => t('The number of times this link has had a failure response'),
'field' => [
'id' => 'numeric',
],
];
$data['ocms_linkchecker_link']['last_checked'] = [
'title' => t('Last Checked'),
'help' => t('A timestamp of when the link was last checked'),
'field' => [
'id' => 'date',
],
'filter' => [
'id' => 'date',
],
'sort' => [
'id' => 'date',
],
];
$data['ocms_linkchecker_link']['status'] = [
'title' => t('Status'),
'help' => t('A boolean indicating whether this link should be checked'),
'field' => [
'id' => 'boolean',
],
];
$data['ocms_linkchecker_entity']['table']['group'] = t('OCMS Linkchecker Entity Table');
$data['ocms_linkchecker_entity']['table']['base'] = [
'field' => 'entity_id',
'title' => t('OCMS Linkchecker Entity Table'),
'help' => t('The Entity table contains the entity IDs that reference given link IDs'),
];
$data['ocms_linkchecker_entity']['entity_id'] = [
'title' => t('ID'),
'help' => t('The ID of the entity referencing a link'),
'field' => [
'id' => 'numeric',
],
'argument' => [
'id' => 'numeric',
],
'filter' => [
'id' => 'numeric',
],
'sort' => [
'id' => 'standard',
],
'relationship' => [
'base' => 'node_field_data',
'base field' => 'nid',
'id' => 'standard',
'help' => t('Node being referenced'),
'title' => t('Node'),
],
];
$data['ocms_linkchecker_entity']['entity_type'] = [
'title' => t('Entity Type'),
'help' => t('The entity type that is referencing a link'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_entity']['bundle'] = [
'title' => t('Bundle'),
'help' => t('The bundle that is referencing a link'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'bundle',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_entity']['langcode'] = [
'title' => t('Language Code'),
'help' => t('The language code of the entity that is referencing a link'),
'field' => [
'id' => 'language',
],
'filter' => [
'id' => 'language',
],
'sort' => [
'id' => 'standard',
],
];
$data['ocms_linkchecker_entity']['lid'] = [
'title' => t('Link ID'),
'help' => t('The link ID of the link being referenced'),
'field' => [
'id' => 'numeric',
],
'filter' => [
'id' => 'numeric',
],
'sort' => [
'id' => 'standard',
],
'relationship' => [
'base' => 'ocms_linkchecker_link',
'base field' => 'lid',
'id' => 'standard',
'help' => t('Link referenced by this node'),
'title' => t('Link'),
],
];
return $data;
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/Form/SettingsForm.php
<?php
namespace Drupal\ocms_linkchecker\Form;
use Drupal\Component\Plugin\FallbackPluginManagerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Url;
use Drupal\filter\FilterPluginCollection;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configures link checker settings for this site.
*/
class SettingsForm extends ConfigFormBase {
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The plugin manager filter service.
*
* @var \Drupal\Component\Plugin\FallbackPluginManagerInterface
*/
protected $pluginManagerFilter;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Constructs a \Drupal\ocms_linkchecker\SettingsForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Component\Plugin\FallbackPluginManagerInterface $plugin_manager_filter
* The plugin manager filter
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter
* @param \Drupal\Core\Database\Connection
* The database connection
*/
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, FallbackPluginManagerInterface $plugin_manager_filter, DateFormatterInterface $date_formatter, Connection $database) {
parent::__construct($config_factory);
$this->moduleHandler = $module_handler;
$this->pluginManagerFilter = $plugin_manager_filter;
$this->dateFormatter = $date_formatter;
$this->connection = $database;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('module_handler'),
$container->get('plugin.manager.filter'),
$container->get('date.formatter'),
$container->get('database')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ocms_linkchecker_admin_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['ocms_linkchecker.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('ocms_linkchecker.settings');
$form['general'] = [
'#type' => 'details',
'#title' => $this->t('General settings'),
'#description' => $this->t('Configure the <a href=":url">content types</a> that should be scanned for broken links.', [':url' => Url::fromRoute('entity.node_type.collection')->toString()]),
'#open' => TRUE,
];
$block_custom_dependencies = '<div class="admin-requirements">';
$block_custom_dependencies .= $this->t('Requires: @module-list', [
'@module-list' => $this->moduleHandler->moduleExists('block') ?
$this->t('@module (<span class="admin-enabled">enabled</span>)', [
'@module' => 'Block'
]) :
$this->t('@module (<span class="admin-disabled">disabled</span>)', [
'@module' => 'Block'
]),
]);
$block_custom_dependencies .= '</div>';
$form['general']['ocms_linkchecker_scan_blocks'] = [
'#default_value' => $config->get('general.scan_blocks'),
'#type' => 'checkbox',
'#title' => $this->t('Scan blocks for links'),
'#description' => $this->t('Enable this checkbox if links in blocks should be checked.') . $block_custom_dependencies,
'#disabled' => !$this->moduleHandler->moduleExists('block'),
];
$form['general']['ocms_linkchecker_check_links_types'] = [
'#type' => 'select',
'#title' => $this->t('What type of links should be checked?'),
'#description' => $this->t('A fully qualified link (http://example.com/foo/bar) to a page is considered external, whereas an absolute (/foo/bar) or relative link (node/123) without a domain is considered internal.'),
'#default_value' => $config->get('general.check_link_types'),
'#options' => [
'0' => $this->t('Internal and external'),
'1' => $this->t('External only (http://example.com/foo/bar)'),
'2' => $this->t('Internal only (node/123)'),
],
];
$form['extract'] = [
'#type' => 'details',
'#title' => $this->t('Link extraction'),
'#open' => TRUE,
];
$form['extract']['ocms_linkchecker_extract_from_a'] = [
'#default_value' => $config->get('extract.from_a'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><a></code> and <code><area></code> tags'),
'#description' => $this->t('Enable this checkbox if normal hyperlinks should be extracted. The anchor element defines a hyperlink, the named target destination for a hyperlink, or both. The area element defines a hot-spot region on an image, and associates it with a hypertext link.'),
];
$form['extract']['ocms_linkchecker_extract_from_audio'] = [
'#default_value' => $config->get('extract.from_audio'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><audio></code> tags including their <code><source></code> and <code><track></code> tags'),
'#description' => $this->t('Enable this checkbox if links in audio tags should be extracted. The audio element is used to embed audio content.'),
];
$form['extract']['ocms_linkchecker_extract_from_embed'] = [
'#default_value' => $config->get('extract.from_embed'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><embed></code> tags'),
'#description' => $this->t('Enable this checkbox if links in embed tags should be extracted. This is an obsolete and non-standard element that was used for embedding plugins in past and should no longer used in modern websites.'),
];
$form['extract']['ocms_linkchecker_extract_from_iframe'] = [
'#default_value' => $config->get('extract.from_iframe'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><iframe></code> tags'),
'#description' => $this->t('Enable this checkbox if links in iframe tags should be extracted. The iframe element is used to embed another HTML page into a page.'),
];
$form['extract']['ocms_linkchecker_extract_from_img'] = [
'#default_value' => $config->get('extract.from_img'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><img></code> tags'),
'#description' => $this->t('Enable this checkbox if links in image tags should be extracted. The img element is used to add images to the content.'),
];
$form['extract']['ocms_linkchecker_extract_from_object'] = [
'#default_value' => $config->get('extract.from_object'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><object></code> and <code><param></code> tags'),
'#description' => $this->t('Enable this checkbox if multimedia and other links in object and their param tags should be extracted. The object tag is used for flash, java, quicktime and other applets.'),
];
$form['extract']['ocms_linkchecker_extract_from_video'] = [
'#default_value' => $config->get('extract.from_video'),
'#type' => 'checkbox',
'#title' => $this->t('Extract links in <code><video></code> tags including their <code><source></code> and <code><track></code> tags'),
'#description' => $this->t('Enable this checkbox if links in video tags should be extracted. The video element is used to embed video content.'),
];
// Get all filters available on the system.
$bag = new FilterPluginCollection($this->pluginManagerFilter, []);
$filter_info = $bag->getAll();
$filter_options = [];
$filter_descriptions = [];
foreach ($filter_info as $name => $filter) {
if (in_array($name, $config->get('extract.filter.default_blacklist'))) {
$filter_options[$name] = $this->t('@title <span class="marker">(Recommended)</span>', array('@title' => $filter->getLabel()));
}
else {
$filter_options[$name] = $filter->getLabel();
}
$filter_descriptions[$name] = [
'#description' => $filter->getDescription(),
];
}
$form['extract']['ocms_linkchecker_filter_blacklist'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Text formats disabled for link extraction'),
'#default_value' => $config->get('extract.filter.blacklist'),
'#options' => $filter_options,
'#description' => $this->t('<strong>NOTE: Do NOT check any of these boxes until <a href="https://www.drupal.org/node/2876287">https://www.drupal.org/node/2876287</a> has been fixed.</strong> If a filter has been enabled for an input format it runs first and afterwards the link extraction. This helps the link checker module to find all links normally created by custom filters (e.g. Markdown filter, Bbcode). All filters used as inline references (e.g. Weblink filter <code>[link: id]</code>) to other content and filters only wasting processing time (e.g. Line break converter) should be disabled. This setting does not have any effect on how content is shown on a page. This feature optimizes the internal link extraction process for link checker and prevents false alarms about broken links in content not having the real data of a link.'),
];
$form['extract']['ocms_linkchecker_filter_blacklist'] = array_merge($form['extract']['ocms_linkchecker_filter_blacklist'], $filter_descriptions);
// @todo: Am I forced to use db_query against my own table? Or is there
// something akin to nodeStorage (entity storage)?
$countLidsEnabled = $this->connection->query("SELECT count(lid) FROM {ocms_linkchecker_link} WHERE status = :status", array(':status' => 1))->fetchField();
$countLidsDisabled = $this->connection->query("SELECT count(lid) FROM {ocms_linkchecker_link} WHERE status = :status", array(':status' => 0))->fetchField();
$form['check'] = [
'#type' => 'details',
'#title' => $this->t('Check settings'),
'#description' => $this->t('Currently the site has @count links (@count_enabled enabled / @count_disabled disabled).', ['@count' => $countLidsEnabled + $countLidsDisabled, '@count_enabled' => $countLidsEnabled, '@count_disabled' => $countLidsDisabled]),
'#open' => TRUE,
];
$form['check']['ocms_linkchecker_check_connections_max'] = [
'#type' => 'select',
'#title' => $this->t('Number of simultaneous connections'),
'#description' => $this->t('Defines the maximum number of simultaneous connections that can be opened by the server. How do we get Guzzle to make sure that a single domain is not overloaded beyond RFC limits? For small hosting plans with very limited CPU and RAM it may be required to reduce the default limit.'),
'#default_value' => $config->get('check.max_connections'),
'#options' => array_combine([2, 4, 8, 16, 24, 32, 48, 64, 96, 128], [2, 4, 8, 16, 24, 32, 48, 64, 96, 128]),
];
$form['check']['ocms_linkchecker_check_useragent'] = [
'#type' => 'select',
'#title' => $this->t('User-Agent'),
'#description' => $this->t('Defines the user agent that will be used for checking links on remote sites. If someone blocks the standard Drupal user agent you can try with a more common browser.'),
'#default_value' => $config->get('check.user_agent'),
'#options' => [
'Drupal (+http://drupal.org/)' => 'Drupal (+http://drupal.org/)',
'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko' => 'Windows 8.1 (x64), Internet Explorer 11.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586' => 'Windows 10 (x64), Edge',
'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0' => 'Windows 8.1 (x64), Mozilla Firefox 47.0',
'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0' => 'Windows 10 (x64), Mozilla Firefox 47.0',
],
];
$intervals = [86400, 172800, 259200, 604800, 1209600, 2419200, 4838400];
$period = array_map([$this->dateFormatter, 'formatInterval'], array_combine($intervals, $intervals));
$form['check']['ocms_linkchecker_check_interval'] = [
'#type' => 'select',
'#title' => $this->t('Check interval for links'),
'#description' => $this->t('This interval setting defines how often cron will re-check the status of links.'),
'#default_value' => $config->get('check.interval'),
'#options' => $period,
];
$form['check']['ocms_linkchecker_disable_link_check_for_urls'] = [
'#default_value' => $config->get('check.disable_for_urls'),
'#type' => 'textarea',
'#title' => $this->t('Do not check the link status of links containing these URLs'),
'#description' => $this->t('By default this list contains the domain names reserved for use in documentation and not available for registration. See <a href=":rfc-2606">RFC 2606</a>, Section 3 for more information. URLs on this list are still extracted, but the link setting <em>Check link status</em> becomes automatically disabled to prevent false alarms. If you change this list you need to clear all link data and re-analyze your content. Otherwise this setting will only affect new links added after the configuration change.', array(':rfc-2606' => 'http://www.rfc-editor.org/rfc/rfc2606.txt')),
];
$form['check']['ocms_linkchecker_logging_level'] = [
'#default_value' => $config->get('log_level'),
'#type' => 'select',
'#title' => $this->t('Log level'),
'#description' => $this->t('Controls the severity of logging.'),
'#options' => [
RfcLogLevel::DEBUG => $this->t('Debug messages'),
RfcLogLevel::INFO => $this->t('All messages (default)'),
RfcLogLevel::NOTICE => $this->t('Notices and errors'),
RfcLogLevel::WARNING => $this->t('Warnings and errors'),
RfcLogLevel::ERROR => $this->t('Errors only'),
],
];
$form['error'] = [
'#type' => 'details',
'#title' => $this->t('Error handling'),
'#description' => $this->t('Defines error handling and custom actions to be executed if specific HTTP requests are failing.'),
'#open' => TRUE,
];
$ocms_linkchecker_default_impersonate_account = User::load(1);
$form['error']['ocms_linkchecker_impersonate_account'] = [
'#type' => 'textfield',
'#title' => $this->t('Impersonate user account'),
'#description' => $this->t('If below error handling actions are executed they can be impersonated with a custom user account. By default this is user %name, but you are able to assign a custom user to allow easier identification of these automatic revision updates. Make sure you select a user with <em>full</em> permissions on your site or the user may not able to access and save all content.', array('%name' => $ocms_linkchecker_default_impersonate_account->getAccountName())),
'#size' => 30,
'#maxlength' => 60,
'#autocomplete_path' => 'user/autocomplete',
'#default_value' => $config->get('error.impersonate_account'),
];
$form['error']['ocms_linkchecker_action_status_code_301'] = [
'#title' => $this->t('Update permanently moved links'),
'#description' => $this->t('If enabled, outdated links in content providing a status <em>Moved Permanently</em> (status code 301) are automatically updated to the most recent URL. If used, it is recommended to use a value of <em>three</em> to make sure this is not only a temporarily change. This feature trust sites to provide a valid permanent redirect. A new content revision is automatically created on link updates if <em>create new revision</em> is enabled in the <a href=":content_types">content types</a> publishing options. It is recommended to create new revisions for all link checker enabled content types. Link updates are logged according to your choice of logging system.', array(':content_types' => Url::fromRoute('entity.node_type.collection')->toString())),
'#type' => 'select',
'#default_value' => $config->get('error.status_301_action_threshold'),
'#options' => [
0 => $this->t('Disabled'),
1 => $this->t('After one failed check'),
2 => $this->t('After two failed checks'),
3 => $this->t('After three failed checks'),
5 => $this->t('After five failed checks'),
10 => $this->t('After ten failed checks'),
],
];
$form['error']['ocms_linkchecker_action_status_code_404'] = [
'#title' => $this->t('Unpublish content on file not found error'),
'#description' => $this->t('If enabled, content with one or more broken links (status code 404) will be unpublished and moved to moderation queue for review after the number of specified checks failed. If used, it is recommended to use a value of <em>three</em> to make sure this is not only a temporarily error.'),
'#type' => 'select',
'#default_value' => $config->get('error.status_404_action_threshold'),
'#options' => [
0 => $this->t('Disabled'),
1 => $this->t('After one file not found error'),
2 => $this->t('After two file not found errors'),
3 => $this->t('After three file not found errors'),
5 => $this->t('After five file not found errors'),
10 => $this->t('After ten file not found errors'),
],
];
$form['error']['ocms_linkchecker_ignore_response_codes'] = [
'#default_value' => $config->get('error.ignore_response_codes'),
'#type' => 'textarea',
'#title' => $this->t("Don't treat these response codes as errors"),
'#description' => $this->t('One HTTP status code per line, e.g. 403.'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$config = $this->config('ocms_linkchecker.settings');
$form_state->setValue('ocms_linkchecker_disable_link_check_for_urls', trim($form_state->getValue('ocms_linkchecker_disable_link_check_for_urls')));
$form_state->setValue('ocms_linkchecker_ignore_response_codes', trim($form_state->getValue('ocms_linkchecker_ignore_response_codes')));
$ignoreResponseCodes = preg_split('/(\r\n?|\n)/', $form_state->getValue('ocms_linkchecker_ignore_response_codes'));
foreach ($ignoreResponseCodes as $ignoreResponseCode) {
// @todo: Switch this to use the PuplinkcheckerUtilityService
if (!$this->validResponseCode($ignoreResponseCode)) {
$form_state->setErrorByName('ocms_linkchecker_ignore_response_codes', $this->t('Invalid response code %code found.', ['%code' => $ignoreResponseCode]));
}
}
// Prevent the removal of RFC documentation domains. These are the official
// and reserved documentation domains and not "example" hostnames!
$ocms_linkchecker_disable_link_check_for_urls = array_filter(preg_split('/(\r\n?|\n)/', $form_state->getValue('ocms_linkchecker_disable_link_check_for_urls')));
$form_state->setValue('ocms_linkchecker_disable_link_check_for_urls', implode("\n", array_unique(array_merge(explode("\n", trim($config->get('check.reserved_urls'))), $ocms_linkchecker_disable_link_check_for_urls))));
// Validate impersonation user.
$ocms_linkchecker_impersonate_account = User::load($form_state->getValue('ocms_linkchecker_impersonate_account'));
if (!$ocms_linkchecker_impersonate_account) {
$form_state->setErrorByName('ocms_linkchecker_impersonate_account', $this->t('User account %id cannot be found.', ['%id' => $form_state->getValue('ocms_linkchecker_impersonate_account')]));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('ocms_linkchecker.settings')
->set('general.scan_blocks', $form_state->getValue('ocms_linkchecker_scan_blocks'))
->set('general.check_link_types', $form_state->getValue('ocms_linkchecker_check_links_types'))
->set('extract.from_a', $form_state->getValue('ocms_linkchecker_extract_from_a'))
->set('extract.from_audio', $form_state->getValue('ocms_linkchecker_extract_from_audio'))
->set('extract.from_embed', $form_state->getValue('ocms_linkchecker_extract_from_embed'))
->set('extract.from_iframe', $form_state->getValue('ocms_linkchecker_extract_from_iframe'))
->set('extract.from_img', $form_state->getValue('ocms_linkchecker_extract_from_img'))
->set('extract.from_object', $form_state->getValue('ocms_linkchecker_extract_from_object'))
->set('extract.from_video', $form_state->getValue('ocms_linkchecker_extract_from_video'))
->set('extract.filter.blacklist', $form_state->getValue('ocms_linkchecker_filter_blacklist'))
->set('check.max_connections', $form_state->getValue('ocms_linkchecker_check_connections_max'))
->set('check.user_agent', $form_state->getValue('ocms_linkchecker_check_useragent'))
->set('check.interval', $form_state->getValue('ocms_linkchecker_check_interval'))
->set('check.disable_for_urls', $form_state->getValue('ocms_linkchecker_disable_link_check_for_urls'))
->set('check.log_level', $form_state->getValue('ocms_linkchecker_logging_level'))
->set('error.impersonate_account', $form_state->getValue('ocms_linkchecker_impersonate_account'))
->set('error.status_301_action_threshold', $form_state->getValue('ocms_linkchecker_action_status_code_301'))
->set('error.status_404_action_threshold', $form_state->getValue('ocms_linkchecker_action_status_code_404'))
->set('error.ignore_response_codes', $form_state->getValue('ocms_linkchecker_ignore_response_codes'))
->save();
// If block scanning has been selected.
// if ($form_state->getValue('ocms_linkchecker_scan_blocks') > $form['general']['ocms_linkchecker_scan_blocks']['#default_value']) {
// module_load_include('inc', 'linkchecker', 'linkchecker.batch');
// batch_set(_linkchecker_batch_import_block_custom());
// }
parent::submitForm($form, $form_state);
}
/**
* Defines the list of allowed response codes for form input validation.
*
* @param int $code
* A numeric response code.
*
* @return bool
* TRUE if the status code is valid, otherwise FALSE.
*/
private function validResponseCode($responseCode) {
$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
return array_key_exists($responseCode, $responses);
}
}
<file_sep>/docroot/themes/custom/ocms_base/js/mega-menu-navigation.js
/* =================================================/
/============ Mega Menu JavaScript ================/
/========= This javascript is used to assist ======/
/======== the mega menu css to control this ======/
/============== menus' visibility ==============/
/==================================================*/
+ function($) {
'use strict';
// Selecting menu items by index
var mMenuNav = $('.header-nav nav'),
mMenuNavH2 = $('.header-nav nav h2'),
menuItemOne = $('.header-nav .navbar-nav > li').eq(0),
menuItemTwo = $('.header-nav .navbar-nav > li').eq(1),
menuItemThree = $('.header-nav .navbar-nav > li').eq(2),
menuItemFour = $('.header-nav .navbar-nav > li').eq(3),
menuItemFive = $('.header-nav .navbar-nav > li').eq(4);
$(mMenuNav).addClass('megamenu'); // adding mega menu class to drupal mega menu
$(mMenuNavH2).remove(); // remove hidden h2 for screen reader
// Appending mega menu items
$('.filing').appendTo(menuItemOne);
$('.payments').appendTo(menuItemTwo);
$('.refunds').appendTo(menuItemThree);
$('.cnd').appendTo(menuItemFour);
$('.fni').appendTo(menuItemFive);
// Adding hover style on hover of sub navigation
$('.filing').hover(function() {
$((menuItemOne)[0].firstElementChild).toggleClass('mm-is-active');
});
$('.payments').hover(function() {
$((menuItemTwo)[0].firstElementChild).toggleClass('mm-is-active');
});
$('.refunds').hover(function() {
$((menuItemThree)[0].firstElementChild).toggleClass('mm-is-active');
});
$('.cnd').hover(function() {
$((menuItemFour)[0].firstElementChild).toggleClass('mm-is-active');
});
$('.fni').hover(function() {
$((menuItemFive)[0].firstElementChild).toggleClass('mm-is-active');
});
// Adding bootstrap classes to sections
// file link
if ($('.filing section').length == 1) {
$('.filing section').addClass('col-lg-12');
} else if ($('.filing section').length == 2) {
$('.filing section').addClass('col-lg-6');
} else if ($('.filing section').length == 3) {
$('.filing section').addClass('col-lg-4');
} else if ($('.filing section').length == 4) {
$('.filing section').addClass('col-lg-3');
}
// payments link
if ($('.payments section').length == 1) {
$('.payments section').addClass('col-lg-12');
} else if ($('.payments section').length == 2) {
$('.payments section').addClass('col-lg-6');
} else if ($('.payments section').length == 3) {
$('.payments section').addClass('col-lg-4');
} else if ($('.payments section').length == 4) {
$('.payments section').addClass('col-lg-3');
}
// refunds link
if ($('.refunds section').length == 1) {
$('.refunds section').addClass('col-lg-12');
} else if ($('.refunds section').length == 2) {
$('.refunds section').addClass('col-lg-6');
} else if ($('.refunds section').length == 3) {
$('.refunds section').addClass('col-lg-4');
} else if ($('.refunds section').length == 4) {
$('.refunds section').addClass('col-lg-3');
}
// credits and deduction link
if ($('.cnd section').length == 1) {
$('.cnd section').addClass('col-lg-12');
} else if ($('.cnd section').length == 2) {
$('.cnd section').addClass('col-lg-6');
} else if ($('.cnd section').length == 3) {
$('.cnd section').addClass('col-lg-4');
} else if ($('.cnd section').length == 4) {
$('.cnd section').addClass('col-lg-3');
}
// forms and publications link
if ($('.fni section').length == 1) {
$('.fni section').addClass('col-lg-12');
} else if ($('.fni section').length == 2) {
$('.fni section').addClass('col-lg-6');
} else if ($('.fni section').length == 3) {
$('.fni section').addClass('col-lg-4');
} else if ($('.fni section').length == 4) {
$('.fni section').addClass('col-lg-3');
}
// remove anchor bottom border from block with descriptions
$('.paragraph--type--ocms-mega-menu-item').each(function() {
if ($(this).children('div').hasClass('field--name-field-ocms-text-plain-long')) {
$(this).find('.field--name-field-ocms-callout-link a').css('border-bottom','none');
}
});
// initialize the megamenu
$(document).ready(function () {
// initialize the megamenu
$(".megamenu").accessibleMegaMenu();
// hack so that the megamenu doesn't show flash of css animation after the page loads.
setTimeout(function () {
$('body').removeClass('init');
}, 500);
});
}(jQuery);<file_sep>/docroot/modules/custom/ocms_viewfiles/src/Controller/OcmsFileView.php
<?php
namespace Drupal\ocms_viewfiles\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\file\Entity;
use Drupal\media_entity\Entity\Media;
use Drupal\file\Entity\File;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Database\Connection;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* @file
* Controller for media_helper module.
*/
class IrsFileView extends ControllerBase {
/**
* View directory folders under sites files which are in our static file taxonomy
*/
public function content() {
$vid="ocms_static_file_path";
$parent = 0;
$max_depth = NULL;
$load_entities = FALSE;
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $parent, $max_depth, $load_entities);
$directory_names=array();
$headers = array(
array('data' => t('Name'))
);
foreach ($terms as $term){
$directory_names[]=$term->name;
}
$directory_tree="This directory listing is considered an expert interface to locating PDF documents. Please refer to the <a href='https://www.ocms.gov/Forms-&-Pubs'>main forms and publications landing page </a> for more details on locating specific forms, publications, or instructions.<br><br>";
$path = "sites/default/files/";
$directories = scandir($path);
if (count($directories)){
foreach ($directories as $directory) {
if (in_array($directory,$directory_names)){
if ($directory !="images"){
$link_url= "/downloads/$directory";
$host = \Drupal::request()->getSchemeAndHttpHost();
$full_path = $host."/sites/default/files/".$directory;
$directoryData[] = array(
'link_url' => $link_url,
'name' => $directory,
);
}
}
}
}
$order = tablesort_get_order($headers);
$rows = array();
foreach ($directoryData as $entry) {
$rows[] = array(
array('data' => new FormattableMarkup('<a href=":link">@name</a>',
[':link' => $entry['link_url'],
'@name' => $entry['name']])
),
);
}
$attributes = array('class' => array('tablesorter'),'id'=>array("myTable"));
$table_element = array(
'#theme' => 'table',
'#header' => $headers,
'#rows' => $rows,
'#empty' =>t('Your table is empty'),
'#attributes'=>$attributes,
);
$html=drupal_render($table_element);
$html=$directory_tree.$html;
$build = array(
'#type' => 'markup',
'#markup' => $html,
'#attached' => array(
'library' => array('ocms_viewfiles/sortfiles_libraries'),
),
);
return $build;
}
/**
* View directory folders
*/
public function dir_content($path_dir='') {
// get the complete path which may be several levels deep
$current_path = \Drupal::service('path.current')->getPath();
$path_dir=str_replace("/downloads/","",$current_path);
$path = "sites/default/files/$path_dir";
// get the taxonoym id for this path
$vid="ocms_static_file_path";
$file_path_tid=getTidByName($path_dir,$vid);
$directoryData=array();
$parent_dirs=explode("/",$path_dir);
$last_element=array_pop($parent_dirs);
$parent_url=implode("/",$parent_dirs);
$host = \Drupal::request()->getSchemeAndHttpHost();
$file_names = scandir($path);
if (count($file_names)) {
foreach ($file_names as $file_name) {
// find out if this is a file or a directory
if ($file_name!="." AND $file_name!="..") {
$array = explode('.', $file_name);
if (count($array)>1){
$extension = end($array);
}else{
$extension ="";
}
if (!$extension){
// if it doesnt have any exension it must be a directory
$link_url= "/downloads/$path_dir/".$file_name;
$directoryData[] = array(
'link_url' => $link_url,
'name' => $file_name,
'changed_date' => "",
'size' => "",
'description' => ""
);
}
}
}
}
$rows = array();
foreach ($directoryData as $entry) {
$dir_rows[] = array(
array('data' => new FormattableMarkup('<a href=":link">@name</a>',
[':link' => $entry['link_url'],
'@name' => $entry['name']])
),
);
}
if (count($directoryData)){
$directory_headers = array(
array('data' => t('Name'))
);
$dir_table_element = array(
'#theme' => 'table',
'#rows' => $dir_rows,
);
$dir_html=drupal_render($dir_table_element);
}else{
$dir_html="";
}
$headers = array(
array('data' => t('Name'),'field' => 'filename', 'sort' => 'asc' ),
array('data' => t('Date'), 'field' => 'changed','sort' => 'asc'),
array('data' => t('Size'), 'field' => 'filesize','sort' => 'asc'),
array('data' => t('Description'), 'field' => 'name','sort' => 'asc'),
);
$db = \Drupal::database();
$query = $db->select('media_field_data', 'mf_data')
->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
->extend('\Drupal\Core\Database\Query\TableSortExtender');
$query->leftJoin('media__field_ocms_posted', 'posted', 'mf_data.mid = posted.entity_id');
$query->leftJoin('media__field_document', 'mf_doc', 'mf_data.mid = mf_doc.entity_id');
$query->innerJoin('media_field_data','mfd','mfd.mid = mf_data.mid');
$query->innerJoin('file_managed', 'fm', 'mf_doc.field_document_target_id = fm.fid');
$query->innerJoin('media__field_ocms_file_public_path', 'pp', 'mf_data.mid = pp.entity_id');
$query->fields('fm',array('filename','uri','changed','filesize'));
$query->fields('mfd',array('name'));
//$query->fields('posted',array('name'));
$query->condition('pp.field_ocms_file_public_path_target_id', $file_path_tid, '=');
$db_or = db_or();
$db_or->condition('mf_data.moderation_state', 'published', '=');
$db_or->condition('mf_data.moderation_state', NULL, 'IS');
$query->condition($db_or);
$result = $query
->limit(50)
->orderByHeader($headers)
->execute();
$host = \Drupal::request()->getSchemeAndHttpHost();
$full_path = $host."/sites/default/files/";
// Populate the rows.
$rows = array();
foreach($result as $row) {
/*
$post_data=null;
if (isset($static_media->field_ocms_posted)){
$posted_date=$static_media->get('field_ocms_posted')->getValue();
$post_date=$posted_date[0]['value'];
}
if ($post_date){
$changed_date= str_replace("T"," ",$post_date);
}else{
$changed_date= date("Y-m-d\ H:i:s", $timestamp);
}
*/
// only show files that are published in the public directory
//if(strpos($row->uri,"public://") !== false){
$link=str_replace("public://",$full_path,$row->uri);
$size = format_size($row->filesize);
$rows[] = array('data' => array(
'Name'=> new FormattableMarkup('<a href=":link">@name</a>',
[':link' => $link,
'@name' => $row->filename])
,
'Date' =>date('Y-m-d\ H:i:s',$row->changed),
'Size' =>$size,
'Description' => $row->name,
));
//}
}
$parent_dirs=explode("/",$path_dir);
$last_element=array_pop($parent_dirs);
$parent_url=implode("/",$parent_dirs);
$host = \Drupal::request()->getSchemeAndHttpHost();
$file_names = scandir($path);
// different text for irm directory
if ($path_dir=="irm") {
$directory_tree="IRM Source Files<br>This page provides links to the Internal Revenue Manual (IRM) source files.
The listing can be sorted by the file name or the date the file was posted. To locate forms, instructions and publications
please see the <a href='/forms-pubs'>Forms & Publications page</a>.<br>";
} else {
$directory_tree="Contents of Directory $path_dir<br><br>";
}
$directory_tree.="<br><a href='/downloads/$parent_url'>Parent Directory</a><br><br>";
if (count($file_names)) {
// headers array, sorting by default on filename
$directoryData=array();
foreach ($file_names as $file_name) {
// find out if this is a file or a directory
if ($file_name!="." AND $file_name!="..") {
$array = explode('.', $file_name);
if (count($array)>1){
$extension = end($array);
}else{
$extension ="";
}
if (!$extension){
// if it doesnt have any exension it must be a directory
$link_url= "/downloads/$path_dir/".$file_name;
$directoryData[] = array(
'link_url' => $link_url,
'name' => $file_name,
'changed_date' => "",
'size' => "",
'description' => ""
);
}
}
}
}
$table_element = array(
'#theme' => 'table',
'#header' => $headers,
'#rows' => $rows,
'#empty' =>t('No files found'),
);
$html=drupal_render($table_element);
$html=$directory_tree.$dir_html.$html;
$build = array(
'#type' => 'markup',
'#markup' => $html,
);
$build['file_table'] = array('#type' => 'pager');
return $build;
}
/**
* Utility: find term by name and vid.
* @param null $name
* Term name
* @param null $vid
* Term vid
* @return int
* Term id or 0 if none.
*/
function getTidByName($name = NULL, $vid = NULL) {
$properties = [];
if (!empty($name)) {
$properties['name'] = $name;
}
if (!empty($vid)) {
$properties['vid'] = $vid;
}
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties($properties);
$term = reset($terms);
return !empty($term) ? $term->id() : 0;
}
protected function getModuleName() {
return 'ocms_viewfiles';
}
function is_this_directory ($file){
return ((fileperms("$file") & 0x4000) == 0x4000);
}
}
<file_sep>/docroot/themes/custom/ocms_education/js/custom/mobile-menu-header-top.js
/**
* Add Javascript - Mobile menu header top
*/
jQuery(document).ready(function($) {
if ($(".header-top-area .sf-menu").length>0) {
$("#header-top").addClass('js-header-top-mobile-menu-active');
};
});
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerHttpInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link http services.
*/
interface PupLinkcheckerHttpInterface {
/**
* Checks if a link is broken.
*
* @param object $link
* The fully loaded link to check.
*/
public function checkLink($link);
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerStatusHandlingInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link status handling services.
*/
interface PupLinkcheckerStatusHandlingInterface {
/**
* Reacts to the status code of a checked link.
*
* @param object $response
* An object containing the HTTP request headers, response code, headers,
* data and redirect status.
* @param string $link
* An object containing the url, lid and fail_count.
*/
public function handleStatus(&$response, $link);
}
<file_sep>/docroot/sites/settings.local.php
<?php
/**
* @file
* Local development override configuration feature.
*
* To activate this feature, copy and rename it such that its path plus
* filename is 'sites/default/settings.local.php'. Then, go to the bottom of
* 'sites/default/settings.php' and uncomment the commented lines that mention
* 'settings.local.php'.
*
* If you are using a site name in the path, such as 'sites/example.com', copy
* this file to 'sites/example.com/settings.local.php', and uncomment the lines
* at the bottom of 'sites/example.com/settings.php'.
*/
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();
/**
* Enable local development services.
*/
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
/**
* Show all error messages, with backtrace information.
*
* In case the error level could not be fetched from the database, as for
* example the database connection failed, we rely only on this value.
*/
$config['system.logging']['error_level'] = 'verbose';
$config_directories = array(
CONFIG_SYNC_DIRECTORY => '../config',
);
$config_directories['vcs'] = '../config/';
/**
* Disable CSS and JS aggregation.
*/
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
#$settings['extension_discovery_scan_tests'] = TRUE;
#$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
// <DDSETTINGS>
// Please don't edit anything between <DDSETTINGS> tags.
// This section is autogenerated by Acquia Dev Desktop.
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_dev_ocms_lamtech_sl_dd.inc')) {
require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_dev_ocms_lamtech_sl_dd.inc';
}
// </DDSETTINGS>
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/Controller/BrokenLinksReport.php
<?php
namespace Drupal\ocms_linkchecker\Controller;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\ocms_linkchecker\PupLinkcheckerAccessInterface;
use Drupal\ocms_linkchecker\BrokenLinksTableTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Display a table of contents for the presentation
*/
class BrokenLinksReport extends ControllerBase {
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Drupal's translation service.
*
* @var \Drupal\Core\StringTranslation\TranslationInterface
*/
protected $translation;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* OCMS Linkchecker Access Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerAccessInterface
*/
protected $access;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The redirect destination service.
*
* @var \Drupal\Core\Routing\RedirectDestinationInterface
*/
protected $redirectDestination;
/**
* The query ::build will use.
*
* @var
*/
protected $query;
/**
* Response codes that should not be considered errors.
*
* @var array
*/
protected $ignoreResponseCodes;
/**
* Constructs the broken links controller object.
*
* @param \Drupal\Core\Database\Connection
* The database connection
* @param \Drupal\Core\StringTranslation\TranslationInterface
* The translation service
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\ocms_linkchecker\PupLinkcheckerAccessInterface
* The OCMS Linkchecker Access service
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Routing\RedirectDestinationInterface
*/
public function __construct(Connection $database, TranslationInterface $string_translation, ConfigFactoryInterface $config_factory, PupLinkcheckerAccessInterface $ocms_linkchecker_access, AccountInterface $current_user, RedirectDestinationInterface $redirect_destination) {
$this->connection = $database;
$this->translation = $string_translation;
$this->configFactory = $config_factory;
$this->access = $ocms_linkchecker_access;
$this->currentUser = $current_user;
$this->redirectDestination = $redirect_destination;
$config = $this->configFactory->get('ocms_linkchecker.settings');
$this->ignoreResponseCodes = preg_split('/(\r\n?|\n)/',
$config->get('error.ignore_response_codes'));
// Search for broken links in entities of all users.
$subquery = $this->connection->select('ocms_linkchecker_entity', 'le')
->distinct()
->fields('le', array('lid'));
// Build pager query.
$query = $this->connection->select('ocms_linkchecker_link', 'll')
->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
->extend('\Drupal\Core\Database\Query\TableSortExtender');
$query->innerJoin($subquery, 'q2', 'q2.lid = ll.lid');
$query->fields('ll');
$query->condition('ll.last_checked', 0, '<>');
$query->condition('ll.status', 1);
$query->condition('ll.code', $this->ignoreResponseCodes, 'NOT IN');
$this->query = $query;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('database'),
$container->get('string_translation'),
$container->get('config.factory'),
$container->get('ocms_linkchecker.access'),
$container->get('current_user'),
$container->get('redirect.destination')
);
}
use BrokenLinksTableTrait;
}
<file_sep>/docroot/modules/custom/ocms_files/ocms_file_operations/src/Tests/SimpleTest/TestFileOperations.php
<?php
namespace Drupal\irs_file_operations\Tests\SimpleTest;
use Drupal\simpletest\WebTestBase;
/**
* Test the existence of IRS File Operations module.
*
* @group irs_file_operations
*/
class TestFileOperations extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('irspup', 'irs_file_operations', 'toolbar', 'media_entity');
protected $profile = 'testing';
/**
*
* @var \Drupal\user\UserInterface
*/
protected function setUp() {
parent::setUp();
}
public function testMediaBundleCreation() {
$directory = 'simpletestpup/ebook/';
$source = DRUPAL_ROOT . '/media_unpublish/' . $directory;
$destination = DRUPAL_ROOT . '/sites/default/files/' . $directory;
$directory_created = file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
if ($directory_created) {
$this->assertTrue($directory_created);
$files = file_scan_directory($source, '/.*\.(txt|pdf|doc|docx)$/');
if (!empty($files)) {
foreach ($files as $file) {
$result = file_unmanaged_copy($file->uri, $destination, FILE_EXISTS_REPLACE);
$this->assertTrue($result, "File copied {$result}.");
}
}
else {
$this->assertTrue(!empty($files), "Files does not exist!");
}
}
else {
$this->assertTrue($directory_created, "Unable to create directory {$destination}.");
}
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/Plugin/QueueWorker/OcmsLinkcheckerCheckLinks.php
<?php
namespace Drupal\ocms_linkchecker\Plugin\QueueWorker;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\ocms_linkchecker\PupLinkcheckerHttpInterface;
use Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Updates the aquifer content types.
*
* @QueueWorker(
* id = "ocms_linkchecker_check_links",
* title = @Translation("Check for broken links"),
* cron = {"time" = 60}
* )
*/
class PupLinkcheckerCheckLinks extends QueueWorkerBase implements ContainerFactoryPluginInterface {
/**
* The Http service
* @var Drupal\ocms_linkchecker\PupLinkcheckerHttpInterface
*/
protected $http;
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs the Queue Worker
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerHttpInterface $http
* The OCMS Linkchecker Http Service.
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface $ocms_linkchecker_utility
* The OCMS Linkchecker Utility Service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
*/
public function __construct(PupLinkcheckerHttpInterface $http, PupLinkcheckerUtilityInterface $ocms_linkchecker_utility, ConfigFactoryInterface $config_factory) {
$this->http = $http;
$this->utilityService = $ocms_linkchecker_utility;
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('ocms_linkchecker.http'),
$container->get('ocms_linkchecker.utility'),
$container->get('config.factory')
);
}
/**
* {@inheritdoc}
*/
public function processItem($data) {
$link = $this->utilityService->loadLink($data);
if (is_object($link)) {
$config = $this->configFactory->get('ocms_linkchecker.settings');
// This link could appear in the queue more than one time if this
// QueueWorker ran out of time on a previous cron run. If the link
// is in the queue more than once and things run fast enough that
// the QueueWorker is able to get to it again within a single cron
// run, it would get processed in less time than was configured. So,
// we double check that this link hasn't already been checked within the
// configured interval on account of it being in the queue more than one
// time.
if ($link->last_checked < (REQUEST_TIME - $config->get('check.interval'))) {
$this->http->checkLink($link);
}
}
}
}
<file_sep>/docroot/modules/custom/ocms_files/ocms_file_operations/src/Tests/Unit/TestFileOperations.php
<?php
namespace Drupal\irs_file_operations\Tests\Unit;
use Drupal\Tests\UnitTestCase;
if (!defined('DRUPAL_ROOT')) {
//Looping to find drupal root folder.
$current_dir = dirname(__DIR__);
while (!file_exists("$current_dir/index.php")) {
$current_dir = dirname($current_dir);
}
define('DRUPAL_ROOT', $current_dir);
}
/**
* Tests the Drupal 8 irspup module functionality
*
* @group irspup
*/
class TestFileOperations extends UnitTestCase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = array('irs_file_operations', 'irspup', 'toolbar');
protected $profile = 'testing';
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
}
/**
* Tests creating a media bundle programmatically.
*/
public function testMediaBundleCreation() {
$directory = 'simpletestpup/ebook/';
$source = DRUPAL_ROOT . '/media_unpublish/' . $directory;
$destination = DRUPAL_ROOT . '/sites/default/files/' . $directory;
$directory_created = false;
if (!file_exists($destination)) {
$directory_created = mkdir($destination, 0777, true);
}
$files = glob($source . "*.{pdf,txt,doc,docx}", GLOB_BRACE);
if(!empty($files)) {
foreach ($files as $file) {
$file_name_array = explode("/", $file);
$count = sizeof($file_name_array);
$file_name = $file_name_array[$count - 1];
$result = copy($file, $destination . $file_name);
$this->assertTrue($result,"File copied.");
}
}
else {
$this->assertTrue(!empty($files), "Files does not exist!");
}
}
} <file_sep>/docroot/modules/custom/ocms_files/ocms_file_operations/src/Controller/OcmsFileOperationsController.php
<?php
namespace Drupal\irs_file_operations\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\irspup\Utility\DescriptionTemplateTrait;
/**
* @file
* Controller for media_helper module.
*/
class IrsFileOperationsController extends ControllerBase {
use DescriptionTemplateTrait;
/**
* Move file to destination
*/
public function moveFileToDestination($fid, $destination) {
$file_storage = \Drupal::entityManager()->getStorage('file');
if (empty($destination)) {
\Drupal::logger('irs_file_operations')->error($destination . 'Destination cannot be empty');
}
$file = $file_storage->load($fid);
$file_uri = $file->get('uri')->value;
$file_name = $file->get('filename')->value;
$query = \Drupal::database()->update('file_managed');
$query->fields([
'uri' => $destination . $file_name,
]);
$query->condition('fid', $fid);
$query->execute();
db_truncate('cache_entity')->execute();
$file_prepare = file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
if ($file_prepare == FALSE) {
\Drupal::logger('irs_file_operations')->error($file_prepare . 'Directory does not exist and it is not creted.');
}
$file_move = file_move($file, $destination, FILE_EXISTS_REPLACE);
if ($file_move == FALSE) {
\Drupal::logger('irs_file_operations')->error($file_move . 'File is not moved');
}
return drupal_flush_all_caches();
}
/**
* Update location path based on folder repository field.
*/
public function irsFileOperationsGetTax($termid) {
$storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
$parents = $storage->loadAllParents($termid);
$termname_result = '';
foreach (array_reverse($parents) as $parent) {
$termname = irs_file_operations_clean_string($parent->get('name')->value) . '/';
$termname_result .= $termname;
}
// remove the last '/'
$termname_result=substr_replace($termname_result, "", -1);
return $termname_result;
}
/**
* Returns URI for the Particular Media
*/
public function irsFileOperationsUri($fid) {
$query = \Drupal::database()->select('file_managed', 'fd');
$query->addField('fd', 'uri');
$query->condition('fd.fid', $fid);
$query->range(0, 1);
$location_path_value = $query->execute()->fetchField();
return $location_path_value;
}
/**
* {@inheritdoc}
*
* We override this so we can see some substitutions.
*/
protected function getModuleName() {
return 'irs_file_operations';
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/Plugin/QueueWorker/OcmsLinkcheckerAddNodeLinks.php
<?php
namespace Drupal\ocms_linkchecker\Plugin\QueueWorker;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\ocms_linkchecker\PupLinkcheckerDatabaseInterface;
use Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Updates the aquifer content types.
*
* @QueueWorker(
* id = "ocms_linkchecker_scan_node",
* title = @Translation("Scan a node for links"),
* cron = {"time" = 60}
* )
*/
class PupLinkcheckerAddNodeLinks extends QueueWorkerBase implements ContainerFactoryPluginInterface {
/**
* The Database service
* @var Drupal\ocms_linkchecker\PupLinkcheckerDatabaseInterface
*/
protected $database;
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* Constructs the Queue Worker
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerDatabaseInterface $database
* The OCMS Linkchecker Database Service.
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface $ocms_linkchecker_utility
* The OCMS Linkchecker Utility Service.
*/
public function __construct(PupLinkcheckerDatabaseInterface $database, PupLinkcheckerUtilityInterface $ocms_linkchecker_utility) {
$this->database = $database;
$this->utilityService = $ocms_linkchecker_utility;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('ocms_linkchecker.database'),
$container->get('ocms_linkchecker.utility')
);
}
/**
* {@inheritdoc}
*/
public function processItem($data) {
$node = $this->utilityService->loadEntity('node', $data);
if (is_object($node)) {
$this->database->addNodeLinks($node);
}
}
}
<file_sep>/docroot/modules/custom/ocms_files/ocms_file_operations/README.txt
/**
* @file
* README for the IRS File Operation.
*/
This module change the Drupal behaviour. Typical Drupal behavior is to rename files on upload to <filename>_0.<ext>
This module modifies that behavior.
1.0 - Behavior is as follows:
If the same file exist in folder. replace the new file with older one.
################################################################################
USAGE
################################################################################
1.Enable the irs_file_operation module on the modules page.
2.Your done
#######################
Required Field:
#######################
1. field_ocms_file_public_path
2. field_document
How its works
1) Login as a Admin or Media User
2) Click on Content Menu
3) Click on Media Tab.
4) Click on 'Add Media'
5) Select Folder Repository
5) Select Document to Upload file
6) Choose file and Hit Save and Publish
4) By default media is stored in the private folder when the media is unpublished. If the user published the media, it will move from private to public directory.
Also instead of renaming the file it will replace any existing file with the same name in the same directory.
<file_sep>/docroot/themes/custom/ocms_corporate/theme-settings.php
<?php
function ocms_corporate_form_system_theme_settings_alter(&$form, &$form_state) {
$form['#attached']['library'][] = 'ocms_corporate/theme-settings';
$form['mtt_settings'] = array(
'#type' => 'fieldset',
'#title' => t('MtT Theme Settings'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['mtt_settings']['tabs'] = array(
'#type' => 'vertical_tabs',
'#default_tab' => 'basic_tab',
);
$form['mtt_settings']['basic_tab']['basic_settings'] = array(
'#type' => 'details',
'#title' => t('Basic Settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['basic_tab']['basic_settings']['breadcrumb_separator'] = array(
'#type' => 'textfield',
'#title' => t('Breadcrumb separator'),
'#description' => t('Enter the class of the icon you want from the Font Awesome library e.g.: fa-angle-right. A list of the available classes is provided here: <a href="http://fortawesome.github.io/Font-Awesome/cheatsheet" target="_blank">http://fortawesome.github.io/Font-Awesome/cheatsheet</a>.'),
'#default_value' => theme_get_setting('breadcrumb_separator', 'ocms_corporate'),
'#size' => 20,
'#maxlength' => 100,
);
$form['mtt_settings']['basic_tab']['basic_settings']['scrolltop'] = array(
'#type' => 'fieldset',
'#title' => t('Scroll to top'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['basic_tab']['basic_settings']['scrolltop']['scrolltop_display'] = array(
'#type' => 'checkbox',
'#title' => t('Show scroll-to-top button'),
'#description' => t('Use the checkbox to enable or disable scroll-to-top button.'),
'#default_value' => theme_get_setting('scrolltop_display', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['basic_tab']['basic_settings']['scrolltop']['scrolltop_icon'] = array(
'#type' => 'textfield',
'#title' => t('Scroll To Top icon'),
'#description' => t('Enter the class of the icon you want from the Font Awesome library e.g.: fa-long-arrow-up. A list of the available classes is provided here: <a href="http://fortawesome.github.io/Font-Awesome/cheatsheet" target="_blank">http://fortawesome.github.io/Font-Awesome/cheatsheet</a>.'),
'#default_value' => theme_get_setting('scrolltop_icon','ocms_corporate'),
'#size' => 20,
'#maxlength' => 100,
);
$form['mtt_settings']['looknfeel_tab']['looknfeel'] = array(
'#type' => 'details',
'#title' => t('Look\'n\'Feel'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['looknfeel_tab']['looknfeel']['color_scheme'] = array(
'#type' => 'select',
'#title' => t('Color Schemes'),
'#description' => t('From the drop-down menu, select the color scheme you prefer.'),
'#default_value' => theme_get_setting('color_scheme', 'ocms_corporate'),
'#options' => array(
'turqoise' => t('Turqoise (Default)'),
'blue' => t('Blue'),
'green' => t('Green'),
'red' => t('Red'),
'pink' => t('Pink'),
'purple' => t('Purple'),
'gray' => t('Gray'),
'orange' => t('Orange'),
'yellow' => t('Yellow'),
'night-blue' => t('Night Blue'),
),
);
$form['mtt_settings']['looknfeel_tab']['looknfeel']['form_style'] = array(
'#type' => 'select',
'#title' => t('Form styles of contact page'),
'#description' => t('From the drop-down menu, select the form style that you prefer.'),
'#default_value' => theme_get_setting('form_style', 'ocms_corporate'),
'#options' => array(
'form-style-1' => t('Style-1 (default)'),
'form-style-2' => t('Style-2'),
),
);
$form['mtt_settings']['regions_tab']['regions'] = array(
'#type' => 'details',
'#title' => t('Region settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['regions_tab']['regions']['animations_state'] = array(
'#type' => 'checkbox',
'#title' => t('Animations'),
'#description' => t('Enable or disable animations globally. You can further adjust this for individual regions below.'),
'#default_value' => theme_get_setting('animations_state', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['header'] = array(
'#type' => 'fieldset',
'#title' => t('Header'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['header']['header_layout_container'] = array(
'#type' => 'select',
'#title' => t('Container'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('header_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['header']['fixed_header'] = array(
'#type' => 'checkbox',
'#title' => t('Fixed Header'),
'#description' => t('Use the checkbox to apply fixed position to the header.'),
'#default_value' => theme_get_setting('fixed_header', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['content_top'] = array(
'#type' => 'fieldset',
'#title' => t('Content Top'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['content_top']['content_top_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('content_top_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['content_top']['content_top_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('content_top_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['content_top']['content_top_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('content_top_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['main_content'] = array(
'#type' => 'fieldset',
'#title' => t('Main Content'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['main_content']['main_content_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('main_content_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['sidebar_first'] = array(
'#type' => 'fieldset',
'#title' => t('Sidebar First'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['sidebar_first']['sidebar_first_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('sidebar_first_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['sidebar_second'] = array(
'#type' => 'fieldset',
'#title' => t('Sidebar Second'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['sidebar_second']['sidebar_second_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('sidebar_second_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['content_bottom'] = array(
'#type' => 'fieldset',
'#title' => t('Content Bottom'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['content_bottom']['content_bottom_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('content_bottom_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['content_bottom']['content_bottom_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('content_bottom_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured_top'] = array(
'#type' => 'fieldset',
'#title' => t('Featured Top'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['featured_top']['featured_top_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('featured_top_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured_top']['featured_top_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('featured_top_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured_top']['featured_top_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('featured_top_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured'] = array(
'#type' => 'fieldset',
'#title' => t('Featured'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['featured']['featured_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('featured_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured']['featured_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('featured_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured']['featured_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('featured_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured_bottom'] = array(
'#type' => 'fieldset',
'#title' => t('Featured Bottom'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['featured_bottom']['featured_bottom_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('featured_bottom_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured_bottom']['featured_bottom_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('featured_bottom_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['featured_bottom']['featured_bottom_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('featured_bottom_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['highlighted'] = array(
'#type' => 'fieldset',
'#title' => t('Highlighted'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['highlighted']['highlighted_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('highlighted_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['highlighted']['highlighted_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('highlighted_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['highlighted']['highlighted_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('highlighted_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['highlighted_bottom'] = array(
'#type' => 'fieldset',
'#title' => t('Highlighted Bottom'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['highlighted_bottom']['highlighted_bottom_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('highlighted_bottom_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['highlighted_bottom']['highlighted_bottom_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('highlighted_bottom_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['highlighted_bottom']['highlighted_bottom_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('highlighted_bottom_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['footer_top'] = array(
'#type' => 'fieldset',
'#title' => t('Footer Top'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['footer_top']['footer_top_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('footer_top_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
'bicolor' => t('Bicolor'),
),
);
$form['mtt_settings']['regions_tab']['regions']['footer_top']['footer_top_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('footer_top_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['footer'] = array(
'#type' => 'fieldset',
'#title' => t('Footer'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['footer']['footer_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('footer_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['footer']['footer_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('footer_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['regions_tab']['regions']['footer']['footer_animation_effect'] = array(
'#type' => 'select',
'#title' => t('Animation Effect'),
'#description' => t('From the drop-down menu, select the animation effect you prefer.'),
'#default_value' => theme_get_setting('footer_animation_effect', 'ocms_corporate'),
'#options' => array(
'no-animation' => t('None'),
'fadeIn' => t('Fade In'),
'fadeInDown' => t('Fade In Down'),
'fadeInUp' => t('Fade In Up'),
'fadeInLeft' => t('Fade In Left'),
'fadeInRight' => t('Fade In Right'),
),
);
$form['mtt_settings']['regions_tab']['regions']['subfooter'] = array(
'#type' => 'fieldset',
'#title' => t('Subfooter'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['regions_tab']['regions']['subfooter']['subfooter_layout_container'] = array(
'#type' => 'select',
'#title' => t('Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer.'),
'#default_value' => theme_get_setting('subfooter_layout_container', 'ocms_corporate'),
'#options' => array(
'container-fluid' => t('Full Width'),
'container' => t('Fixed Width'),
),
);
$form['mtt_settings']['regions_tab']['regions']['subfooter']['subfooter_background_color'] = array(
'#type' => 'select',
'#title' => t('Background Color'),
'#description' => t('From the drop-down menu, select the background color you prefer.'),
'#default_value' => theme_get_setting('subfooter_background_color', 'ocms_corporate'),
'#options' => array(
'white-region' => t('White'),
'light-gray-region' => t('Light Gray'),
'colored-region' => t('Colored'),
'colored-region dark' => t('Dark'),
),
);
$form['mtt_settings']['post_tab']['post'] = array(
'#type' => 'details',
'#title' => t('Post'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['post_tab']['post']['reading_time'] = array(
'#type' => 'checkbox',
'#title' => t('Time to read'),
'#description' => t('Use the checkbox to enable or disable the "Time to read" indicator.'),
'#default_value' => theme_get_setting('reading_time', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['post_tab']['post']['post_progress'] = array(
'#type' => 'checkbox',
'#title' => t('Read so far'),
'#description' => t('Use the checkbox to enable or disable the reading progress indicator.'),
'#default_value' => theme_get_setting('post_progress', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['post_tab']['post']['affix'] = array(
'#type' => 'fieldset',
'#title' => t('Affix configuration'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('If you add or remove blocks from the header please change the corresponding values bellow to make the affix implementation work as expected.'),
);
$form['mtt_settings']['post_tab']['post']['affix']['affix_admin_height'] = array(
'#type' => 'textfield',
'#title' => t('Admin toolbar height (px)'),
'#default_value' => theme_get_setting('affix_admin_height', 'ocms_corporate'),
'#description' => t('The height of the admin toolbar in pixels'),
);
$form['mtt_settings']['post_tab']['post']['affix']['affix_fixedHeader_height'] = array(
'#type' => 'textfield',
'#title' => t('Fixed header height (px)'),
'#default_value' => theme_get_setting('affix_fixedHeader_height', 'ocms_corporate'),
'#description' => t('The height of the header when fixed at the top of the window in pixels'),
);
$form['mtt_settings']['layout_tab']['layout_modes'] = array(
'#type' => 'details',
'#title' => t('Theme Layout'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['layout_tab']['layout_modes']['layout_mode'] = array(
'#type' => 'select',
'#title' => t('Global Layout Mode'),
'#description' => t('From the drop-down menu, select the layout mode you prefer. This global setting overrides the individual region-specific layout settings.'),
'#default_value' => theme_get_setting('layout_mode', 'ocms_corporate'),
'#options' => array(
'wide' => t('Wide'),
'boxed' => t('Boxed'),
),
);
$form['mtt_settings']['font_tab']['font'] = array(
'#type' => 'details',
'#title' => t('Font Settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['font_tab']['font']['font_title'] = array(
'#type' => 'item',
'#markup' => 'For every region pick the <strong>font-family</strong> that corresponds to your needs.',
);
$form['mtt_settings']['font_tab']['font']['sitename_font_family'] = array(
'#type' => 'select',
'#title' => t('Site name'),
'#default_value' => theme_get_setting('sitename_font_family', 'ocms_corporate'),
'#options' => array(
'sff-31' => t('Alegreya SC, Georgia, Times, Times New Roman, Serif'),
'sff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'sff-40' => t('Archivo Narrow, Arial, Helvetica Neue, Sans-serif'),
'sff-42' => t('Arimo, Arial, Helvetica Neue, Sans-serif'),
'sff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'sff-16' => t('Cinzel, Georgia, Times, Serif'),
'sff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'sff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'sff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'sff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'sff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'sff-13' => t('Georgia, Times, Serif'),
'sff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'sff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'sff-36' => t('Julius Sans One, Arial, Helvetica Neue, Sans-serif'),
'sff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'sff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'sff-01' => t('Merriweather, Georgia, Times, Serif'),
'sff-32' => t('Montserrat SC, Arial, Helvetica Neue, Sans-serif'),
'sff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif'),
'sff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'sff-38' => t('Open Sans Condensed, Arial, Helvetica Neue, Sans-serif'),
'sff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'sff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'sff-15' => t('Philosopher, Georgia, Times, Serif'),
'sff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'sff-14' => t('Playfair Display, Times, Serif'),
'sff-39' => t('PT Sans Narrow, Arial, Helvetica Neue, Sans-serif'),
'sff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'sff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'sff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'sff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'sff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'sff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'sff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'sff-02' => t('Source Sans Pro, Helvetica Neue, Arial, Sans-serif'),
'sff-30' => t('Times, Times New Roman, Serif'),
'sff-41' => t('Ubuntu Condensed, Arial, Helvetica Neue, Sans-serif'),
'sff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'sff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'sff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'sff-37' => t('Work Sans, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['font_tab']['font']['slogan_font_family'] = array(
'#type' => 'select',
'#title' => t('Slogan'),
'#default_value' => theme_get_setting('slogan_font_family', 'ocms_corporate'),
'#options' => array(
'slff-31' => t('Alegreya SC, Georgia, Times, Times New Roman, Serif'),
'slff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'slff-40' => t('Archivo Narrow, Arial, Helvetica Neue, Sans-serif'),
'slff-42' => t('Arimo, Arial, Helvetica Neue, Sans-serif'),
'slff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'slff-16' => t('Cinzel, Georgia, Times, Serif'),
'slff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'slff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'slff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'slff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'slff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'slff-13' => t('Georgia, Times, Serif'),
'slff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'slff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'slff-36' => t('Julius Sans One, Arial, Helvetica Neue, Sans-serif'),
'slff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'slff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'slff-01' => t('Merriweather, Georgia, Times, Serif'),
'slff-32' => t('Montserrat SC, Arial, Helvetica Neue, Sans-serif'),
'slff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif'),
'slff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'slff-38' => t('Open Sans Condensed, Arial, Helvetica Neue, Sans-serif'),
'slff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'slff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'slff-15' => t('Philosopher, Georgia, Times, Serif'),
'slff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'slff-14' => t('Playfair Display, Times, Serif'),
'slff-39' => t('PT Sans Narrow, Arial, Helvetica Neue, Sans-serif'),
'slff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'slff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'slff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'slff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'slff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'slff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'slff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'slff-02' => t('Source Sans Pro, Helvetica Neue, Arial, Sans-serif'),
'slff-30' => t('Times, Times New Roman, Serif'),
'slff-41' => t('Ubuntu Condensed, Arial, Helvetica Neue, Sans-serif'),
'slff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'slff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'slff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'slff-37' => t('Work Sans, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['font_tab']['font']['headings_font_family'] = array(
'#type' => 'select',
'#title' => t('Headings'),
'#default_value' => theme_get_setting('headings_font_family', 'ocms_corporate'),
'#options' => array(
'hff-31' => t('Alegreya SC, Georgia, Times, Times New Roman, Serif'),
'hff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'hff-40' => t('Archivo Narrow, Arial, Helvetica Neue, Sans-serif'),
'hff-42' => t('Arimo, Arial, Helvetica Neue, Sans-serif'),
'hff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'hff-16' => t('Cinzel, Georgia, Times, Serif'),
'hff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'hff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'hff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'hff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'hff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'hff-13' => t('Georgia, Times, Serif'),
'hff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'hff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'hff-36' => t('Julius Sans One, Arial, Helvetica Neue, Sans-serif'),
'hff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'hff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'hff-01' => t('Merriweather, Georgia, Times, Serif'),
'hff-32' => t('Montserrat SC, Arial, Helvetica Neue, Sans-serif'),
'hff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif'),
'hff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'hff-38' => t('Open Sans Condensed, Arial, Helvetica Neue, Sans-serif'),
'hff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'hff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'hff-15' => t('Philosopher, Georgia, Times, Serif'),
'hff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'hff-14' => t('Playfair Display, Times, Serif'),
'hff-39' => t('PT Sans Narrow, Arial, Helvetica Neue, Sans-serif'),
'hff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'hff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'hff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'hff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'hff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'hff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'hff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'hff-02' => t('Source Sans Pro, Helvetica Neue, Arial, Sans-serif'),
'hff-30' => t('Times, Times New Roman, Serif'),
'hff-41' => t('Ubuntu Condensed, Arial, Helvetica Neue, Sans-serif'),
'hff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'hff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'hff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'hff-37' => t('Work Sans, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['font_tab']['font']['paragraph_font_family'] = array(
'#type' => 'select',
'#title' => t('Paragraph'),
'#default_value' => theme_get_setting('paragraph_font_family', 'ocms_corporate'),
'#options' => array(
'pff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'pff-40' => t('Archivo Narrow, Arial, Helvetica Neue, Sans-serif'),
'pff-42' => t('Arimo, Arial, Helvetica Neue, Sans-serif'),
'pff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'pff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'pff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'pff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'pff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'pff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'pff-13' => t('Georgia, Times, Serif'),
'pff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'pff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'pff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'pff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'pff-01' => t('Merriweather, Georgia, Times, Serif'),
'pff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif'),
'pff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'pff-38' => t('Open Sans Condensed, Arial, Helvetica Neue, Sans-serif'),
'pff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'pff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'pff-15' => t('Philosopher, Georgia, Times, Serif'),
'pff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'pff-14' => t('Playfair Display, Times, Serif'),
'pff-39' => t('PT Sans Narrow, Arial, Helvetica Neue, Sans-serif'),
'pff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'pff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'pff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'pff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'pff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'pff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'pff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'pff-02' => t('Source Sans Pro, Helvetica Neue, Arial, Sans-serif'),
'pff-30' => t('Times, Times New Roman, Serif'),
'pff-41' => t('Ubuntu Condensed, Arial, Helvetica Neue, Sans-serif'),
'pff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'pff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'pff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'pff-37' => t('Work Sans, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow'] = array(
'#type' => 'details',
'#title' => t('Slideshow Settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullscreen'] = array(
'#type' => 'fieldset',
'#title' => t('Full Screen (Slider Revolution)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullscreen']['rs_slideshow_fullscreen_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_fullscreen_effect', 'ocms_corporate'),
'#options' => array(
'fade' => t('Fade'),
'slideup' => t('Slide To Top'),
'slidedown' => t('Slide To Bottom'),
'slideright' => t('Slide To Right'),
'slideleft' => t('Slide To Left'),
'slidehorizontal' => t('Slide Horizontal'),
'slidevertical' => t('Slide Vertical'),
'boxslide' => t('Slide Boxes'),
'slotslide-horizontal' => t('Slide Slots Horizontal'),
'slotslide-vertical' => t('Slide Slots Vertical'),
'boxfade' => t('Fade Boxes'),
'slotfade-horizontal' => t('Fade Slots Horizontal'),
'slotfade-vertical' => t('Fade Slots Vertical'),
'fadefromright' => t('Fade and Slide from Right'),
'fadefromleft' => t('Fade and Slide from Left'),
'fadefromtop' => t('Fade and Slide from Top'),
'fadefrombottom' => t('Fade and Slide from Bottom'),
'fadetoleftfadefromright' => t('Fade To Left and Fade From Right'),
'fadetorightfadefromleft' => t('Fade To Right and Fade From Left'),
'fadetotopfadefrombottom' => t('Fade To Top and Fade From Bottom'),
'fadetobottomfadefromtop' => t('Fade To Bottom and Fade From Top'),
'parallaxtoright' => t('Parallax to Right'),
'parallaxtoleft' => t('Parallax to Left'),
'parallaxtotop' => t('Parallax to Top'),
'parallaxtobottom' => t('Parallax to Bottom'),
'scaledownfromright' => t('Zoom Out and Fade From Right'),
'scaledownfromleft' => t('Zoom Out and Fade From Left'),
'scaledownfromtop' => t('Zoom Out and Fade From Top'),
'scaledownfrombottom' => t('Zoom Out and Fade From Bottom'),
'zoomout' => t('ZoomOut'),
'zoomin' => t('ZoomIn'),
'slotzoom-horizontal' => t('Zoom Slots Horizontal'),
'slotzoom-vertical' => t('Zoom Slots Vertical'),
'curtain-1' => t('Curtain from Left'),
'curtain-2' => t('Curtain from Right'),
'curtain-3' => t('Curtain from Middle'),
'3dcurtain-horizontal' => t('3D Curtain Horizontal'),
'3dcurtain-vertical' => t('3D Curtain Vertical'),
'cube' => t('Cube Vertical'),
'cube-horizontal' => t('Cube Horizontal'),
'incube' => t('In Cube Vertical'),
'incube-horizontal' => t('In Cube Horizontal'),
'turnoff' => t('TurnOff Horizontal'),
'turnoff-vertical' => t('TurnOff Vertical'),
'papercut' => t('Paper Cut'),
'flyin' => t('Fly In'),
'random-static' => t('Random Flat'),
'random-premium' => t('Random Premium'),
'random' => t('Random Flat and Premium/Default'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullscreen']['rs_slideshow_fullscreen_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('rs_slideshow_fullscreen_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullscreen']['rs_slideshow_fullscreen_bullets_position'] = array(
'#type' => 'select',
'#title' => t('Navigation bullets position'),
'#description' => t('From the drop-down menu, select the position you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_fullscreen_bullets_position', 'ocms_corporate'),
'#options' => array(
'left' => t('Left'),
'right' => t('Right'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullscreen']['transparent_header_state'] = array(
'#type' => 'checkbox',
'#title' => t('Transparent Header'),
'#description' => t('Use the checkbox to display the header over the slideshow in a transparent style.'),
'#default_value' => theme_get_setting('transparent_header_state', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullscreen']['transparent_header_opacity'] = array(
'#type' => 'textfield',
'#title' => t('Transparent Header Background Opacity'),
'#description' => t('Set the % opacity for the background of the transparent header over the full screen slideshow.'),
'#default_value' => theme_get_setting('transparent_header_opacity', 'ocms_corporate'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullwidth'] = array(
'#type' => 'fieldset',
'#title' => t('Full Width (Slider Revolution)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullwidth']['rs_slideshow_fullwidth_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_fullwidth_effect', 'ocms_corporate'),
'#options' => array(
'fade' => t('Fade'),
'slideup' => t('Slide To Top'),
'slidedown' => t('Slide To Bottom'),
'slideright' => t('Slide To Right'),
'slideleft' => t('Slide To Left'),
'slidehorizontal' => t('Slide Horizontal'),
'slidevertical' => t('Slide Vertical'),
'boxslide' => t('Slide Boxes'),
'slotslide-horizontal' => t('Slide Slots Horizontal'),
'slotslide-vertical' => t('Slide Slots Vertical'),
'boxfade' => t('Fade Boxes'),
'slotfade-horizontal' => t('Fade Slots Horizontal'),
'slotfade-vertical' => t('Fade Slots Vertical'),
'fadefromright' => t('Fade and Slide from Right'),
'fadefromleft' => t('Fade and Slide from Left'),
'fadefromtop' => t('Fade and Slide from Top'),
'fadefrombottom' => t('Fade and Slide from Bottom'),
'fadetoleftfadefromright' => t('Fade To Left and Fade From Right'),
'fadetorightfadefromleft' => t('Fade To Right and Fade From Left'),
'fadetotopfadefrombottom' => t('Fade To Top and Fade From Bottom'),
'fadetobottomfadefromtop' => t('Fade To Bottom and Fade From Top'),
'parallaxtoright' => t('Parallax to Right'),
'parallaxtoleft' => t('Parallax to Left'),
'parallaxtotop' => t('Parallax to Top'),
'parallaxtobottom' => t('Parallax to Bottom'),
'scaledownfromright' => t('Zoom Out and Fade From Right'),
'scaledownfromleft' => t('Zoom Out and Fade From Left'),
'scaledownfromtop' => t('Zoom Out and Fade From Top'),
'scaledownfrombottom' => t('Zoom Out and Fade From Bottom'),
'zoomout' => t('ZoomOut'),
'zoomin' => t('ZoomIn'),
'slotzoom-horizontal' => t('Zoom Slots Horizontal'),
'slotzoom-vertical' => t('Zoom Slots Vertical'),
'curtain-1' => t('Curtain from Left'),
'curtain-2' => t('Curtain from Right'),
'curtain-3' => t('Curtain from Middle'),
'3dcurtain-horizontal' => t('3D Curtain Horizontal'),
'3dcurtain-vertical' => t('3D Curtain Vertical'),
'cube' => t('Cube Vertical'),
'cube-horizontal' => t('Cube Horizontal'),
'incube' => t('In Cube Vertical'),
'incube-horizontal' => t('In Cube Horizontal'),
'turnoff' => t('TurnOff Horizontal'),
'turnoff-vertical' => t('TurnOff Vertical'),
'papercut' => t('Paper Cut'),
'flyin' => t('Fly In'),
'random-static' => t('Random Flat'),
'random-premium' => t('Random Premium'),
'random' => t('Random Flat and Premium/Default'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullwidth']['rs_slideshow_fullwidth_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('rs_slideshow_fullwidth_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullwidth']['rs_slideshow_fullwidth_initial_height'] = array(
'#type' => 'textfield',
'#title' => t('Initial Height (px)'),
'#default_value' => theme_get_setting('rs_slideshow_fullwidth_initial_height', 'ocms_corporate'),
'#description' => t('Set the initial height, in pixels.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_fullwidth']['rs_slideshow_fullwidth_bullets_position'] = array(
'#type' => 'select',
'#title' => t('Navigation bullets position'),
'#description' => t('From the drop-down menu, select the position you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_fullwidth_bullets_position', 'ocms_corporate'),
'#options' => array(
'left' => t('Left'),
'center' => t('Center'),
'right' => t('Right'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth'] = array(
'#type' => 'fieldset',
'#title' => t('Boxed Width (Slider Revolution)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_effect', 'ocms_corporate'),
'#options' => array(
'fade' => t('Fade'),
'slideup' => t('Slide To Top'),
'slidedown' => t('Slide To Bottom'),
'slideright' => t('Slide To Right'),
'slideleft' => t('Slide To Left'),
'slidehorizontal' => t('Slide Horizontal'),
'slidevertical' => t('Slide Vertical'),
'boxslide' => t('Slide Boxes'),
'slotslide-horizontal' => t('Slide Slots Horizontal'),
'slotslide-vertical' => t('Slide Slots Vertical'),
'boxfade' => t('Fade Boxes'),
'slotfade-horizontal' => t('Fade Slots Horizontal'),
'slotfade-vertical' => t('Fade Slots Vertical'),
'fadefromright' => t('Fade and Slide from Right'),
'fadefromleft' => t('Fade and Slide from Left'),
'fadefromtop' => t('Fade and Slide from Top'),
'fadefrombottom' => t('Fade and Slide from Bottom'),
'fadetoleftfadefromright' => t('Fade To Left and Fade From Right'),
'fadetorightfadefromleft' => t('Fade To Right and Fade From Left'),
'fadetotopfadefrombottom' => t('Fade To Top and Fade From Bottom'),
'fadetobottomfadefromtop' => t('Fade To Bottom and Fade From Top'),
'parallaxtoright' => t('Parallax to Right'),
'parallaxtoleft' => t('Parallax to Left'),
'parallaxtotop' => t('Parallax to Top'),
'parallaxtobottom' => t('Parallax to Bottom'),
'scaledownfromright' => t('Zoom Out and Fade From Right'),
'scaledownfromleft' => t('Zoom Out and Fade From Left'),
'scaledownfromtop' => t('Zoom Out and Fade From Top'),
'scaledownfrombottom' => t('Zoom Out and Fade From Bottom'),
'zoomout' => t('ZoomOut'),
'zoomin' => t('ZoomIn'),
'slotzoom-horizontal' => t('Zoom Slots Horizontal'),
'slotzoom-vertical' => t('Zoom Slots Vertical'),
'curtain-1' => t('Curtain from Left'),
'curtain-2' => t('Curtain from Right'),
'curtain-3' => t('Curtain from Middle'),
'3dcurtain-horizontal' => t('3D Curtain Horizontal'),
'3dcurtain-vertical' => t('3D Curtain Vertical'),
'cube' => t('Cube Vertical'),
'cube-horizontal' => t('Cube Horizontal'),
'incube' => t('In Cube Vertical'),
'incube-horizontal' => t('In Cube Horizontal'),
'turnoff' => t('TurnOff Horizontal'),
'turnoff-vertical' => t('TurnOff Vertical'),
'papercut' => t('Paper Cut'),
'flyin' => t('Fly In'),
'random-static' => t('Random Flat'),
'random-premium' => t('Random Premium'),
'random' => t('Random Flat and Premium/Default'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_initial_height'] = array(
'#type' => 'textfield',
'#title' => t('Initial Height (px)'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_initial_height', 'ocms_corporate'),
'#description' => t('Set the initial height, in pixels.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_bullets_position'] = array(
'#type' => 'select',
'#title' => t('Navigation bullets position'),
'#description' => t('From the drop-down menu, select the position you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_bullets_position', 'ocms_corporate'),
'#options' => array(
'left' => t('Left'),
'center' => t('Center'),
'right' => t('Right'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal'] = array(
'#type' => 'fieldset',
'#title' => t('Internal Banner (Slider Revolution)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_internal_effect', 'ocms_corporate'),
'#options' => array(
'fade' => t('Fade'),
'slideup' => t('Slide To Top'),
'slidedown' => t('Slide To Bottom'),
'slideright' => t('Slide To Right'),
'slideleft' => t('Slide To Left'),
'slidehorizontal' => t('Slide Horizontal'),
'slidevertical' => t('Slide Vertical'),
'boxslide' => t('Slide Boxes'),
'slotslide-horizontal' => t('Slide Slots Horizontal'),
'slotslide-vertical' => t('Slide Slots Vertical'),
'boxfade' => t('Fade Boxes'),
'slotfade-horizontal' => t('Fade Slots Horizontal'),
'slotfade-vertical' => t('Fade Slots Vertical'),
'fadefromright' => t('Fade and Slide from Right'),
'fadefromleft' => t('Fade and Slide from Left'),
'fadefromtop' => t('Fade and Slide from Top'),
'fadefrombottom' => t('Fade and Slide from Bottom'),
'fadetoleftfadefromright' => t('Fade To Left and Fade From Right'),
'fadetorightfadefromleft' => t('Fade To Right and Fade From Left'),
'fadetotopfadefrombottom' => t('Fade To Top and Fade From Bottom'),
'fadetobottomfadefromtop' => t('Fade To Bottom and Fade From Top'),
'parallaxtoright' => t('Parallax to Right'),
'parallaxtoleft' => t('Parallax to Left'),
'parallaxtotop' => t('Parallax to Top'),
'parallaxtobottom' => t('Parallax to Bottom'),
'scaledownfromright' => t('Zoom Out and Fade From Right'),
'scaledownfromleft' => t('Zoom Out and Fade From Left'),
'scaledownfromtop' => t('Zoom Out and Fade From Top'),
'scaledownfrombottom' => t('Zoom Out and Fade From Bottom'),
'zoomout' => t('ZoomOut'),
'zoomin' => t('ZoomIn'),
'slotzoom-horizontal' => t('Zoom Slots Horizontal'),
'slotzoom-vertical' => t('Zoom Slots Vertical'),
'curtain-1' => t('Curtain from Left'),
'curtain-2' => t('Curtain from Right'),
'curtain-3' => t('Curtain from Middle'),
'3dcurtain-horizontal' => t('3D Curtain Horizontal'),
'3dcurtain-vertical' => t('3D Curtain Vertical'),
'cube' => t('Cube Vertical'),
'cube-horizontal' => t('Cube Horizontal'),
'incube' => t('In Cube Vertical'),
'incube-horizontal' => t('In Cube Horizontal'),
'turnoff' => t('TurnOff Horizontal'),
'turnoff-vertical' => t('TurnOff Vertical'),
'papercut' => t('Paper Cut'),
'flyin' => t('Fly In'),
'random-static' => t('Random Flat'),
'random-premium' => t('Random Premium'),
'random' => t('Random Flat and Premium/Default'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('rs_slideshow_internal_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_initial_height'] = array(
'#type' => 'textfield',
'#title' => t('Initial Height (px)'),
'#default_value' => theme_get_setting('rs_slideshow_internal_initial_height', 'ocms_corporate'),
'#description' => t('Set the initial height, in pixels.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_bullets_position'] = array(
'#type' => 'select',
'#title' => t('Navigation bullets position'),
'#description' => t('From the drop-down menu, select the position you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_internal_bullets_position', 'ocms_corporate'),
'#options' => array(
'left' => t('Left'),
'center' => t('Center'),
'right' => t('Right'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['rs_global'] = array(
'#type' => 'fieldset',
'#title' => t('Slider Revolution global settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['rs_global']['rs_slideshow_caption_opacity'] = array(
'#type' => 'textfield',
'#title' => t('Caption Background Opacity'),
'#description' => t('Set the % opacity for the background of the captions in all sliders implemented with Slider Revolution.'),
'#default_value' => theme_get_setting('rs_slideshow_caption_opacity', 'ocms_corporate'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['testimonial_slideshow'] = array(
'#type' => 'fieldset',
'#title' => t('Testimonials Slider (Flexslider)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['testimonial_slideshow']['testimonial_slideshow_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('testimonial_slideshow_effect', 'ocms_corporate'),
'#options' => array(
'fade' => t('fade'),
'slide' => t('slide'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['testimonial_slideshow']['testimonial_slideshow_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('testimonial_slideshow_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['in_page_slider'] = array(
'#type' => 'fieldset',
'#title' => t('In Page Images Slider (Flexslider)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['in_page_slider']['in_page_slider_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('in_page_slider_effect', 'ocms_corporate'),
'#options' => array(
'fade' => t('fade'),
'slide' => t('slide'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_posts'] = array(
'#type' => 'fieldset',
'#title' => t('Promoted Posts (Owl Carousel)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_posts']['owl_posts_autoplay'] = array(
'#type' => 'checkbox',
'#title' => t('Autoplay'),
'#default_value' => theme_get_setting('owl_posts_autoplay', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_posts']['owl_posts_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('owl_posts_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_team'] = array(
'#type' => 'fieldset',
'#title' => t('Team Members (Owl Carousel)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_team']['owl_team_autoplay'] = array(
'#type' => 'checkbox',
'#title' => t('Autoplay'),
'#default_value' => theme_get_setting('owl_team_autoplay', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_team']['owl_team_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('owl_team_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_testimonials'] = array(
'#type' => 'fieldset',
'#title' => t('Testimonials (Owl Carousel)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_testimonials']['owl_testimonials_autoplay'] = array(
'#type' => 'checkbox',
'#title' => t('Autoplay'),
'#default_value' => theme_get_setting('owl_testimonials_autoplay', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_testimonials']['owl_testimonials_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('owl_testimonials_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_companies'] = array(
'#type' => 'fieldset',
'#title' => t('Companies (Owl Carousel)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_companies']['owl_companies_autoplay'] = array(
'#type' => 'checkbox',
'#title' => t('Autoplay'),
'#default_value' => theme_get_setting('owl_companies_autoplay', 'ocms_corporate'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['carousel']['owl_companies']['owl_companies_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('owl_companies_effect_time', 'ocms_corporate'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['parallax_tab']['parallax_and_video_bg'] = array(
'#type' => 'details',
'#title' => t('Parallax/Video Background region'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['parallax_tab']['parallax_and_video_bg']['highlighted_bottom'] = array(
'#type' => 'fieldset',
'#title' => t('Highlighted Bottom Region'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['mtt_settings']['parallax_tab']['parallax_and_video_bg']['highlighted_bottom']['parallax_and_video_bg_state'] = array(
'#type' => 'select',
'#title' => t('Select Background effect'),
'#default_value' => theme_get_setting('parallax_and_video_bg_state', 'ocms_corporate'),
'#options' => array(
'none' => t('None'),
'parallax' => t('Parallax Background Effect'),
'video' => t('Video Background'),
),
);
$form['mtt_settings']['parallax_tab']['parallax_and_video_bg']['highlighted_bottom']['parallax_and_video_bg_opacity'] = array(
'#type' => 'textfield',
'#title' => t('Parallax Background/Video Background Opacity'),
'#description' => t('Set the % opacity for the background of the parallax/video background region.'),
'#default_value' => theme_get_setting('parallax_and_video_bg_opacity', 'ocms_corporate'),
);
$form['mtt_settings']['isotope_tab'] = array(
'#type' => 'details',
'#title' => t('Isotope Filters'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['isotope_tab']['isotope_filters_text'] = array(
'#type' => 'textfield',
'#title' => t('Text of isotope "All" filter'),
'#default_value' => theme_get_setting('isotope_filters_text', 'ocms_corporate'),
'#description' => t('Change the text of "All" filter'),
);
$form['mtt_settings']['google_maps_tab'] = array(
'#type' => 'details',
'#title' => t('Google Maps Settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#group' => 'tabs',
);
$form['mtt_settings']['google_maps_tab']['google_maps_key'] = array(
'#type' => 'textfield',
'#title' => t('Google Maps API Key'),
'#description' => t('Google requires an API key to be included to all calls to Google Maps API. Please create an API key and populate the above field.'),
'#default_value' => theme_get_setting('google_maps_key','ocms_corporate'),
'#size' => 50,
'#maxlength' => 50,
);
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerExtractionInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link extraction services.
*/
interface PupLinkcheckerExtractionInterface {
/**
* Extracts links from content.
*
* @param string $text
* The text to be scanned for links.
* @param string $contentPath
* Path to the content that is currently scanned for links. This value is
* required to build full qualified links from relative links. Relative links
* are not extracted from content, if path is not provided.
*
* @return array
* Array whose keys are fully qualified and unique URLs found in the
* content, and whose values are arrays of actual text (raw URLs or paths)
* corresponding to each fully qualified URL.
*/
public function extractContentLinks($text, $contentPath);
/**
* Extracts links from a node.
*
* @param object $node
* The fully populated node object.
* @param boolean $returnFieldNames
* If set to TRUE, the returned array will contain the link URLs as keys, and
* each element will be an array containing all field names in which the URL
* is found. Otherwise, a simple array of URLs will be returned.
*
* @return array
* An array whose keys are fully qualified and unique URLs found in the node
* (as returned by extractContentLinks()), or a more complex
* structured array (see above) if $returnFieldNames is TRUE.
*/
public function extractNodeLinks($node, $returnFieldNames = FALSE);
/**
* Extracts links from a comment.
*
* @param object $comment
* The fully populated comment object.
* @param boolean $returnFieldNames
* If set to TRUE, the returned array will contain the link URLs as keys, and
* each element will be an array containing all field names in which the URL
* is found. Otherwise, a simple array of URLs will be returned.
*
* @return array
* An array whose keys are fully qualified and unique URLs found in the node
* (as returned by extractContentLinks()), or a more complex
* structured array (see above) if $returnFieldNames is TRUE.
*/
public function extractCommentLinks($comment, $returnFieldNames = FALSE);
/**
* Extracts links from a block.
*
* @param object $block
* The fully populated block object.
* @param boolean $returnFieldNames
* If set to TRUE, the returned array will contain the link URLs as keys, and
* each element will be an array containing all field names in which the URL
* is found. Otherwise, a simple array of URLs will be returned.
*
* @return array
* An array whose keys are fully qualified and unique URLs found in the node
* (as returned by extractContentLinks()), or a more complex
* structured array (see above) if $returnFieldNames is TRUE.
*/
public function extractBlockLinks($block, $returnFieldNames = FALSE);
}
<file_sep>/docroot/modules/custom/ocms_universal_assets/src/Controller/UniversalAssetsController.php
<?php
namespace Drupal\ocms_universal_assets\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Controller routines for page example routes.
*/
class UniversalAssetsController extends ControllerBase {
/**
* Universal assets page content.
*
* @return array
* Markup to display on universal asset page.
*/
public function content() {
return [
'#markup' => '',
];
}
}
<file_sep>/docroot/themes/custom/ocms_corporate/js/init/owl-carousel-companies-init.js
jQuery(document).ready(function($) {
$(".view-companies-carousel .owl-carousel.companies").owlCarousel({
items: 5,
itemsDesktopSmall: [992,3],
itemsTablet: [768,3],
autoPlay: drupalSettings.ocms_corporate.owlCarouselCompaniesInit.owlCompaniesEffectTime,
navigation: true,
pagination: false
});
});
<file_sep>/docroot/themes/custom/ocms_corporate/js/init/video-background-init.js
jQuery(document).ready(function($) {
$("body").addClass("video-bg-active");
$(".video-bg-active #highlighted-bottom").vide({
mp4: drupalSettings.ocms_corporate.VideoBackgroundInit.PathToVideo_mp4,
webm: drupalSettings.ocms_corporate.VideoBackgroundInit.PathToVideo_webm,
poster: drupalSettings.ocms_corporate.VideoBackgroundInit.pathToVideo_jpg
},{
posterType: 'jpg',
className: 'video-container'
});
});<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerDatabaseInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link database services.
*/
interface PupLinkcheckerDatabaseInterface {
/**
* Adds node links to database.
*
* @param object $node
* The fully populated node object.
* @param bool $skipMissingLinksDetection
* To prevent endless batch loops the value needs to be TRUE. With FALSE
* the need for content re-scans is detected by the number of missing links.
*/
public function addNodeLinks($node, $skipMissingLinksDetection = FALSE);
/**
* Adds comment links to database.
*
* @param object $comment
* The fully populated comment object.
* @param bool $skipMissingLinksDetection
* To prevent endless batch loops the value needs to be TRUE. With FALSE
* the need for content re-scans is detected by the number of missing links.
*/
public function addCommentLinks($comment, $skipMissingLinksDetection = FALSE);
/**
* Adds block links to database.
*
* @param array|object $block
* The fully populated block object.
* @param int $bid
* Block id from table {block}.bid.
* @param bool $skipMissingLinksDetection
* To prevent endless batch loops the value needs to be TRUE. With FALSE
* the need for content re-scans is detected by the number of missing links.
*/
public function addBlockLinks($block, $bid, $skipMissingLinksDetection = FALSE);
/**
* Removes all node references to links in the {ocms_linkchecker_entity} table.
*
* @param \Drupal\node\NodeInterface $node
* The node object.
*/
public function deleteNodeLinks(\Drupal\node\NodeInterface $node);
/**
* Sets all references to a node as broken.
*
* @param \Drupal\node\NodeInterface $node
* The node object.
*/
public function setBrokenNodeReferences(\Drupal\node\NodeInterface $node);
/**
* Removes all comment references to links in the {ocms_linkchecker_entity}
* table.
*
* @param object $comment
* The comment object.
*/
public function deleteCommentLinks($comment);
/**
* Removes all block references to links in the {ocms_linkchecker_entity} table.
*
* @param object $block
* The block object.
*/
public function deleteBlockLinks($block);
/**
* Deletes expired node references to links in the {ocms_linkchecker_entity}
* table.
*
* @param \Drupal\node\NodeInterface $node
* The node object.
* @param array $links
*/
public function deleteExpiredNodeReferences(\Drupal\node\NodeInterface $node, $links = array());
/**
* Deletes expired comment references to links in the
* {ocms_linkchecker_entity} table.
*
* @param object $comment
* The comment object.
* @param array $links
*/
public function deleteExpiredCommentReferences($comment, $links = array());
/**
* Deletes expired block references to links in the {ocms_linkchecker_entity}
* table.
*
* @param object $block
* The block object.
* @param array $links
*/
public function deleteBlockReferences($block, $links = array());
/**
* Returns an array of node references missing in the {ocms_linkchecker_entity}
* table.
*
* @param \Drupal\node\NodeInterface $node
* The node object.
* @param array $links
* An array of links.
*
* @return array
* An array of node references missing in the {ocms_linkchecker_entity} table.
*/
public function getMissingNodeReferences(\Drupal\node\NodeInterface $node, $links);
/**
* Returns an array of comment references missing in the
* {ocms_linkchecker_entity} table.
*
* @param object $comment
* The comment object.
* @param array $links
* An array of links.
*
* @return array
* An array of comment references missing in the {ocms_linkchecker_entity}
* table.
*/
public function getMissingCommentReferences($comment, $links);
/**
* Returns an array of block references missing in the {ocms_linkchecker_entity}
* table.
*
* @param object $block
* The block object.
* @param array $links
* An array of links.
*
* @return array
* An array of block references missing in the {ocms_linkchecker_entity}
* table.
*/
public function getMissingBlockReferences($block, $links);
/**
* Unpublishes all nodes having the specified link id.
*
* @param int $lid
* A link ID that have reached a defined failcount.
*/
public function unpublishNodes($lid);
}
<file_sep>/docroot/themes/custom/ocms_education/theme-settings.php
<?php
function ocms_education_form_system_theme_settings_alter(&$form, &$form_state) {
$form['#attached']['library'][] = 'ocms_education/theme-settings';
$form['mtt_settings'] = array(
'#type' => 'fieldset',
'#title' => t('MtT Theme Settings'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['mtt_settings']['tabs'] = array(
'#type' => 'vertical_tabs',
'#default_tab' => 'basic_tab',
);
$form['mtt_settings']['basic_tab']['basic_settings'] = array(
'#type' => 'details',
'#title' => t('Basic Settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#group' => 'tabs',
);
$form['mtt_settings']['basic_tab']['basic_settings']['breadcrumb_separator'] = array(
'#type' => 'textfield',
'#title' => t('Breadcrumb separator'),
'#default_value' => theme_get_setting('breadcrumb_separator','ocms_education'),
'#size' => 5,
'#maxlength' => 10,
);
$form['mtt_settings']['basic_tab']['basic_settings']['header'] = array(
'#type' => 'item',
'#markup' => t('<div class="theme-settings-title">Header positioning</div>'),
);
$form['mtt_settings']['basic_tab']['basic_settings']['fixed_header'] = array(
'#type' => 'checkbox',
'#title' => t('Fixed position'),
'#description' => t('Use the checkbox to apply fixed position to the header.'),
'#default_value' => theme_get_setting('fixed_header', 'ocms_education'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['mtt_settings']['basic_tab']['basic_settings']['scrolltop'] = array(
'#type' => 'fieldset',
'#title' => t('Scroll to top'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['basic_tab']['basic_settings']['scrolltop']['scrolltop_display'] = array(
'#type' => 'checkbox',
'#title' => t('Show scroll-to-top button'),
'#description' => t('Use the checkbox to enable or disable scroll-to-top button.'),
'#default_value' => theme_get_setting('scrolltop_display', 'ocms_education'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['basic_tab']['basic_settings']['scrolltop']['scrolltop_icon'] = array(
'#type' => 'textfield',
'#title' => t('Scroll To Top icon'),
'#description' => t('Enter the class of the icon you want from the Font Awesome library e.g.: fa-angle-up. A list of the available classes is provided here: <a href="http://fortawesome.github.io/Font-Awesome/cheatsheet" target="_blank">http://fortawesome.github.io/Font-Awesome/cheatsheet</a>.'),
'#default_value' => theme_get_setting('scrolltop_icon','ocms_education'),
'#size' => 20,
'#maxlength' => 100,
);
$form['mtt_settings']['layout_tab']['layout'] = array(
'#type' => 'details',
'#title' => t('Layout'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['layout_tab']['layout']['three_columns_grid_layout'] = array(
'#type' => 'select',
'#title' => t('Adjustments to the three-column, Bootstrap layout grid'),
'#description' => t('From the drop-down menu, select the grid of the three-column layout you would like to use. This way, you can set the width of each of your columns, when choosing a three-column layout.
<br><br>Note: All options refer to Bootstrap columns.'),
'#default_value' => theme_get_setting('three_columns_grid_layout', 'ocms_education'),
'#options' => array(
'grid_3_6_3' => t('3-6-3/Default'),
'grid_2_6_4' => t('2-6-4'),
'grid_4_6_2' => t('4-6-2'),
),
);
$form['mtt_settings']['looknfeel_tab']['looknfeel'] = array(
'#type' => 'details',
'#title' => t('Look\'n\'Feel'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['looknfeel_tab']['looknfeel']['color_scheme'] = array(
'#type' => 'select',
'#title' => t('Color Schemes'),
'#description' => t('From the drop-down menu, select the color scheme you prefer.'),
'#default_value' => theme_get_setting('color_scheme', 'ocms_education'),
'#options' => array(
'gray' => t('Gray'),
'gray-green' => t('Gray Green'),
'gray-orange' => t('Gray Orange'),
'gray-red' => t('Gray Red'),
'gray-pink' => t('Gray Pink'),
'gray-purple' => t('Gray Purple'),
'blue' => t('Blue'),
'green' => t('Green'),
'orange' => t('Orange'),
'red' => t('Red'),
'pink' => t('Pink'),
'purple' => t('Purple'),
),
);
$form['mtt_settings']['looknfeel_tab']['looknfeel']['form_style'] = array(
'#type' => 'select',
'#title' => t('Form styles of contact page'),
'#description' => t('From the drop-down menu, select the form style that you prefer.'),
'#default_value' => theme_get_setting('form_style', 'ocms_education'),
'#options' => array(
'form-style-1' => t('Style-1 (default)'),
'form-style-2' => t('Style-2'),
),
);
$form['mtt_settings']['font_tab']['font'] = array(
'#type' => 'details',
'#title' => t('Font Settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['font_tab']['font']['font_title'] = array(
'#type' => 'item',
'#markup' => 'For every region pick the <strong>font-family</strong> that corresponds to your needs.',
);
$form['mtt_settings']['font_tab']['font']['sitename_font_family'] = array(
'#type' => 'select',
'#title' => t('Site name'),
'#default_value' => theme_get_setting('sitename_font_family', 'ocms_education'),
'#options' => array(
'sff-01' => t('Merriweather, Georgia, Times, Serif'),
'sff-02' => t('Source Sans Pro, Helvetica Neuee, Arial, Sans-serif'),
'sff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'sff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'sff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'sff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'sff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'sff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'sff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'sff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'sff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'sff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'sff-13' => t('Georgia, Times, Serif'),
'sff-14' => t('Playfair Display, Times, Serif'),
'sff-15' => t('Philosopher, Georgia, Times, Serif'),
'sff-16' => t('Cinzel, Georgia, Times, Serif'),
'sff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'sff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'sff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'sff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif;'),
'sff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'sff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'sff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'sff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'sff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'sff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'sff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'sff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'sff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'sff-30' => t('Times, Times New Roman, Serif'),
'sff-31' => t('Alegreya SC, Georgia, Times, Times New Roman, Serif'),
'sff-32' => t('Montserrat SC, Arial, Helvetica Neue, Sans-serif'),
'sff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'sff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'sff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'sff-36' => t('Julius Sans One, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['font_tab']['font']['slogan_font_family'] = array(
'#type' => 'select',
'#title' => t('Slogan'),
'#default_value' => theme_get_setting('slogan_font_family', 'ocms_education'),
'#options' => array(
'slff-01' => t('Merriweather, Georgia, Times, Serif'),
'slff-02' => t('Source Sans Pro, Helvetica Neuee, Arial, Sans-serif'),
'slff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'slff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'slff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'slff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'slff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'slff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'slff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'slff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'slff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'slff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'slff-13' => t('Georgia, Times, Serif'),
'slff-14' => t('Playfair Display, Times, Serif'),
'slff-15' => t('Philosopher, Georgia, Times, Serif'),
'slff-16' => t('Cinzel, Georgia, Times, Serif'),
'slff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'slff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'slff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'slff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif;'),
'slff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'slff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'slff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'slff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'slff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'slff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'slff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'slff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'slff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'slff-30' => t('Times, Times New Roman, Serif'),
'slff-31' => t('Alegreya SC, Georgia, Times, Times New Roman, Serif'),
'slff-32' => t('Montserrat SC, Arial, Helvetica Neue, Sans-serif'),
'slff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'slff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'slff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'slff-36' => t('Julius Sans One, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['font_tab']['font']['headings_font_family'] = array(
'#type' => 'select',
'#title' => t('Headings'),
'#default_value' => theme_get_setting('headings_font_family', 'ocms_education'),
'#options' => array(
'hff-01' => t('Merriweather, Georgia, Times, Serif'),
'hff-02' => t('Source Sans Pro, Helvetica Neuee, Arial, Sans-serif'),
'hff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'hff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'hff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'hff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'hff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'hff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'hff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'hff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'hff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'hff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'hff-13' => t('Georgia, Times, Serif'),
'hff-14' => t('Playfair Display, Times, Serif'),
'hff-15' => t('Philosopher, Georgia, Times, Serif'),
'hff-16' => t('Cinzel, Georgia, Times, Serif'),
'hff-17' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'hff-18' => t('Playfair Display SC, Georgia, Times, Serif'),
'hff-19' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'hff-20' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif;'),
'hff-21' => t('Helvetica Neue, Arial, Sans-serif'),
'hff-22' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'hff-23' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'hff-24' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'hff-25' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'hff-26' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'hff-27' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'hff-28' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'hff-29' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'hff-30' => t('Times, Times New Roman, Serif'),
'hff-31' => t('Alegreya SC, Georgia, Times, Times New Roman, Serif'),
'hff-32' => t('Montserrat SC, Arial, Helvetica Neue, Sans-serif'),
'hff-33' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'hff-34' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'hff-35' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
'hff-36' => t('Julius Sans One, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['font_tab']['font']['paragraph_font_family'] = array(
'#type' => 'select',
'#title' => t('Paragraph'),
'#default_value' => theme_get_setting('paragraph_font_family', 'ocms_education'),
'#options' => array(
'pff-01' => t('Merriweather, Georgia, Times, Serif'),
'pff-02' => t('Source Sans Pro, Helvetica Neuee, Arial, Sans-serif'),
'pff-03' => t('Ubuntu, Helvetica Neue, Arial, Sans-serif'),
'pff-04' => t('PT Sans, Helvetica Neue, Arial, Sans-serif'),
'pff-05' => t('Roboto, Helvetica Neue, Arial, Sans-serif'),
'pff-06' => t('Open Sans, Helvetica Neue, Arial, Sans-serif'),
'pff-07' => t('Lato, Helvetica Neue, Arial, Sans-serif'),
'pff-08' => t('Roboto Condensed, Arial Narrow, Arial, Sans-serif'),
'pff-09' => t('Exo, Arial, Helvetica Neue, Sans-serif'),
'pff-10' => t('Roboto Slab, Trebuchet MS, Sans-serif'),
'pff-11' => t('Raleway, Helvetica Neue, Arial, Sans-serif'),
'pff-12' => t('Josefin Sans, Georgia, Times, Serif'),
'pff-13' => t('Georgia, Times, Serif'),
'pff-14' => t('Playfair Display, Times, Serif'),
'pff-15' => t('Philosopher, Georgia, Times, Serif'),
'pff-16' => t('Oswald, Helvetica Neue, Arial, Sans-serif'),
'pff-17' => t('Playfair Display SC, Georgia, Times, Serif'),
'pff-18' => t('Cabin, Helvetica Neue, Arial, Sans-serif'),
'pff-19' => t('Noto Sans, Arial, Helvetica Neue, Sans-serif;'),
'pff-20' => t('Helvetica Neue, Arial, Sans-serif'),
'pff-21' => t('Droid Serif, Georgia, Times, Times New Roman, Serif'),
'pff-22' => t('PT Serif, Georgia, Times, Times New Roman, Serif'),
'pff-23' => t('Vollkorn, Georgia, Times, Times New Roman, Serif'),
'pff-24' => t('Alegreya, Georgia, Times, Times New Roman, Serif'),
'pff-25' => t('Noto Serif, Georgia, Times, Times New Roman, Serif'),
'pff-26' => t('Crimson Text, Georgia, Times, Times New Roman, Serif'),
'pff-27' => t('Gentium Book Basic, Georgia, Times, Times New Roman, Serif'),
'pff-28' => t('Volkhov, Georgia, Times, Times New Roman, Serif'),
'pff-29' => t('Times, Times New Roman, Serif'),
'pff-30' => t('Fira Sans, Arial, Helvetica Neue, Sans-serif'),
'pff-31' => t('Lora, Georgia, Times, Times New Roman, Serif'),
'pff-32' => t('Quattrocento Sans, Arial, Helvetica Neue, Sans-serif'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow'] = array(
'#type' => 'details',
'#title' => t('Sliders'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'tabs',
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth'] = array(
'#type' => 'fieldset',
'#title' => t('Boxed Width (Slider Revolution)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_effect', 'ocms_education'),
'#options' => array(
'fade' => t('Fade'),
'slideup' => t('Slide To Top'),
'slidedown' => t('Slide To Bottom'),
'slideright' => t('Slide To Right'),
'slideleft' => t('Slide To Left'),
'slidehorizontal' => t('Slide Horizontal'),
'slidevertical' => t('Slide Vertical'),
'boxslide' => t('Slide Boxes'),
'slotslide-horizontal' => t('Slide Slots Horizontal'),
'slotslide-vertical' => t('Slide Slots Vertical'),
'boxfade' => t('Fade Boxes'),
'slotfade-horizontal' => t('Fade Slots Horizontal'),
'slotfade-vertical' => t('Fade Slots Vertical'),
'fadefromright' => t('Fade and Slide from Right'),
'fadefromleft' => t('Fade and Slide from Left'),
'fadefromtop' => t('Fade and Slide from Top'),
'fadefrombottom' => t('Fade and Slide from Bottom'),
'fadetoleftfadefromright' => t('Fade To Left and Fade From Right'),
'fadetorightfadefromleft' => t('Fade To Right and Fade From Left'),
'fadetotopfadefrombottom' => t('Fade To Top and Fade From Bottom'),
'fadetobottomfadefromtop' => t('Fade To Bottom and Fade From Top'),
'parallaxtoright' => t('Parallax to Right'),
'parallaxtoleft' => t('Parallax to Left'),
'parallaxtotop' => t('Parallax to Top'),
'parallaxtobottom' => t('Parallax to Bottom'),
'scaledownfromright' => t('Zoom Out and Fade From Right'),
'scaledownfromleft' => t('Zoom Out and Fade From Left'),
'scaledownfromtop' => t('Zoom Out and Fade From Top'),
'scaledownfrombottom' => t('Zoom Out and Fade From Bottom'),
'zoomout' => t('ZoomOut'),
'zoomin' => t('ZoomIn'),
'slotzoom-horizontal' => t('Zoom Slots Horizontal'),
'slotzoom-vertical' => t('Zoom Slots Vertical'),
'curtain-1' => t('Curtain from Left'),
'curtain-2' => t('Curtain from Right'),
'curtain-3' => t('Curtain from Middle'),
'3dcurtain-horizontal' => t('3D Curtain Horizontal'),
'3dcurtain-vertical' => t('3D Curtain Vertical'),
'cube' => t('Cube Vertical'),
'cube-horizontal' => t('Cube Horizontal'),
'incube' => t('In Cube Vertical'),
'incube-horizontal' => t('In Cube Horizontal'),
'turnoff' => t('TurnOff Horizontal'),
'turnoff-vertical' => t('TurnOff Vertical'),
'papercut' => t('Paper Cut'),
'flyin' => t('Fly In'),
'random-static' => t('Random Flat'),
'random-premium' => t('Random Premium'),
'random' => t('Random Flat and Premium/Default'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_effect_time', 'ocms_education'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_boxedwidth']['rs_slideshow_boxedwidth_initial_height'] = array(
'#type' => 'textfield',
'#title' => t('Initial Height (px)'),
'#default_value' => theme_get_setting('rs_slideshow_boxedwidth_initial_height', 'ocms_education'),
'#description' => t('Set the initial height, in pixels.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal'] = array(
'#type' => 'fieldset',
'#title' => t('Internal Banner (Slider Revolution)'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_effect'] = array(
'#type' => 'select',
'#title' => t('Effects'),
'#description' => t('From the drop-down menu, select the slideshow effect you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_internal_effect', 'ocms_education'),
'#options' => array(
'fade' => t('Fade'),
'slideup' => t('Slide To Top'),
'slidedown' => t('Slide To Bottom'),
'slideright' => t('Slide To Right'),
'slideleft' => t('Slide To Left'),
'slidehorizontal' => t('Slide Horizontal'),
'slidevertical' => t('Slide Vertical'),
'boxslide' => t('Slide Boxes'),
'slotslide-horizontal' => t('Slide Slots Horizontal'),
'slotslide-vertical' => t('Slide Slots Vertical'),
'boxfade' => t('Fade Boxes'),
'slotfade-horizontal' => t('Fade Slots Horizontal'),
'slotfade-vertical' => t('Fade Slots Vertical'),
'fadefromright' => t('Fade and Slide from Right'),
'fadefromleft' => t('Fade and Slide from Left'),
'fadefromtop' => t('Fade and Slide from Top'),
'fadefrombottom' => t('Fade and Slide from Bottom'),
'fadetoleftfadefromright' => t('Fade To Left and Fade From Right'),
'fadetorightfadefromleft' => t('Fade To Right and Fade From Left'),
'fadetotopfadefrombottom' => t('Fade To Top and Fade From Bottom'),
'fadetobottomfadefromtop' => t('Fade To Bottom and Fade From Top'),
'parallaxtoright' => t('Parallax to Right'),
'parallaxtoleft' => t('Parallax to Left'),
'parallaxtotop' => t('Parallax to Top'),
'parallaxtobottom' => t('Parallax to Bottom'),
'scaledownfromright' => t('Zoom Out and Fade From Right'),
'scaledownfromleft' => t('Zoom Out and Fade From Left'),
'scaledownfromtop' => t('Zoom Out and Fade From Top'),
'scaledownfrombottom' => t('Zoom Out and Fade From Bottom'),
'zoomout' => t('ZoomOut'),
'zoomin' => t('ZoomIn'),
'slotzoom-horizontal' => t('Zoom Slots Horizontal'),
'slotzoom-vertical' => t('Zoom Slots Vertical'),
'curtain-1' => t('Curtain from Left'),
'curtain-2' => t('Curtain from Right'),
'curtain-3' => t('Curtain from Middle'),
'3dcurtain-horizontal' => t('3D Curtain Horizontal'),
'3dcurtain-vertical' => t('3D Curtain Vertical'),
'cube' => t('Cube Vertical'),
'cube-horizontal' => t('Cube Horizontal'),
'incube' => t('In Cube Vertical'),
'incube-horizontal' => t('In Cube Horizontal'),
'turnoff' => t('TurnOff Horizontal'),
'turnoff-vertical' => t('TurnOff Vertical'),
'papercut' => t('Paper Cut'),
'flyin' => t('Fly In'),
'random-static' => t('Random Flat'),
'random-premium' => t('Random Premium'),
'random' => t('Random Flat and Premium/Default'),
),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_effect_time'] = array(
'#type' => 'textfield',
'#title' => t('Effect duration (sec)'),
'#default_value' => theme_get_setting('rs_slideshow_internal_effect_time', 'ocms_education'),
'#description' => t('Set the speed of animations, in seconds.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_initial_height'] = array(
'#type' => 'textfield',
'#title' => t('Initial Height (px)'),
'#default_value' => theme_get_setting('rs_slideshow_internal_initial_height', 'ocms_education'),
'#description' => t('Set the initial height, in pixels.'),
);
$form['mtt_settings']['slideshows_tab']['slideshow']['revolution_slider_internal']['rs_slideshow_internal_bullets_position'] = array(
'#type' => 'select',
'#title' => t('Navigation bullets position'),
'#description' => t('From the drop-down menu, select the position you prefer.'),
'#default_value' => theme_get_setting('rs_slideshow_internal_bullets_position', 'ocms_education'),
'#options' => array(
'left' => t('Left'),
'center' => t('Center'),
'right' => t('Right'),
),
);
$form['mtt_settings']['google_maps_tab']['google_maps_settings'] = array(
'#type' => 'details',
'#title' => t('Google Maps Settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#group' => 'tabs',
);
$form['mtt_settings']['google_maps_tab']['google_maps_settings']['google_maps_key'] = array(
'#type' => 'textfield',
'#title' => t('Google Maps API Key'),
'#description' => t('Google requires an API key to be included to all calls to Google Maps API. Please create an API key and populate the above field.'),
'#default_value' => theme_get_setting('google_maps_key','ocms_education'),
'#size' => 50,
'#maxlength' => 50,
);
}
<file_sep>/docroot/modules/custom/ocms_unpublish/src/Plugin/views/field/ScheduledExpirationRange.php
<?php
namespace Drupal\ocms_unpublish\Plugin\views\field;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use DateTime;
/**
* Field handler to for date range until expiration.
*
* @ingroup views_field_handlers
*
* @ViewsField("scheduled_expiration_range")
*/
class ScheduledExpirationRange extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function query() {
// Leave empty to avoid a query on this field.
}
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
$node = $values->_entity;
// Unpublished scheduled_update entity.
$unpublished_tid = $node->schedule_unpublished_date->target_id;
if ($unpublished_tid) {
$schedule_unpublished_entity = \Drupal::entityTypeManager()
->getStorage('scheduled_update')
->load($unpublished_tid);
$unpublished_datetime = DrupalDateTime::createFromTimestamp($schedule_unpublished_entity->update_timestamp->value);
$now = new DateTime();
$diff = $unpublished_datetime->diff($now);
if ($diff->days > 90) {
$diff_range = '> 90';
}
elseif ($diff->days > 60) {
$diff_range = '90';
}
elseif ($diff->days > 30) {
$diff_range = '60';
}
elseif ($diff->days > 15) {
$diff_range = '30';
}
elseif ($diff->days > 5) {
$diff_range = '15';
}
elseif ($diff->days > 1) {
$diff_range = '5';
}
else {
$diff_range = '01';
}
return $this->t('@expire_group', array('@expire_group' => $diff_range));
}
else {
return $this->t('No scheduled unpublish date');
}
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerFilteringInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link filtering services.
*/
interface PupLinkcheckerFilteringInterface {
/**
* Calls the core check_markup function with the "filters to skip" argument.
*
* @see: https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check_markup/8.3.x
*/
public function checkMarkup($text, $formatId = NULL, $langcode = '');
}
<file_sep>/docroot/themes/custom/ocms_corporate/js/init/owl-carousel-testimonials-init.js
jQuery(document).ready(function($) {
$(".view-testimonials-carousel .owl-carousel.testimonials").owlCarousel({
items: 4,
itemsDesktopSmall: [992,2],
itemsTablet: [768,2],
autoPlay: drupalSettings.ocms_corporate.owlCarouselTestimonialsInit.owlTestimonialsEffectTime,
navigation: true,
pagination: false
});
});
<file_sep>/docroot/themes/custom/ocms_showcase/js/init/video-background-init.js
jQuery(document).ready(function($) {
$("body").addClass("video-bg-active");
$(".video-bg-active .media-background").vide({
mp4: drupalSettings.ocms_showcase.VideoBackgroundInit.PathToVideo_mp4,
webm: drupalSettings.ocms_showcase.VideoBackgroundInit.PathToVideo_webm,
poster: drupalSettings.ocms_showcase.VideoBackgroundInit.pathToVideo_jpg
},{
posterType: 'jpg',
className: 'video-container'
});
});<file_sep>/docroot/themes/custom/ocms_base/js/header-mobile.js
+function ($) {
'use strict';
// Set variables
var dropdownBody = $('#block-infomenumobile').find('.dropdown-menu'),
dropdownBtn = $('#block-infomenumobile').find('.dropdown-toggle'),
mobileMenuBtns = $('.ocms-header-mobile-menu').children(),
on = 'none',
clicked,
btnThatWasOn,
faCaretIcon = $('<i class="fa fa-angle-down pull-right" aria-hidden="true"></i>');
$(dropdownBtn).click(function(e){
e.preventDefault();
});
// Change behavior of dropdown in info sub-menu to collapse
$(dropdownBtn).removeAttr('href data-target data-toggle');
$('.caret').replaceWith(faCaretIcon);
$(dropdownBody).attr('class', 'collapse');
$(dropdownBtn).click(function(){
$(dropdownBody).collapse('toggle');
});
$('#ocms-mobile-navbar-infoBtn').mouseup(function(){
$(this).removeClass('mobile-navbar-close').addClass('mobile-info-icon');
});
$('#ocms-mobile-navbar-infoBtn').mousedown(function(){
$(this).removeClass('mobile-info-icon').addClass('mobile-navbar-close');
});
// Click behavior for mobile menu buttons
$(mobileMenuBtns).click(function(){
// var target = $(this).data("target");
var btnThatWasClicked = $(this);
var wasClickedTarget = $(btnThatWasClicked).data('target');
// Version #3: Non-Exclusive Button Toggling
// Turn off the button that was on, if any, including the clicked button
if ($(btnThatWasOn) != undefined) {
$(btnThatWasOn).removeClass('ocms-toggle-onBtn-color');
switch ($(btnThatWasOn).attr('id')) {
case 'ocms-mobile-navbar-searchBtn':
$(btnThatWasOn).css({"background-color": "#EAF2FA", "color": "black", "border": "none"});
break;
case 'ocms-mobile-navbar-menuBtn':
$(btnThatWasOn).addClass('mobile-menu-icon').removeClass('mobile-navbar-close');
break;
default:
}
$($(btnThatWasOn).data('target')).collapse('hide');
}
// Turn on the clicked button unless it was already on
if (wasClickedTarget != $(btnThatWasOn).data('target')) {
switch ($(btnThatWasClicked).attr('id')) {
case 'ocms-mobile-navbar-searchBtn':
$(btnThatWasClicked).css({"background-color": "#2DA5E5", "color": "white", "border": "1px solid #CCCCCC"});
break;
case 'ocms-mobile-navbar-menuBtn':
$(btnThatWasClicked).removeClass('mobile-menu-icon').addClass('mobile-navbar-close');
break;
default:
}
$(wasClickedTarget).collapse('show');
}
// Change the value of btnThatWasOn, but only after we use it above
if (wasClickedTarget == $(btnThatWasOn).data('target')) {
btnThatWasOn = undefined;
} else {
btnThatWasOn = btnThatWasClicked;
}
});
}(jQuery);
<file_sep>/docroot/themes/custom/ocms_base/js/footer.js
/* ================================================/
/=========== AccordionJavascript ====================/
/======== This is used to apply dynamically =======/
/========== Accordion classes and ids ===========/
/=============================================== */
;(function($){
'use strict';
// Setting the ocms-footer Accordion object
var Accordion = Accordion || {},
foot = $('.ocms-footer').find(':header'), // finding all ocms-footer headers
fnav = $('.ocms-footer').find('ul'); // finding all ocms-footer uls
Accordion = {
// Setup mobile view
addingClsNids: function(elem) {
$(fnav).addClass('collapse');
$(foot).addClass("collapsed");
$(fnav).each(function(item, ele) { // for ul interactions
elem = $(ele).attr('id', 'ocms-foot-collapse-' + (item + 1));
});
$(foot).each(function(item, ele) { // for h2 interactions
elem = $(ele).attr({
"data-toggle" : "collapse",
"data-parent" : "#ocms-footer-accordion",
"href" : "#ocms-foot-collapse-" + (item + 1)
});
});
$(foot).click(function(event) {
if($(event.currentTarget).siblings('ul').hasClass('collapse')) {
$(this).addClass("up").toggleClass("collapsed");
$(this).find('ul').toggleClass('collapse');
} else {
$(this).addClass("collapsed").toggleClass("up");
}
});
return false;
},
// Setup desktop view
removingClsNids: function() {
$(fnav).attr({'id':'', 'ocms-foot-collapse-': ''});
$(fnav).removeClass('collapse');
$(foot).attr({"data-toggle" : "","data-parent" : "","href" : ""}).removeClass('collapsed');
return false;
}
}
$(window).resize( function() {
if (window.innerWidth <= 768) { // mobile views
Accordion.addingClsNids();
} else {
Accordion.removingClsNids();
}
});
})(jQuery);<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerAccessService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Core\Database\Connection;
/**
* Implements the PupLinkcheckerAccessInterface.
*/
class PupLinkcheckerAccessService implements PupLinkcheckerAccessInterface {
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* Constructs the OCMS Linkchecker Access Service object.
*
* @param \Drupal\Core\Database\Connection
* The database connection
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface $ocms_linkchecker_utility
* The OCMS Linkchecker Utility Service.
*/
public function __construct(Connection $database, PupLinkcheckerUtilityInterface $ocms_linkchecker_utility) {
$this->connection = $database;
$this->utilityService = $ocms_linkchecker_utility;
}
/**
* {@inheritdoc}
*/
public function accessBlockIds($link) {
}
/**
* {@inheritdoc}
*/
public function accessCommentIds($link, $commentAuthorAccount = NULL) {
}
/**
* {@inheritdoc}
*/
public function accessLink($link) {
}
/**
* {@inheritdoc}
*/
public function accessNodeIds($link, $nodeAuthorAccount = NULL) {
static $fieldsWithNodeLinks = array();
// Exit if all node types are disabled or if the user cannot access content.
$linkcheckerScanNodeTypes = $this->utilityService->scanNodeTypes();
// if (empty($linkchecker_scan_nodetypes) || !user_access('access content')) {
if (empty($linkcheckerScanNodeTypes)) {
return array();
}
// @todo: Port over the rest of the logic that actually checks for access
// This is just a cherry-picked snippet of the code I'm supposed to
// have.
$query = $this->connection->select('node', 'n');
$query->innerJoin('ocms_linkchecker_entity', 'le', 'le.entity_id = n.nid');
$query->condition('le.lid', $link->lid);
$query->condition('le.entity_type', 'node');
$query->fields('n', array('nid'));
$nodes = $query->execute();
foreach ($nodes as $node) {
$nids[] = $node->nid;
}
return $nids;
}
}
<file_sep>/docroot/themes/custom/ocms_corporate/js/init/flexslider-testimonials-init.js
jQuery(document).ready(function($) {
if ($(".view-testimonials-slider").length>0){
$(window).load(function() {
$(".view-testimonials-slider .flexslider").fadeIn("slow");
$(".view-testimonials-slider .flexslider").flexslider({
animation: drupalSettings.ocms_corporate.flexsliderTestimonialsInit.TestimonialsSliderEffect,
slideshowSpeed: drupalSettings.ocms_corporate.flexsliderTestimonialsInit.TestimonialsSliderEffectTime,
useCSS: false,
prevText: "prev",
nextText: "next",
controlNav: false
});
});
}
});
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/Form/LinkSettingEdit.php
<?php
namespace Drupal\ocms_linkchecker\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LinkSettingEdit extends FormBase {
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Constructs a form object.
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface $ocms_linkchecker_utility
* The OCMS Linkchecker Utility Service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter
*/
public function __construct(PupLinkcheckerUtilityInterface $ocms_linkchecker_utility, ConfigFactoryInterface $config_factory, DateFormatterInterface $date_formatter) {
$this->utilityService = $ocms_linkchecker_utility;
$this->configFactory = $config_factory;
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('ocms_linkchecker.utility'),
$container->get('config.factory'),
$container->get('date.formatter')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ocms_linkchecker_link_setting_edit';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $linkId = NULL) {
$link = $this->utilityService->loadLink($linkId);
$config = $this->configFactory->get('ocms_linkchecker.settings');
$form['settings'] = array(
'#type' => 'fieldset',
'#title' => t('Settings'),
'#collapsible' => FALSE
);
$form['settings']['link'] = array('#type' => 'value', '#value' => $link);
$form['settings']['message'] = array(
'#type' => 'item',
'#markup' => $this->t('The link <a href="@url">@url</a> was last checked on @lastChecked and failed @failCount times.', array('@url' => $link->url, '@failCount' => $link->fail_count, '@lastChecked' => $this->dateFormatter->format($link->last_checked)))
);
$form['settings']['method'] = array(
'#type' => 'select',
'#title' => $this->t('Select request method'),
'#default_value' => $link->method,
'#options' => array(
'HEAD' => $this->t('HEAD'),
'GET' => $this->t('GET'),
),
'#description' => $this->t('Select the request method used for link checks of this link. If you encounter issues like status code 500 errors with the HEAD request method you should try the GET request method before ignoring a link.'),
);
$form['settings']['status'] = array(
'#default_value' => $link->status,
'#type' => 'checkbox',
'#title' => $this->t('Check link status'),
'#description' => $this->t("Uncheck if you wish to ignore this link. Use this setting only as a last resort if there is no other way to solve a failed link check."),
);
$form['maintenance'] = array(
'#type' => 'fieldset',
'#title' => t('Maintenance'),
'#collapsible' => FALSE,
);
$form['maintenance']['recheck'] = array(
'#default_value' => 0,
'#type' => 'checkbox',
'#title' => $this->t('Re-check link status on next cron run'),
'#description' => $this->t('Enable this checkbox if you want to re-check the link during the next cron job rather than wait for the next scheduled check on @date.', array('@date' => $this->dateFormatter->format($link->last_checked + $config->get('check.interval')))),
);
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save Configuration'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$link = $values['link'];
// Force link re-check asap.
if ($values['recheck']) {
$link->last_checked = 0;
drupal_set_message($this->t('The link %url will be checked again on the next cron run.', array('%url' => $link->url)));
}
if ($values['method'] != $link->method) {
// Update settings and reset statistics for a quick re-check.
$link->method = $values['method'];
$link->fail_count = 0;
$link->last_checked = 0;
$link->status = $values['status'];
drupal_set_message(t('The link settings for %url have been saved and the fail counter has been reset.', array('%url' => $link->url)));
}
else {
// Update setting only.
$link->method = $values['method'];
$link->status = $values['status'];
drupal_set_message(t('The link settings for %url have been saved.', array('%url' => $link->url)));
}
$this->utilityService->updateLink($link);
}
}
<file_sep>/docroot/modules/custom/ocms_files/ocms_file_operations/ocms_file_operations.api.php
<?php
/**
* @file
* Hooks provided by the module.
*/
/**
* Implements hook_form_alter().
*/
function hooks_form_alter() {
}
/**
* Submit handler for media published.
*/
function hooks_form_submit_handler() {
}
/*
* Implements hooks_cron() for the remove Temp folders
*/
function hooks_cron() {
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerReplacementInterface.php
<?php
namespace Drupal\ocms_linkchecker;
/**
* Defines an interface for the Link replacement services.
*/
interface PupLinkcheckerReplacementInterface {
/**
* Replaces the old url by a new url on 301 status codes.
*
* @param string $entityType
* The type of entity; e.g., 'node', 'comment'.
* @param string $bundleName
* The name of the bundle aka node type, e.g., 'article', 'page'.
* @param object $entity
* The entity to parse, a $node or a $comment object.
* @param string $oldUrl
* The previous url.
* @param string $newUrl
* The new url to replace the old.
*
* @return object
*/
public function replaceFields($entityType, $bundleName, $entity, $oldUrl, $newUrl);
/**
* Replaces an old link with a new link in text.
*
* @param string $text
* The text a link is inside. Passed in as a reference.
* @param string $oldLink
* The old link to search for in strings.
* @param string $newLink
* The old link should be overwritten with this new link.
*/
public function replaceLink(&$text, $oldLink, $newLink);
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerDatabaseService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Database\Connection;
use Drupal\node\NodeInterface;
/**
* Implements the PupLinkcheckerDatabaseInterface
*/
class PupLinkcheckerDatabaseService implements PupLinkcheckerDatabaseInterface {
/**
* OCMS Linkchecker Extraction Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerExtractionInterface
*/
protected $extractionService;
/**
* OCMS Linkchecker Utility Service.
*
* @var \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface
*/
protected $utilityService;
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Constructs the OCMS Linkchecker Database Service object.
*
* @param \Drupal\ocms_linkchecker\PupLinkcheckerExtractionInterface $ocms_linkchecker_extraction
* The OCMS Linkchecker Extraction Service.
* @param \Drupal\ocms_linkchecker\PupLinkcheckerUtilityInterface $ocms_linkchecker_utility
* The OCMS Linkchecker Utility Service.
* @param \Drupal\Core\Database\Connection
* The database connection
*/
public function __construct(PupLinkcheckerExtractionInterface $ocms_linkchecker_extraction, PupLinkcheckerUtilityInterface $ocms_linkchecker_utility, Connection $database) {
$this->extractionService = $ocms_linkchecker_extraction;
$this->utilityService = $ocms_linkchecker_utility;
$this->connection = $database;
}
/**
* {@inheritdoc}
*/
public function addNodeLinks($node, $skipMissingLinksDetection = FALSE) {
$links = array_keys($this->extractionService->extractNodeLinks($node));
// The node had links
if (!empty($links)) {
// Remove all links from the links array already in the database and only
// add missing links to database.
$missingLinks = $this->getMissingNodeReferences($node, $links);
// Only add links to database that do not exists.
$i = 0;
// @todo: Make this a configurable value
$maxLinksLimit = 100;
foreach ($missingLinks as $url) {
$urlhash = Crypt::hashBase64($url);
$link = $this->connection->query('SELECT lid FROM {ocms_linkchecker_link} WHERE urlhash = :urlhash', array(':urlhash' => $urlhash))->fetchObject();
if (!$link) {
$link = new \stdClass();
$link->lid = $this->connection->insert('ocms_linkchecker_link')
->fields(array(
'urlhash' => $urlhash,
'url' => $url,
'status' => $this->utilityService->shouldCheckLink($url)
))
->execute();
}
$this->connection->insert('ocms_linkchecker_entity')
->fields(array(
'entity_id' => $node->nid->value,
'entity_type' => 'node',
'bundle' => $node->bundle(),
'langcode' => $node->language()->getId(),
'lid' => $link->lid,
))
->execute();
// Break processing if max links limit per run has been reached.
$i++;
if ($i >= $maxLinksLimit) {
break;
}
}
// The first chunk of links not yet found in the {ocms_linkchecker_link}
// table have now been imported by the above code. If the number of
// missing links still exceeds $maxLinksLimit the content need to be
// re-scanned until all links have been collected and saved in
// {ocms_linkchecker_link} table.
//
// Above code has already scanned a number of $maxLinksLimit links and
// need to be substracted from the number of missing links to calculate
// the correct number of re-scan rounds.
//
// To prevent endless loops the $skipMissingLinksDetection need to be
// TRUE. This value will be set by the calling batch process that already
// knows that it is running a batch job and the number of required re-scan
// rounds.
$missingLinksCount = count($missingLinks) - $maxLinksLimit;
if (!$skipMissingLinksDetection && $missingLinksCount > 0) {
// @todo: I'm not worrying about processing in batch right now.
// Just fire of something to load some links.
//module_load_include('inc', 'linkchecker', 'linkchecker.batch');
//batch_set(_linkchecker_batch_import_single_node($node->nid->value, $missing_links_count));
// If batches were set in the submit handlers, we process them now,
// possibly ending execution. We make sure we do not react to the batch
// that is already being processed (if a batch operation performs a
// drupal_execute).
//if ($batch = &batch_get() && !isset($batch['current_set'])) {
//batch_process('node/' . $node->nid->value);
//}
}
}
// Remove dead link references for cleanup reasons as very last step.
$this->deleteExpiredNodeReferences($node, $links);
}
/**
* {@inheritdoc}
*/
public function addCommentLinks($comment, $skipMissingLinksDetection = FALSE) {
}
/**
* {@inheritdoc}
*/
public function addBlockLinks($block, $bid, $skipMissingLinksDetection = FALSE) {
}
/**
* {@inheritdoc}
*/
public function deleteNodeLinks(NodeInterface $node) {
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_id', $node->nid->value)
->condition('entity_type', 'node')
->condition('langcode', $node->language()->getId())
->execute();
}
/**
* {@inheritdoc}
*/
public function setBrokenNodeReferences(NodeInterface $node) {
if ($node->language()) {
$url = $node->toUrl('canonical', ['absolute' => true, 'language' => $node->language()]);
if ($node->language()->isDefault()) {
$permaLink = '/node/' . $node->nid->value;
}
else {
$permaLink = '/' . $node->language()->getId() . '/node/' . $node->nid->value;
}
}
else {
$url = $node->toUrl('canonical', ['absolute' => true]);
$permaLink = '/node/' . $node->nid->value;
}
$aliasedUrl = $url->toString();
$this->connection->update('ocms_linkchecker_link')
->fields(array(
'code' => 404,
'error' => 'Not Found',
'fail_count' => 1,
'last_checked' => REQUEST_TIME
))
->condition('url', $aliasedUrl)
->execute();
// This is just being extra careful to make sure that both the aliased and
// unaliased links are marked as broken. Some pieces of content may be
// referencing this node with its alias and others with is "permalink."
// Unfortunately, we don't have a guaranteed way to know about any
// past aliases that this node had. Those old aliases will just have to
// work their way through the Broken Links report.
$uri = @parse_url($aliasedUrl);
if ($uri['path'] != $permaLink) {
$unaliasedUrl = str_replace($uri['path'], $permaLink, $aliasedUrl);
$this->connection->update('ocms_linkchecker_link')
->fields(array(
'code' => 404,
'error' => 'Not Found',
'fail_count' => 1,
'last_checked' => REQUEST_TIME
))
->condition('url', $unaliasedUrl)
->execute();
}
}
/**
* {@inheritdoc}
*/
public function deleteCommentLinks($comment) {
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_id', $comment->cid->value)
->condition('entity_type', 'comment')
->condition('langcode', $comment->language()->getId())
->execute();
}
/**
* {@inheritdoc}
*/
public function deleteBlockLinks($block) {
}
/**
* {@inheritdoc}
*/
public function deleteExpiredNodeReferences(NodeInterface $node, $links = array()) {
if (empty($links)) {
// Node do not have links. Delete all references if exists.
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_id', $node->nid->value)
->condition('entity_type', 'node')
->condition('langcode', $node->language()->getId())
->execute();
}
else {
// The node still have more than one link, but other links may have been
// removed and links no longer in the content need to be deleted from the
// linkchecker_node reference table.
// @todo: Switch to using the Utility service
$urlsHashed = array();
foreach ($links as $link) {
$urlsHashed[] = Crypt::hashBase64($link);
}
$keepLinks = $this->connection->select('ocms_linkchecker_link')
->fields('ocms_linkchecker_link', array('lid'))
->condition('urlhash', $urlsHashed, 'IN')
->execute()
->fetchAllKeyed(0,0);
$this->connection->delete('ocms_linkchecker_entity')
->condition('entity_id', $node->nid->value)
->condition('entity_type', 'node')
->condition('langcode', $node->language()->getId())
->condition('lid', $keepLinks, 'NOT IN')
->execute();
}
}
/**
* {@inheritdoc}
*/
public function deleteExpiredCommentReferences($comment, $links = array()) {
}
/**
* {@inheritdoc}
*/
public function deleteBlockReferences($block, $links = array()) {
}
/**
* {@inheritdoc}
*/
public function getMissingNodeReferences(NodeInterface $node, $links) {
// @todo: Switch to using the Utility service
$urlsHashed = array();
foreach ($links as $link) {
$urlsHashed[] = Crypt::hashBase64($link);
}
$keepLinks = $this->connection->select('ocms_linkchecker_link', 'll');
$keepLinks->innerJoin('ocms_linkchecker_entity', 'le', 'le.lid = ll.lid');
$keepLinks->fields('ll', array('url'));
$keepLinks->condition('ll.urlhash', $urlsHashed, 'IN');
$keepLinks->condition('le.entity_id', $node->nid->value);
$keepLinks->condition('le.entity_type', 'node');
$keepLinks->condition('le.langcode', $node->language()->getId());
$results=$keepLinks->execute()->fetchAllKeyed(0,0);
$linksInDatabase = array();
foreach ($results as $row) {
$linksInDatabase[] = $row;
}
return array_diff($links, $linksInDatabase);
}
/**
* {@inheritdoc}
*/
public function getMissingCommentReferences($comment, $links) {
}
/**
* {@inheritdoc}
*/
public function getMissingBlockReferences($block, $links) {
}
/**
* {@inheritdoc}
*/
public function unpublishNodes($lid) {
}
}
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/BrokenLinksTableTrait.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Component\Utility\Html;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Provides logic to build the table of broken links.
*/
trait BrokenLinksTableTrait {
/**
* Builds the broken links report table with pager.
*/
public function build() {
$links_unchecked = $this->connection->query('SELECT COUNT(1) FROM {ocms_linkchecker_link} WHERE last_checked = :last_checked AND status = :status', array(':last_checked' => 0, ':status' => 1))->fetchField();
if ($links_unchecked > 0) {
$links_all = $this->connection->query('SELECT COUNT(1) FROM {ocms_linkchecker_link} WHERE status = :status', array(':status' => 1))->fetchField();
drupal_set_message($this->translation->formatPlural($links_unchecked,
'There is 1 unchecked link of about @links_all links in the database. Please be patient until all links have been checked via cron.',
'There are @count unchecked links of about @links_all links in the database. Please be patient until all links have been checked via cron.',
array('@links_all' => $links_all)), 'warning');
}
$query = $this->query;
$header = array(
array('data' => $this->t('URL'), 'field' => 'url', 'sort' => 'desc'),
array('data' => $this->t('Response'), 'field' => 'code', 'sort' => 'desc'),
array('data' => $this->t('Error'), 'field' => 'error'),
array('data' => $this->t('Operations')),
);
$result = $query
->limit(50)
->orderByHeader($header)
->execute();
// Evaluate permission once for performance reasons.
$accessEditLinkSettings = $this->currentUser->hasPermission('edit link settings');
$accessAdministerBlocks = $this->currentUser->hasPermission('administer blocks');
$accessAdministerRedirects = $this->currentUser('administer redirects');
$rows = array();
foreach ($result as $link) {
// Get the node, block and comment IDs that refer to this broken link and
// that the current user has access to.
$nids = $this->access->accessNodeIds($link, $this->currentUser);
// $cids = _linkchecker_link_comment_ids($link, $this->currentUser);
// $bids = _linkchecker_link_block_ids($link);
// If the user does not have access to see this link anywhere, do not
// display it, for reasons explained in _linkchecker_link_access(). We
// still need to fill the table row, though, so as not to throw off the
// number of items in the pager.
// if (empty($nids) && empty($cids) && empty($bids)) {
if (empty($nids)) {
$rows[] = array(array('data' => $this->t('Permission restrictions deny you access to this broken link.'), 'colspan' => count($header)));
continue;
}
$links = array();
// Show links to link settings.
if ($accessEditLinkSettings) {
$url = Url::fromRoute('ocms_linkchecker.edit_link', array('linkId' => $link->lid), array('query' => $this->redirectDestination->getAsArray()));
$links[] = Link::fromTextAndUrl($this->t('Edit link settings'), $url)->toString();
}
// Show link to nodes having this broken link.
foreach ($nids as $nid) {
$url = Url::fromUri('internal:/node/' . $nid . '/edit', array('query' => $this->redirectDestination->getAsArray()));
$links[] = Link::fromTextAndUrl($this->t('Edit node @node', array('@node' => $nid)), $url)->toString();
}
// Show link to comments having this broken link.
// $comment_types = linkchecker_scan_comment_types();
// if (module_exists('comment') && !empty($comment_types)) {
// foreach ($cids as $cid) {
// $links[] = l(t('Edit comment @comment', array('@comment' => $cid)), 'comment/' . $cid . '/edit', array('query' => drupal_get_destination()));
// }
// }
// Show link to blocks having this broken link.
// if ($accessAdministerBlocks) {
// foreach ($bids as $bid) {
// $links[] = l(t('Edit block @block', array('@block' => $bid)), 'admin/structure/block/manage/block/' . $bid . '/configure', array('query' => drupal_get_destination()));
// }
// }
// Show link to redirect this broken internal link.
// if (module_exists('redirect') && $access_administer_redirects && _linkchecker_is_internal_url($link)) {
// $links[] = l(t('Create redirection'), 'admin/config/search/redirect/add', array('query' => array('source' => $link->internal, drupal_get_destination())));
// }
$url = Url::fromUri($link->url);
// Create table data for output.
$rows[] = array(
'data' => array(
Link::fromTextAndUrl(Html::escape($link->url), $url)->toString(),
Html::escape($link->code),
Html::escape($link->error),
['data' => ['#theme' => 'item_list', '#items' => $links]],
),
);
}
$build['broken_links_table'] = array(
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('No broken links have been found.'),
);
$build['broken_links_pager'] = array('#type' => 'pager');
// I think I may not need to set cache meta data
// @todo: How do I want to cache this page?
// Will I use cache tags, cache contexts, both of them?
//$build['#cache']['tags'][] = 'node_list';
return $build;
}
}
<file_sep>/docroot/themes/custom/ocms_education/js/custom/fixed-header.js
/**
* Add Javascript - Fixed Header
*/
jQuery(document).ready(function($) {
var preHeaderHeight = $("#pre-header").outerHeight(),
headerTopHeight = $("#header-top").outerHeight(),
headerHeight = $("#header").outerHeight();
$(window).load(function() {
if(($(window).width() > 767)) {
$("body").addClass("fixed-header-enabled");
} else {
$("body").removeClass("fixed-header-enabled");
}
});
$(window).resize(function() {
if(($(window).width() > 767)) {
$("body").addClass("fixed-header-enabled");
} else {
$("body").removeClass("fixed-header-enabled");
}
});
$(window).scroll(function() {
if(($(this).scrollTop() > preHeaderHeight + headerTopHeight) && ($(window).width() > 767)) {
$("body").addClass("onscroll");
$("#header + div").css("paddingTop", (headerHeight)+"px");
var adminHeight = $('body').css('paddingTop');
$("#header").css("top", adminHeight);
} else {
$("body").removeClass("onscroll");
$("#header").css("top", (0)+"px");
$("#header + div").css("paddingTop", (0)+"px");
}
});
});
<file_sep>/docroot/modules/custom/ocms_linkchecker/src/OcmsLinkcheckerUtilityService.php
<?php
namespace Drupal\ocms_linkchecker;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\State\StateInterface;
/**
* Implements the PupLinkcheckeryUtilityInterface.
*/
class PupLinkcheckerUtilityService implements PupLinkcheckerUtilityInterface {
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The state service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* Drupal's database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Drupal's entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs the OCMS Linkchecker Utility Service object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\State\StateInterface
* The state service
* @param \Drupal\Core\Database\Connection
* The database connection
* @param \Drupal\Core\Entity\EntityTypeManagerInterface
* The entity type manager service
*/
public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, Connection $database, EntityTypeManagerInterface $entity_type_manager) {
$this->configFactory = $config_factory;
$this->state = $state;
$this->connection = $database;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function isValidResponseCode($responseCode) {
}
/**
* {@inheritdoc}
*/
public function isDefaultrevision($entity) {
}
/**
* {@inheritdoc}
*/
public function recurseArrayValues(array $array) {
$arrayValues = array();
foreach ($array as $value) {
if (is_array($value)) {
$arrayValues = array_merge($arrayValues, $this->recurseArrayValues($value));
}
else {
$arrayValues[] = $value;
}
}
return $arrayValues;
}
/**
* {@inheritdoc}
*/
public function shouldCheckLink($url) {
$config = $this->configFactory->get('ocms_linkchecker.settings');
$status = TRUE;
// Is url in domain blacklist?
$excludedUrls = $config->get('check.disable_for_urls');
if (!empty($excludedUrls)) {
$excludeLinks = preg_split('/(\r\n?|\n)/', $excludedUrls);
$escapedExcludedLinks = array();
foreach ($excludeLinks as $excludeLink) {
$escapedExcludedLinks[] = preg_quote($excludeLink, '/');
}
$pattern = implode('|', $escapedExcludedLinks);
if (preg_match('/' . $pattern . '/', $url)) {
$status = FALSE;
}
}
// Protocol whitelist check (without curl, only http/https is supported).
if (!preg_match('/^(https?):\/\//i', $url)) {
$status = FALSE;
}
return $status;
}
/**
* {@inheritdoc}
*/
public function isInternalUrl(&$link) {
}
/**
* {@inheritdoc}
*/
public function getBlock($bid) {
}
/**
* {@inheritdoc}
*/
public function scanNodeTypes() {
$types = array();
foreach (node_type_get_names() as $type => $name) {
$scanNode = $this->state->get('ocms_linkchecker.scan_node_' . $type) ?: 0;
if ($scanNode) {
$types[$type] = $type;
}
}
return $types;
}
/**
* {@inheritdoc}
*/
public function scanCommentTypes() {
}
/**
* {@inheritdoc}
*/
public function impersonateUser($newUser = NULL) {
}
/**
* {@inheritdoc}
*/
public function revertUser() {
}
/**
* {@inheritdoc}
*/
public function loadLink($lid) {
return $this->connection->query('SELECT *
FROM {ocms_linkchecker_link}
WHERE lid = :lid',
array(':lid' => $lid)
)->fetchObject();
}
/**
* {@inheritdoc}
*/
public function updateLink($link) {
$this->connection->update('ocms_linkchecker_link')
->fields(array(
'method' => $link->method,
'fail_count' => $link->fail_count,
'last_checked' => $link->last_checked,
'status' => $link->status
))
->condition('lid', $link->lid)
->execute();
}
/**
* {@inheritdoc}
*/
public function loadEntity($entityType, $id) {
return $this->entityTypeManager->getStorage($entityType)->load($id);
}
}
<file_sep>/docroot/sites/settings.php
<?php
/**
* @file
* Drupal site-specific configuration file.
*
*/
$databases = array();
# $databases['default']['default'] = array(
# 'driver' => 'pgsql',
# 'database' => 'databasename',
# 'username' => 'sqlusername',
# 'password' => '<PASSWORD>',
# 'host' => 'localhost',
# 'prefix' => '',
# );
$config_directories = array();
$config_directories = array(
CONFIG_SYNC_DIRECTORY => '../config',
);
$settings['hash_salt'] = '';
$settings['update_free_access'] = FALSE;
# $settings['omit_vary_cookie'] = TRUE;
# $settings['file_chmod_directory'] = 0775;
# $settings['file_chmod_file'] = 0664;
# $settings['file_public_base_url'] = 'http://downloads.example.com/files';
$settings['file_public_path'] = 'downloads';
$settings['file_private_path'] = '../files-private';
# $settings['session_write_interval'] = 180;
# $settings['locale_custom_strings_en'][''] = array(
# 'forum' => 'Discussion board',
# '@count min' => '@count minutes',
# );
# $settings['maintenance_theme'] = 'bartik';
# ini_set('pcre.backtrack_limit', 200000);
# ini_set('pcre.recursion_limit', 200000);
# $config['system.site']['name'] = 'My Drupal site';
# $config['system.theme']['default'] = 'stark';
$config['user.settings']['anonymous'] = 'Visitor';
$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';
$settings['file_scan_ignore_directories'] = [
'node_modules',
'bower_components',
];
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
include $app_root . '/' . $site_path . '/settings.local.php';
}
$settings['trusted_host_patterns'] = array(
'^dev.ocms.lamtech\.sl',
'^.+\.gov\.sl',
'^lamtech\.sl',
'^.+\.lamtech\.sl',
);
$settings['install_profile'] = 'lightning';
<file_sep>/docroot/modules/custom/ocms_files/ocms_file_operations/src/Tests/Kernel/TestFileOperations.php
<?php
namespace Drupal\Tests\irs_file_operations\Kernel;
use Drupal\Tests\irs_file_operations;
use Drupal\Core\Language\Language;
use Drupal\Core\Entity;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
/**
* Tests token handling.
*
* @requires module token
* @requires module entity
*
* @group media_entity
*/
class TestFileOperations extends EntityKernelTestBase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
}
public function testMediaBundleCreation() {
$fid = 1;
$directory = 'simpletestpup/ebook/';
$source = DRUPAL_ROOT . '/media_unpublish/' . $directory;
$destination = DRUPAL_ROOT . '/sites/default/files/' . $directory . 'tmp';
$directory_created = file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
if($directory_created) {
$this->assertTrue($directory_created);
$files = file_scan_directory($source, '/.*\.(txt|pdf|doc|docx)$/');
if(!empty($files)) {
foreach ($files as $file) {
$result = file_unmanaged_copy($file->uri, $destination, FILE_EXISTS_REPLACE);
$this->assertTrue($result,"Unable to copy {$file->uri} to $destination.");
}
}
else {
$this->assertTrue(!empty($files), "Files does not exist!");
}
}
else {
$this->assertTrue($directory_created, "Unable to create directory $destination.");
}
}
/**
* Tests some of the tokens provided by media_entity.
*/
}
<file_sep>/docroot/themes/custom/ocms_base/js/node--article.js
+function ($) {
'use strict';
// Set variables
var accordHeadings = $('.content').find('.ocms-accordion-heading'),
accordBodies = $('.content').find('.ocms-accordion-body');
// Add id to the parent element
$('.content').attr( "id", "article-accordion-content");
function classesAndIds() {
if (window.innerWidth <= 768) {
// add classes and ids in mobile view
$(accordBodies).addClass('collapse');
$(accordHeadings).addClass('collapsed');
$(accordBodies).each(function(item, element){
var el = $(element).attr({"id" : "collapse-" + (item+1)});
});
$(accordHeadings).each(function(item, element) {
var el = $(element).attr({
"data-toggle" : "collapse",
"data-parent" : "#article-accordion-content",
"href" : "#collapse-" + (item +1)
});
});
} else {
// remove classes and ids in desktop view
$(accordBodies).removeAttr('id href style').removeClass('collapse');
$(accordHeadings).removeAttr('data-toggle data-parent href').removeClass('collapsed');
}
};
$(window).resize( function() {
classesAndIds();
});
classesAndIds();
}(jQuery);
<file_sep>/docroot/modules/custom/ocms_hierarchical_taxonomy_menu/src/Plugin/Block/OcmsHierarchicalTaxonomyMenuBlock.php
<?php
namespace Drupal\ocms_hierarchical_taxonomy_menu\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Template\Attribute;
use Drupal\field\Entity\FieldConfig;
use Drupal\taxonomy\Entity\Term;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a 'PupHierarchicalTaxonomyMenuBlock' block.
*
* @Block(
* id = "ocms_hierarchical_taxonomy_menu",
* admin_label = @Translation("OCMS Hierarchical Taxonomy Menu"),
* category = @Translation("OCMS Custom"),
* context = {
* "node" = @ContextDefinition(
* "entity:node",
* label = @Translation("Current Node")
* )
* }
* )
*/
class PupHierarchicalTaxonomyMenuBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManager
*/
protected $entityFieldManager;
/**
* The term storage handler.
*
* @var \Drupal\taxonomy\TermStorageInterface
*/
protected $storageController;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Constructs a PupHierarchicalTaxonomyMenuBlock object.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager service
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager service.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
EntityFieldManagerInterface $entity_field_manager,
EntityTypeManagerInterface $entity_type_manager,
LanguageManagerInterface $language_manager
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityFieldManager = $entity_field_manager;
$this->storageController = $entity_type_manager->getStorage('taxonomy_term');
$this->languageManager = $language_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_field.manager'),
$container->get('entity_type.manager'),
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'vocabulary' => '',
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['vocabulary'] = [
'#title' => $this->t('Vocabulary'),
'#type' => 'select',
'#options' => $this->getVocabularyOptions(),
'#required' => TRUE,
'#default_value' => $this->configuration['vocabulary'],
];
return $form;
}
/**
* Generate vocabulary select options.
*/
private function getVocabularyOptions() {
$options = [];
$vocabularies = taxonomy_vocabulary_get_names();
foreach ($vocabularies as $vocabulary) {
$options[$vocabulary] = $vocabulary;
}
return $options;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['vocabulary'] = $form_state->getValue('vocabulary');
}
/**
* {@inheritdoc}
*/
public function build() {
$node = $this->getContextValue('node');
$nodeReferencesConfiguredVocabulary = false;
$fields = $this->entityFieldManager->getFieldDefinitions('node', $node->getType());
foreach ($fields as $field) {
if (($field instanceof FieldConfig) && method_exists($field, 'getSettings')) {
$settings = $field->getSettings();
if (isset($settings['handler_settings']['target_bundles']) && in_array($this->configuration['vocabulary'], $settings['handler_settings']['target_bundles'])) {
$nodeReferencesConfiguredVocabulary = true;
$nodeVocabularyReferenceField = $field->getName();
continue;
}
}
}
if ($nodeReferencesConfiguredVocabulary) {
$language = $this->languageManager->getCurrentLanguage()->getId();
$nodeReferencedTid = $node->get($nodeVocabularyReferenceField)->getValue()[0]['target_id'];
// Load the parents of the current term
// Note: This also loads the current term itself
$parentsObjects = $this->storageController->loadAllParents($nodeReferencedTid);
$parentsIds = [];
foreach ($parentsObjects as $parentObject) {
$parentsIds[] = $parentObject->id();
}
// The root term is Level 1
$levels = count($parentsIds);
if ($levels >= 2) {
$activeTrailIndex = $levels - 2;
$activeTrailId = $parentsIds[$activeTrailIndex];
$activeParentId = $parentsIds[1];
}
else {
$activeTrailId = 0;
$activeParentId = 0;
}
$vocabularyConfig = $this->configuration['vocabulary'];
$vocabularyConfig = explode('|', $vocabularyConfig);
$vocabulary = isset($vocabularyConfig[0]) ? $vocabularyConfig[0] : NULL;
$vocabularyTree = $this->storageController->loadTree($vocabulary, 0, NULL, FALSE);
$listItems = [];
foreach ($vocabularyTree as $item) {
$includeItem = false;
$parentId = 0;
if (in_array($item->tid, $parentsIds)) {
// This is a parent that we want to show
$includeItem = true;
$level = $levels - array_search($item->tid, $parentsIds);
$itemsParentsObjects = $this->storageController->loadParents($item->tid);
foreach ($itemsParentsObjects as $parentObject) {
if (in_array($parentObject->id(), $parentsIds) && ($parentObject->id() != $nodeReferencedTid)) {
$parentId = $parentObject->id();
break;
}
}
}
else {
$itemsParentsObjects = $this->storageController->loadParents($item->tid);
foreach ($itemsParentsObjects as $parentObject) {
if (in_array($parentObject->id(), $parentsIds)) {
// This is a child of a parent that we are showing
// Note: This results in showing the children of the active term,
// which is exactly as the client requested.
$includeItem = true;
$level = $levels - array_search($parentObject->id(), $parentsIds) + 1;
$parentId = $parentObject->id();
break;
}
}
}
if ($includeItem) {
if ($item->tid == $nodeReferencedTid) {
$class = [
'level-' . $level,
'is-active',
];
}
else {
$class = [
'level-' . $level,
];
}
if ($item->tid == $activeTrailId) {
$class[] = 'is-active-trail';
}
if ($item->tid == $activeParentId) {
$class[] = 'is-active-parent';
}
$term = Term::load($item->tid);
$translationLanguages = $term->getTranslationLanguages();
if (isset($translationLanguages[$language])) {
$itemTranslated = $term->getTranslation($language);
}
else {
$itemTranslated = $term;
}
$options = [
'title' => $itemTranslated->label(),
'id' => $this->t('term-:termId', array(':termId' => $itemTranslated->id())),
'rel' => $parentId ? 'child' : 'parent',
];
$listItems[] = [
'title' => $itemTranslated->label(),
'id' => $itemTranslated->id(),
'url' => $itemTranslated->toUrl(),
'options' => $options,
'attributes' => new Attribute([
'class' => $class,
'data-indent-level' => $level,
]),
'parentId' => $parentId,
'below' => [],
];
}
}
$items = [];
// The items *should* already be in an order such that a child will never
// appear before the parent has already been loaded. Just to make this
// more robust we will use a while loop and unset elements as they are
// placed in the hierarchy found.
while ($listItems) {
foreach ($listItems as $key => $item) {
if ($item['parentId']) {
$found = $this->setItemBelow($items, $item);
}
else {
$items[$item['id']] = $item;
$found = true;
}
if ($found) {
unset($listItems[$key]);
}
}
}
// There should be only one root key.
$rootKey = array_keys($items);
// We never show Level 1 (root) items in the secondary navigation.
if (isset($items[$rootKey[0]]['below'])) {
$items = $items[$rootKey[0]]['below'];
}
else {
$items = [];
}
if ($items) {
return [
'#theme' => 'ocms_hierarchical_taxonomy_menu',
'#items' => $items,
];
}
}
}
/**
* Places an item in its parent's below attribute
*
* @param array $items
* The master item tree
* @param object $item
* The item being processed
*/
private function setItemBelow(&$items, $item) {
if (isset($items[$item['parentId']])) {
$items[$item['parentId']]['below'][$item['id']] = $item;
return true;
}
else {
foreach ($items as $itemId => $itemArray) {
$found = $this->setItemBelow($itemArray['below'], $item);
if ($found) {
$items[$itemId]['below'] = $itemArray['below'];
return true;
}
}
}
}
}
| 3acc6180ba185f86774ea4ff56244080450d7e26 | [
"JavaScript",
"Text",
"PHP"
] | 63 | PHP | click2tman/slmdinc.org | ad2f70a03a3509c9d9ecb584b7453a7f88e003ff | ffc494395521d494e0189f072b916bf430ea6274 | |
refs/heads/master | <file_sep>const validator = require('node-validator')
const UserSchema = require('../models/user.js')
/**
* User
* @Class
* {Object} app - express context
*/
class User {
constructor (app, connect) {
this.app = app
this.UserSchema = connect.model('User', UserSchema)
this.create()
this.delete()
this.search()
this.show()
this.update()
}
/**
* Create
*/
create () {
const check = validator.isObject()
.withRequired('firstName', validator.isString())
.withRequired('lastName', validator.isString())
.withRequired('gender', validator.isString())
.withRequired('age', validator.isNumber())
.withRequired('adressNumber', validator.isNumber())
.withRequired('adressType', validator.isString())
.withRequired('adressName', validator.isString())
.withRequired('cityCode', validator.isString())
.withRequired('cityName', validator.isString())
this.app.post('/user/create', validator.express(check), (req, res) => {
try {
const userSchema = new this.UserSchema(req.body)
userSchema.save().then(user => {
res.status(200).json(user)
}).catch(() => {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
})
} catch (err) {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
}
})
}
/**
* Delete
*/
delete () {
this.app.delete('/user/delete/:id', (req, res) => {
try {
this.UserSchema.findByIdAndDelete(req.params.id).then(user => {
res.status(200).json(user)
}).catch(() => {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
})
} catch (err) {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
}
})
}
/**
* Search
*/
search () {
const check = validator.isObject()
.withOptional('firstName', validator.isString())
.withOptional('gender', validator.isString())
.withOptional('age_max', validator.isNumber())
.withOptional('age_min', validator.isNumber())
.withOptional('limit', validator.isNumber())
.withOptional('sort', validator.isNumber())
this.app.post('/users/search', validator.express(check), (req, res) => {
try {
const filters = []
if (req.body.firstName) {
filters.push({
$match: {
firstName: req.body.firstName
}
})
}
if (req.body.gender) {
filters.push({
$match: {
gender: req.body.gender
}
})
}
if (req.body.age_max) {
filters.push({
$match: {
age: {
$gte: req.body.age_max
}
}
})
}
if (req.body.age_min) {
filters.push({
$match: {
age: {
$lte: req.body.age_min
}
}
})
}
if (req.body.sort) {
filters.push({
$sort: {
age: req.body.sort
}
})
}
filters.push({ $limit: req.body.limit || 10 })
this.UserSchema.aggregate(filters)
.then(users => {
res.status(200).json(users.map(user => {
user.id = user._id
delete user._id
return user
}) || [])
}).catch(err => {
res.status(500).json({
code: 500,
message: err
})
})
} catch (err) {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
}
})
}
/**
* Show
*/
show () {
this.app.get('/user/show/:id', (req, res) => {
try {
this.UserSchema.findById(req.params.id)
.then(user => {
res.status(200).json(user || {})
}).catch(err => {
res.status(500).json({
code: 500,
message: err
})
})
} catch (err) {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
}
})
}
/**
* Update
*/
update () {
const check = validator.isObject()
.withOptional('firstName', validator.isString())
.withOptional('lastName', validator.isString())
.withOptional('gender', validator.isString())
.withOptional('age', validator.isNumber())
.withOptional('adressNumber', validator.isNumber())
.withOptional('adressType', validator.isString())
.withOptional('adressName', validator.isString())
.withOptional('cityCode', validator.isString())
.withOptional('cityName', validator.isString())
this.app.put('/user/update/:id', validator.express(check), (req, res) => {
try {
this.UserSchema.findByIdAndUpdate(req.params.id, req.body, {new: true})
.then(user => {
res.status(200).json(user)
}).catch(() => {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
})
} catch (err) {
res.status(500).json({
code: 500,
message: 'Internal Server Error'
})
}
})
}
}
module.exports = User
<file_sep>const mongoose = require('mongoose')
const Schema = new mongoose.Schema({
firstName: String,
lastName: String,
gender: String,
age: Number,
adressNumber: Number,
adressType: String,
adressName: String,
cityCode: String,
cityName: String
}, {
collection: 'users',
minimize: false,
versionKey: false
}).set('toJSON', {
transform: (doc, ret) => {
ret.id = ret._id
delete ret._id
}
})
module.exports = Schema
<file_sep># api-2020-v2 | 273b3de8d0dbeb92cbc0da2fbf4e43420ed25968 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | xzen/api-2020-v2 | fffc3428d78fefea9e0a0d6c177de206b6529051 | bd27773fa1712bb71c021596b8720bab75378fd3 | |
refs/heads/master | <file_sep>'''
Check status of flight arriving at Zurich Airport. Sounds a beep if status changes.
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
import time
import winsound
frequeny = 2000 # Hz
duration = 2000 # 1000 = 1sec
driver = webdriver.Firefox()
driver.get("https://www.zurich-airport.com/passengers-and-visitors/arrivals-and-departures/arrivals")
input("You have to manually give cookie consent and then press 'Enter'.")
airport_dep = str(input("Departing Airport: "))
flight_no = str(input("Flight Number: "))
scroll = input("Flight is on next page? [y/n]")
if scroll in ["y", "yes", "Y", "Yes"]:
later_button = driver.find_element_by_id("later2")
later_button.click()
print("searching for flight from '%s' with flight number '%s'" % (airport_dep, flight_no))
first = True
status = ""
while True:
table_rows = driver.find_elements(By.TAG_NAME, "tr")
# print(len(table_rows))
counter = 0 # iteration counter for location on table row list
save_loc = [] # save location of city in table row list
for row in table_rows:
counter += 1
td_text = row.text
# print(td_text)
if airport_dep in td_text and flight_no in td_text:
save_loc.append(counter-1)
if len(save_loc) == 0:
print("Your flight has not been found")
else:
table_row = []
# title_row = ["Time: ", "| Expected: ", "| From: ", "| Airport: ", "| Flight: ", "| Arrival: ",
# "| Baggage Claim: ", "| Status: "]
for item in save_loc:
table_row = table_rows[item].text.split("\n")
len_row = len(table_row)
print(table_row)
# out_list = []
# for i in range(len_row):
# out_list.append(title_row[i])
# out_list.append(str(table_row[i]))
# print("".join(out_list))
# print(len(table_row), "length table row")
# print(type(table_row), "type table row")
new_status = table_row[-1]
if new_status != status:
winsound.Beep(frequeny, duration)
status = new_status
time.sleep(60)
| 0c2d054bb41bb4d00ceb2500f725b81688dc0fd8 | [
"Python"
] | 1 | Python | kratzlos/flight-arrival-checker | 7ff3e2a5659a7eeb1c0f00ee7d50522a5ee74bbb | 67bd52e3a5ae0f3cccc11a3d474d2e4399cc6f77 | |
refs/heads/master | <repo_name>chandanitschool/PremTest<file_sep>/src/main/java/com/tcs/com/JsondataobjApplication.java
package com.tcs.com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tcs.com.model.Student;
@SpringBootApplication
public class JsondataobjApplication {
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(JsondataobjApplication.class, args);
Student st = new Student();
st.setStudentId(5);
st.setStudentName("Ram");
st.setStudentSkill("Java");
ObjectMapper maper= new ObjectMapper();
String stringJson = maper.writeValueAsString(st);
System.out.println(stringJson);
}
}
| f41b0e90b619969e22a47dd576e5294b4325d747 | [
"Java"
] | 1 | Java | chandanitschool/PremTest | e4e7e9a0a82263c80d783ffdb0f35c85f0a4e805 | 7eba8274ef26fc086dfb931e9bf21b06c7059b9f | |
refs/heads/master | <repo_name>dcfreema/CSE337project<file_sep>/src/main.go
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
"os"
"strconv"
"strings"
"time"
_ "github.com/lib/pq"
)
var templates *template.Template
var databaseConnection DatabaseConnection
var database *sql.DB
type ErrorMsg struct {
Error string
}
type State struct {
Url string
Action string
}
type User struct {
Username string
Password string
}
type DatabaseConnection struct {
Host string
Port int64
Username string
Password string
Dbname string
}
type Forum struct {
Id int64
ForumPostId int64
Name string
Description string
Posts []ForumPost
}
type ForumPost struct {
ForumId int64
Id int64
Name string
Author string
Timestamp string
Threads []ForumPostThread
}
type ForumPostThread struct {
FormPostId int64
Id int64
Body string
Author string
Timestamp string
}
type GetForumRequest struct {
ForumId int64
ForumPostId int64
}
func getDatabaseConnectionInfo(filename string) (DatabaseConnection, error) {
file, err := os.Open(filename)
if err != nil {
fmt.Println(err.Error())
return DatabaseConnection{}, err
}
var config DatabaseConnection
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
fmt.Println(err.Error())
return DatabaseConnection{}, err
}
return config, nil
}
func init() {
t, err := template.ParseFiles(
"tmpl/header.tmpl",
"tmpl/index.tmpl",
"tmpl/footer.tmpl",
"tmpl/forumlist.tmpl",
"tmpl/forumposts.tmpl",
"tmpl/forumpostthreads.tmpl",
"tmpl/newpost.tmpl",
"tmpl/signup.tmpl",
"tmpl/congrats.tmpl",
"tmpl/login.tmpl",
"tmpl/game.tmpl",
)
templates = template.Must(t, err)
databaseConnection, err = getDatabaseConnectionInfo("datasource.json")
if err != nil {
panic("Cannot connect to the database")
}
dbUrl := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", databaseConnection.Username, databaseConnection.Password, databaseConnection.Host, databaseConnection.Dbname)
database, err = sql.Open("postgres", dbUrl)
if err != nil {
panic(err)
}
}
func forum(w http.ResponseWriter, r *http.Request) {
var state State
_, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
urlParts := strings.Split(r.URL.Path, "/")
fmt.Println(urlParts)
var request GetForumRequest
if len(urlParts) > 3 {
forumId, _ := strconv.ParseInt(urlParts[2], 10, 64)
request.ForumId = forumId
}
if len(urlParts) >= 4 {
forumPostId, _ := strconv.ParseInt(urlParts[3], 10, 64)
request.ForumPostId = forumPostId
}
fmt.Println(request)
//Display all the forums to the user
if request.ForumId <= 0 {
var forums []Forum
rows, err := database.Query("SELECT id, name, description from forum")
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
for rows.Next() {
var forum Forum
if err := rows.Scan(&forum.Id, &forum.Name, &forum.Description); err != nil {
fmt.Println(err)
} else {
forums = append(forums, forum)
}
}
fmt.Println(forums)
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "forumlist.tmpl", &forums)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
//Display all the posts of the forum to the user
if request.ForumId >= 1 && request.ForumPostId <= 0 {
var forum Forum
err := database.QueryRow("select name from forum where id = $1", request.ForumId).Scan(&forum.Name)
if err != nil {
fmt.Println(err)
return
}
forum.Id = request.ForumId
var forumPosts []ForumPost
rows, err := database.Query("SELECT id, forumid, name, author, timestamp from forumpost where forumid = $1", request.ForumId)
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
for rows.Next() {
var forumPost ForumPost
if err := rows.Scan(&forumPost.Id, &forumPost.ForumId, &forumPost.Name, &forumPost.Author, &forumPost.Timestamp); err != nil {
fmt.Println(err)
} else {
forumPosts = append(forumPosts, forumPost)
}
}
fmt.Println(forumPosts)
forum.Posts = forumPosts
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "forumposts.tmpl", &forum)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
//Display all the threads of the post of the forum to the use
if request.ForumId >= 1 && request.ForumPostId >= 1 {
var forum Forum
forum.Id = request.ForumId
forum.ForumPostId = request.ForumPostId
err := database.QueryRow("select name from forum where id = $1", request.ForumId).Scan(&forum.Name)
if err != nil {
fmt.Println(err)
return
}
var forumPost ForumPost
err = database.QueryRow("SELECT name from forumpost where id = $1", request.ForumPostId).Scan(&forumPost.Name)
if err != nil {
fmt.Println(err)
return
}
var forumPostThreads []ForumPostThread
rows, err := database.Query("SELECT id, body, author, timestamp from forumpostthread where forumpostid = $1", request.ForumPostId)
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
for rows.Next() {
var forumPostThread ForumPostThread
if err := rows.Scan(&forumPostThread.Id, &forumPostThread.Body, &forumPostThread.Author, &forumPostThread.Timestamp); err != nil {
fmt.Println(err)
} else {
forumPostThreads = append(forumPostThreads, forumPostThread)
}
}
forumPost.Threads = forumPostThreads
forum.Posts = append(forum.Posts, forumPost)
fmt.Println(forum)
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "forumpostthreads.tmpl", &forum)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
}
func newpost(w http.ResponseWriter, r *http.Request) {
var state State
_, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
urlParts := strings.Split(r.URL.Path, "/")
fmt.Println(urlParts)
var request GetForumRequest
if len(urlParts) > 3 {
forumId, _ := strconv.ParseInt(urlParts[2], 10, 64)
request.ForumId = forumId
}
if len(urlParts) >= 4 {
forumPostId, _ := strconv.ParseInt(urlParts[3], 10, 64)
request.ForumPostId = forumPostId
}
fmt.Println(request)
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "newpost.tmpl", &request)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
func insertNewPost(forumId int64, author, name string) int64 {
var id int64
t := time.Now()
date := fmt.Sprintf("%d-%02d-%02d\n", t.Year(), t.Month(), t.Day())
err := database.QueryRow(`insert into forumpost (forumid, name, author, timestamp) values($1, $2, $3, $4) returning id`, forumId, name, author, date).Scan(&id)
fmt.Println(err)
fmt.Println(id)
return id
}
func insertNewPostThread(id int64, body, author, timestamp string) {
t := time.Now()
date := fmt.Sprintf("%d-%02d-%02d\n", t.Year(), t.Month(), t.Day())
err := database.QueryRow(`insert into forumpostthread (forumpostid, body, author, timestamp) values($1, $2, $3, $4) returning id`, id, body, author, date).Scan(&id)
if err != nil {
fmt.Println(err)
}
}
func post(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Invalid Request!", http.StatusMethodNotAllowed)
return
}
var state State
cookie, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
if err != nil {
//user not logged in
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if cookie.Value == "" {
//user not logged in
http.Redirect(w, r, "/login", http.StatusFound)
return
}
username := cookie.Value
r.ParseForm()
fmt.Println(r.Form)
forumId, _ := strconv.ParseInt(r.PostFormValue("forum"), 10, 64)
forumPostId, _ := strconv.ParseInt(r.PostFormValue("forumpost"), 10, 64)
body := r.PostFormValue("body")
//If it is a new post to the forum
if forumId > 0 && forumPostId == 0 {
name := r.PostFormValue("name")
id := insertNewPost(forumId, username, name)
insertNewPostThread(id, body, username, "2015-10-28")
fmt.Println("New Thread Created")
}
//If it is a new reply to the forum post
if forumId > 0 && forumPostId > 0 {
insertNewPostThread(forumPostId, body, username, "2015-10-28")
fmt.Println("New Post added")
}
url := fmt.Sprintf("http://localhost:8080/forum/%d/%d", forumId, forumPostId)
http.Redirect(w, r, url, http.StatusFound)
}
func signup(w http.ResponseWriter, r *http.Request) {
var state State
_, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
if r.Method == "POST" {
r.ParseForm()
username := r.PostFormValue("username")
password := r.PostFormValue("<PASSWORD>")
verify := r.PostFormValue("verify")
user := User{username, password}
if password != verify {
data := ErrorMsg{"passwords do not match"}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "signup.tmpl", data)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
rows, err := database.Query("SELECT username from users where username=$1", username)
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
for rows.Next() {
data := ErrorMsg{"username already taken"}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "signup.tmpl", data)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
var id int
err = database.QueryRow(`insert into users (username, password) values($1, $2) returning id`, username, password).Scan(&id)
if err != nil {
fmt.Println(err)
}
err = database.QueryRow(`insert into savedata (username, data) values($1, $2) returning id`, username, "").Scan(&id)
if err != nil {
fmt.Println(err)
}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "congrats.tmpl", user)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "signup.tmpl", nil)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
}
func login(w http.ResponseWriter, r *http.Request) {
var state State
_, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
if r.Method == "POST" {
r.ParseForm()
username := r.PostFormValue("username")
password := r.PostFormValue("<PASSWORD>")
rows, err := database.Query("SELECT username from users where username=$1 and password=$2", username, password)
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
for rows.Next() {
//user logged in
loginCookie := &http.Cookie{Name: "username", Value: username, Expires: time.Now().Add(time.Hour), Path: "/"}
http.SetCookie(w, loginCookie)
http.Redirect(w, r, "/game", http.StatusFound)
return
}
//not logged in
data := ErrorMsg{"invalid username and or password"}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "login.tmpl", data)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
return
}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "login.tmpl", nil)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
}
func game(w http.ResponseWriter, r *http.Request) {
var state State
_, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "game.tmpl", nil)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
}
func createSave(username, data string) error {
var id int
err := database.QueryRow(`update savedata set data = $1 where username = $2 returning id`, data, username).Scan(&id)
return err
}
func loadSave(username string) (string, error) {
var data string
fmt.Println("loading data for" + username)
err := database.QueryRow(`SELECT data FROM savedata where username=$1`, username).Scan(&data)
return data, err
}
func checkLogin(r *http.Request) (string, error) {
cookie, err := r.Cookie("username")
if err != nil {
return "", err
}
if cookie.Value == "" {
return "", errors.New("Invalid username")
}
username := cookie.Value
return username, nil
}
func save(w http.ResponseWriter, r *http.Request) {
username, err := checkLogin(r)
if err != nil {
http.Error(w, "bad!", http.StatusNotAcceptable)
return
}
if r.Method == "POST" {
r.ParseForm()
data := r.PostFormValue("data")
if data == "" {
http.Error(w, "bad!", http.StatusNotAcceptable)
return
}
err := createSave(username, data)
if err != nil {
fmt.Println(err)
http.Error(w, "bad!", http.StatusNotAcceptable)
return
}
}
}
func load(w http.ResponseWriter, r *http.Request) {
username, err := checkLogin(r)
if err != nil {
http.Error(w, "bad!", http.StatusNotAcceptable)
fmt.Println(err)
return
}
if r.Method == "POST" {
data, err := loadSave(username)
if err != nil {
fmt.Println(err)
data = ""
}
fmt.Println(data)
out, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(out)
}
}
func logout(w http.ResponseWriter, r *http.Request) {
loginCookie := &http.Cookie{Name: "username", Value: "", Expires: time.Now(), Path: "/"}
http.SetCookie(w, loginCookie)
http.Redirect(w, r, "/login", http.StatusFound)
}
func index(w http.ResponseWriter, r *http.Request) {
var state State
_, err := r.Cookie("username")
if err != nil {
state.Url = "/login"
state.Action = "Login"
} else {
state.Url = "/logout"
state.Action = "Logout"
}
templates.ExecuteTemplate(w, "header.tmpl", state)
templates.ExecuteTemplate(w, "index.tmpl", nil)
templates.ExecuteTemplate(w, "footer.tmpl", nil)
}
func main() {
http.HandleFunc("/forum/", forum)
http.HandleFunc("/newpost/", newpost)
http.HandleFunc("/post", post)
http.HandleFunc("/signup", signup)
http.HandleFunc("/login", login)
http.HandleFunc("/game", game)
http.HandleFunc("/save", save)
http.HandleFunc("/load", load)
http.HandleFunc("/logout", logout)
http.HandleFunc("/", index)
http.Handle("/imgs/", http.StripPrefix("/imgs/", http.FileServer(http.Dir("imgs"))))
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
http.ListenAndServe(":8080", nil)
}
<file_sep>/README.md
<NAME>
<NAME>
<NAME>
<NAME>
# CSE337project
## Requirements
1. Postgresql
2. Go 1.5+
## Setup
1. Update the database.json file to be for your environment
2. run go get to get libpq
3. insert the contents of database.sql
4. go run main.go
<file_sep>/src/js/game.js
var baseHeros = [
{"name":"hero 1","growth": 0.1, "basedps":1, "dps": 0, "cost": 0.5, "level":0, "img":"imgs/Knight1.png"},
{"name":"hero 2", "growth": 0.1, "basedps":1, "dps": 0, "cost": 100, "level":0, "img":"imgs/Knight2.png"},
];
var listOfEnemy = [
{"id":0, "name":"Ghost", "hp": 20, "money": 2, "img":"imgs/one.png"},
{"id":1, "name":"Poltergeist", "hp": 60, "money": 5, "img":"imgs/two.png"},
{"id":2, "name":"Phantom", "hp": 100, "money": 8, "img":"imgs/three.png"},
{"id":3, "name":"<NAME>", "hp": 80, "money": 7, "img":"imgs/Orb.png"},
{"id":4, "name":"Apeclopse", "hp": 160, "money": 13, "img":"imgs/ManApe.png"},
{"id":5, "name":"<NAME>", "hp": 40, "money": 4, "img":"imgs/Scorpion.png"},
];
var saveExpire = localStorage.getItem("expire");
var data = null;
var currentEnemy = null;
if(saveExpire == null || saveExpire < (new Date()).getTime()) {
console.log("Local Save Expired: " + saveExpire);
} else {
data = JSON.parse(localStorage.getItem("data"));
currentEnemy = JSON.parse(localStorage.getItem("currentEnemy"));
}
if (data===null) {
data = {
"heros" : $.extend(true, {}, baseHeros),
"money" : 0,
"clicks" : 0,
"clickdamage": 1,
"clickprice" : 1,
"clicklvl" : 1,
"clickgrowth" : 0.1,
"dps": 0
};
}
if (currentEnemy == null) {
currentEnemy = $.extend(true, {},listOfEnemy[0]);
}
if (data.clickprice == null) {
data.clickprice = 15;
}
if (data.clicklvl == null) {
data.clicklvl = 1;
}
if (data.clickgrowth == null) {
data.clickgrowth = 0.1;
}
function setnames() {
$('.heroname').html(function(i, obj) {
return "<h1><span class=\"label label-default\">" + data.heros[i]["name"] + "</span></h1>";
});
$('.upgradename').html(function(i,obj) {
return "<h1><span class=\"label label-default\">click</span></h1>";
});
}
function setprice() {
$('.heroprice').html(function(i, obj) {
return "<button class=\"btn btn-primary\" onclick=\"buyhero("+i+")\">LVL UP<br />$" + (data.heros[i]["cost"]).toFixed(2) + "</button>";
});
}
function setclickprice(price) {
$('.upgradeprice').html(function(i,obj) {
return "<button class=\"btn btn-primary\" onclick=\"buyClick()\">LVL UP <br />$" + price + "</button>";
});
}
function buyClick() {
curdmg = data.clickdamage;
price = data.clickprice;
if(price > data["money"]) {
console.log("Not enough money");
return;
}
data["money"] -= price;
data.clickdamage += data.clickgrowth;
data.clicklvl++;
data.clickprice = data.clicklvl * data.clicklvl;
setclickpower();
setclickprice(data.clickprice.toFixed(2));
setstats();
}
function setclickpower() {
$('.upgradelevel').html(function(i,obj) {
return "<h1><span class=\"label label-default\">Lvl " + data.clicklvl + "</h1>";
});
}
function setstats() {
$('.user-stats').html(function(i, obj) {
return "Money: " + (data["money"]).toFixed(2) + "<br>" +
"Click power: " + data["clickdamage"].toFixed(2) + "<br>" +
"Total Hero Power: " + (data["dps"]).toFixed(2) + "<br>";;
});
}
function setlevel() {
$('.herolevel').html(function(i, obj) {
return "<h1><span class=\"label label-default\">Lvl " + data.heros[i]["level"] + "</span></h1>";
});
}
function buyhero(heroid) {
hero = data.heros[heroid];
if(hero["cost"] > data["money"]) {
console.log("Not enough money");
return;
}
data["money"] -= hero["cost"];
data.heros[heroid]["level"]++;
newcost(heroid);
newdps(heroid);
setlevel();
setstats();
}
function newcost(heroid) {
data.heros[heroid]["cost"] += (data.heros[heroid]["cost"] * 0.1);
setprice();
}
function newdps(heroid) {
data.heros[heroid]["dps"] = data.heros[heroid]["basedps"] + data.heros[heroid]["level"]*data.heros[heroid]["growth"];
dps = 0;
for (var key in data.heros) {
dps += data.heros[key]["dps"];
}
data["dps"] = dps;
setstats();
}
function setenemyname() {
$('.enemyname').each(function(i, obj) {
obj.textContent = currentEnemy["name"];
});
}
function setupnewenemy() {
$('.progress-bar').attr("value", currentEnemy["hp"]);
if (currentEnemy["id"] != null)
max = listOfEnemy[currentEnemy["id"]]["hp"];
else
max = currentEnemy["hp"];
$('.progress-bar').attr('max', max);
setenemyname();
$('#enemyimg').attr("src", currentEnemy["img"]);
}
function isEnemyDead() {
if (currentEnemy["hp"] <= 0) {
data["money"] += currentEnemy["money"];
i = Math.floor(Math.random() * listOfEnemy.length);
currentEnemy = $.extend(true, {},listOfEnemy[i]);
setupnewenemy();
setstats();
return true;
}
return false;
}
function setEnemyBar() {
max = $('.progress-bar').attr('max');
$('.progress-bar').attr("value", currentEnemy["hp"]);
}
function clickdamage() {
data["clicks"]++;
causeDamage(data["clickdamage"]);
}
function damagepersecond() {
causeDamage(data["dps"]);
}
function causeDamage( dmg) {
currentEnemy["hp"] -= dmg;
if(isEnemyDead()==true) {
return;
}
setEnemyBar();
}
function savelocalstoarge() {
localStorage.setItem("data", JSON.stringify(data));
localStorage.setItem("expire", (new Date()).getTime() + 10000);
localStorage.setItem("currentEnemy", JSON.stringify(currentEnemy));
}
function saveData() {
$.ajax({
type: "POST",
url: "/save",
data: "data="+JSON.stringify(data),
success: function(d, textStatus, jqXHR) { alert ("Game saved!"); },
error: function(d, textStatus, err) { loginScreen(); }
});
}
function fixUI() {
setstats();
setprice();
setclickprice(data.clickprice);
setclickpower();
setlevel();
setnames();
}
function loadData() {
$.ajax({
type: "POST",
url: "/load",
data: "data="+JSON.stringify(data),
success: function(d,textStatus,jqXHR) { if (d != "") data = JSON.parse(d); fixUI(); alert("Game Loaded"); },
error: function(d,textStatus,err) { loginScreen(); }
});
}
function loginScreen() {
savelocalstoarge();
window.location.replace("http://localhost:8080/login");
}
setupnewenemy();
fixUI();
dpsInterval = setInterval(damagepersecond, 1000);
saveInterval = setInterval(savelocalstoarge, 1000);
| 2ec93b36f2e74dfe7998429f1ba4fb59bd486856 | [
"Markdown",
"JavaScript",
"Go"
] | 3 | Go | dcfreema/CSE337project | bd494289ff14d3f6e7d5ad620e48ef651246b372 | 3906da2315d24bfc30417e4529aa6ad8b3f0ba37 | |
refs/heads/main | <file_sep><?php
session_start();
include_once "config.php";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(!empty($fname) && !empty($lname) && !empty($email) && !empty($password)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
//let check email already exit in the database or not
$sql = mysqli_query($conn, "SELECT email FROM users WHERE email = '{$email}'");
if(mysqli_num_rows($sql) > 0){//if emailalready exist
echo "$email - This email already exist";
} else{
//check user upload file or not
if(isset($_FILES['image'])){ //if file upload
$img_name = $_FILES['image']['name'];//get name user uploaded
$tmp_name = $_FILES['image']['tmp_name'];//temp name is used to save/move file in our folder
//let's explode img and get the last extension like jpg png
$img_explode = explode('.', $img_name);
$img_ext = end($img_explode);//get the extension of user upload file
$extensions = ['png', 'jpg', 'jpeg'];//array store the valid value
if(in_array($img_ext, $extensions) === true){//if the file user upload match with array
$time = time();//this is return us current time
// because when we will rename this file with current in our folder
//let's move the user uploaded img to our particular folder
$new_img_name = $time.$img_name;
if (move_uploaded_file($tmp_name, "images/".$new_img_name)){//if user upload img move to our folder sucessfully
$status = "Active now";//once user sign up his status wil be actived now
$random_id = rand(time(), 10000000); // create ID random for user
//let's insert all user data inside table
$sql2 = mysqli_query($conn, "INSERT INTO users (unique_id, fname, lname, email, password, img, status)
VALUES ({$random_id}, '{$fname}', '{$lname}', '{$email}', '{$password}', '{$new_img_name}', '{$status}')");
if($sql2){//if data inserted
$sql3 = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}'");
if(mysqli_num_rows($sql3) > 0){
$row = mysqli_fetch_assoc($sql3);
$_SESSION['unique_id'] = $row['unique_id'];//using this session we used user unique_id in another php file
echo "success";
}
} else{
echo "Something went wrong";
}
}
} else{
echo "Please select an image file - PNG, JPG, JPEG";
}
} else{
echo "Please upload a file";
}
}
} else{
echo "$email - This is not a valid email";
}
} else{
echo "All input are required";
}
?> | f8a81a60437b9f77ec172bc8b2ce62d2e30a2f31 | [
"PHP"
] | 1 | PHP | phunguyen58/ChatAppRealtime-JS-PHP-MySQL | 1598248c16318070cef514c2222ea7e60a7e1fb6 | a5ffe589ba1edac3ff5c5e572653e07984deb406 | |
refs/heads/master | <repo_name>qiaokang92/linux-desert<file_sep>/.bashrc
# quick navigation
export p4tutorials="~/p4-workspace/tutorials/P4D2_2018_East/exercises"
alias go2p4tutorials="cd $p4tutorials"
export hotcloud18="~/p4-workspace/Poise/HotCloud-2018/p4"
alias go2hotcloud18="cd $hotcloud18"
# commond commands
if [[ `uname` == 'Linux' ]]; then
alias ls="ls --color"
else
# MACOS X11 forwarding
export DISPLAY=:0
alias ls="ls -color"
fi
alias l="ls -hlF"
alias ll="ls -halF"
# vim
alias vim="vim -i NONE --noplugin"
# command prompt display
export PS1="[\[\e[32m\]#\##\[\e[31m\]\u@\[\e[36m\]\h:\w]\$\[\e[m\]"
# LANG config
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
# Tofino switch/server addresses
for i in `seq 1 9`; do
export NAME_SERVER_0${i}="ds0${i}.cs.rice.edu"
last=$(($i+5))
export IP_SERVER_0${i}="128.42.61.$last"
done
export IP_SERVER_10="172.16.17.32"
export NAME_SERVER_10="ds10.cs.rice.edu"
export IP_SWITCH="172.16.17.32"
export IP_MAC_OFFICE="10.211.179.42"
alias go2server01="ssh -Y qiaokang@$IP_SERVER_01"
alias go2server02="ssh -Y qiaokang@$IP_SERVER_02"
alias go2server10="ssh -Y qiaokang@$IP_SERVER_10"
# Private IP addresses for SDE VMs in ds01
export IP_SDE_86="192.168.122.246"
alias go2sde86="ssh qiaokang@$IP_SDE_86"
cd ~
export GEM_HOME="$HOME/gems"
export PATH="$HOME/gems/bin:$PATH"
alias go2host="ssh [email protected]"
alias go2vm="ssh [email protected]"
alias go2vm2="ssh [email protected]"
<file_sep>/README.md
# Linux Desert
This repo includes:
* a personalized vimrc file for kernel development using C/C++.
* a config file including frequently used info(e.g. hostnames, IPs, etc)
* a bashrc file for Ubuntu Linux
TODO
* a list of frequentely used apt software packages
<file_sep>/install-apts.sh
#!/bin/bash
sudo apt update
sudo apt install \
git \
python-pip \
net-tools \
vim \
| 82f6deb0c6a67224bdfad29ce9f7d70c6fb80e62 | [
"Markdown",
"Shell"
] | 3 | Shell | qiaokang92/linux-desert | 54222fbd423b40ebfd93e7d336c2a253b2f2b7c5 | de3954d671d34ad8ab14807b9b3f2ecab213c537 | |
refs/heads/master | <file_sep>/*!
* # Gremp
*
* `gremp` is a utility for searching for a string pattern in a file.
*/
use std::{
fs,
env,
error::Error,
};
pub struct Config {
pub pattern: String,
pub filename: String,
pub case_sensitive: bool,
}
impl Config {
pub fn new(
mut args: impl Iterator<Item=String>,
) -> Result<Self, &'static str> {
args.next();
let pattern = match args.next() {
Some(p) => p,
None => return Err("Didn't get pattern to match"),
};
let filename = match args.next() {
Some(f) => f,
None => return Err("Didn't get filename"),
};
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
Ok(Self { pattern, filename, case_sensitive })
}
}
/// Searches for a token in a string. It is case sensitive.
///
/// # Examples
///
/// ```
/// use gremp::*;
///
/// let pattern = "ust";
/// let contents = "Rust. Effective.\nWithout DUST.";
///
/// let result = search(pattern, contents);
///
/// assert_eq!(result, vec![(1, "Rust. Effective.")]);
/// ```
pub fn search<'a>(
pattern: &str,
contents: &'a str,
) -> Vec<(usize, &'a str)> {
contents.lines()
.enumerate()
.map(|(idx, line)| (idx + 1, line))
.filter(|(_, line)| line.contains(pattern))
.collect()
}
/// Searches for a token in a string. It is NOT case sensitive.
///
/// # Examples
///
/// ```
/// use gremp::*;
///
/// let pattern = "ust";
/// let contents = "Rust. Effective.\nWithout DUST.";
///
/// let result = search_case_insensitive(pattern, contents);
///
/// assert_eq!(result, vec![(1, "Rust. Effective."), (2, "Without DUST.")]);
/// ```
pub fn search_case_insensitive<'a>(
pattern: &str,
contents: &'a str,
) -> Vec<(usize, &'a str)> {
contents.lines()
.enumerate()
.map(|(idx, line)| (idx + 1, line))
.filter(|(_, line)| line.to_lowercase().contains(&pattern.to_lowercase()))
.collect()
}
/// Searches for a pattern in a file.
///
/// # Examples
///
/// ```
/// use gremp::*;
///
/// let args = vec![
/// String::from("/path/to/binary"),
/// String::from("pattern"),
/// String::from("sample.txt"),
/// ];
///
/// let config = Config::new(args.into_iter()).unwrap_or_else(|err| {
/// panic!(err);
/// });
///
/// let result = run(&config);
/// assert!(result.is_ok(), "Should have accepted input");
/// ```
pub fn run(
config: &Config
) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(&config.filename)?;
let results = if config.case_sensitive {
search(&config.pattern, &contents)
} else {
search_case_insensitive(&config.pattern, &contents)
};
for (line_no, line) in results {
println!("{}. {}", line_no, line);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_parses_cli_arguments() {
let args = vec![
String::from("/path/to/binary"),
];
let result = Config::new(args.into_iter());
assert!(result.is_err(), "Missing all arguments");
let args = vec![
String::from("/path/to/binary"),
String::from("pattern_here"),
];
let result = Config::new(args.into_iter());
assert!(result.is_err(), "Missing file argument");
}
#[test]
fn it_creates_a_config() {
let args = vec![
String::from("/path/to/binary"),
String::from("pattern"),
String::from("filename"),
];
let result = Config::new(args.into_iter());
assert!(result.is_ok(), "Should have accepted configuration");
}
#[test]
fn it_checks_file_existence() {
let args = vec![
String::from("/path/to/binary"),
String::from("pattern"),
String::from("filename"),
];
let config = Config::new(args.into_iter()).unwrap_or_else(|err| {
panic!(err);
});
let result = run(&config);
assert!(result.is_err(), "Specified file does not exist");
}
#[test]
fn it_searches_case_sensitive() {
let pattern = "duct";
let contents = "Rust:\nSafe, fast, productive.\nPick three.\nDuct tape.";
assert_eq!(
vec![
(2, "Safe, fast, productive."),
],
search(pattern, contents),
);
}
#[test]
fn it_searches_case_insensitive() {
let pattern = "rUsT";
let contents = "Rust:\nSafe, fast, productive.\nPick three.\nTrust me.";
assert_eq!(
vec![
(1, "Rust:"),
(4, "Trust me.",)
],
search_case_insensitive(pattern, contents),
);
}
#[test]
fn it_searches_in_file() {
let args = vec![
String::from("/path/to/binary"),
String::from("pattern"),
String::from("sample.txt"),
];
let config = Config::new(args.into_iter()).unwrap_or_else(|err| {
panic!(err);
});
let result = run(&config);
assert!(result.is_ok(), "Should have accepted input");
// Search case insensitive
env::set_var("CASE_INSENSITIVE", "1");
let args = vec![
String::from("/path/to/binary"),
String::from("pattern"),
String::from("sample.txt"),
];
let config = Config::new(args.into_iter()).unwrap_or_else(|err| {
panic!(err);
});
let result = run(&config);
assert!(result.is_ok(), "Should have accepted input");
}
}
<file_sep># Gremp #
> A minimal, nifty grep implementation.
## TODO
- [x] Tests util functions.
- [x] Robust documentation (Usage, how to install etc).
- [ ] Optimizations (e.g. read file into buffers or stream from a file).
- [ ] Capability to grep multiple files/directory.
- [ ] Command line flags for options.
- [x] Publish to a publish registry?? (crates.io)
<file_sep>[package]
name = "gremp"
license = "MIT"
description = "A minimal, nifty grep implementation."
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
| e748e50acb9b90d628b2ef82caf2693d3ce8a8b9 | [
"Markdown",
"Rust",
"TOML"
] | 3 | Rust | crispinkoech/gremp | 0ee4466c638966a9be8458e4c1e2921f994f0af5 | e6df004bd4d87114676228a811d82e7ca92bf532 | |
refs/heads/master | <repo_name>baicaiking0422/369A3<file_sep>/ext2_mkdir.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
#include "ext2_helper.h"
unsigned char *disk;
int main(int argc, const char * argv[]) {
/* Check arg */
if (argc != 3) {
fprintf(stderr, "Usage: ext2_mkdir <image file name> <abs path>\n");
exit(1);
}
int fd = open(argv[1], O_RDWR);
//record target path
char *path;
char *r_path;
int r_len;
int path_len;
path_len = strlen(argv[2]);
path = malloc(path_len + 1);
strncpy(path, argv[2], path_len);
path[path_len] = '\0';
r_len = strlen(argv[2]);
r_path = malloc(r_len + 1);
strncpy(r_path, argv[2], r_len);
r_path[r_len] = '\0';
if (path[0] != '/') {
fprintf(stderr, "This is not an absolute path!\n");
exit(1);
}
/* Map to memory */
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (disk == MAP_FAILED) {
perror("mmap");
exit(1);
}
struct ext2_group_desc * gd = (struct ext2_group_desc *)(disk + 2048);
void *inodes = disk + 1024 * gd->bg_inode_table;
int inode_num = get_inode_num(path, inodes, disk);
if (inode_num != -1) {
perror("The directory already exists.\n");
exit(EEXIST);
}
char *parent_path;
char *file_name;
struct ext2_inode *inode;
get_file_parent_path(r_path, &parent_path);
get_file_name(r_path, &file_name);
// parent dir inode num
inode_num = get_inode_num(parent_path, inodes, disk);
if (inode_num == -1) {
perror("The directory does not exist.\n");
exit(ENOENT);
}
// inode for parent path
inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + sizeof(struct ext2_inode) * (inode_num - 1));
//get inode and block bitmap
int *inode_bitmap = get_inode_bitmap(disk + 1024 * gd->bg_inode_bitmap);
int *block_bitmap = get_block_bitmap(disk + 1024 * gd->bg_block_bitmap);
//get a free new inode from inode bitmap
int new_inode_idx = -1;
int i;
for (i = 0; i < 32; i++) {
if (inode_bitmap[i] == 0) {
new_inode_idx = i;
break;
}
}
//check new node for copy file
if (new_inode_idx == -1){ // no free inode to assign
fprintf(stderr, "No free inode\n");
exit(1);
}
//get one free blocks from block bitmap for new dir
int *free_blocks = get_free_block(block_bitmap, 1);
//check free_blocks enough
if (free_blocks == NULL){
fprintf(stderr, "Not enough blocks in the disk\n");
exit(1);
}
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, *free_blocks, 1);
gd->bg_free_blocks_count --;
//assign new node
struct ext2_inode *n_inode = inodes + sizeof(struct ext2_inode) * new_inode_idx;
n_inode->i_mode = EXT2_S_IFDIR;
n_inode->i_size = EXT2_BLOCK_SIZE;
n_inode->i_links_count = 1;//change lnk?
n_inode->i_blocks = 2;
n_inode->i_block[0] = *free_blocks + 1;
set_inode_bitmap(disk + 1024 * gd->bg_inode_bitmap, new_inode_idx, 1);
gd->bg_free_inodes_count --;
//set to parent entry
int count;
struct ext2_dir_entry_2 *n_entry;
struct ext2_dir_entry_2 *past_entry;
struct ext2_dir_entry_2 *chk_entry;
int required_rec_len = ((7 + strlen(file_name)) / 4 + 1) * 4;
int dir_num_blocks = (inode->i_size - 1) / 1024 + 1;
int empty_rec_len = 0;
//not indirected
count = 0;
if (inode->i_block[dir_num_blocks - 1] != 0) {
while (count < 1024) {
chk_entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[dir_num_blocks-1] + count);
count += chk_entry->rec_len;
if (count == 1024) {
past_entry = chk_entry;
int final_entry_rec_len = ((7 + chk_entry->name_len) / 4 + 1) * 4;
empty_rec_len = chk_entry->rec_len - final_entry_rec_len;
break;
}
}
}
if ((empty_rec_len > 0) && (empty_rec_len >= required_rec_len)) {
past_entry->rec_len = ((7 + past_entry->name_len) / 4 + 1) * 4;
n_entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[dir_num_blocks-1] + (1024 - empty_rec_len));
n_entry->inode = new_inode_idx + 1;
n_entry->rec_len = empty_rec_len;
n_entry->name_len = strlen(file_name);
n_entry->file_type = EXT2_FT_DIR;
strncpy(n_entry->name, file_name, (int) n_entry->name_len +1);
n_entry->name[(int) n_entry->name_len +1] = '\0';
}
// not enough empty_rec_len for this entry, need to open a new block
if ((empty_rec_len = 0) || ((empty_rec_len > 0) && (empty_rec_len < required_rec_len))) {
int *n_free_block = get_free_block(block_bitmap, 1);
if (n_free_block == NULL){
fprintf(stderr, "No empty block\n");
exit(1);
}
inode->i_block[dir_num_blocks + 1] = *n_free_block;
n_entry =(struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[dir_num_blocks+1]);
n_entry->inode = new_inode_idx + 1;
n_entry->rec_len = 1024;
n_entry->name_len = strlen(file_name);
n_entry->file_type = EXT2_FT_DIR;
strncpy(n_entry->name, file_name, (int) n_entry->name_len +1);
n_entry->name[(int) n_entry->name_len +1] = '\0';
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, inode->i_block[dir_num_blocks+1], 1);
gd->bg_free_blocks_count --;
inode->i_size += 1024;
inode->i_blocks += 2;
}
struct ext2_dir_entry_2 *self_entry;
// Add .
self_entry = (struct ext2_dir_entry_2 *)(disk + 1024 * n_inode->i_block[0]);
self_entry->inode = new_inode_idx + 1;
self_entry->rec_len = 12;
self_entry->name_len = 1;
self_entry->file_type |= EXT2_FT_DIR;
strcpy(self_entry->name, ".");
// Add ..
self_entry = (struct ext2_dir_entry_2 *)(disk + 1024 * n_inode->i_block[0] + 12);
self_entry->inode = inode_num;
self_entry->rec_len = 1024 - 12;
self_entry->name_len = 2;
self_entry->file_type |= EXT2_FT_DIR;
strcpy(self_entry->name, "..");
return 0;
}
<file_sep>/readimage.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "ext2.h"
#include <string.h>
#include <strings.h>
unsigned char *disk;
void aaaa(int *a) {
*a += 1;
}
int main(int argc, char **argv) {
if(argc != 2) {
fprintf(stderr, "Usage: readimg <image file name>\n");
exit(1);
}
int fd = open(argv[1], O_RDWR);
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(disk == MAP_FAILED) {
perror("mmap");
exit(1);
}
struct ext2_super_block *sb = (struct ext2_super_block *)(disk + 1024);
struct ext2_group_desc *gd = (struct ext2_group_desc *)(disk + 2048);
struct ext2_dir_entry_2 *entry;
printf("Inodes: %d\n", sb->s_inodes_count);
printf("Blocks: %d\n", sb->s_blocks_count);
printf("Block group:\n");
printf("\tblock bitmap: %d\n", gd->bg_block_bitmap);
printf("\tinode bitmap: %d\n", gd->bg_inode_bitmap);
printf("\tinode table: %d\n", gd->bg_inode_table);
printf("\tfree blocks: %d\n", gd->bg_free_blocks_count);
printf("\tfree inodes: %d\n", gd->bg_free_inodes_count);
printf("\tused_dirs: %d\n", gd->bg_used_dirs_count);
int i, j, tmp;
printf("Block bitmap:");
for(i = 0; i < 16; i++) {
tmp = disk[gd->bg_block_bitmap * 1024 + i];
for(j = 0; j < 8; j++) {
if (tmp & 1)
printf("1");
else
printf("0");
tmp >>= 1;
}
printf(" ");
}
printf("\n");
printf("Inode bitmap:");
for(i = 0; i < 4; i++) {
tmp = disk[gd->bg_inode_bitmap * 1024 + i];
for(j = 0; j < 8; j++) {
if (tmp & 1)
printf("1");
else
printf("0");
tmp >>= 1;
}
printf(" ");
}
printf("\n\nInodes:\n");
int count;
char type;
for(i = 1; i < sb->s_inodes_count; i++) {
if(i < EXT2_GOOD_OLD_FIRST_INO && i != EXT2_ROOT_INO - 1) {
continue;
}
struct ext2_inode *inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + sizeof(struct ext2_inode) * i);
if ((inode->i_mode & EXT2_S_IFLNK) == EXT2_S_IFLNK) {
type = 'l';
} else if (inode->i_mode & EXT2_S_IFDIR) {
type = 'd';
} else if ((inode->i_mode & EXT2_S_IFREG) == EXT2_S_IFREG ) {
type = 'f';
}
if(inode->i_size != 0) {
printf("[%d] type: %c size: %d links: %d blocks: %d\n", i + 1, type, inode->i_size, inode->i_links_count, inode->i_blocks);
printf("[%d] Blocks: ", i + 1);
for(j = 0; j < 12; j++) {
if(inode->i_block[j] != 0)
printf(" %d", inode->i_block[j]);
}
if(inode->i_block[12] != 0) {
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[12]);
count = 0;
while(count < 1024 && disk[1024 * inode->i_block[12] + count] != 0) {
printf(" %d", disk[1024 * inode->i_block[12] + count]);
count += 4;
}
}
printf("\n");
}
}
char *name;
for(i = 0; i < sb->s_inodes_count; i++) {
if(i < EXT2_GOOD_OLD_FIRST_INO && i != EXT2_ROOT_INO - 1) {
continue;
}
struct ext2_inode *inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + 128 * i);
if(inode->i_mode & EXT2_S_IFREG) {
continue;
}
if(inode->i_size != 0) {
for(j = 0; j < 12; j++) {
if(inode->i_block[j] != 0) {
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[j]);
printf("\tDIR BLOCK NUM: %d (for inode %d)\n", inode->i_block[j], i + 1);
count = 0;
while(count < 1024) {
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[j] + count);
if (entry->file_type == EXT2_FT_REG_FILE) {
type = 'f';
} else if (entry->file_type == EXT2_FT_DIR) {
type = 'd';
} else if (entry->file_type == EXT2_FT_SYMLINK) {
type = 'l';
} else if (entry->file_type == EXT2_FT_UNKNOWN) {
type = 'u';
}
count += entry->rec_len;
name = malloc(sizeof(char) * (entry->name_len + 1));
strncpy(name, entry->name, entry->name_len);
name[entry->name_len] = '\0';
printf("Inode: %d rec_len: %d name_len: %d type= %c name=%s\n", entry->inode, entry->rec_len, entry->name_len, type, name);
free(name);
}
}
}
}
}
return 0;
}
<file_sep>/ext2_cp.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
#include "ext2_helper.h"
unsigned char *disk;
int main(int argc, const char * argv[]){
if (argc != 4) {
fprintf(stderr, "Usage: ext2_cp <image file name> <source file> <target path>\n");
exit(1);
}
//image fd
int fd = open(argv[1], O_RDWR);
//local file
int local_fd = open(argv[2], O_RDONLY);
if (local_fd == -1) {
fprintf(stderr, "This file does not exist.\n");
return ENOENT;
}
//local file size and required blocks
int file_size = lseek(local_fd, 0, SEEK_END);
int file_block_num = (file_size - 1) / EXT2_BLOCK_SIZE + 1;
int indirection = 0; // 0: no indirection, 1: indirection
if (file_block_num > 12){
indirection = 1;
file_block_num++;
}
//record target path
int path_len;
int r_path;
char *record_path;
char *path;
path_len = strlen(argv[3]);
r_path = strlen(argv[3]);
record_path = malloc(r_path+1);
path = malloc(path_len+1);
strncpy(record_path, argv[3],r_path);
record_path[r_path] = '\0';
strncpy(path, argv[3],path_len);
path[path_len] = '\0';
//record local filename
int lc_len;
char *lc_name;
lc_len = strlen(argv[2]);
lc_name = malloc(sizeof(char) * (lc_len + 1));
strncpy(lc_name, argv[2], lc_len);
lc_name[lc_len] = '\0';
// check absolute path
if (path[0] != '/') {
fprintf(stderr, "This is not an absolute path!");
exit(1);
}
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(disk == MAP_FAILED) {
perror("mmap");
exit(1);
}
struct ext2_group_desc * gd = (struct ext2_group_desc *)(disk + 2048);
void *inodes = disk + 1024 * gd->bg_inode_table;
//get inode and block bitmap
int *inode_bitmap = get_inode_bitmap(disk + 1024 * gd->bg_inode_bitmap);
int *block_bitmap = get_block_bitmap(disk + 1024 * gd->bg_block_bitmap);
struct ext2_inode *inode;
struct ext2_inode *check_inode;
// get inode number from absolute path
//check if already dir
// /a/c/ /a/c are different
int inode_num, inode_num_p, type_add;
char *file_name;
char *file_parent_path;
char *new_path;
type_add = 1;
//int new_path_len;
inode_num = get_inode_num(path, inodes, disk);
//inode for full path
check_inode = (struct ext2_inode *)(inodes + sizeof(struct ext2_inode) * (inode_num - 1));
// inode is file and already exist
if (inode_num != -1) {
// /abc/a
if (check_inode->i_mode & EXT2_S_IFREG || check_inode->i_mode & EXT2_S_IFLNK ){
perror("This file name existed.\n");
exit(EEXIST);
}
else if (check_entry_file(lc_name, check_inode, disk) == -1) {
perror("This file name existed2.\n");
exit(EEXIST);
}
type_add = 0;//find correct directory /abc/a or /abc/a/ type0
}
// not exist
if (inode_num == -1){
get_file_parent_path(record_path, &file_parent_path);
get_file_name(record_path, &file_name); //record file name
new_path = malloc(strlen(file_parent_path));
strcpy(new_path, file_parent_path); // record new path
inode_num_p = get_inode_num(new_path, inodes, disk);
if ((inode_num_p != -1) && (record_path[strlen(record_path) - 1] == '/')) {
fprintf(stderr, "Illegal target path for copy1\n");
return ENOENT;
}
// inode for parent path
inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + sizeof(struct ext2_inode) * (inode_num_p - 1));
//check parent path
//printf("%d\n",inode_num_p);
if (inode_num_p == -1) {
fprintf(stderr, "Illegal target path for copy2\n");
return ENOENT;
}
}
//get a free new inode from inode bitmap
int new_inode_idx = -1;
int i;
for (i = 0; i < 32; i++) {
if (inode_bitmap[i] == 0) {
new_inode_idx = i;
break;
}
}
//check new node for copy file
if (new_inode_idx == -1){ // no free inode to assign
fprintf(stderr, "No free inode\n");
exit(1);
}
//get free blocks from block bitmap
int *free_blocks = get_free_block(block_bitmap, file_block_num);
//check free_blocks enough
if (free_blocks == NULL){
fprintf(stderr, "Not enough blocks in the disk\n");
exit(1);
}
//copy local file
unsigned char* local_file = mmap(NULL, file_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, local_fd, 0);
if(local_file == MAP_FAILED) {
perror("mmap");
exit(1);
}
// copy local file to disk block
int j,k;
int total_size = file_size;
int record = 0;
// indirection and set reserved blocks
// if need to do indirection
if (indirection == 1){
for (j = 0; j < 12; j++){
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, free_blocks[j], 1);
gd->bg_free_blocks_count --;
if (total_size < EXT2_BLOCK_SIZE){
memcpy(disk + 1024 * (free_blocks[j] +1), local_file + record, total_size);
total_size = 0;
break;
}else{
memcpy(disk + 1024 * (free_blocks[j] +1), local_file + record, 1024);
total_size -= EXT2_BLOCK_SIZE;
record += EXT2_BLOCK_SIZE;
}
}
// set the last position to be the master idx to store blocks
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, free_blocks[12], 1);
gd->bg_free_blocks_count --;
for (j = 13; j < file_block_num; j++){
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, free_blocks[j], 1);
gd->bg_free_blocks_count --;
if (total_size < EXT2_BLOCK_SIZE){
memcpy(disk + 1024 * (free_blocks[j] +1), local_file + record, total_size);
total_size = 0;
break;
}else{
memcpy(disk + 1024 * (free_blocks[j] +1), local_file + record, 1024);
total_size -= EXT2_BLOCK_SIZE;
record += EXT2_BLOCK_SIZE;
}
}
disk[1024 * (free_blocks[12] + 1)] = free_blocks[12] + 1;
int idx = 4;
while (idx < 1024) {
for (k = 13; k < file_block_num; k++){
disk[1024 * (free_blocks[12] + 1) + idx] = free_blocks[k] + 1;
idx += 4;
}
disk[1024 * (free_blocks[12] + 1) + idx] = 0;
idx += 4;
}
}
// not indirection
// copy all file to block
if (indirection == 0){
for (j = 0; j < file_block_num; j++){
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, free_blocks[j], 1);
gd->bg_free_blocks_count --;
if (total_size < EXT2_BLOCK_SIZE){
memcpy(disk + 1024 * (free_blocks[j] +1), local_file + record, total_size);
total_size = 0;
break;
}else{
memcpy(disk + 1024 * (free_blocks[j] +1), local_file + record, 1024);
total_size -= EXT2_BLOCK_SIZE;
record += EXT2_BLOCK_SIZE;
}
}
}
//assign new node
struct ext2_inode *n_inode = inodes + sizeof(struct ext2_inode) * new_inode_idx;
//new_inode num = new_inode + 1
n_inode->i_mode = EXT2_S_IFREG;
n_inode->i_size = file_size;
n_inode->i_links_count = 1;
n_inode->i_blocks = file_block_num * 2;
int z;
for (z = 0; z < file_block_num; z++){
if (z > 11){
break;
}
n_inode->i_block[z] = free_blocks[z] + 1;
}
if (indirection == 1){
n_inode->i_block[12] = free_blocks[12] + 1;
}
set_inode_bitmap(disk + 1024 * gd->bg_inode_bitmap, new_inode_idx, 1);
gd->bg_free_inodes_count --;
//condition1: type0 use current path node
//condition2: type1 use parent path node with new name
//new entry for new file in parent dir
int count;
struct ext2_dir_entry_2 *n_entry;
struct ext2_dir_entry_2 *chk_entry;
struct ext2_dir_entry_2 *past_entry;
struct ext2_inode *dir_inode;
char *final_name;
if (type_add == 0) {
dir_inode = check_inode;
final_name = lc_name;
}
if (type_add == 1) {
dir_inode = inode;
final_name = file_name;
}
int required_rec_len = ((7 + strlen(final_name)) / 4 + 1) * 4;
int dir_num_blocks = (dir_inode->i_size - 1) / 1024 + 1;
int empty_rec_len = 0;
//not indirected
count = 0;
if (dir_inode->i_block[dir_num_blocks - 1] != 0) {
while (count < 1024) {
chk_entry = (struct ext2_dir_entry_2*)(disk + 1024 * dir_inode->i_block[dir_num_blocks-1] + count);
count += chk_entry->rec_len;
if (count == 1024) {
past_entry = chk_entry;
int final_entry_rec_len = ((7 + chk_entry->name_len) / 4 + 1) * 4;
empty_rec_len = chk_entry->rec_len - final_entry_rec_len;
break;
}
}
}
//not indirected
// enough empty rec_len for new entry name
if ((empty_rec_len > 0) && (empty_rec_len >= required_rec_len)) {
past_entry->rec_len = ((7 + past_entry->name_len) / 4 + 1) * 4;
n_entry = (struct ext2_dir_entry_2*)(disk + 1024 * dir_inode->i_block[dir_num_blocks-1] + (1024 - empty_rec_len));
n_entry->inode = new_inode_idx + 1;
n_entry->rec_len = empty_rec_len;
n_entry->name_len = strlen(final_name);
n_entry->file_type = EXT2_FT_REG_FILE;
strncpy(n_entry->name, final_name, (int) n_entry->name_len +1);
n_entry->name[(int) n_entry->name_len +1] = '\0';
}
// not enough empty_rec_len for this entry, need to open a new block
if ((empty_rec_len = 0) || ((empty_rec_len > 0) && (empty_rec_len < required_rec_len))) {
int *n_free_block = get_free_block(block_bitmap, 1);
if (n_free_block == NULL){
fprintf(stderr, "No empty block\n");
exit(1);
}
//get a new block and then set new entry
dir_inode->i_block[dir_num_blocks + 1] = *n_free_block;
n_entry =(struct ext2_dir_entry_2*)(disk + 1024 * dir_inode->i_block[dir_num_blocks+1]);
n_entry->inode = new_inode_idx + 1;
n_entry->rec_len = 1024;
n_entry->name_len = strlen(final_name);
n_entry->file_type = EXT2_FT_REG_FILE;
strncpy(n_entry->name, final_name, (int) n_entry->name_len +1);
n_entry->name[(int) n_entry->name_len +1] = '\0';
set_block_bitmap(disk + 1024 * gd->bg_block_bitmap, dir_inode->i_block[dir_num_blocks+1], 1);
gd->bg_free_blocks_count --;
dir_inode->i_size += 1024;
dir_inode->i_blocks += 2;
}
return 0;
}
<file_sep>/ext2_mkdir copy.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
#include "ext2_helper.h"
unsigned char *disk;
int main(int argc, const char * argv[]) {
/* Check arg */
if (argc != 3) {
fprintf(stderr, "Usage: ext2_mkdir <image file name> <abs path>\n");
exit(1);
}
int fd = open(argv[1], O_RDWR);
char *path;
path = malloc(strlen(argv[2]));
strcpy(path, argv[2]);
if (path[0] != '/') {
fprintf(stderr, "This is not an absolute path!\n");
exit(1);
}
/* Map to memory */
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (disk == MAP_FAILED) {
perror("mmap");
exit(1);
}
struct ext2_group_desc * gd = (struct ext2_group_desc *)(disk + 2048);
void *inodes = disk + 1024 * gd->bg_inode_table;
int inode_num = get_inode_num(path, inodes, disk);
if (inode_num != -1) {
perror("The directory already exists.\n");
exit(EEXIST);
}
char *parent_path;
char *file_name;
get_file_parent_path(path, &parent_path);
inode_num = get_inode_num(parent_path, inodes, disk);
if (inode_num == -1) {
perror("The directory does not exist.\n");
exit(ENOENT);
}
int i, j, k, l, tmp, set;
set = 0;
for (k = 0; k < 16; k ++) {
tmp = disk[gd->bg_block_bitmap * 1024 + k];
for (l = 0; l < 8; l ++) {
if (!(tmp & 1)) {
// printf("k: %d\tj: %d\n", k, l);
set_block_bitmap(&disk[gd->bg_block_bitmap * 1024 + k], l, 1);
gd->bg_free_blocks_count ++;
set = 1;
break;
}
tmp >>= 1;
}
if (set) break;
}
set = 0;
for (i = 0; i < 16; i ++) {
tmp = disk[gd->bg_inode_bitmap * 1024 + i];
for (j = 0; j < 8; j ++) {
if (!(tmp & 1)) {
set_inode_bitmap(&disk[gd->bg_inode_bitmap * 1024 + i], j, 1);
gd->bg_free_inodes_count ++;
set = 1;
break;
}
tmp >>= 1;
}
if (set) break;
}
struct ext2_inode *inode;
inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + 128 * (i * 8 + j));
inode->i_size = 1;
inode->i_mode |= EXT2_S_IFDIR;
int inode_block_num;
struct ext2_dir_entry_2 *entry;
inode_block_num = 0;
// Add .
inode->i_block[0] = k * 8 + l;
entry = (struct ext2_dir_entry_2 *)(disk + 1024 * inode->i_block[0]);
entry->inode = i * 8 + j + 1;
entry->rec_len = 12;
entry->name_len = 1;
entry->file_type |= EXT2_FT_DIR;
strcpy(entry->name, ".");
// Add ..
entry = (struct ext2_dir_entry_2 *)(disk + 1024 * inode->i_block[0] + 12);
entry->inode = inode_num;
entry->rec_len = 1024 - 12;
entry->name_len = 2;
entry->file_type |= EXT2_FT_DIR;
strcpy(entry->name, "..");
// Add Entry in its parent node
struct ext2_inode *parent_inode;
parent_inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + sizeof(struct ext2_inode) * (inode_num - 1));
int count, timeout;
count = 0;
timeout = 0;
while (count < 1024) {
entry = (struct ext2_dir_entry_2 *)(disk + 1024 * parent_inode->i_block[0] + count);
if (count + entry->rec_len >= 1024) {
// If it is the last one
entry->rec_len = ((7 + entry->name_len) / 4 + 1) * 4;
count += entry->rec_len;
break;
}
count += entry->rec_len;
timeout ++;
if (timeout > 10) {
printf("Timeout, break.\n");
break;
}
}
// Entry for the new directory
entry = (struct ext2_dir_entry_2 *)(disk + 1024 * parent_inode->i_block[0] + count);
entry->file_type |= EXT2_FT_DIR;
entry->rec_len = 1024 - count;
get_file_name(path, &file_name);
entry->name_len = strlen(file_name);
strncpy(entry->name, file_name, entry->name_len);
entry->inode = i * 8 + j + 1;
}
<file_sep>/ext2_helper.h
#ifndef ext2_helper_h
#define ext2_helper_h
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
/*
* Get inode number with a path.
*
*/
int get_inode_num(char *path, void *inodes, unsigned char *disk);
/*
* Seperate file path and get the file name.
*
*/
void get_file_name(char *file_path, char **file_name);
/*
* Seperate file path and get the parent path of this file.
*
*/
void get_file_parent_path(char *file_path, char **file_parent_path);
/*
* Get an inode bitmap from disk
*/
int *get_inode_bitmap(void *inode_info);
/*
* Get a block bitmap from disk
*/
int *get_block_bitmap(void *block_info);
/*
* Get an array of free block index with block bitmap
*/
int *get_free_block(int *block_bitmap, int needed_num_blocks);
/*
* Set bit to 0 or 1 on inode bitmap
*/
void set_inode_bitmap(void *inode_info, int inode_num, int bit);
/*
* Set bit to 0 or 1 on block bitmap
*/
void set_block_bitmap(void *block_info, int block_num, int bit);
/*
* Check where inode has already get the local file entry
*/
int check_entry_file(char *lc_file, struct ext2_inode *check_inode, unsigned char *disk);
#endif /* ext2_helper_h */
<file_sep>/ext2_helper.c
//
// ext2_helper.c
//
//
#include "ext2_helper.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
/*
* Get an inode index with path from disk
*/
int get_inode_num(char *path, void *inodes, unsigned char *disk){
int cur_inode_num = EXT2_ROOT_INO;
int new_inode_num;
int check_exist = -1;
int count;
char *name;
char *token;
//int inode_block_num;
token = strtok(path, "/");
struct ext2_inode *inode;
struct ext2_dir_entry_2 *entry;
if (strcmp(path, "/") == 0){
return cur_inode_num;
}
new_inode_num = cur_inode_num;
while (token != NULL){
//printf("%s\n", token);
check_exist = -1;
inode = (struct ext2_inode *)(inodes + (new_inode_num - 1) * sizeof(struct ext2_inode));
//inode->i_size?
if (inode->i_size != 0) {
count = 0;
int i;
for (i = 0; i < 12; i ++) {
if (inode->i_block[i] != 0) {
while (count < 1024) {
entry = (struct ext2_dir_entry_2*)(disk+1024 * inode->i_block[i] + count);
count += entry->rec_len;
name = malloc(sizeof(char) * (entry->name_len+1));
strncpy(name, entry->name, entry->name_len);
name[entry->name_len] = '\0';
if (strcmp(token, name) == 0) {
new_inode_num = entry->inode;
check_exist = 0;
break;
}
}
}
}
// indirection
if (inode->i_block[12] != 0){
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[12]);
count = 4;
while (count < 1024 && (disk[1024 * inode->i_block[12] + count] != 0)){
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[12] + count);
count += 4;
name = malloc(sizeof(char) * (entry->name_len+1));
strncpy(name, entry->name, entry->name_len);
name[entry->name_len] = '\0';
if (strcmp(token, name) == 0){
new_inode_num = entry->inode;
check_exist = 0;
break;
}
}
}
}
free(name);
// check whether this token exists in entries of this inode
if (check_exist == -1) {
return -1;
}
token = strtok(NULL, "/");
}
if (check_exist == 0) {
return new_inode_num;
}
else {
return -1;
}
}
/*
* Seperate original path to a parent directory path
*/
void get_file_name(char *file_path, char **file_name) {
int i;
i = strlen(file_path) - 1;
if (file_path[i] != '/'){
while (i >= 0 && file_path[i] != '/') {
i--;
}
*file_name = malloc(sizeof(char) * (strlen(file_path) - i));
strncpy(*file_name, file_path + i + 1, strlen(file_path) - i);
} else {
while (i >= 0 && file_path[i-1] != '/') {
i--;
}
*file_name = malloc(sizeof(char) * (strlen(file_path) - i - 1));
strncpy(*file_name, file_path + i, strlen(file_path) - i - 1);
}
//return file_name;
}
/*
* Seperate original path to a file path
*/
void get_file_parent_path(char *file_path, char **file_parent_path){
int i;
i = strlen(file_path) - 1;
if (file_path[i] != '/'){
while (i >= 0 && file_path[i] != '/') {
i--;
}
*file_parent_path = malloc(sizeof(char) * (i + 1 + 1));
strncpy(*file_parent_path, file_path, i +1);
(*file_parent_path)[i+1] = '\0';
}else{
i--;
while (i >= 0 && file_path[i] != '/') {
i--;
}
*file_parent_path = malloc(sizeof(char) * (i + 1 + 1));
strncpy(*file_parent_path, file_path, i + 1);
(*file_parent_path)[i+1]= '\0';
}
} //return file_parent_path;
/*
* Get an inode bitmap from disk
*/
int *get_inode_bitmap(void *inode_info){
int *inode_bitmap = malloc(sizeof(int) * 32);
int i;
for (i = 0; i < 32; i++) {
char *byte = inode_info + (i / 8);
inode_bitmap[i] = (*byte >> (i % 8)) & 1;
}
return inode_bitmap;
}
/*
* Get a block bitmap from disk
*/
int *get_block_bitmap(void *block_info){
int *block_bitmap = malloc(sizeof(int) * 128);
int i;
for (i = 0; i < 128; i++) {
char *byte = block_info + (i / 8);
block_bitmap[i] = (*byte >> (i % 8)) & 1;
}
return block_bitmap;
}
/*
* Get an array of free block index with block bitmap
*/
int *get_free_block(int *block_bitmap, int needed_num_blocks){
int i, j;
j = 0;
int *new_blocks = malloc(sizeof(int) * needed_num_blocks);
for (i = 0; i < needed_num_blocks; i ++) {
while (block_bitmap[j] != 0) {
j++;
if (j == 128) {
return NULL;
}
}
new_blocks[i] = j;
j++;
}
return new_blocks;
}
/*
* Set bit to 0 or 1 on inode bitmap
*/
void set_inode_bitmap(void *inode_info, int inode_num, int bit){
int byte = inode_num / 8;
int i_bit = inode_num % 8;
char *change = inode_info + byte;
*change = (*change & ~(1 << i_bit)) | (bit << i_bit);
}
/*
* Set bit to 0 or 1 on block bitmap
*/
void set_block_bitmap(void *block_info, int block_num, int bit){
int byte = block_num / 8;
int b_bit = block_num % 8;
char *change = block_info + byte;
*change = (*change & ~(1 << b_bit)) | (bit << b_bit);
}
/*
* Check where inode has already get the local file entry
*/
int check_entry_file(char *lc_file, struct ext2_inode *check_inode, unsigned char *disk){
int i, count;
char *name;
struct ext2_dir_entry_2 *entry;
if (check_inode->i_size != 0) {
count = 0;
for (i = 0; i < 12; i++) {
if (check_inode->i_block[i] != 0) {
while (count < 1024) {
entry = (struct ext2_dir_entry_2*)(disk + 1024 * check_inode->i_block[i] + count);
count += entry->rec_len;
if (entry->file_type == EXT2_FT_REG_FILE){
name = malloc(sizeof(char) * (entry->name_len+1));
strncpy(name, entry->name, entry->name_len);
name[entry->name_len] = '\0';
if (strcmp(lc_file, name) == 0) {
return -1;
}
}
}
}
}
return 0;
}
return 1;
}
<file_sep>/ext2_rm.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
#include "ext2_helper.h"
unsigned char *disk;
int main(int argc, const char * argv[]) {
/* Check arg */
if (argc != 3) {
fprintf(stderr, "Usage: ext2_mkdir <image file name> <abs path>\n");
exit(1);
}
/* Open */
int fd = open(argv[1], O_RDWR);
char *path;
path = malloc(strlen(argv[2]));
strcpy(path, argv[2]);
if (path[0] != '/') {
fprintf(stderr, "This is not an absolute path!\n");
exit(1);
}
/* Map to memory */
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (disk == MAP_FAILED) {
perror("mmap");
exit(1);
}
struct ext2_group_desc * gd = (struct ext2_group_desc *)(disk + 2048);
void *inodes = disk + 1024 * gd->bg_inode_table;
char *parent_path;
char *file_name;
get_file_parent_path(path, &parent_path);
get_file_name(path, &file_name);
int inode_num = get_inode_num(parent_path, inodes, disk);
if (inode_num == -1) {
perror("The file does not exist.\n");
exit(ENOENT);
}
struct ext2_inode *inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + sizeof(struct ext2_inode) * (inode_num - 1));
struct ext2_dir_entry_2 *entry;
struct ext2_dir_entry_2 *next_entry;
int count, timeout, offset, found;
char *name;
count = 0;
timeout = 0;
offset = 0;
found = 0;
while (count < 1024) {
entry = (struct ext2_dir_entry_2 *)(disk + 1024 * inode->i_block[0] + count);
count += entry->rec_len;
next_entry = (struct ext2_dir_entry_2 *)(disk + 1024 * inode->i_block[0] + count);
name = malloc(sizeof(char) * next_entry->name_len + 1);
strncpy(name, next_entry->name, next_entry->name_len);
name[next_entry->name_len] = '\0';
// If found
if (strcmp(file_name, name) == 0) {
found = 1;
// If not a regular file
if (next_entry->file_type & EXT2_S_IFREG) {
perror("This is not a regular file.\n");
exit(ENOENT);
}
// If is a regular file
entry->rec_len += next_entry->rec_len;
next_entry->rec_len = 0;
next_entry->name_len = 0;
strcpy(next_entry->name, "");
next_entry->inode = 0;
}
free(name);
timeout ++;
if (timeout > 10) {
break;
}
}
/* If the file does not exist. */
if (!found) {
perror("The file does not exist.\n");
exit(ENOENT);
}
}
<file_sep>/Makefile
FLAGS = -Wall -g -std=c99
all : ext2_ls ext2_mkdir ext2_rm ext2_cp ext2_ln
ext2_ls: ext2_ls.o ext2_helper.o
gcc ${FLAGS} -o ext2_ls ext2_ls.o ext2_helper.o
ext2_mkdir: ext2_mkdir.o ext2_helper.o
gcc ${FLAGS} -o ext2_mkdir ext2_mkdir.o ext2_helper.o
ext2_rm: ext2_rm.o ext2_helper.o
gcc ${FLAGS} -o ext2_rm ext2_rm.o ext2_helper.o
ext2_cp: ext2_cp.o ext2_helper.o
gcc ${FLAGS} -o ext2_cp ext2_cp.o ext2_helper.o
ext2_ln: ext2_ln.o ext2_helper.o
gcc ${FLAGS} -o ext2_ln ext2_ln.o ext2_helper.o
ext2_helper.o: ext2_helper.c ext2_helper.h ext2.h
gcc ${FLAGS} -c ext2_helper.c
ext2_ls.o: ext2_ls.c ext2.h ext2_helper.h
gcc ${FLAGS} -c ext2_ls.c
ext2_mkdir.o: ext2_mkdir.c ext2.h ext2_helper.h
gcc ${FLAGS} -c ext2_mkdir.c
ext2_rm.o: ext2_rm.c ext2.h ext2_helper.h
gcc ${FLAGS} -c ext2_rm.c
ext2_cp.o: ext2_cp.c ext2.h ext2_helper.h
gcc ${FLAGS} -c ext2_cp.c
ext2_ln.o: ext2_ln.c ext2.h ext2_helper.h
gcc ${FLAGS} -c ext2_ln.c
clean:
rm *.o ext2_ls ext2_cp ext2_mkdir ext2_rm ext2_ln
<file_sep>/ext2_ls.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
#include "ext2_helper.h"
unsigned char *disk;
int main(int argc, const char * argv[]) {
/* check correct path*/
if((argc != 3) && (argc != 4)) {
fprintf(stderr, "Usage: readimg <image file name> <abs path>\n");
exit(1);
}
/* list all */
if (argc == 4 && (strcmp(argv[2], "-a") != 0)) {
fprintf(stderr, "Wrong command\n");
exit(1);
}
/* Read and record path*/
int fd = open(argv[1], O_RDWR);
int path_len;
char *path;
char *record_path;
int r_path;
if (argc == 4 && (strcmp(argv[2], "-a") == 0)) {
path_len = strlen(argv[3]);
r_path = strlen(argv[3]);
record_path = malloc(r_path+1);
path = malloc(path_len+1);
strncpy(record_path, argv[3],r_path);
record_path[r_path] = '\0';
strncpy(path, argv[3],path_len);
path[path_len] = '\0';
}
if (argc == 3) {
path_len = strlen(argv[2]);
r_path = strlen(argv[2]);
record_path = malloc(r_path+1);
path = malloc(path_len+1);
strncpy(record_path, argv[2],r_path);
record_path[r_path] = '\0';
strncpy(path, argv[2],path_len);
path[path_len] = '\0';
}
if (path[0] != '/') {
fprintf(stderr, "This is not an absolute path!\n");
exit(1);
}
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(disk == MAP_FAILED) {
perror("mmap");
exit(1);
}
struct ext2_group_desc * gd = (struct ext2_group_desc *)(disk + 2048);
void *inodes = disk + 1024 * gd->bg_inode_table;
/* Test full pat*/
int inode_num = get_inode_num(path, inodes, disk);
if (inode_num == -1) {
fprintf(stderr, "The directory or file does not exist.\n");
return ENOENT;
}
struct ext2_inode *inode = (struct ext2_inode *)(disk + 1024 * gd->bg_inode_table + sizeof(struct ext2_inode) * (inode_num - 1));
if (inode->i_mode & EXT2_S_IFREG || inode->i_mode & EXT2_S_IFLNK){
char *file_name;
get_file_name(record_path, &file_name);
printf("%s\n", file_name);
return 0;
}
if (inode -> i_size != 0) {
int inode_block_num;
int count;
char *name;
int check;
struct ext2_dir_entry_2 *entry;
/* print all entry name*/
for (inode_block_num = 0; inode_block_num < 12; inode_block_num ++) {
count = 0;
check = 0;
if (inode->i_block[inode_block_num] != 0) {
while (count < 1024) {
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode -> i_block[inode_block_num] + count);
count += entry->rec_len;
check ++;
name = malloc(sizeof(char) * (entry->name_len+1));
strncpy(name, entry->name, entry->name_len);
name[entry->name_len] = '\0';
/* if -a, need to printf . & ..*/
if (argc == 4) {
printf("%s", name);
if (entry->rec_len != 1024) {
printf("\n");
}
}
else {
if (check >= 3) {
printf("%s", name);
if (entry -> rec_len != 1024) {
printf("\n");
}
}
}
}
}
}
/* indirection part */
if (inode->i_block[12] != 0){
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[12]);
count = 4;
while (count < 1024 && (disk[1024 * inode->i_block[12] + count != 0])) {
entry = (struct ext2_dir_entry_2*)(disk + 1024 * inode->i_block[12] + count);
count += 4;
name = malloc(sizeof(char) * (entry->name_len + 1));
strncpy(name, entry->name, entry->name_len);
name[entry->name_len] = '\0';
printf("%s\n",name);
}
}
}
return 0;
}
<file_sep>/ext2_ln.c
//
// ext2_ln.c
//
//
// Created by <NAME> on 2016-07-28.
//
//
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "ext2.h"
#include "ext2_helper.h"
// helper functions, better write in ext2_helper but there is a warning when compile it, might relate to C99
// if have time find a way to put it back to helper
unsigned char *disk;
int find_dirn(char* list, char* buf) {
int i, j;
if (list[0] != '/') {
return -1;
}
for (i = 1, j = 0; list[i] != '/'; i++, j++) {
if (list[i] == '\0') {
break;
}
buf[j] = list[i];
}
buf[j] = '\0';
return i;
}
int find_dir_inode(char* query, void* inodes) {
struct ext2_inode* inode;
struct ext2_dir_entry_2* dir;
int n_inode = EXT2_ROOT_INO;
int n_block;
char buf[512];
while (1) {
inode = (struct ext2_inode*)
(inodes + (n_inode - 1) * sizeof(struct ext2_inode));
int total_size = inode->i_size;
if (strcmp(query, "/") == 0) {
return n_inode - 1;
}
if (strcmp(query, "") == 0) {
query[1] = '\0';
query[0] = '/';
}
int n = find_dirn(query, buf);
query += n;
int new_n_inode = -1;
int n_blockidx = 0;
int size = 0;
n_block = inode->i_block[n_blockidx];
dir = (struct ext2_dir_entry_2*)(disk + EXT2_BLOCK_SIZE * n_block);
while (size < total_size) {
size += dir->rec_len;
if (dir->file_type == EXT2_FT_DIR) {
if (strlen(buf) == dir->name_len &&
strncmp(buf, dir->name, dir->name_len) == 0) {
new_n_inode = dir->inode;
break;
}
}
dir = (void*)dir + dir->rec_len;
if (size % EXT2_BLOCK_SIZE == 0) {
n_blockidx++;
n_block = inode->i_block[n_blockidx];
dir = (struct ext2_dir_entry_2*)(disk + EXT2_BLOCK_SIZE * n_block);
}
}
if (new_n_inode == -1) {
return -1;
} else {
n_inode = new_n_inode;
}
}
}
/*
detach a file
*/
void file_detach(char* path, char* name) {
int length = strlen(path);
int counter = length - 1;
while (path[counter] != '/') {
counter--;
}
int len_n = length - 1 - counter;
strncpy(name, path + length - len_n, len_n + 1);
if (counter != 0) {
path[counter] = '\0';
} else {
path[counter + 1] = '\0';
}
}
int main(int argc, char **argv) {
if ((argc != 4) && (argc != 5)) {
fprintf(stderr, "Usage: ext2_ln <image file name> <source path> <target path>\n");
exit(1);
}
if ((argc == 5) && strcmp(argv[2], "-a") != 0) {
fprintf(stderr, "Wrong command\n");
}
int fd = open(argv[1], O_RDWR);
char* src;
char* des;
if (argc == 4) {
src = argv[2];
des = argv[3];
}
if (argc == 5) {
src = argv[3];
des = argv[4];
}
src = argv[2];
des = argv[3]; // how to put these in an if statement???
// error checking => if either location refers to a directory (EISDIR)
if (src[strlen(src) - 1] == '/' || des[strlen(src) - 1] == '/'){
errno = EISDIR;
if (src[strlen(src) - 1] == '/') {
perror(src);
} else {
perror(des);
}
exit(errno);
}
// error checking => absolute path TODO: Is the check necessary?
if (src[0] != '/' || des[0] != '/') {
fprintf(stderr, "not absolute path\n");
exit(1);
}
int i;
char src_n[1024];
char des_n[1024];
int src_nlength;
int des_nlength;
file_detach(src, src_n);
file_detach(des, des_n);
src_nlength = strlen(src_n);
des_nlength = strlen(des_n);
// map disk to memory
disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
struct ext2_group_desc* gd = (void*)disk + 1024 + EXT2_BLOCK_SIZE;
void* inodes = disk + EXT2_BLOCK_SIZE * gd->bg_inode_table;
void* block_bitmaploc = disk + EXT2_BLOCK_SIZE * gd->bg_block_bitmap;
int* block_bitmap = get_block_bitmap(block_bitmaploc);
// error checking => in case map Failed
if (disk == MAP_FAILED) {
perror("mmap map failed\n");
exit(1);
}
// find src dir, des dir
int src_inodeidx = find_dir_inode(src, inodes); //TODO: move find_dir_inode
int des_inodeidx = find_dir_inode(des, inodes); //TODO: move find_dir_inode
// error checking =>
if (src_inodeidx < 0 || des_inodeidx < 0) {
errno = ENOENT;
if (src_inodeidx < 0) {
perror(src);
}
if (des_inodeidx < 0) {
perror(des);
}
exit(errno);
}
int desf_inodeidx = -1;
struct ext2_inode* des_inode = des_inodeidx * sizeof(struct ext2_inode) + inodes;
int des_num_blocks = des_inode->i_size / EXT2_BLOCK_SIZE;
int block_pos;
struct ext2_dir_entry_2* dir;
for (i = 0; i < des_num_blocks; i++) {
block_pos = des_inode->i_block[i];
dir = (void*)dir + EXT2_BLOCK_SIZE * block_pos;
int size = 0;
while (size < EXT2_BLOCK_SIZE) {
size += dir->rec_len;
if (des_nlength == dir->name_len && strncmp(des_n, dir->name, des_nlength) == 0) {
desf_inodeidx = dir->inode - 1;
break;
}
dir = (void*)dir + dir->rec_len;
}
if (desf_inodeidx != -1) {
break;
}
}
// error checking => file is already in directory
if (desf_inodeidx != -1) {
errno = EEXIST;
perror(des_n);
exit(errno);
}
// find the source file in source directory
int srcf_inodeidx = -1;
struct ext2_inode* src_inode = inodes + src_inodeidx * sizeof(struct ext2_inode);
int src_num_blocks = src_inode->i_size / EXT2_BLOCK_SIZE;
for (i = 0; i < src_num_blocks; i++) {
block_pos = src_inode->i_block[i];
dir = (void*)disk + EXT2_BLOCK_SIZE * block_pos;
int size = 0;
while (size < EXT2_BLOCK_SIZE) {
size += dir->rec_len;
if (des_nlength == dir->name_len && strncmp(des_n, dir->name, des_nlength) == 0) {
if (dir->file_type == EXT2_FT_REG_FILE) {
srcf_inodeidx = dir->inode - 1;
break;
}
}
dir = (void*)dir + dir->rec_len;
}
if (srcf_inodeidx != -1) {
break;
}
}
// error checking => file not in directory
if (srcf_inodeidx == -1) {
errno = ENOENT;
perror(src_n);
exit(errno);
}
int exist = 1;
int req_size = ((des_nlength - 1)/4+1)*4+8;
for (i = 0; i < des_num_blocks; i++) {
block_pos = des_inode->i_block[i];
dir = (void*)disk + block_pos * EXT2_BLOCK_SIZE;
int size = 0;
while (size < EXT2_BLOCK_SIZE) {
size += dir->rec_len;
if (size == EXT2_BLOCK_SIZE){
if ((dir->rec_len) >= req_size + 8 + ((dir->name_len - 1)/4+1)*4) {
exist = 0;
break;
}
}
dir = (void*)dir + dir->rec_len;
}
if (exist == 0) {
break;
}
}
if (exist == 1) { // not found in this case
block_bitmap = get_block_bitmap(block_bitmaploc);
int* free_block = get_free_block(block_bitmap, 1);
if (free_block == NULL) {
errno = ENOSPC;
perror("not enough free block\n");
exit(errno);
}
int idx_temp = *free_block;
dir = (void*)disk + EXT2_BLOCK_SIZE * (idx_temp + 1);
dir->inode = srcf_inodeidx + 1;
dir->file_type = EXT2_FT_REG_FILE;
dir->rec_len = EXT2_BLOCK_SIZE;
dir->name_len = des_nlength;
strncpy((void*)dir + 8, des_n, des_nlength);
set_block_bitmap(block_bitmaploc, idx_temp, 1);
des_inode->i_size += EXT2_BLOCK_SIZE;
des_inode->i_blocks += 2;
des_inode->i_block[des_num_blocks] = idx_temp + 1;
} else {
int prev = dir->rec_len;
int cls = ((dir->name_len -1)/4+1)*4+8;
dir->rec_len = cls;
dir = (void*)dir + cls;
dir->inode = srcf_inodeidx + 1;
dir->file_type = EXT2_FT_REG_FILE;
dir->rec_len = prev - cls;
dir->name_len = des_nlength;
strncpy((void*)dir + 8, des_n, des_nlength);
}
// dont forget to update the count of links
struct ext2_inode* inode = inodes + sizeof(struct ext2_inode) * srcf_inodeidx;
inode->i_links_count++;
return 0;
}
| 4b7a87a0ec8e5c340c55a912f8d33986b4ab3831 | [
"C",
"Makefile"
] | 10 | C | baicaiking0422/369A3 | a33bce9711771433aa3be8046adb889c6435a21d | d07ef40496cb902ee643c6b954545a70837d334d | |
refs/heads/master | <file_sep>import java.util.Random;
public enum BaseColor {
Red,
Green,
Black,
Orange,
White,
Purple,
Haze,
Nutella,
Banana,
Ice,
Mat,
XYZ,
Space,
A41,
B56,
C8585,
D90,
Zwart,
Groy,
Pop,
Blue;
/**
* Pick a random value of the BaseColor enum.
* @return a random BaseColor.
*/
public static BaseColor getRandomColor() {
Random random = new Random();
return values()[random.nextInt(values().length)];
}
}<file_sep>import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import com.google.common.util.concurrent.Striped;
public class App {
static ExecutorService service = Executors.newFixedThreadPool(100);
static final int SIZE = 10;
static final int LOOP = 100;
static final int TASK_COUNT = 1000;
static List<Bag> bags = new ArrayList<>();
static final Object mtx = new Object();
static Striped<Lock> stripedLocks = Striped.lock(SIZE); // total number of Locks
public static void main(String[] args) {
populateBags();
distribute();
dispose();
checkBagsForRaceCondition();
}
static void checkBagsForRaceCondition() {
for (Bag bag : bags) {
if(bag.getColors().size() > BaseColor.values().length) {
System.out.println(bag.toString());
}
}
}
static void distribute() {
for(int j = 0; j < LOOP; j++) {
System.out.println("Tasking...");
for (int i = 0; i < TASK_COUNT; i++) {
service.submit(new Runnable() {
@Override
public void run() {
int index = (int) (Math.random() * SIZE);
BaseColor color = BaseColor.getRandomColor();
Bag bag = bags.get(index);
// Better memory footprints compared to creating a new lock per runnable, good throughput
Lock lock = stripedLocks.get(bag.getIndex());
lock.lock();
if (!bag.containsItem(color)) {
bag.addItem(new Item(color));
}
lock.unlock();
/* One lock for all runnables -> bad throughput, less efficient
synchronized(mtx) {
if (!bag.containsItem(color)) {
bag.addItem(new Item(color));
}
}
*/
}
});
}
}
}
static void dispose() {
System.out.println("Shutting down...");
try {
service.shutdown();
if (!service.awaitTermination(10000, TimeUnit.MILLISECONDS)) {
System.out.println("Shutting down with awating...");
service.shutdownNow();
}
} catch (InterruptedException e) {
System.out.println("Shutting down with exception...");
service.shutdownNow();
}
}
static void populateBags() {
bags.clear();
System.out.println("Populating bags...");
for (int i = 0; i < SIZE; i++) {
bags.add(new Bag(i));
}
}
}
<file_sep># StripedLock Usage
Sample usage of Striped lock's from Guava library. | b9d259808497a322a149d06e913e4e460bbd89ce | [
"Markdown",
"Java"
] | 3 | Java | atapazvant/StripedLock | 84e19ced09ed7f5c00308eaf84163dbe63d49fd6 | 59676edcd235a019a1dc01d15b03ba726921118b | |
refs/heads/master | <repo_name>andychen199/Student-management-system<file_sep>/src/attendance/dao/TeachDao.java
package attendance.dao;
//任职记录DAO,给管理员看的
import java.sql.*;
import javax.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import attendance.bean.Course;
import attendance.bean.Teach;
import attendance.bean.TeachforUI;;
public class TeachDao {
public TeachDao(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
}
public Connection getConnection()throws SQLException{
//抛出异常
return DriverManager.getConnection("jdbc:sqlserver://sql.cerny.cn:1433;DatabaseName=attendance", "sa", "Myclassdesign330");
//数据库的名字叫attendance,我的数据库账户是sa,密码是sa
//这里我建立连接的时候不是用try-catcth来捕捉异常,而是主动抛出,那么我下面调用这个函数时要么继续抛出,要么用try-catcth捕捉,我选择用try-catcth捕捉,到时候主函数就不用处理了
}
public int getTotal() {
//得到目前表Teach总数有多少条
int total = 0;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "select count(*) from Teach";
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
total = rs.getInt(1);// 这里getInt是因为rs这个结果集这里是返回的结果行数
}
// System.out.println("total:" + total);
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
public boolean add(int Tno,int Cno,int Tschool,int Tsgrade) {
//任课老师职工号,课程号,学时,学分
String sql = " insert into Teach(Tno, Cno,Tschool,Tsgrade) values(?,?,?,?) ";
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);) {
ps.setInt(1,Tno);
ps.setInt(2,Cno);
ps.setInt(3,Tschool);
ps.setInt(4,Tsgrade);
ps.execute();
return true;
//ResultSet rs = ps.getGeneratedKeys();//如果因为主码自增不插,然后通过这里得到主码赋值给对象对应的属性
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean update(int Tno,int Cno,int Tno1,int Cno1,int Tschool,int Tsgrade) {
//任课老师职工号,课程号,学时,学分
//因为这个任课表的主码是参照别的表的,可以修改,Tno,Cno是原来的主码,Tno1,Cno1是后来要修改的
String sql = "update Teach set Tno=?, Cno=? ,Tschool=?, Tsgrade=? where Cno ="+Cno+" and "+"Tno="+Tno;
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
ps.setInt(1,Tno1);
ps.setInt(2,Cno1);
ps.setInt(3,Tschool);
ps.setInt(4,Tsgrade);
ps.execute();
return true;
// System.out.println("修改成功");
}catch (SQLException e1) {
e1.printStackTrace();
}catch (Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
return false;
}
public void delete(int Tno,int Cno) {
//删除函数
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "delete from Course where Cno ="+Cno+"and"+"Tno="+Tno;
s.execute(sql);
//System.out.println("删除成功");
}catch(SQLException e1) {
e1.printStackTrace();
}catch(Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
}
public List<Teach> list1(int Tno,int Cno) {
List<Teach> teachs = new ArrayList<Teach>();
//把符合条件的Teach数据查询出来,转换为Teach对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
int Tschool=0;//学时
int Tsgrade=0;//学分
//按即主码查询,单个
//System.out.println("请输入要查询任课老师职工号,课程号:");
String sql = "select * from Teach where Cno ="+Cno+"and"+"Tno="+Tno;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Teach的对象teach ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Teach teach=new Teach() ;
Tno= rs.getInt(1);
Cno=rs.getInt(2);
Tschool = rs.getInt("Tschool");
Tsgrade=rs.getInt(4);
teach.Tno=Tno;
teach.Cno=Cno;
teach.Tschool=Tschool;
teach.Tsgrade=Tsgrade;
teachs.add(teach);
}
}catch (SQLException e) {
e.printStackTrace();}
return teachs;//返回系集合,符合条件的系的信息
}
public List<Teach> list2() {
List<Teach> teachs = new ArrayList<Teach>();
//把Teach数据查询出来,转换为Teach对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
int Tno=0;//任课老师职工号
int Cno=0;//课程号
int Tschool=0;//学时
int Tsgrade=0;//学分
//都查询出来
//System.out.println("请输入要查询任课老师职工号,课程号:");
String sql = "select * from Teach ";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Teach teach=new Teach() ;
Tno= rs.getInt(1);
Cno=rs.getInt(2);
Tschool = rs.getInt("Tschool");
Tsgrade=rs.getInt(4);
teach.Tno=Tno;
teach.Cno=Cno;
teach.Tschool=Tschool;
teach.Tsgrade=Tsgrade;
teachs.add(teach);
}
}catch (SQLException e) {
e.printStackTrace();}
return teachs;//返回系集合,符合条件的系的信息
}
public List<Teach> list3(int Tno) {
List<Teach> teachs = new ArrayList<Teach>();
//把符合条件的Teach数据查询出来,转换为Teach对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
int Cno = 0;
int Tschool=0;//学时
int Tsgrade=0;//学分
//按即主码查询,单个
//System.out.println("请输入要查询任课老师职工号,课程号:");
String sql = "select * from Teach where Tno ="+Tno;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Teach的对象teach ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Teach teach=new Teach() ;
Tno= rs.getInt(1);
Cno=rs.getInt(2);
Tschool = rs.getInt("Tschool");
Tsgrade=rs.getInt(4);
teach.Tno=Tno;
teach.Cno=Cno;
teach.Tschool=Tschool;
teach.Tsgrade=Tsgrade;
teachs.add(teach);
}
}catch (SQLException e) {
e.printStackTrace();}
return teachs;//返回系集合,符合条件的系的信息
}
public List<TeachforUI> list3forUI(int Tno) {
List<TeachforUI> teachs = new ArrayList<TeachforUI>();
//把符合条件的Teach数据查询出来,转换为Teach对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
int Cno = 0;
String Cname=null;
int Tschool=0;//学时
int Tsgrade=0;//学分
//按即主码查询,单个
//System.out.println("请输入要查询任课老师职工号,课程号:");
String sql = "select distinct Course.Cno,Cname,Tschool,Tsgrade from Course,Teach where Course.Cno=Teach.Cno and Tno="+Tno;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Teach的对象teach ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
TeachforUI teach=new TeachforUI();
Cno= rs.getInt(1);
Cname=rs.getString(2);
Tschool = rs.getInt("Tschool");
Tsgrade=rs.getInt(4);
teach.Cno=Cno;
teach.setCname(Cname);
teach.Tschool=Tschool;
teach.Tsgrade=Tsgrade;
teachs.add(teach);
}
}catch (SQLException e) {
e.printStackTrace();}
return teachs;//返回系集合,符合条件的系的信息
}
}
<file_sep>/src/teacher/TRController.java
package teacher;
import java.time.format.DateTimeFormatter;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import admin.studentUI.pwdtrans;
import admin.teachinfoUI.TeachInfoUI.TeachCourse;
import attendance.bean.AC;
import attendance.bean.Course;
import attendance.bean.PC;
import attendance.bean.SC;
import attendance.bean.Student;
import attendance.bean.Teach;
import attendance.bean.TeachforUI;
import attendance.dao.ACDao;
import attendance.dao.CourseDao;
import attendance.dao.PCDao;
import attendance.dao.SCDao;
import attendance.dao.StudentDao;
import attendance.dao.TeachDao;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.Callback;
import javafx.util.StringConverter;
import jdk.nashorn.internal.runtime.options.Options;
public class TRController {
@FXML private ComboBox classcombo;
@FXML private ComboBox coursecombo;
@FXML private ComboBox namecombo;
@FXML private DatePicker datecombo;
@FXML private TableView tablecombo;
@FXML private Button savebutton;
@FXML private Button loadbutton;
@FXML private ComboBox findchoose;
@FXML private RadioButton insertcheck;
@FXML private RadioButton findcheck;
@FXML private TableColumn<TeachRoutine, String> classid;
@FXML private TableColumn<TeachRoutine, String> id;
@FXML private TableColumn<TeachRoutine, String> name;
@FXML private TableColumn<TeachRoutine, String> courseid;
@FXML private TableColumn<TeachRoutine, String> coursename;
@FXML private TableColumn<TeachRoutine, String> date;
@FXML private TableColumn<TeachRoutine, String> situation;
@FXML private ToggleGroup group;
@FXML private Label totallabel;
@FXML private Button deleteall;
final ObservableList<TeachRoutine> data = FXCollections.observableArrayList();
int max = 0;
private final String pattern = "yyyy-MM-dd";
@FXML
protected void save(ActionEvent event) {
// PCDao pcdao= new PCDao();
// List<PC> pcis =new ArrayList<PC>();
// pcis=pcdao.list2();
// for(PC c:pcis) {
// System.out.println(c.Pname);
// //classcombo.getItems().addAll(c.Pname);
// classcombo.getItems().addAll(pcis);
// }
// TeachRoutine t1 = (TeachRoutine) tablecombo.getSelectionModel().selectedItemProperty().getBean();
// System.out.println(t1.getTcname());
ACDao dao = new ACDao();
//解决检测选中删除后重复删除提示成功的问题
if(TeachRoutineTrans.getClassname()==null&&TeachRoutineTrans.getCourseid()==0&&TeachRoutineTrans.getCoursename()==null&&TeachRoutineTrans.getDate()==null&&TeachRoutineTrans.getId()==0&&TeachRoutineTrans.getName()==null&&TeachRoutineTrans.getSituation()==null) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("请先选中一行再执行删除操作");
alert.showAndWait();
return;
}
else {
if(dao.delete(TeachRoutineTrans.getId(), TeachRoutineTrans.getCourseid(), TeachRoutineTrans.getDate())) {
// LoadTableView();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("删除成功");
if(max!=0) {
max = max - 1;
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
tablecombo.getItems().clear();
try {
if(group.getSelectedToggle().getUserData().toString().equals("查询")) {
//situation.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
System.out.println("当前是查询模式");
if(findchoose.getValue().equals("班级")) {
System.out.println("查询班级");
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
// CourseDao cdao = new CourseDao();
// List<Course> course = new ArrayList<Course>();
// course = cdao.list2();
// int Cno = 0;
// for(Course c:course) {
// if(c.Cname.equals(coursecombo.getValue().toString())) {
// Cno = c.Cno;
// System.out.println(Cno);
// }
// }
ac = acdao.list3(classcombo.getValue().toString());
max = 0;
for(AC a:ac) {
System.out.printf("%d\t%d\t%s\t%s\t%s\t%s\n", a.Cno, a.Sno, a.Aname, a.APname,a.Acdate,a.Asituation);
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
max++;
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
else if(findchoose.getValue().equals("课程名")) {
System.out.println("查询课程名");
TeachDao tdao = new TeachDao();
List<TeachforUI> tis =new ArrayList<TeachforUI>();
tis = tdao.list3forUI(TeachIdentity.getTno());
max = 0;
for(TeachforUI t:tis) {
System.out.println(t.Cno);
//coursecombo.getItems().addAll(t.Cname);
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
ac = acdao.list6(t.Cname);
String match = coursecombo.getValue().toString();
for(AC a:ac) {
if(a.Cname.equals(match)) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
max++;
}
}
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
//System.out.println(data.get(max-1).getTname());
tablecombo.setItems(data);
tablecombo.refresh();
}
else if(findchoose.getValue().equals("姓名")) {
System.out.println("查询姓名");
int idstart = 0;
String item = namecombo.getValue().toString();
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
ac = acdao.list5(idstart);
max = 0;
for(AC a:ac) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
//break;
max++;
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
else if(findchoose.getValue().equals("日期")) {
System.out.println("查询日期");
int idstart = 0;
TeachDao tdao = new TeachDao();
List<TeachforUI> tis =new ArrayList<TeachforUI>();
tis = tdao.list3forUI(TeachIdentity.getTno());
max = 0;
for(TeachforUI t:tis) {
//System.out.println(t.Cno);
//coursecombo.getItems().addAll(t.Cname);
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
ac = acdao.list4(datecombo.getValue().toString());
//String match = coursecombo.getValue().toString();
for(AC a:ac) {
if(t.Cno==a.Cno) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
max++;
}
}
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
}
else if(group.getSelectedToggle().getUserData().toString().equals("插入")) {
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
//try()
//int idstart = 0;
//String item = namecombo.getValue().toString();
// for(int i=0;i<item.length();i++) {
// if(Character.isDigit(item.charAt(i))) {
// idstart=Integer.parseInt(item.substring(i));
// //System.out.println(item.substring(i));
// }
// }
String classname = classcombo.getValue().toString();
String date = datecombo.getValue().toString();
String coursename = coursecombo.getValue().toString();
CourseDao coursedao = new CourseDao();
List<Course> cis = new ArrayList<Course>();
cis = coursedao.list3(coursename);
int courseid = 0;
for(Course c:cis) {
courseid = c.getCno();
}
System.out.println(courseid);
// if(acdao.add(classname, courseid, date)) {
//
// }else {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// alert.setTitle("提示");
// alert.setHeaderText(null);
// alert.setContentText("所选班级中有同学已录入考勤!请删除后重试。");
// alert.showAndWait();
//
// }
ac = acdao.list7(classname,coursename,date);
max = 0;
for(AC a:ac) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
//break;
max++;
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
}catch(Exception e){
//System.out.println(e);
e.printStackTrace();
totallabel.setText("");
savebutton.setDisable(true);
deleteall.setDisable(true);
Alert alert1 = new Alert(Alert.AlertType.ERROR);
alert1.setTitle("提示");
alert1.setHeaderText(null);
alert1.setContentText("未选择对象!");
alert1.showAndWait();
}
alert.showAndWait();
TeachRoutineTrans.setClassname(null);
TeachRoutineTrans.setCourseid(0);
TeachRoutineTrans.setCoursename(null);
TeachRoutineTrans.setDate(null);
TeachRoutineTrans.setId(0);
TeachRoutineTrans.setName(null);
TeachRoutineTrans.setSituation(null);
}
else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("删除失败!");
alert.showAndWait();
}
}
}
@FXML
protected void FindCheckSelected(ActionEvent event) {
System.out.print("Hello");
}
@FXML
protected void DeleteAll(ActionEvent event) {
//System.out.print("Hello");
if(max==0) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("表中无内容");
alert.showAndWait();
}
else {
ACDao dao = new ACDao();
for(int i=0;i<max;i++) {
dao.delete(Integer.valueOf(data.get(i).getTid()), Integer.valueOf(data.get(i).getTcid()), data.get(i).getTdate());
}
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("删除成功!");
TeachRoutineTrans.setClassname(null);
TeachRoutineTrans.setCourseid(0);
TeachRoutineTrans.setCoursename(null);
TeachRoutineTrans.setDate(null);
TeachRoutineTrans.setId(0);
TeachRoutineTrans.setName(null);
TeachRoutineTrans.setSituation(null);
max=0;
savebutton.setDisable(true);
deleteall.setDisable(true);
alert.showAndWait();
}
}
@FXML
protected void Load(ActionEvent event) {
tablecombo.getItems().clear();
ObservableList<String> options = FXCollections.observableArrayList("出勤", "请假", "旷课", "迟到", "早退");
situation.setCellFactory(tc -> {
ComboBox<String>combo = new ComboBox<String>();
combo.setItems(options);
combo.setEditable(false);
TableCell<TeachRoutine, String> cell = new TableCell<TeachRoutine, String>(){
protected void updateItem(String chuzhi,boolean empty) {
super.updateItem(chuzhi, empty);
if(empty) {
setGraphic(null);
}
else {
combo.setValue(chuzhi);
setGraphic(combo);
}
}
};
combo.setOnAction(e -> {
int rank = cell.getIndex();
String value = combo.getValue();
//System.out.println(onetemp);
String two = classid.getTableView().getItems().get(
rank).getTid();
String three = classid.getTableView().getItems().get(
rank).getTname();
String four = classid.getTableView().getItems().get(
rank).getTcid();
String six = classid.getTableView().getItems().get(
rank).getTdate();
String seventemp = classid.getTableView().getItems().get(
rank).getTroutine();
String seven = value;
ACDao dao = new ACDao();
if(dao.update(Integer.valueOf(two), Integer.valueOf(four), six, seven)) {
System.out.println(three + "的考勤修改成功!!");
}
else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改失败");
alert.showAndWait();
}
if(value.equals(options.get(0))){
System.out.println("选择了出勤");
}
else if(value.equals(options.get(1))) {
}
else if(value.equals(options.get(2))) {
}
else if(value.equals(options.get(3))) {
}
else if(value.equals(options.get(4))) {
}
});
return cell;
});
LoadTableView();
}
public static class TeachRoutine {
private final SimpleStringProperty Tclassid;
private final SimpleStringProperty Tid;
private final SimpleStringProperty Tname;
private final SimpleStringProperty Tcid;
private final SimpleStringProperty Tcname;
private final SimpleStringProperty Tdate;
private final SimpleStringProperty Troutine;
private TeachRoutine(String Tclassid1, String Tid1, String Tname1, String Tcid1, String Tcname1, String Tdate1, String Troutine1) {
this.Tclassid = new SimpleStringProperty(Tclassid1);
this.Tid = new SimpleStringProperty(Tid1);
this.Tname = new SimpleStringProperty(Tname1);
this.Tcid = new SimpleStringProperty(Tcid1);
this.Tcname = new SimpleStringProperty(Tcname1);
this.Tdate = new SimpleStringProperty(Tdate1);
this.Troutine = new SimpleStringProperty(Troutine1);
}
public String getTclassid() {
return Tclassid.get();
}
public void setTClassid(String TClassid1) {
Tclassid.set(TClassid1);
}
public String getTid() {
return Tid.get();
}
public void setTid(String Tid1) {
Tid.set(Tid1);
}
public String getTname() {
return Tname.get();
}
public void setTname(String Tname1) {
Tname.set(Tname1);
}
public String getTcid() {
return Tcid.get();
}
public void setTcid(String Tcid1) {
Tcname.set(Tcid1);
}
public String getTcname() {
return Tcname.get();
}
public void setTcname(String Tcname1) {
Tcname.set(Tcname1);
}
public String getTdate() {
return Tdate.get();
}
public String getTroutine() {
return Troutine.get();
}
}
public void InitUI() {
TeachRoutineTrans.setClassname(null);
TeachRoutineTrans.setCourseid(0);
TeachRoutineTrans.setCoursename(null);
TeachRoutineTrans.setDate(null);
TeachRoutineTrans.setId(0);
TeachRoutineTrans.setName(null);
TeachRoutineTrans.setSituation(null);
deleteall.setDisable(true);
savebutton.setDisable(true);
//日期切换格式yyyy-mm-dd
StringConverter converter = new StringConverter<LocalDate>() {
DateTimeFormatter dateFormatter =
DateTimeFormatter.ofPattern(pattern);
@Override
public String toString(LocalDate date) {
if (date != null) {
return dateFormatter.format(date);
} else {
return "";
}
}
@Override
public LocalDate fromString(String string) {
if (string != null && !string.isEmpty()) {
return LocalDate.parse(string, dateFormatter);
} else {
return null;
}
}
};
//设置日期选择不能选择未来的时间
final Callback<DatePicker, DateCell> dayCellFactory =
new Callback<DatePicker, DateCell>() {
@Override
public DateCell call(final DatePicker datePicker) {
return new DateCell() {
@Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item.isAfter(LocalDate.now().plusDays(0))) {
setDisable(true);
setStyle("-fx-background-color: #ffc0cb;");
}
}
};
}
};
datecombo.setDayCellFactory(dayCellFactory);
datecombo.setConverter(converter);
//加载选项框数据
PCDao pcdao= new PCDao();
List<PC> pcis =new ArrayList<PC>();
pcis=pcdao.list2();
for(PC c:pcis) {
System.out.println(c.Pname);
classcombo.getItems().addAll(c.Pname);
//classcombo.getItems().addAll(pcis);
}
CourseDao dao = new CourseDao();
List<Course> is =new ArrayList<Course>();
TeachDao tdao = new TeachDao();
List<TeachforUI> tis =new ArrayList<TeachforUI>();
tis = tdao.list3forUI(TeachIdentity.getTno());
for(TeachforUI t:tis) {
System.out.println(t.Cno);
coursecombo.getItems().addAll(t.Cname);
}
classcombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
StudentDao stdao= new StudentDao();
List<Student> stis =new ArrayList<Student>();
stis=stdao.list3();
namecombo.getItems().clear();
//必须加入判断,否则会出错
if(group.getSelectedToggle().getUserData().toString().equals("查询")) {
if(findchoose.getValue().toString().equals("姓名")) {
stis=stdao.list3();
}
else if(findchoose.getValue().toString().equals("班级")){
stis=stdao.list2(classcombo.getValue().toString());
}
}
else if(group.getSelectedToggle().getUserData().toString().equals("插入")) {
stis=stdao.list2(classcombo.getValue().toString());
}
// int count1 = pwdtrans.getCount();
// if(fileList.getSelectionModel().getSelectedItem().equals("新建学生")&&count1==0) {
// pcis=pcdao.list3("计算机系");
// }
for(Student s:stis) {
//classoptions.add(c.Pname);
// int count = pwdtrans.getCount();
// if(count==0)break;
String longname = s.Sname + " " + s.Sno;
namecombo.getItems().addAll(longname);
//System.out.println(count);
}
}
});
StudentDao stdao = new StudentDao();
List<Student> stis =new ArrayList<Student>();
stis = stdao.list3();
for(Student s:stis) {
String longname = s.Sname + " " + s.Sno;
namecombo.getItems().addAll(longname);
}
findchoose.getItems().addAll("班级", "姓名", "课程名", "日期");
//System.out.print(group.getSelectedToggle().getUserData().toString());
//final ToggleGroup group = new ToggleGroup();
findcheck.setToggleGroup(group);
findcheck.setUserData("查询");
insertcheck.setUserData("插入");
insertcheck.setToggleGroup(group);
findcheck.setSelected(true);
findchoose.setVisible(true);
classcombo.setDisable(true);
coursecombo.setDisable(true);
datecombo.setDisable(true);
namecombo.setDisable(true);
// group.getSelectedToggle().selectedProperty().addListener()
findchoose.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if(findchoose.getValue().equals("班级")) {
classcombo.setDisable(false);
namecombo.setDisable(true);
coursecombo.setDisable(true);
datecombo.setDisable(true);
classcombo.getSelectionModel().clearSelection();
namecombo.getSelectionModel().clearSelection();
coursecombo.getSelectionModel().clearSelection();
datecombo.setValue(null);
classcombo.setPromptText("班级");
namecombo.setPromptText("不可用");
coursecombo.setPromptText("不可用");
datecombo.setPromptText("不可用");
}
else if(findchoose.getValue().equals("姓名")) {
classcombo.setDisable(true);
namecombo.setDisable(false);
coursecombo.setDisable(true);
datecombo.setDisable(true);
classcombo.getSelectionModel().clearSelection();
namecombo.getSelectionModel().clearSelection();
coursecombo.getSelectionModel().clearSelection();
datecombo.setValue(null);
classcombo.setPromptText("不可用");
namecombo.setPromptText("姓名");
coursecombo.setPromptText("不可用");
datecombo.setPromptText("不可用");
}
else if(findchoose.getValue().equals("课程名")) {
classcombo.setDisable(true);
namecombo.setDisable(true);
coursecombo.setDisable(false);
datecombo.setDisable(true);
classcombo.getSelectionModel().clearSelection();
namecombo.getSelectionModel().clearSelection();
coursecombo.getSelectionModel().clearSelection();
datecombo.setValue(null);
classcombo.setPromptText("不可用");
namecombo.setPromptText("不可用");
coursecombo.setPromptText("课程名");
datecombo.setPromptText("不可用");
}
else if(findchoose.getValue().equals("日期")) {
classcombo.setDisable(true);
namecombo.setDisable(true);
coursecombo.setDisable(true);
datecombo.setDisable(false);
classcombo.getSelectionModel().clearSelection();
namecombo.getSelectionModel().clearSelection();
coursecombo.getSelectionModel().clearSelection();
datecombo.setValue(null);
classcombo.setPromptText("不可用");
namecombo.setPromptText("不可用");
coursecombo.setPromptText("不可用");
datecombo.setPromptText("日期(yyyy-mm-dd)");
}
else {
System.out.println("选项框被清空啦~");
}
}
});
group.selectedToggleProperty().addListener(
(ObservableValue<? extends Toggle> ov, Toggle old_Toggle,
Toggle new_Toggle) -> {
if (group.getSelectedToggle() != null) {
if(group.getSelectedToggle().getUserData().toString().equals("查询")) {
namecombo.getItems().clear();
loadbutton.setText("查询");
tablecombo.getItems().clear();
findchoose.getSelectionModel().clearSelection();
classcombo.getSelectionModel().clearSelection();
namecombo.getSelectionModel().clearSelection();
coursecombo.getSelectionModel().clearSelection();
datecombo.setValue(null);
findchoose.setVisible(true);
namecombo.setDisable(true);
classcombo.setDisable(true);
coursecombo.setDisable(true);
datecombo.setDisable(true);
StudentDao stdao1= new StudentDao();
List<Student> stis1 =new ArrayList<Student>();
stis1=stdao.list3();
for(Student s:stis1) {
String longname = s.Sname + " " + s.Sno;
namecombo.getItems().addAll(longname);
}
}
else if(group.getSelectedToggle().getUserData().toString().equals("插入")) {
loadbutton.setText("插入");
tablecombo.getItems().clear();
findchoose.setVisible(false);
classcombo.setDisable(false);
namecombo.setDisable(true);
coursecombo.setDisable(false);
datecombo.setDisable(false);
classcombo.getSelectionModel().clearSelection();
namecombo.getSelectionModel().clearSelection();
coursecombo.getSelectionModel().clearSelection();
datecombo.setValue(null);
classcombo.setPromptText("班级");
namecombo.setPromptText("姓名");
coursecombo.setPromptText("课程名");
datecombo.setPromptText("日期");
}
// final Image image = new Image(
// getClass().getResourceAsStream(
// group.getSelectedToggle().getUserData().toString() +
// ".jpg"));
// icon.setImage(image);
}
});
classid.setCellValueFactory(
new PropertyValueFactory<>("Tclassid"));
classid.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
id.setCellValueFactory(
new PropertyValueFactory<>("Tid"));
id.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
name.setCellValueFactory(
new PropertyValueFactory<>("Tname"));
name.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
courseid.setCellValueFactory(
new PropertyValueFactory<>("Tcid"));
courseid.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
coursename.setCellValueFactory(
new PropertyValueFactory<>("Tcname"));
coursename.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
date.setCellValueFactory(
new PropertyValueFactory<>("Tdate"));
date.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
situation.setCellValueFactory(
new PropertyValueFactory<>("Troutine"));
//situation.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
classid.setStyle("-fx-alignment: CENTER;");
id.setStyle("-fx-alignment: CENTER;");
name.setStyle("-fx-alignment: CENTER;");
courseid.setStyle("-fx-alignment: CENTER;");
coursename.setStyle("-fx-alignment: CENTER;");
date.setStyle("-fx-alignment: CENTER;");
situation.setStyle("-fx-alignment: CENTER;");
//tablecombo.setEditable(true);
classid.setOnEditCommit(
(CellEditEvent<TeachRoutine, String> t) -> {
String onetemp = classid.getTableView().getItems().get(
t.getTablePosition().getRow()).getTclassid();
((TeachRoutine) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setTClassid(t.getNewValue());
String one = t.getNewValue();
//System.out.println("Test");
String two = id.getTableView().getItems().get(
t.getTablePosition().getRow()).getTid();
//System.out.println(tc.getCoName());
String three = name.getTableView().getItems().get(
t.getTablePosition().getRow()).getTname();
String four = courseid.getTableView().getItems().get(
t.getTablePosition().getRow()).getTcid();
String five = coursename.getTableView().getItems().get(
t.getTablePosition().getRow()).getTcname();
String six = date.getTableView().getItems().get(
t.getTablePosition().getRow()).getTdate();
String seven = situation.getTableView().getItems().get(
t.getTablePosition().getRow()).getTroutine();
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
acdao.update(Integer.valueOf(two), Integer.valueOf(four), six, seven);
int idstart = pwdtrans.getSno();
System.out.println(t.getNewValue());
if(acdao.update(Integer.valueOf(two), Integer.valueOf(four), six, seven)) {
System.out.println("修改成功");
}
else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改失败");
alert.showAndWait();
((TeachRoutine) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setTcname(onetemp);
tablecombo.refresh();
}
});
tablecombo.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
if (newValue != null) {
System.out.println("Selected Person: "
+ ((TeachRoutine) newValue).getTcname() + " | "
+ ((TeachRoutine) newValue).getTname()
);
TeachRoutineTrans.setClassname(((TeachRoutine) newValue).getTcname());
TeachRoutineTrans.setId(Integer.valueOf(((TeachRoutine) newValue).getTid()));
TeachRoutineTrans.setName(((TeachRoutine) newValue).getTname());
TeachRoutineTrans.setCourseid(Integer.valueOf(((TeachRoutine) newValue).getTcid()));
TeachRoutineTrans.setCoursename(((TeachRoutine) newValue).getTcname());
TeachRoutineTrans.setDate(((TeachRoutine) newValue).getTdate());
TeachRoutineTrans.setSituation(((TeachRoutine) newValue).getTroutine());
System.out.printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\n", ((TeachRoutine) newValue).getTcname(), ((TeachRoutine) newValue).getTid(), ((TeachRoutine) newValue).getTname(), ((TeachRoutine) newValue).getTcid(), ((TeachRoutine) newValue).getTcname(), ((TeachRoutine) newValue).getTdate(), ((TeachRoutine) newValue).getTroutine());
}
});
}
public void LoadTableView() {
tablecombo.getItems().clear();
try {
if(group.getSelectedToggle().getUserData().toString().equals("查询")) {
//situation.setCellFactory(TextFieldTableCell.<TeachRoutine>forTableColumn());
System.out.println("当前是查询模式");
if(findchoose.getValue().equals("班级")) {
System.out.println("查询班级");
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
// CourseDao cdao = new CourseDao();
// List<Course> course = new ArrayList<Course>();
// course = cdao.list2();
// int Cno = 0;
// for(Course c:course) {
// if(c.Cname.equals(coursecombo.getValue().toString())) {
// Cno = c.Cno;
// System.out.println(Cno);
// }
// }
ac = acdao.list3(classcombo.getValue().toString());
max = 0;
for(AC a:ac) {
System.out.printf("%d\t%d\t%s\t%s\t%s\t%s\n", a.Cno, a.Sno, a.Aname, a.APname,a.Acdate,a.Asituation);
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
max++;
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
else if(findchoose.getValue().equals("课程名")) {
System.out.println("查询课程名");
TeachDao tdao = new TeachDao();
List<TeachforUI> tis =new ArrayList<TeachforUI>();
tis = tdao.list3forUI(TeachIdentity.getTno());
max = 0;
for(TeachforUI t:tis) {
System.out.println(t.Cno);
//coursecombo.getItems().addAll(t.Cname);
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
ac = acdao.list6(t.Cname);
String match = coursecombo.getValue().toString();
for(AC a:ac) {
if(a.Cname.equals(match)) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
max++;
}
}
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
//System.out.println(data.get(max-1).getTname());
tablecombo.setItems(data);
tablecombo.refresh();
}
else if(findchoose.getValue().equals("姓名")) {
System.out.println("查询姓名");
int idstart = 0;
String item = namecombo.getValue().toString();
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
ac = acdao.list5(idstart);
max = 0;
for(AC a:ac) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
//break;
max++;
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
else if(findchoose.getValue().equals("日期")) {
System.out.println("查询日期");
int idstart = 0;
TeachDao tdao = new TeachDao();
List<TeachforUI> tis =new ArrayList<TeachforUI>();
tis = tdao.list3forUI(TeachIdentity.getTno());
max = 0;
for(TeachforUI t:tis) {
//System.out.println(t.Cno);
//coursecombo.getItems().addAll(t.Cname);
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
ac = acdao.list4(datecombo.getValue().toString());
//String match = coursecombo.getValue().toString();
for(AC a:ac) {
if(t.Cno==a.Cno) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
max++;
}
}
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
}
else if(group.getSelectedToggle().getUserData().toString().equals("插入")) {
ACDao acdao = new ACDao();
List<AC> ac = new ArrayList<AC>();
//try()
//int idstart = 0;
//String item = namecombo.getValue().toString();
// for(int i=0;i<item.length();i++) {
// if(Character.isDigit(item.charAt(i))) {
// idstart=Integer.parseInt(item.substring(i));
// //System.out.println(item.substring(i));
// }
// }
String classname = classcombo.getValue().toString();
String date = datecombo.getValue().toString();
String coursename = coursecombo.getValue().toString();
CourseDao coursedao = new CourseDao();
List<Course> cis = new ArrayList<Course>();
cis = coursedao.list3(coursename);
int courseid = 0;
for(Course c:cis) {
courseid = c.getCno();
}
System.out.println(courseid);
if(acdao.add(classname, courseid, date)) {
}else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("所选班级中有同学已录入考勤!请删除后重试。");
alert.showAndWait();
}
ac = acdao.list7(classname,coursename,date);
max = 0;
for(AC a:ac) {
data.add(new TeachRoutine(a.APname,String.valueOf(a.Sno), a.Aname, String.valueOf(a.Cno), a.Cname, a.Acdate, a.Asituation));
//break;
max++;
}
if(max!=0) {
savebutton.setDisable(false);
deleteall.setDisable(false);
}
else if(max==0) {
savebutton.setDisable(true);
deleteall.setDisable(true);
}
totallabel.setText("获得数据"+max+"条");
tablecombo.setItems(data);
tablecombo.refresh();
}
}catch(Exception e){
//System.out.println(e);
e.printStackTrace();
totallabel.setText("");
savebutton.setDisable(true);
deleteall.setDisable(true);
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("未选择对象!");
alert.showAndWait();
}
}
}
<file_sep>/src/attendance/test/QimoTestDao.java
package attendance.test;
import java.util.ArrayList;
import java.util.List;
import attendance.dao.QimoDao;
import attendance.bean.Qimo;
public class QimoTestDao {
public static void main(String[] args){
QimoDao dao= new QimoDao();
List<Qimo> is =new ArrayList<Qimo>();
//dao.add(1, 1, "2020");
// dao.add("计算机181", 1, "2020-02-02");
// dao.update1(2, 1, "2020-02-02", "旷课");
//is =dao.list4("2020-02-02",1);
/* for(Qimo b:is){
System.out.printf("%d\t%d\t%s\t%s\t%s\t%s\t%s\n",b.Sno,b.Cno,b.Cname,b.APname,b.Aname,b.Acdate,b.Asituation);
System.out.println();
}*/
//dao.add(1, 2, "2020");
//dao.add(Sno, Cno, Qstartdate, Qenddate);
//is =dao.list1(1);
for(Qimo b:is){
//System.out.printf("%s\t%s\t%d\t%s\t%d\t%s\t%s\t%d\t%d\t%d\t%d\n",b.Pcname,b.Pname,b.Sno,b.Sname,b.Cno,b.Cname,b.Qtimeyear,b.Qan,b.Qaln,b.Qtn,b.Qlen);
System.out.println();
}
}
}
<file_sep>/src/admin/teachinfoUI/changeController.java
package admin.teachinfoUI;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.Teacher;
import attendance.dao.TeacherDao;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class changeController {
@FXML private Button confirmButton;
@FXML private TextField pwdField;
@FXML
protected void comfirmAction(ActionEvent event) {
//Stage stage = (Stage) rootGridPane.getScene().getWindow();
//stage.close();
TeacherDao dao= new TeacherDao();
List<Teacher> is =new ArrayList<Teacher>();
//FileItem item = fileList.data().get(index);
is =dao.list3();
for (Teacher b : is) {
if(pwdtrans.getName().equals(b.Tname))
{
//System.out.printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n",b.Tcname,b.Tname,b.Tname,b.Sno,b.Sex,b.Sage,b.Sbirthtime,b.Snative);
//System.out.printf("%d\t%s\t%s\t%d\t%s\t%s\n",b.Sno,b.Tname,b.Sex,b.Sage,b.Snative,b.Spassword);
//System.out.println();
//String item = String.valueOf(b.Sno);
System.out.print(b);
if(b.Tno==pwdtrans.getSno()) {
if(dao.update2(pwdtrans.getSno(), pwdField.getText())==true) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改成功");
pwdtrans.setpwd(pwdField.getText());
alert.showAndWait();
}
}
}
else continue;
//openFile(item);
}
Stage stage = (Stage)confirmButton.getScene().getWindow();
stage.close();
}
public void Initpwd() {
pwdField.setText(pwdtrans.getpwd());
}
}
<file_sep>/src/attendance/bean/SC.java
package attendance.bean;
//选课表
//课程名,姓名是为了查询,实际SC表没有
public class SC {
public int Sno ;//学号
public int Cno ;//课程号
public String Sname;//姓名
public String Cname;//课程名
public int getSno() {
return Sno;
}
public void setSno(int sno) {
this.Sno = sno;
}
public int getCno() {
return Cno;
}
public void setCno(int cno) {
this.Cno = cno;
}
public String getSname() {
return Sname;
}
public void setSname(String sname) {
this.Sname = sname;
}
public String getCname() {
return Cname;
}
public void setCname(String cname) {
this.Cname = cname;
}
public SC() {
super();
// TODO Auto-generated constructor stub
}
public SC(int sno, int cno, String sname, String cname) {
super();
this.Sno = sno;
this.Cno = cno;
this.Sname = sname;
this.Cname = cname;
}
@Override
public String toString() {
return "SC [Sno=" + Sno + ", Cno=" + Cno + ", Sname=" + Sname + ", Cname=" + Cname + "]";
}
}
<file_sep>/src/attendance/dao/StudentDao.java
package attendance.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.Student;
//学生Dao,有些操作给管理员做的,有些给学生做的
public class StudentDao {
public StudentDao(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
}
public Connection getConnection()throws SQLException{
//抛出异常
return DriverManager.getConnection("jdbc:sqlserver://sql.cerny.cn:1433;DatabaseName=attendance", "sa", "Myclassdesign330");
//数据库的名字叫attendance,我的数据库账户是sa,密码是sa
//这里我建立连接的时候不是用try-catcth来捕捉异常,而是主动抛出,那么我下面调用这个函数时要么继续抛出,要么用try-catcth捕捉,我选择用try-catcth捕捉,到时候主函数就不用处理了
}
public int getTotal() {
//得到目前表Teacher总数有多少条
int total = 0;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "select count(*) from Student";
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
total = rs.getInt(1);// 这里getInt是因为rs这个结果集这里是返回的结果行数
}
// System.out.println("total:" + total);
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
public boolean add(int Sno,String Sname,String Sex,int Sage,String Snative,int SPno) {
//给管理员用的
//这里增加函数学号(本来主码可以自增不插,但我这里还是打开自增规则插进去)学号,姓名,性别,年龄,籍贯,专业班级号
//密码在增加函数这里不插,默认,后期再自己改密码
String sql = "set identity_insert Student ON insert into Student(Sno,Sname,Sex,Sage,Snative,SPno) values(?,?,?,?,?,?) set identity_insert Student OFF";
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);) {
ps.setInt(1,Sno);
ps.setString(2,Sname);
ps.setString(3,Sex);
ps.setInt(4,Sage);
ps.setString(5,Snative);
ps.setInt(6,SPno);
ps.execute();
return true;
//ResultSet rs = ps.getGeneratedKeys();//如果因为主码自增不插,然后通过这里得到主码赋值给对象对应的属性
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean delete(int Sno) {
//删除函数
//给管理员用
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "delete from Student where Sno= " +"'"+Sno+"'";
s.execute(sql);
return true;
//System.out.println("删除成功");
}catch(SQLException e1) {
e1.printStackTrace();
}catch(Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
return false;
}
public void update1(int Sno,String Sname,String Sex,int Sage,String Snative,int SPno) {
//给管理员用,不更新密码,因为管理员没有权限
//学号,姓名,性别,年龄,籍贯,专业班级号
//不更新主码,主码一般不允许更新,一般允许更新主码的数据库设计都是不合理的
String sql = "update Student set Sname=?,Sex=? ,Sage=?,Snative=?,SPno=? where Sno ="+Sno;
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
ps.setString(1, Sname);
ps.setString(2, Sex);
ps.setInt(3, Sage);
ps.setString(4, Snative);
ps.setInt(5, SPno);
ps.execute();
// System.out.println("修改成功");
}catch (SQLException e1) {
e1.printStackTrace();
}catch (Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
}
public boolean update2(int Sno,String Spassword) {
//给学生用,新密码
//不更新主码,主码一般不允许更新,一般允许更新主码的数据库设计都是不合理的
String sql = "update Student set Spassword=? where Sno ="+Sno;
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
ps.setString(1, Spassword);
ps.execute();
return true;
// System.out.println("修改成功");
}catch (SQLException e1) {
e1.printStackTrace();
}catch (Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
return false;
}
public List<Student> list1(int Sno) {
List<Student> students = new ArrayList<Student>();
//把符合条件的Student数据查询出来,转换为Student对象后,放在一个集合中返回
//从视图里查询,看不到密码,给学生用,查询某个人或者自己
//String sql = "select * from hero order by id desc limit ?,? ";
String Pcname=null;
String Pname=null;
String Sname=null;
String Sex=null;
int Sage=0;
String Sbirthtime=null;
String Snative=null;
//按即主码查询,单个
String sql = "select * from Student_view where 学号="+Sno;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Teacher的对象 Teacher ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Student student=new Student() ;
Pcname= rs.getString(1);
Pname = rs.getString(2);
Sname=rs.getString(3);
Sno = rs.getInt(4);
Sex=rs.getString(5);
Sage=rs.getInt(6);
Sbirthtime=rs.getString(7);
Snative=rs.getString(8);
student.Pcname=Pcname;
student.Pname=Pname;
student.Sname=Sname;
student.Sno=Sno;
student.Sex=Sex;
student.Sage=Sage;
student.Sbirthtime=Sbirthtime;
student.Snative=Snative;
students.add(student);
}
}catch (SQLException e) {
e.printStackTrace();}
return students;//返回系集合,符合条件的系的信息
}
public List<Student> list2(String Pname) {
List<Student> students = new ArrayList<Student>();
//把符合条件的Student数据查询出来,转换为Student对象后,放在一个集合中返回
//从视图里查询,看不到密码,给别的用,查询一个班级
//String sql = "select * from hero order by id desc limit ?,? ";
String Pcname=null;
String Sname=null;
int Sno=0;
String Sex=null;
int Sage=0;
String Sbirthtime=null;
String Snative=null;
//按即主码查询,单个
String sql = "select * from Student_view where 专业班级="+"'"+Pname+"'";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Teacher的对象 Teacher ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Student student=new Student() ;
Pcname= rs.getString(1);
Pname = rs.getString(2);
Sname=rs.getString(3);
Sno = rs.getInt(4);
Sex=rs.getString(5);
Sage=rs.getInt(6);
Sbirthtime=rs.getString(7);
Snative=rs.getString(8);
student.Pcname=Pcname;
student.Pname=Pname;
student.Sname=Sname;
student.Sno=Sno;
student.Sex=Sex;
student.Sage=Sage;
student.Sbirthtime=Sbirthtime;
student.Snative=Snative;
students.add(student);
}
}catch (SQLException e) {
e.printStackTrace();}
return students;//返回系集合,符合条件的系的信息
}
public String getpwd(int Sno) {
//把符合条件的Student数据查询出来,转换为Student对象后,放在一个集合中返回
//从表查询,给管理员用,看得到密码,查询所有人
//String sql = "select * from hero order by id desc limit ?,? ";
//int Sno=0;
// String Sname=null;
// String Sex=null;
// int Sage=0;
// String Snative=null;
// int SPno=0;
String Spassword=null;
//按即主码查询,单个
String sql = "select Spassword from Student where Sno="+Sno;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Spassword=rs.getString(1);
}
}catch (SQLException e) {
e.printStackTrace();}
return Spassword;//返回系集合,符合条件的系的信息
}
public List<Student> list3() {
List<Student> students = new ArrayList<Student>();
//把符合条件的Student数据查询出来,转换为Student对象后,放在一个集合中返回
//从表查询,给管理员用,看得到密码,查询所有人
//String sql = "select * from hero order by id desc limit ?,? ";
int Sno=0;
String Sname=null;
String Sex=null;
int Sage=0;
String Snative=null;
int SPno=0;
String Spassword=null;
//按即主码查询,单个
String sql = "select * from Student";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Student student=new Student() ;
Sno = rs.getInt(1);
Sname=rs.getString(2);
Sex = rs.getString(3);
Sage=rs.getInt(4);
Snative=rs.getString(5);
SPno=rs.getInt(6);
Spassword=rs.getString(7);
student.Sno=Sno;
student.Sname=Sname;
student.Sex=Sex;
student.Sage=Sage;
student.Snative=Snative;
student.SPno=SPno;
student.Spassword=Spassword;
students.add(student);
}
}catch (SQLException e) {
e.printStackTrace();}
return students;//返回系集合,符合条件的系的信息
}
public boolean login(int Sno,String pwd) {
int sqlSno = 0;
String sqlpwd = null;
String sql = "select * from Student where Sno="+Sno+" and "+"Spassword="+"'"+pwd+"'";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
// System.out.println(Sno);
// System.out.println(pwd);
while (rs.next()) {
sqlSno = rs.getInt(1);
sqlpwd = rs.getString(7);
if(Sno==sqlSno&&pwd.equals(sqlpwd))
{
return true;
}
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
return false;
}
public List<Student> list4(int Sno,String Spassword) {
List<Student> students = new ArrayList<Student>();
//把符合条件的Student数据查询出来,转换为Student对象后,放在一个集合中返回
//从表查询,用于登录
//String sql = "select * from hero order by id desc limit ?,? ";
String Sname=null;
String Sex=null;
int Sage=0;
String Snative=null;
int SPno=0;
//按即主码查询,单个
String sql = "select * from Student where Sno="+Sno+" and "+"Spassword="+"'"+Spassword+"'";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Student student=new Student() ;
Sno = rs.getInt(1);
Sname=rs.getString(2);
Sex = rs.getString(3);
Sage=rs.getInt(4);
Snative=rs.getString(5);
SPno=rs.getInt(6);
Spassword=rs.getString(7);
student.Sno=Sno;
student.Sname=Sname;
student.Sex=Sex;
student.Sage=Sage;
student.Snative=Snative;
student.SPno=SPno;
student.Spassword=Spassword;
students.add(student);
}
}catch (SQLException e) {
e.printStackTrace();
return null;}
return students;
}
}
<file_sep>/src/admin/studentUI/changeController.java
package admin.studentUI;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.Student;
import attendance.dao.StudentDao;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class changeController {
@FXML private Button confirmButton;
@FXML private TextField pwdField;
@FXML
protected void comfirmAction(ActionEvent event) {
//Stage stage = (Stage) rootGridPane.getScene().getWindow();
//stage.close();
StudentDao dao= new StudentDao();
List<Student> is =new ArrayList<Student>();
//FileItem item = fileList.data().get(index);
is =dao.list3();
for (Student b : is) {
if(pwdtrans.getName().equals(b.Sname))
{
System.out.printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n",b.Pcname,b.Pname,b.Sname,b.Sno,b.Sex,b.Sage,b.Sbirthtime,b.Snative);
//System.out.printf("%d\t%s\t%s\t%d\t%s\t%s\n",b.Sno,b.Sname,b.Sex,b.Sage,b.Snative,b.Spassword);
System.out.println();
//String item = String.valueOf(b.Sno);
System.out.print(b);
if(b.Sno==pwdtrans.getSno()) {
if(dao.update2(pwdtrans.getSno(), pwdField.getText())==true) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改成功");
pwdtrans.setpwd(pwdField.getText());
alert.showAndWait();
}
}
}
else continue;
//openFile(item);
}
Stage stage = (Stage)confirmButton.getScene().getWindow();
stage.close();
}
public void Initpwd() {
pwdField.setText(pwdtrans.getpwd());
}
}
<file_sep>/src/Login/ChangeAdminpwd.java
package Login;
import java.io.IOException;
import attendance.dao.SuperAdminDao;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.stage.Stage;
public class ChangeAdminpwd {
public void start(Stage stage) throws IOException {
stage.setTitle("更改管理员密码");
Parent root = FXMLLoader.load(getClass().getResource("ChangeAdminpwd.fxml"));
Scene scene = new Scene(root, 320, 261);
stage.setScene(scene);
stage.show();
}
@FXML private Button confirmButton;
@FXML private PasswordField pwdField;
@FXML
protected void confirm(ActionEvent event) {
SuperAdminDao dao = new SuperAdminDao();
if(dao.changepassword(pwdField.getText().toString())) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改成功!");
alert.showAndWait();
Stage stage = (Stage)confirmButton.getScene().getWindow();
stage.close();
}
else {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改失败");
alert.showAndWait();
}
}
}
<file_sep>/src/student/StudAdded.java
package student;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class StudAdded {
public void start(Stage stage) throws IOException {
stage.setTitle("主界面");
//Parent root = FXMLLoader.load(getClass().getResource("TeachChooseUI.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("StudAdded.fxml"));
Parent root =loader.load();
SAController Controller = loader.getController();
Scene scene = new Scene(root, 387, 463);
stage.setScene(scene);
stage.show();
Controller.InitUI();
//Controller.InitUI();
}
}
<file_sep>/src/attendance/dao/SuperAdminDao.java
package attendance.dao;
//管理员DAO
//给管理员用的
import java.sql.*;
//import attendance.bean.Academy;
public class SuperAdminDao {
public SuperAdminDao(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
}
public Connection getConnection()throws SQLException{
//抛出异常
return DriverManager.getConnection("jdbc:sqlserver://sql.cerny.cn:1433;DatabaseName=attendance", "sa", "Myclassdesign330");
//数据库的名字叫attendance,我的数据库账户是sa,密码是sa
//这里我建立连接的时候不是用try-catcth来捕捉异常,而是主动抛出,那么我下面调用这个函数时要么继续抛出,要么用try-catcth捕捉,我选择用try-catcth捕捉,到时候主函数就不用处理了
}
public boolean changepassword(String pwd) {
String sql = "update SuperAdmin set pwd=? where id='Admin'";
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
ps.setString(1, pwd);
ps.execute();
return true;
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean login(String pwd) {
String sql = "select * from SuperAdmin where id='admin'";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
String sqlpwd = rs.getString(2);
if(pwd.equals(sqlpwd))
{
return true;
}
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
return false;
}
}
<file_sep>/src/attendance/bean/Afl.java
package attendance.bean;
public class Afl {
//请假申请记录(申请成功的保存没成自动从数据库删除)
public int Sno;//学号
public int Cno;//课程号
public String APname;//班级名
public String Aname;//姓名
public String Adate;//申请日期
public String ABegindate;//开始请假日期
public String Aenddate;//请假结束日期
public String Areason;//请假原因
public String Aresults;//请假结果,默认待审核
//数据库中Datetime类型对应java中的java util.data
public int getSno() {
return Sno;
}
public void setSno(int sno) {
this.Sno = sno;
}
public int getCno() {
return Cno;
}
public void setCno(int cno) {
this.Cno = cno;
}
public String getAPname() {
return APname;
}
public void setAPname(String aPname) {
this.APname = aPname;
}
public String getAname() {
return Aname;
}
public void setAname(String aname) {
this.Aname = aname;
}
public String getAdate() {
return Adate;
}
public void setAdate(String adate) {
this.Adate = adate;
}
public String getABegindat() {
return ABegindate;
}
public void setABegindat(String aBegindat) {
this.ABegindate = aBegindat;
}
public String getAenddate() {
return Aenddate;
}
public void setAenddate(String aenddate) {
this.Aenddate = aenddate;
}
public String getAreason() {
return Areason;
}
public void setAreason(String areason) {
this.Areason = areason;
}
public String getAresults() {
return Aresults;
}
public void setAresults(String aresults) {
this.Aresults = aresults;
}
public Afl() {
super();
// TODO Auto-generated constructor stub
}
public Afl(int sno, int cno, String aPname, String aname, String adate, String aBegindate, String aenddate, String areason,
String aresults) {
super();
this.Sno = sno;
this.Cno = cno;
this.APname = aPname;
this.Aname = aname;
this.Adate = adate;
this.ABegindate = aBegindate;
this.Aenddate = aenddate;
this.Areason = areason;
this.Aresults = aresults;
}
@Override
public String toString() {
return "Afl [Sno=" + Sno + ", Cno=" + Cno + ", APname=" + APname + ", Aname=" + Aname + ", Adate=" + Adate
+ ", ABegindate=" + ABegindate + ", Aenddate=" + Aenddate + ", Areason=" + Areason + ", Aresults=" + Aresults
+ "]";
}
}
<file_sep>/src/teacher/TQController.java
package teacher;
import java.util.ArrayList;
import java.util.List;
import admin.studentUI.pwdtrans;
import attendance.bean.Afl;
import attendance.bean.Course;
import attendance.bean.PC;
import attendance.bean.Student;
import attendance.dao.AflDao;
import attendance.dao.CourseDao;
import attendance.dao.PCDao;
import attendance.dao.StudentDao;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
public class TQController {
@FXML private Label id;
@FXML private Label classname;
@FXML private Label name;
@FXML private Label courseid;
@FXML private Label coursename;
@FXML private Label applytime;
@FXML private Label startdate;
@FXML private Label enddate;
@FXML private Label label1;
@FXML private Label label2;
@FXML private Label label3;
@FXML private Label label4;
@FXML private Label label5;
@FXML private Label label6;
@FXML private Label label7;
@FXML private Label label8;
@FXML private Label label9;
@FXML private TextArea reason1;
@FXML private Button accept;
@FXML private Button inject;
@FXML private Button reload;
@FXML private ComboBox ifaccept;
@FXML private ListView list;
@FXML
protected void Accept(ActionEvent event) {
AflDao dao = new AflDao();
List<Afl> is = new ArrayList<Afl>();
dao.update2(Integer.valueOf(id.getText().toString()), Integer.valueOf(courseid.getText().toString()), applytime.getText().toString(), "已批准");
accept.setDisable(true);
accept.setText("已批准");
inject.setDisable(false);
inject.setText("拒绝");
}
@FXML
protected void Reload(ActionEvent event) {
list.getItems().clear();
ReloadList();
}
@FXML
protected void Inject(ActionEvent event) {
AflDao dao = new AflDao();
List<Afl> is = new ArrayList<Afl>();
dao.update2(Integer.valueOf(id.getText().toString()), Integer.valueOf(courseid.getText().toString()), applytime.getText().toString(), "未通过");
inject.setDisable(true);
inject.setText("已拒绝");
accept.setDisable(false);
accept.setText("批准");
}
public void InitUI() {
id.setVisible(false);
classname.setVisible(false);
name.setVisible(false);
courseid.setVisible(false);
coursename.setVisible(false);
applytime.setVisible(false);
startdate.setVisible(false);
enddate.setVisible(false);
reason1.setVisible(false);
accept.setVisible(false);
inject.setVisible(false);
label1.setVisible(false);
label2.setVisible(false);
label3.setVisible(false);
label4.setVisible(false);
label5.setVisible(false);
label6.setVisible(false);
label7.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
ifaccept.getItems().addAll("待审核","已批准","未通过");
ifaccept.setValue("待审核");
ifaccept.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
AflDao dao= new AflDao();
List<Afl> is =new ArrayList<Afl>();
is=dao.list(TeachIdentity.getTno());
for(Afl a:is) {
//classoptions.add(c.Pname);
list.getItems().clear();
}
String results = ifaccept.getValue().toString();
System.out.println(results);
is = dao.get(TeachIdentity.getTno(), results);
System.out.println(TeachIdentity.getTno());
for(Afl a:is) {
System.out.println(a.Aname);
list.getItems().addAll(a.Aname+" "+a.Sno);
}
id.setVisible(false);
classname.setVisible(false);
name.setVisible(false);
courseid.setVisible(false);
coursename.setVisible(false);
applytime.setVisible(false);
startdate.setVisible(false);
enddate.setVisible(false);
reason1.setVisible(false);
accept.setVisible(false);
inject.setVisible(false);
label1.setVisible(false);
label2.setVisible(false);
label3.setVisible(false);
label4.setVisible(false);
label5.setVisible(false);
label6.setVisible(false);
label7.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
}
});
list.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event)
{
if(event.getClickCount()== 1)
{
try {
onFileListDbclicked();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
ReloadList();
}
public void onFileListDbclicked() {
//String item = list.selectionModelProperty().getValue().toString();
String item = list.getSelectionModel().getSelectedItem().toString();
int idstart = 0;
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}
int index = list.getSelectionModel().getSelectedIndex();
id.setVisible(true);
classname.setVisible(true);
name.setVisible(true);
courseid.setVisible(true);
coursename.setVisible(true);
applytime.setVisible(true);
startdate.setVisible(true);
enddate.setVisible(true);
reason1.setVisible(true);
accept.setVisible(true);
inject.setVisible(true);
reason1.setEditable(false);
AflDao dao = new AflDao();
List<Afl> is = new ArrayList<Afl>();
String status = ifaccept.getValue().toString();
is = dao.get(TeachIdentity.getTno(),status);
CourseDao dao1 = new CourseDao();
List<Course> is1 = new ArrayList<Course>();
id.setText(String.valueOf(is.get(index).Sno));
classname.setText(is.get(index).APname);
name.setText(is.get(index).Aname);
courseid.setText(String.valueOf(is.get(index).Cno));
is1=dao1.list1(is.get(index).Cno);
coursename.setText(is1.get(0).getCname());
applytime.setText(is.get(index).Adate);
startdate.setText(is.get(index).ABegindate);
enddate.setText(is.get(index).Aenddate);
reason1.setText(is.get(index).Areason);
if(is.get(index).Aresults.equals("待审核")) {
accept.setDisable(false);
accept.setText("批准");
inject.setDisable(false);
inject.setText("拒绝");
}
else if(is.get(index).Aresults.equals("未通过")) {
accept.setDisable(false);
inject.setDisable(true);
inject.setText("已拒绝");
accept.setText("批准");
}else if(is.get(index).Aresults.equals("已批准")) {
accept.setDisable(true);
inject.setDisable(false);
inject.setText("拒绝");
accept.setText("已批准");
}
label1.setVisible(true);
label2.setVisible(true);
label3.setVisible(true);
label4.setVisible(true);
label5.setVisible(true);
label6.setVisible(true);
label7.setVisible(true);
label8.setVisible(true);
label9.setVisible(true);
//ReloadList();
}
public void ReloadList() {
list.getItems().clear();
AflDao dao = new AflDao();
List<Afl> is = new ArrayList<Afl>();
String status = ifaccept.getValue().toString();
is = dao.get(TeachIdentity.getTno(), status);
for(Afl a:is) {
list.getItems().addAll(a.Aname+" "+a.Sno);
}
}
}
<file_sep>/src/attendance/test/AflDaoTest.java
package attendance.test;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.AC;
import attendance.bean.Afl;
import attendance.dao.ACDao;
import attendance.dao.AflDao;
public class AflDaoTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
AflDao dao= new AflDao();
List<Afl> is =new ArrayList<Afl>();
dao.add(4, 1, "计算机181", "陈世恩", "2020-04-14", "2020-04-15", "2020-04-16", "身体不适,需要请假");
}
}
<file_sep>/src/teacher/TCController.java
package teacher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import Login.Main;
import attendance.bean.Afl;
import attendance.bean.PC;
import attendance.bean.Teacher;
import attendance.dao.AflDao;
import attendance.dao.PCDao;
import attendance.dao.TeacherDao;
import javafx.event.ActionEvent;
import javafx.fxml.*;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class TCController {
public String name;
@FXML private Button kaoqinbutton;
@FXML private Button qingjiabutton;
@FXML private Button totalbutton;
@FXML private Button logoutbutton;
@FXML private Button changepwd;
@FXML private Label namelabel;
@FXML private Label qingjia;
@FXML private ImageView image;
@FXML
protected void LoadRoutine(ActionEvent event) throws IOException {
new TeachRoutineUI().start(new Stage());
}
@FXML
protected void LoadTotal(ActionEvent event) throws IOException {
new TeachTotalUI().start(new Stage());
}
@FXML
protected void LogOut(ActionEvent event) throws IOException {
new Main().start(new Stage());
Stage stage = (Stage)logoutbutton.getScene().getWindow();
stage.hide();
}
@FXML
protected void Changepwd(ActionEvent event) throws IOException {
new TeachDetail().start(new Stage());
}
@FXML
protected void Qingjia(ActionEvent event) throws IOException {
new TeachQingjia().start(new Stage());
}
public void getno() {
int Tno = TeachIdentity.getTno();
TeacherDao dao = new TeacherDao();
List<Teacher> is =new ArrayList<Teacher>();
is = dao.list3();
for(Teacher t:is) {
if(t.Tno==Tno) {
namelabel.setText(t.Tname);
break;
}
}
// namelabel.setText("霸道总裁");
AflDao adao = new AflDao();
List<Afl> ais =new ArrayList<Afl>();
ais = adao.get(Tno, "待审核");
int count = 0;
for(Afl a:ais) {
count++;
}
if(count==0) {
image.setVisible(false);
qingjia.setVisible(false);
}
else {
image.setVisible(true);
qingjia.setVisible(true);
qingjia.setText(count+"条请假消息待审核");
}
qingjiabutton.setId("button-custom");
}
}
<file_sep>/src/admin/xueqinfoUI/XueqinfoUI.java
package admin.xueqinfoUI;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import teacher.TRController;
public class XueqinfoUI {
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("XueqinfoUI.fxml"));
Parent root =loader.load();
XQController Controller = loader.getController();
Scene scene = new Scene(root, 784, 482);
stage.setScene(scene);
stage.setTitle("学期信息管理");
stage.show();
Controller.InitUI();
}
}
<file_sep>/src/attendance/dao/CourseDao.java
package attendance.dao;
//课程DAO,给管理员用的
import java.sql.*;
import javax.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import attendance.bean.Course;
public class CourseDao {
public CourseDao(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
}
public Connection getConnection()throws SQLException{
//抛出异常
return DriverManager.getConnection("jdbc:sqlserver://sql.cerny.cn:1433;DatabaseName=attendance", "sa", "Myclassdesign330");
//数据库的名字叫attendance,我的数据库账户是sa,密码是sa
//这里我建立连接的时候不是用try-catcth来捕捉异常,而是主动抛出,那么我下面调用这个函数时要么继续抛出,要么用try-catcth捕捉,我选择用try-catcth捕捉,到时候主函数就不用处理了
}
public int getTotal() {
//得到目前表Course总数有多少条
int total = 0;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "select count(*) from Course";
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
total = rs.getInt(1);// 这里getInt是因为rs这个结果集这里是返回的结果行数
}
// System.out.println("total:" + total);
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
public boolean add(int Cno,String Cname) {
//这里增加函数课程号(本来主码可以自增不插,但我这里还是打开自增规则插进去),
//课程号,课程名
String sql = "set identity_insert Course ON insert into Course(Cno,Cname) values(?,?) set identity_insert Course OFF";
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);) {
ps.setInt(1,Cno);
ps.setString(2,Cname);
ps.execute();
return true;
//ResultSet rs = ps.getGeneratedKeys();//如果因为主码自增不插,然后通过这里得到主码赋值给对象对应的属性
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean update(int Cno,String Cname) {
//课程号,课程名
//不更新主码,主码一般不允许更新,一般允许更新主码的数据库设计都是不合理的
String sql = "update Course set Cname=? where Cno ="+Cno;
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
ps.setString(1, Cname);
ps.execute();
return true;
// System.out.println("修改成功");
}catch (SQLException e1) {
e1.printStackTrace();
}catch (Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
return false;
}
public boolean delete(int Cno) {
//删除函数
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "delete from Course where Cno ="+Cno;
s.execute(sql);
return true;
//System.out.println("删除成功");
}catch(SQLException e1) {
e1.printStackTrace();
}catch(Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
return false;
}
public List<Course> list1(int Cno) {
List<Course> courses = new ArrayList<Course>();
//把符合条件的Course数据查询出来,转换为Course对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
String Cname=null;//课程名
//按即主码查询,单个
//System.out.println("请输入要查询课程号:");
String sql = "select * from Course where Cno ="+Cno;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Course的对象course ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Course course=new Course() ;
Cno= rs.getInt(1);
Cname = rs.getString("Cname");
course.Cno=Cno;
course.Cname=Cname;
courses.add(course);
}
}catch (SQLException e) {
e.printStackTrace();}
return courses;//返回系集合,符合条件的系的信息
}
public List<Course> list2() {
List<Course> courses = new ArrayList<Course>();
//把Course数据查询出来,转换为Course对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
int Cno=0;//课程号
String Cname=null;//课程名
//都查询出来
//System.out.println("请输入要查询课程号:");
String sql = "select * from Course ";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Course的对象course ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* */
Course course=new Course() ;
Cno= rs.getInt(1);
Cname = rs.getString("Cname");
course.Cno=Cno;
course.Cname=Cname;
courses.add(course);
}
}catch (SQLException e) {
e.printStackTrace();}
return courses;//返回系集合,符合条件的系的信息
}
public List<Course> list3(String Cname) {
List<Course> courses = new ArrayList<Course>();
//把符合条件的Course数据查询出来,转换为Course对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
//String Cname=null;//课程名
int Cno = 0;
//按即主码查询,单个
//System.out.println("请输入要查询课程号:");
String sql = "select * from Course where Cname =" + "'" + Cname + "'";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Course的对象course ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Course course=new Course() ;
Cno= rs.getInt(1);
Cname = rs.getString("Cname");
course.Cno=Cno;
course.Cname=Cname;
courses.add(course);
}
}catch (SQLException e) {
e.printStackTrace();}
return courses;//返回系集合,符合条件的系的信息
}
}
<file_sep>/src/teacher/TeachRoutineTrans.java
package teacher;
public class TeachRoutineTrans {
public static String classname;
public static int id;
public static String name;
public static int courseid;
public static String coursename;
public static String date;
public static String situation;
public static String getClassname() {
return classname;
}
public static void setClassname(String classname) {
TeachRoutineTrans.classname = classname;
}
public static int getId() {
return id;
}
public static void setId(int id) {
TeachRoutineTrans.id = id;
}
public static String getName() {
return name;
}
public static void setName(String name) {
TeachRoutineTrans.name = name;
}
public static int getCourseid() {
return courseid;
}
public static void setCourseid(int courseid) {
TeachRoutineTrans.courseid = courseid;
}
public static String getCoursename() {
return coursename;
}
public static void setCoursename(String coursename) {
TeachRoutineTrans.coursename = coursename;
}
public static String getDate() {
return date;
}
public static void setDate(String date) {
TeachRoutineTrans.date = date;
}
public static String getSituation() {
return situation;
}
public static void setSituation(String situation) {
TeachRoutineTrans.situation = situation;
}
}
<file_sep>/src/student/StuDetail.java
package student;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class StuDetail {
public void start(Stage stage) throws IOException {
stage.setTitle("主界面");
//Parent root = FXMLLoader.load(getClass().getResource("TeachChooseUI.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("StuDetail.fxml"));
Parent root =loader.load();
SDController Controller = loader.getController();
Scene scene = new Scene(root, 441, 501);
stage.setScene(scene);
stage.show();
Controller.InitUI();
//Controller.InitUI();
}
}
<file_sep>/src/attendance/bean/Xueqi.java
package attendance.bean;
import java.util.Date;
public class Xueqi {
public Date startdate;
public Date enddate;
public int Xueqi;
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
public int getXueqi() {
return Xueqi;
}
public void setXueqi(int xueqi) {
Xueqi = xueqi;
}
public Xueqi() {
super();
}
public Xueqi(Date startdate, Date enddate, int Xueqi) {
this.startdate = startdate;
this.enddate = enddate;
this.Xueqi = Xueqi;
}
}
<file_sep>/src/student/StudIdentityTrans.java
package student;
public class StudIdentityTrans {
public static int Cno;
public static String Cname;
public static int Status;//判断右键菜单是否展开
public static int getStatus() {
return Status;
}
public static void setStatus(int status) {
StudIdentityTrans.Status = status;
}
public static int getCno() {
return Cno;
}
public static void setCno(int Cno) {
StudIdentityTrans.Cno = Cno;
}
public static String getCname() {
return Cname;
}
public static void setCname(String Cname) {
StudIdentityTrans.Cname = Cname;
}
}
<file_sep>/src/attendance/test/XueqiDaoTest.java
package attendance.test;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import attendance.bean.Qimo;
import attendance.bean.Xueqi;
import attendance.dao.QimoDao;
import attendance.dao.XueqiDao;
public class XueqiDaoTest {
public static void main(String[] args) throws ParseException{
XueqiDao dao= new XueqiDao();
List<Xueqi> is =new ArrayList<Xueqi>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//ParsePosition pos = new ParsePosition(0);
Date date1 = sdf.parse("2020-01-01");
Date date2 = sdf.parse("2020-04-10");
//System.out.println(date1);
//System.out.println(date2);
//dao.add(date1, date2,2);
// is = dao.getList();
// for(Xueqi x:is) {
// String s = new SimpleDateFormat("yyyy").format(x.startdate);
// System.out.println(s);
// System.out.println(x.enddate);
// System.out.println(x.Xueqi);
// }
dao.delete("2020-01-01", "2020-04-10");
}
}
<file_sep>/src/admin/teachinfoUI/TeachInfoUI.java
package admin.teachinfoUI;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import admin.studentUI.AfImagePane;
import admin.studentUI.FileItem;
import admin.studentUI.TextFileUtils;
import admin.teacherUI.pwdtrans;
import attendance.bean.PC;
import attendance.bean.Student;
import attendance.bean.Teach;
import attendance.bean.Teacher;
import attendance.bean.TeachforUI;
import attendance.dao.PCDao;
import attendance.dao.StudentDao;
import attendance.dao.TeachDao;
import attendance.dao.TeacherDao;
public class TeachInfoUI{
int idstart = 0;
ListView fileList = new ListView();
TabPane tabPane = new TabPane(); // 中间放一个Tab容器
// 必须static 类型
final ObservableList<TeachCourse> data = FXCollections.observableArrayList();
public void start(Stage stage) throws IOException {
initList();
// tabPane.getSelectionModel().selectedItemProperty().addListener(
// new ChangeListener<Tab>() {
// @Override
// public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1) {
//
// System.out.println("Tab Selection changed");
// String item = tabPane.getSelectionModel().getSelectedItem().toString();
// try {
// openFile1(item);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
// );
stage.setTitle("教师任课信息管理");
BorderPane border = new BorderPane();
HBox hbox = addHBox();
border.setTop(hbox);
//border.setLeft(addVBox());
addStackPane(hbox); //添加一个堆栈面板到上方区域的HBox中
Label label = new Label("色彩块");
label.setPrefSize(200, 300);
label.setStyle("-fx-background-color: #ffffff");
//border.setRight(label);
border.setLeft(fileList);
border.setCenter(tabPane);
//border.setCenter(addGridPane());
//border.setRight(addFlowPane());
//Parent root = FXMLLoader.load(getClass().getResource("Student.fxml"));
Scene scene = new Scene(border, 1327, 547);
//ListView<String> list = new ListView<>();
//ObservableList<String> items =FXCollections.observableArrayList (
// "Single", "Double", "Suite", "Family App");
//list.setItems(items);
/**
* listView的事件处理添加
*/
stage.setScene(scene);
stage.show();
}
public static class TeachCourse {
private final SimpleStringProperty Cono;
private final SimpleStringProperty CoName;
private final SimpleStringProperty Coschool;
private final SimpleStringProperty Cograde;
private TeachCourse(String Cono1, String CoName1, String Coschool1, String Cograde1) {
this.Cono = new SimpleStringProperty(Cono1);
this.CoName = new SimpleStringProperty(CoName1);
this.Coschool = new SimpleStringProperty(Coschool1);
this.Cograde = new SimpleStringProperty(Cograde1);
}
public String getCono() {
return Cono.get();
}
public void setCono(String Cono1) {
Cono.set(Cono1);
}
public String getCoName() {
return CoName.get();
}
public void setCoName(String CoName1) {
CoName.set(CoName1);
}
public String getCoschool() {
return Coschool.get();
}
public void setCoschool(String Coschool1) {
Coschool.set(Coschool1);
}
public String getCograde() {
return Cograde.get();
}
public void setCograde(String Cograde1) {
Cograde.set(Cograde1);
}
}
private void initList()
{
fileList.setPrefWidth(200);
TeacherDao dao= new TeacherDao();
List<Teacher> is =new ArrayList<Teacher>();
is =dao.list3();
ObservableList<String> items =FXCollections.observableArrayList ();
for (Teacher b : is) {
//System.out.printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n",b.Pcname,b.Pname,b.Sname,b.Sno,b.Sex,b.Sage,b.Sbirthtime,b.Snative);
//System.out.printf("%d\t%s\t%s\t%d\t%s\t%s\n",b.Sno,b.Sname,b.Sex,b.Sage,b.Snative,b.Spassword);
System.out.println();
//String item = String.valueOf(b.Sname);
String item = b.Tname + " " + b.Tno;
items.add(item);
//System.out.println(item.length());
//Character.isDigit(item.charAt(9));
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}
System.out.println(idstart);
}
// 左侧加载examples目录下的文件
fileList.setItems(items);
// 当双击左侧时,右侧显示内容
fileList.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event)
{
if(event.getClickCount()== 2)
{
try {
onFileListDbclicked();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public void addStackPane(HBox hb){
StackPane stack = new StackPane();
Rectangle helpIcon = new Rectangle(30.0, 25.0);
helpIcon.setFill(new LinearGradient(0,0,0,1, true, CycleMethod.NO_CYCLE,
new Stop[]{
new Stop(0,Color.web("#4977A3")),
new Stop(0.5, Color.web("#B0C6DA")),
new Stop(1,Color.web("#9CB6CF")),}));
helpIcon.setStroke(Color.web("#D0E6FA"));
helpIcon.setArcHeight(3.5);
helpIcon.setArcWidth(3.5);
Text helpText = new Text("?");
helpText.setFont(Font.font("Verdana", FontWeight.BOLD, 18));
helpText.setFill(Color.WHITE);
helpText.setStroke(Color.web("#7080A0"));
stack.getChildren().addAll(helpIcon, helpText);
stack.setAlignment(Pos.CENTER_RIGHT); //右对齐节点
StackPane.setMargin(helpText, new Insets(0, 10, 0, 0)); //设置问号居中显示
hb.getChildren().add(stack); // 将StackPane添加到HBox中
HBox.setHgrow(stack, Priority.ALWAYS); // 将HBox水平多余的所有空间都给StackPane,这样前面设置的右对齐就能保证问号按钮在最右边
}
public VBox addVBox(){
VBox vbox = new VBox();
vbox.setPadding(new Insets(10)); //内边距
vbox.setSpacing(8); //节点间距
Text title = new Text("Data");
title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
vbox.getChildren().add(title);
Hyperlink options[] = new Hyperlink[] {
new Hyperlink("Sales"),
new Hyperlink("Marketing"),
new Hyperlink("Distribution"),
new Hyperlink("Costs")};
for (int i=0; i<4; i++){
VBox.setMargin(options[i], new Insets(0, 0, 0, 8)); //为每个节点设置外边距
vbox.getChildren().add(options[i]);
}
return vbox;
}
public TableView addTableView() {
TableView table = new TableView();
data.clear();
table.setEditable(true);
TableColumn<TeachCourse, String> firstCol =
new TableColumn<>("课程号");
firstCol.setCellValueFactory(
new PropertyValueFactory<>("Cono"));
firstCol.setCellFactory(TextFieldTableCell.<TeachCourse>forTableColumn());
table.setRowFactory( tv -> {
System.out.println("Test");
TableRow<TeachCourse> row = new TableRow<TeachCourse>();
String item = fileList.getSelectionModel().getSelectedItem().toString();
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}TeachCourse tc=null;
tc = row.getItem();
return row ;
});
// table.setRowFactory( tv -> {
// TableRow<TeachCourse> row = new TableRow<TeachCourse>();
// row.setOnMouseClicked(event -> {
//
// if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
// TeachCourse tc = row.getItem();
// System.out.println(tc.getCoName());
// }
// });
// return row ;
// });
TableColumn<TeachCourse, String> secondCol =
new TableColumn<>("课程名");
secondCol.setCellValueFactory(
new PropertyValueFactory<>("CoName"));
secondCol.setCellFactory(TextFieldTableCell.<TeachCourse>forTableColumn());
TableColumn<TeachCourse, String> thirdCol =
new TableColumn<>("所需学时");
thirdCol.setCellValueFactory(
new PropertyValueFactory<>("Coschool"));
thirdCol.setCellFactory(TextFieldTableCell.<TeachCourse>forTableColumn());
TableColumn<TeachCourse, String> fourthCol =
new TableColumn<>("学分");
fourthCol.setCellValueFactory(
new PropertyValueFactory<>("Cograde"));
fourthCol.setCellFactory(TextFieldTableCell.<TeachCourse>forTableColumn());
firstCol.setPrefWidth(170);
secondCol.setPrefWidth(270);
thirdCol.setPrefWidth(120);
fourthCol.setPrefWidth(120);
table.getColumns().addAll(firstCol,secondCol,thirdCol,fourthCol);
String item = fileList.getSelectionModel().getSelectedItem().toString();
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
pwdtrans.setPno(idstart);
//System.out.println(item.substring(i));
}
}
firstCol.setOnEditCommit(
(CellEditEvent<TeachCourse, String> t) -> {
String onetemp = firstCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCono();
((TeachCourse) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setCono(t.getNewValue());
String one = t.getNewValue();
//System.out.println("Test");
String two = secondCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoName();
//System.out.println(tc.getCoName());
String three = thirdCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoschool();
String four = fourthCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCograde();
TeachDao dao = new TeachDao();
List<Teach>is = new ArrayList<Teach>();
int idstart = pwdtrans.getSno();
System.out.println(t.getNewValue());
if(dao.update(idstart, Integer.valueOf(onetemp) , idstart, Integer.valueOf(t.getNewValue()), Integer.valueOf(three), Integer.valueOf(four))) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改成功");
alert.showAndWait();
}
else {
((TeachCourse) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setCoName(onetemp);
table.refresh();
}
});
secondCol.setOnEditCommit(
(CellEditEvent<TeachCourse, String> t) -> {
// String onetemp = firstCol.getTableView().getItems().get(
// t.getTablePosition().getRow()).getCono();
// ((TeachCourse) t.getTableView().getItems().get(
// t.getTablePosition().getRow())
// ).setCono(t.getNewValue());
String one = firstCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCono();
String twotemp = secondCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoName();
//String two = t.getNewValue();
//System.out.println(tc.getCoName());
String three = thirdCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoschool();
String four = fourthCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCograde();
TeachDao dao = new TeachDao();
List<Teach>is = new ArrayList<Teach>();
int idstart = pwdtrans.getSno();
System.out.println(t.getNewValue());
//if(dao.update(idstart, Integer.valueOf(twotemp) , idstart, Integer.valueOf(t.getNewValue()), Integer.valueOf(three), Integer.valueOf(four))) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("此项目无法更改,请前往课程管理界面修改");
alert.showAndWait();
System.out.println(twotemp);
((TeachCourse) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setCoName(twotemp);
table.refresh();
});
thirdCol.setOnEditCommit(
(CellEditEvent<TeachCourse, String> t) -> {
//System.out.println("Test");
String one = firstCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCono();
String two = secondCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoName();
//System.out.println(tc.getCoName());
String threetemp = thirdCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoschool();
String three = t.getNewValue();
String four = fourthCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCograde();
TeachDao dao = new TeachDao();
List<Teach>is = new ArrayList<Teach>();
int idstart = pwdtrans.getSno();
System.out.println(t.getNewValue());
if(dao.update(idstart, Integer.valueOf(one) , idstart, Integer.valueOf(one), Integer.valueOf(three), Integer.valueOf(four))) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改成功");
alert.showAndWait();
}
else {
((TeachCourse) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setCoName(threetemp);
table.refresh();
}
});
fourthCol.setOnEditCommit(
(CellEditEvent<TeachCourse, String> t) -> {
String one = firstCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCono();
String two = secondCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoName();
//System.out.println(tc.getCoName());
String three = thirdCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCoschool();
String fourtemp = fourthCol.getTableView().getItems().get(
t.getTablePosition().getRow()).getCograde();
String four = t.getNewValue();
TeachDao dao = new TeachDao();
List<Teach>is = new ArrayList<Teach>();
int idstart = pwdtrans.getSno();
System.out.println(t.getNewValue());
if(dao.update(idstart, Integer.valueOf(one) , idstart, Integer.valueOf(one), Integer.valueOf(three), Integer.valueOf(four))) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("修改成功");
alert.showAndWait();
}
else {
((TeachCourse) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setCoName(fourtemp);
table.refresh();
}
});
TeachDao dao = new TeachDao();
List<TeachforUI> is = new ArrayList<TeachforUI>();
is = dao.list3forUI(idstart);
for(TeachforUI t:is) {
System.out.printf("\n%d\t%s\t%d\t%d\n", t.Cno,t.Cname,t.Tschool,t.Tsgrade);
data.add(new TeachCourse(String.valueOf(t.Cno),t.Cname,String.valueOf(t.Tschool),String.valueOf(t.Tsgrade)));
//data.add(new TeachCourse("Jacob", "Smith", "<EMAIL>", "Test"));
System.out.println();
}
table.setItems(data);
return table;
}
public void SeletedTabPane(String item) {
// TableView table = new TableView();
//
// table.setEditable(true);
// TableColumn firstCol = new TableColumn("课程号");
// TableColumn secondCol = new TableColumn("课程名");
// TableColumn thirdCol = new TableColumn("所需学时");
// TableColumn fourthCol = new TableColumn("学分");
// firstCol.setPrefWidth(170);
// secondCol.setPrefWidth(270);
// thirdCol.setPrefWidth(120);
// fourthCol.setPrefWidth(120);
// table.getColumns().addAll(firstCol,secondCol,thirdCol,fourthCol);
TeachDao dao = new TeachDao();
List<TeachforUI> is = new ArrayList<TeachforUI>();
int idstart = 0;
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}
is = dao.list3forUI(idstart);
for(TeachforUI t:is) {
System.out.printf("\n%d\t%s\t%d\t%d\n", t.Cno,t.Cname,t.Tschool,t.Tsgrade);
data.add(new TeachCourse(String.valueOf(t.Cno),t.Cname,String.valueOf(t.Tschool),String.valueOf(t.Tsgrade)));
}
}
public HBox addHBox(){
HBox hbox = new HBox();
hbox.setAlignment(Pos.CENTER);
hbox.setPadding(new Insets(15, 12, 15, 12)); //节点到边缘的距离
hbox.setSpacing(10);//节点之间的间距
hbox.setStyle("-fx-background-color: #336699"); //背景色
Button buttonCurrent = new Button("刷新数据");
buttonCurrent.setPrefSize(100, 20);
Button buttonAdd = new Button("新增课程(当前选择)");
TextField Cno = new TextField();
TextField Cname = new TextField();
TextField Tschool = new TextField();
TextField Tsgrade = new TextField();
Cno.setPromptText("课程号");
Cname.setPromptText("课程名");
Tschool.setPromptText("所需学时");
Tsgrade.setPromptText("学分");
//buttonAdd.setPrefSize(100, 20);
buttonAdd.setOnAction((ActionEvent e) -> {
// data.add(new TeachforUI(
// Integer.parseInt(Cno.getText()),
// Cname.getText().toString(),
// Integer.parseInt(Tschool.getText()),
// Integer.parseInt(Tsgrade.getText())
// ));
TeachDao dao = new TeachDao();
if(tabPane.getTabs().isEmpty()) {
Alert alert1 = new Alert(Alert.AlertType.ERROR);
alert1.setTitle("错误");
alert1.setHeaderText(null);
alert1.setContentText("添加失败!当前无打开的面板。");
alert1.showAndWait();
}
else {
if(dao.add(idstart, Integer.valueOf(Cno.getText()), Integer.valueOf(Tschool.getText()), Integer.valueOf(Tsgrade.getText()))) {
data.add(new TeachCourse(String.valueOf(Cno.getText()),Cname.getText().toString(),Tschool.getText(),Tsgrade.getText()));
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("添加成功");
alert.showAndWait();
Cno.clear();
Cname.clear();
Tschool.clear();
Tsgrade.clear();
}
else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText("添加失败!请检查课程号与课程名是否对应!");
alert.showAndWait();
}
}
});
hbox.getChildren().addAll(buttonCurrent, buttonAdd,Cno ,Cname, Tschool, Tsgrade);
buttonCurrent.setOnAction((ActionEvent e) -> {
initList();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("读取成功");
alert.showAndWait();
});
return hbox;
}
private void onFileListDbclicked() throws Exception
{
TeacherDao dao= new TeacherDao();
List<Teacher> is =new ArrayList<Teacher>();
int id=0;
int index = fileList.getSelectionModel().getSelectedIndex();
String name_id = fileList.getSelectionModel().getSelectedItem().toString();
for(int i=0;i<name_id.length();i++) {
if(Character.isDigit(name_id.charAt(i))) {
id=Integer.parseInt(name_id.substring(i));
//System.out.println(item.substring(i));
}
}
//FileItem item = fileList.data().get(index);
is =dao.list3();
for (Teacher b : is) {
//System.out.printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n",b.Pcname,b.Pname,b.Sname,b.Sno,b.Sex,b.Sage,b.Sbirthtime,b.Snative);
//System.out.printf("%d\t%s\t%s\t%d\t%s\t%s\n",b.Sno,b.Sname,b.Sex,b.Sage,b.Snative,b.Spassword);
System.out.println();
//String item = String.valueOf(b.Sname);
String item = b.Tname + " " + b.Tno;
Tab tab = null;
tab = findTab(item);
if(tab!=null) {
tabPane.getTabs().remove(tab);
}
System.out.print(b);
if(id==b.Tno) {
openFile(item);
}
}
}
private void openFile1(String item) throws Exception
{
// 查看选项卡是否已经打开
Tab tab = findTab ( item );
if( tab != null)
{
int tabIndex = tabPane.getTabs().indexOf(tab);
tabPane.getSelectionModel().select(tabIndex);
SeletedTabPane(item);
}
}
// 打开文件
private void openFile(String item) throws Exception
{
// 查看选项卡是否已经打开
Tab tab = findTab ( item );
if( tab != null)
{
int tabIndex = tabPane.getTabs().indexOf(tab);
tabPane.getSelectionModel().select(tabIndex);
return;
}
// 打开一个新选项卡
Node contentView = null;
if(true) // text file
{
// 注意: 这里演示的文件是GBK的
//GridPane grid = addGridPane();
TableView table = addTableView();
//String text = TextFileUtils.read(item.file, "GBK");
//TextArea t = new TextArea();
//t.setText( text );
contentView = table;
}
// 添加一个TAB页
tab = new Tab();
tab.setText( item );
tab.setContent(contentView);
tabPane.getTabs().add(tab);
int tabIndex = tabPane.getTabs().indexOf(tab);
tabPane.getSelectionModel().select(tabIndex);
}
// 查找选项卡是否已经打开
private Tab findTab (String item)
{
ObservableList<Tab> tabs = tabPane.getTabs();
for(int i=0; i< tabs.size(); i++)
{
Tab t = tabs.get(i);
if( t.getText().equals(item))
{
return t;
}
}
return null;
}
private void closeFile(String item) throws Exception
{
// 查看选项卡是否已经打开
Tab tab = findTab ( item );
if( tab != null)
{
if(item.equals("新建教师")) {
int tabIndex = tabPane.getTabs().indexOf(tab);
tabPane.getTabs().remove(tabIndex);
}
else {
int tabIndex = tabPane.getTabs().indexOf(tab);
for(int i=0;i<tabIndex;i++) {
tabPane.getSelectionModel().select(tabIndex);
tabPane.getTabs().remove(tabIndex);
}
}
return;
}
}
}
<file_sep>/src/student/SXController.java
package student;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.Course;
import attendance.bean.SC;
import attendance.dao.CourseDao;
import attendance.dao.SCDao;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
public class SXController {
//@FXML private Button commitbutton;
@FXML private ComboBox select;
@FXML
protected void Confirm(ActionEvent event) {
SCDao dao = new SCDao();
CourseDao cdao = new CourseDao();
List<Course> is = new ArrayList<Course>();
is = cdao.list3(select.getValue().toString());
if(dao.add(StudIdentityTrans.getCno(), is.get(0).Cno)) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("选课成功!");
select.getItems().clear();
InitUI();
alert.showAndWait();
}
else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("未选择课程!");
alert.showAndWait();
}
}
public void InitUI() {
SCDao dao = new SCDao();
List<Course> is = new ArrayList<Course>();
is = dao.listweixuan(StudIdentityTrans.getCno());
for(Course c:is) {
System.out.println(c.Cname);
select.getItems().add(c.Cname);
}
}
}
<file_sep>/src/admin/banjiinfoUI/XueyuanInfoUI.java
package admin.banjiinfoUI;
import java.io.IOException;
import admin.studentUI.pwdtrans;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class XueyuanInfoUI {
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("XueyuanInfoUI.fxml"));
Parent root =loader.load();
XIController Controller = loader.getController();
Scene scene = new Scene(root, 573, 400);
stage.setScene(scene);
stage.setTitle("学院信息管理");
stage.setOnHiding(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
System.out.println("监听到窗口关闭1");
// FXMLLoader loader1 = new FXMLLoader(ClassInfoUI.class.getResource("ClassInfoUI.fxml"));
// CIController Controller1 = loader1.getController();
// Controller1.ReloadCombo();
}
});
stage.show();
Controller.InitUI();
}
}
<file_sep>/src/teacher/TTController.java
package teacher;
import java.time.format.DateTimeFormatter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import admin.studentUI.pwdtrans;
import admin.teachinfoUI.TeachInfoUI.TeachCourse;
import attendance.bean.AC;
import attendance.bean.Course;
import attendance.bean.PC;
import attendance.bean.Qimo;
import attendance.bean.SC;
import attendance.bean.Student;
import attendance.bean.Teach;
import attendance.bean.TeachforUI;
import attendance.bean.Xueqi;
import attendance.dao.ACDao;
import attendance.dao.CourseDao;
import attendance.dao.PCDao;
import attendance.dao.QimoDao;
import attendance.dao.SCDao;
import attendance.dao.StudentDao;
import attendance.dao.TeachDao;
import attendance.dao.XueqiDao;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.Callback;
import javafx.util.StringConverter;
import teacher.TRController.TeachRoutine;
public class TTController {
@FXML private ComboBox xueqicombo;
@FXML private ComboBox namecombo;
@FXML private ComboBox classcombo;
@FXML private ComboBox coursenamecombo;
@FXML private Button addbutton;
@FXML private Button loadbutton;
@FXML private Button addallbutton;
@FXML private TableView table;
@FXML private TableColumn classname;
@FXML private TableColumn id;
@FXML private TableColumn name;
@FXML private TableColumn term;
@FXML private TableColumn courseid;
@FXML private TableColumn coursename;
@FXML private TableColumn Qan;
@FXML private TableColumn Qaln;
@FXML private TableColumn Qtn;
@FXML private TableColumn Qlen;
@FXML private TableColumn Qlate;
final ObservableList<TeachTotal> data = FXCollections.observableArrayList();
int count1 = 0;
String[][] storage = null;
int i = 0;
public static class TeachTotal {
private final SimpleStringProperty classname;
private final SimpleStringProperty id;
private final SimpleStringProperty name;
private final SimpleStringProperty xueqi;
private final SimpleStringProperty courseid;
private final SimpleStringProperty coursename;
private final SimpleStringProperty Qan;
private final SimpleStringProperty Qaln;
private final SimpleStringProperty Qtn;
private final SimpleStringProperty Qlen;
private final SimpleStringProperty Qlate;
private TeachTotal(String classname1, String id1, String name1, String xueqi1, String courseid1, String coursename1, String Qan1, String Qaln1, String Qtn1, String Qlen1, String Qlate1) {
this.classname = new SimpleStringProperty(classname1);
this.id = new SimpleStringProperty(id1);
this.name = new SimpleStringProperty(name1);
this.xueqi = new SimpleStringProperty(xueqi1);
this.courseid = new SimpleStringProperty(courseid1);
this.coursename = new SimpleStringProperty(coursename1);
this.Qan = new SimpleStringProperty(Qan1);
this.Qaln = new SimpleStringProperty(Qaln1);
this.Qtn = new SimpleStringProperty(Qtn1);
this.Qlen = new SimpleStringProperty(Qlen1);
this.Qlate = new SimpleStringProperty(Qlate1);
}
public String getClassname() {
return classname.get();
}
public void setclassname(String classname1) {
classname.set(classname1);
}
public String getId() {
return id.get();
}
public void setid(String id1) {
id.set(id1);
}
public String getName() {
return name.get();
}
public void setname(String xueqi1) {
xueqi.set(xueqi1);
}
public String getXueqi() {
return xueqi.get();
}
public void setxueqi(String name1) {
name.set(name1);
}
public String getCourseid() {
return courseid.get();
}
public void setcourseid(String courseid1) {
courseid.set(courseid1);
}
public String getCoursename() {
return coursename.get();
}
public void setcoursename(String coursename1) {
coursename.set(coursename1);
}
public String getQan() {
return Qan.get();
}
public void setQan(String Qan1) {
Qan.set(Qan1);
}
public String getQaln() {
return Qaln.get();
}
public void setQaln(String Qaln1) {
Qaln.set(Qaln1);
}
public String getQtn() {
return Qtn.get();
}
public void setQtn(String Qtn1) {
Qtn.set(Qtn1);
}
public String getQlen() {
return Qlen.get();
}
public void setQlen(String Qlen1) {
Qlen.set(Qlen1);
}
public String getQlate() {
return Qlate.get();
}
public void setQlate(String Qlate1) {
Qlate.set(Qlate1);
}
}
@FXML
protected void Load(ActionEvent event) throws ParseException {
table.getItems().clear();
int max = 0;
QimoDao dao = new QimoDao();
List<Qimo> is = new ArrayList<Qimo>();
int index = xueqicombo.getSelectionModel().getSelectedIndex();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date startd = format.parse(storage[index][0]);
java.util.Date endd = format.parse(storage[index][1]);
java.sql.Date startd1 = new java.sql.Date(startd.getTime());
java.sql.Date endd1 = new java.sql.Date(endd.getTime());
is = dao.list7(startd1,endd1,TeachIdentity.getTno());
for(Qimo q:is) {
data.add(new TeachTotal(q.Pname, String.valueOf(q.Sno), q.Sname, q.Qstartdate.toString()+" ~ "+q.Qenddate.toString(), String.valueOf(q.Cno), q.Cname, String.valueOf(q.Qan), String.valueOf(q.Qaln), String.valueOf(q.Qtn), String.valueOf(q.Qlen), String.valueOf(q.Qlate)));
max++;
}
table.setItems(data);
table.refresh();
}
@FXML
protected void AddAll(ActionEvent event) {
try {
xueqicombo.getSelectionModel().getSelectedIndex();
coursenamecombo.getValue().toString();
StudentDao dao1 = new StudentDao();
List<Student> is1 = new ArrayList<Student>();
is1 = dao1.list2(classcombo.getValue().toString());
for(Student s:is1) {
String longname = s.Sname + " " + s.Sno;
SaveData(longname);
}
}catch(Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("请选择所要添加的班级/学期/课程");
alert.showAndWait();
}
}
@FXML
protected void Add(ActionEvent event) {
try {
SaveData(namecombo.getValue().toString());
}catch(Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("请选择所要添加的班级/学期/课程/学生");
alert.showAndWait();
}
}
public void SaveData(String item) {
try{
int num = xueqicombo.getSelectionModel().getSelectedIndex();
String start = storage[num][0];
String end = storage[num][1];
int idstart = 0;
int Cno = 0;
//String item = namecombo.getValue().toString();
for(int i=0;i<item.length();i++) {
if(Character.isDigit(item.charAt(i))) {
idstart=Integer.parseInt(item.substring(i));
//System.out.println(item.substring(i));
}
}
String kcname = coursenamecombo.getValue().toString();
CourseDao dao = new CourseDao();
List<Course> is = new ArrayList<Course>();
is = dao.list2();
for(Course c:is) {
if(c.Cname.equals(kcname)) {
Cno=c.Cno;
}
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date startd = format.parse(start);
java.util.Date endd = format.parse(end);
java.sql.Date startd1 = new java.sql.Date(startd.getTime());
java.sql.Date endd1 = new java.sql.Date(endd.getTime());
QimoDao qimodao = new QimoDao();
System.out.println(idstart);
System.out.println(Cno);
System.out.println(startd1);
System.out.println(endd1);
qimodao.add(idstart, Cno, startd1, endd1);
}catch(Exception e) {
e.printStackTrace();
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("已添加该学生考勤!无法重复添加!");
alert.showAndWait();
}
}
public void InitUI() {
InitComboBox();
InitNameComboBox();
classcombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
StudentDao stdao= new StudentDao();
List<Student> stis =new ArrayList<Student>();
stis=stdao.list3();
namecombo.getItems().clear();
stis=stdao.list2(classcombo.getValue().toString());
for(Student s:stis) {
String longname = s.Sname + " " + s.Sno;
namecombo.getItems().addAll(longname);
//System.out.println(count);
}
}
});
classname.setCellValueFactory(
new PropertyValueFactory<>("classname"));
classname.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
id.setCellValueFactory(
new PropertyValueFactory<>("id"));
id.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
name.setCellValueFactory(
new PropertyValueFactory<>("name"));
name.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
term.setCellValueFactory(
new PropertyValueFactory<>("xueqi"));
term.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
courseid.setCellValueFactory(
new PropertyValueFactory<>("courseid"));
courseid.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
coursename.setCellValueFactory(
new PropertyValueFactory<>("coursename"));
coursename.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
Qan.setCellValueFactory(
new PropertyValueFactory<>("Qan"));
Qan.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
Qaln.setCellValueFactory(
new PropertyValueFactory<>("Qaln"));
Qaln.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
Qtn.setCellValueFactory(
new PropertyValueFactory<>("Qtn"));
Qtn.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
Qlen.setCellValueFactory(
new PropertyValueFactory<>("Qlen"));
Qlen.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
Qlate.setCellValueFactory(
new PropertyValueFactory<>("Qlate"));
Qlate.setCellFactory(TextFieldTableCell.<TeachTotal>forTableColumn());
classname.setStyle("-fx-alignment: CENTER;");
id.setStyle("-fx-alignment: CENTER;");
name.setStyle("-fx-alignment: CENTER;");
term.setStyle("-fx-alignment: CENTER;");
courseid.setStyle("-fx-alignment: CENTER;");
coursename.setStyle("-fx-alignment: CENTER;");
Qan.setStyle("-fx-alignment: CENTER;");
Qaln.setStyle("-fx-alignment: CENTER;");
Qtn.setStyle("-fx-alignment: CENTER;");
Qlen.setStyle("-fx-alignment: CENTER;");
Qlate.setStyle("-fx-alignment: CENTER;");
LoadTableView();
}
public void LoadTableView() {
int max = 0;
QimoDao dao = new QimoDao();
List<Qimo> is = new ArrayList<Qimo>();
is = dao.list6(TeachIdentity.getTno());
for(Qimo q:is) {
data.add(new TeachTotal(q.Pname, String.valueOf(q.Sno), q.Sname, q.Qstartdate.toString()+" ~ "+q.Qenddate.toString(), String.valueOf(q.Cno), q.Cname, String.valueOf(q.Qan), String.valueOf(q.Qaln), String.valueOf(q.Qtn), String.valueOf(q.Qlen), String.valueOf(q.Qlate)));
max++;
}
table.setItems(data);
table.refresh();
}
public void InitComboBox() {
XueqiDao xueqi = new XueqiDao();
List<Xueqi> is = new ArrayList<Xueqi>();
is = xueqi.getList();
xueqicombo.getItems().clear();
for(Xueqi x:is) {
count1++;
}
storage = new String[count1][2];
for(Xueqi x:is) {
int start = 0;
int end = 0;
String s = new SimpleDateFormat("yyyy").format(x.startdate);
String e = new SimpleDateFormat("yyyy").format(x.enddate);
start = Integer.valueOf(s);
end = Integer.valueOf(e);
if(start==end) {
start = start - 1;
}
else if((start+1)==end) {
}
String count = null;
if(x.Xueqi==1) {
count = "一";
}
else if(x.Xueqi==2) {
count = "二";
}
String all = start + " - " + end + "学年" + "第" + count + "学期" + " ( " + x.startdate + " ~ " + x.enddate + " ) ";
xueqicombo.getItems().addAll(all);
storage[i][0]=x.startdate.toString();
storage[i][1]=x.enddate.toString();
i++;
}
for(i=0;i<count1;i++) {
System.out.println(storage[i][0]);
System.out.println(storage[i][1]);
}
TeachDao tdao = new TeachDao();
List<TeachforUI> tis =new ArrayList<TeachforUI>();
tis = tdao.list3forUI(TeachIdentity.getTno());
for(TeachforUI t:tis) {
System.out.println(t.Cno);
coursenamecombo.getItems().addAll(t.Cname);
}
}
public void InitNameComboBox() {
classcombo.getItems().clear();
PCDao pcdao= new PCDao();
List<PC> pcis =new ArrayList<PC>();
pcis=pcdao.list2();
for(PC c:pcis) {
System.out.println(c.Pname);
classcombo.getItems().addAll(c.Pname);
//classcombo.getItems().addAll(pcis);
}
}
}
<file_sep>/src/student/StudQingjia.java
package student;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class StudQingjia {
public void start(Stage stage) throws IOException {
stage.setTitle("主界面");
//Parent root = FXMLLoader.load(getClass().getResource("TeachChooseUI.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("StudQingjia.fxml"));
Parent root =loader.load();
SQController Controller = loader.getController();
Scene scene = new Scene(root, 832, 558);
stage.setScene(scene);
stage.show();
//Controller.getno();
Controller.InitUI();
}
}
<file_sep>/src/student/StudXuanke.java
package student;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import teacher.TCController;
public class StudXuanke {
public void start(Stage stage) throws IOException {
stage.setTitle("主界面");
//Parent root = FXMLLoader.load(getClass().getResource("TeachChooseUI.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("StudXuanke.fxml"));
Parent root =loader.load();
SXController Controller = loader.getController();
Scene scene = new Scene(root, 336, 343);
stage.setScene(scene);
stage.show();
//Controller.getno();
Controller.InitUI();
}
}
<file_sep>/src/teacher/TeachTotalUI.java
package teacher;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TeachTotalUI {
public void start(Stage stage) throws IOException {
stage.setTitle("主界面");
//Parent root = FXMLLoader.load(getClass().getResource("TeachChooseUI.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("TeachTotalUI.fxml"));
Parent root =loader.load();
TTController Controller = loader.getController();
Scene scene = new Scene(root, 1424, 727);
stage.setScene(scene);
stage.show();
Controller.InitUI();
}
}
<file_sep>/src/attendance/bean/PC.java
package attendance.bean;
public class PC {
public int Pno;//班级号
public String Pname;//班级名
public int Pnum;//班级总人数
public String Pcname;//系名
public int getPno() {
return Pno;
}
public void setPno(int pno) {
this.Pno = pno;
}
public String getPname() {
return Pname;
}
public void setPname(String pname) {
this.Pname = pname;
}
public int getPnum() {
return Pnum;
}
public void setPnum(int pnum) {
this.Pnum = pnum;
}
public String getPcname() {
return Pcname;
}
public void setPcname(String pcname) {
this.Pcname = pcname;
}
public PC() {
super();
// TODO Auto-generated constructor stub
}
public PC(int pno, String pname, int pnum, String pcname) {
super();
this.Pno = pno;
this.Pname = pname;
this.Pnum = pnum;
this.Pcname = pcname;
}
@Override
public String toString() {
return "PC [Pno=" + Pno + ", Pname=" + Pname + ", Pnum=" + Pnum + ", Pcname=" + Pcname + "]";
}
}
<file_sep>/src/attendance/bean/Teacher.java
package attendance.bean;
public class Teacher {
public int Tno;//职工号
public String Tname;//姓名
public String Tsex;//性别
public int Tage;//教龄
public String Tphone ;//电话
public String Tcname;//系名
public String Tbirthtime;//出生日期
public String Tpassword;//密码
public int getTno() {
return Tno;
}
public void setTno(int tno) {
this.Tno = tno;
}
public String getTname() {
return Tname;
}
public void setTname(String tname) {
this.Tname = tname;
}
public String getTsex() {
return Tsex;
}
public void setTsex(String tsex) {
this.Tsex = tsex;
}
public int getTage() {
return Tage;
}
public void setTage(short tage) {
this.Tage = tage;
}
public String getTphone() {
return Tphone;
}
public void setTphone(String tphone) {
this.Tphone = tphone;
}
public String getTcname() {
return Tcname;
}
public void setTcname(String tcname) {
this.Tcname = tcname;
}
public String getTbirthtime() {
return Tbirthtime;
}
public void setTbirthtime(String tbirthtime) {
Tbirthtime = tbirthtime;
}
public String getTpassword() {
return Tpassword;
}
public void setTpassword(String tpassword) {
this.Tpassword = tpassword;
}
public Teacher() {
super();
// TODO Auto-generated constructor stub
}
public Teacher(int tno, String tname, String tsex, int tage, String tphone, String tcname,String Tpassword, String tpassword) {
super();
this.Tno = tno;
this.Tname = tname;
this.Tsex = tsex;
this.Tage = tage;
this.Tphone = tphone;
this.Tcname = tcname;
this.Tpassword=<PASSWORD>;
this.Tpassword = <PASSWORD>;
}
@Override
public String toString() {
return "Teacher [Tno=" + Tno + ", Tname=" + Tname + ", Tsex=" + Tsex + ", Tage=" + Tage + ", Tphone=" + Tphone
+ ", Tcname=" + Tcname + ", Tbirthtime=" + Tbirthtime + ", Tpassword=" + Tpassword + "]";
}
}
<file_sep>/src/admin/studentUI/AfImagePane.java
package admin.studentUI;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
/*
* 用于显示图片的工具类
*
*/
public class AfImagePane extends Pane
{
ImageView imageView = new ImageView();
Image image;
public AfImagePane()
{
getChildren().add(imageView);
}
public void showImage(Image image)
{
this.image = image;
imageView.setImage(image);
layout();
}
@Override
protected void layoutChildren()
{
double w = getWidth();
double h = getHeight();
// 对ImageView进行摆放,使其适应父窗口
imageView.resizeRelocate(0, 0, w, h);
imageView.setFitWidth(w);
imageView.setFitHeight(h);
imageView.setPreserveRatio(true);
}
}
<file_sep>/src/attendance/bean/Qimo.java
package attendance.bean;
import java.sql.Date;
//期末考勤总记录,给老师用的
//这里的属性系名,班级,姓名,课程名并不是真正的期末考勤表里的属性,而是从期末视图查询出来,插入的是并没有插入期末表
public class Qimo {
public String Pcname;//系名
public String Pname;//班级
public int Sno;//学号
public String Sname;//姓名
public int Cno;//课程号
public String Cname;//课程名
public Date Qstartdate;//开始学年
public Date Qenddate;//结束学年
public int Qan;//出勤次数
public int Qaln;//请假次数
public int Qtn;//旷课次数
public int Qlen;//早退次数
public int Qlate;//迟到次数
public int getQlate() {
return Qlate;
}
public void setQlate(int qlate) {
this.Qlate = qlate;
}
public String getPcname() {
return Pcname;
}
public void setPcname(String pcname) {
this.Pcname = pcname;
}
public String getPname() {
return Pname;
}
public void setPname(String pname) {
this.Pname = pname;
}
public int getSno() {
return Sno;
}
public void setSno(int sno) {
this.Sno = sno;
}
public String getSname() {
return Sname;
}
public void setSname(String sname) {
this.Sname = sname;
}
public int getCno() {
return Cno;
}
public void setCno(int cno) {
this.Cno = cno;
}
public String getCname() {
return Cname;
}
public void setCname(String cname) {
this.Cname = cname;
}
public java.sql.Date getQstartdate() {
return Qstartdate;
}
public void setQstartdate(Date qstartdate) {
this.Qstartdate = qstartdate;
}
public Date getQenddate() {
return Qenddate;
}
public void setQenddate(Date qenddate) {
this.Qenddate = qenddate;
}
public int getQan() {
return Qan;
}
public void setQan(int qan) {
this.Qan = qan;
}
public int getQaln() {
return Qaln;
}
public void setQaln(int qaln) {
this.Qaln = qaln;
}
public int getQtn() {
return Qtn;
}
public void setQtn(int qtn) {
this.Qtn = qtn;
}
public int getQlen() {
return Qlen;
}
public void setQlen(int qlen) {
this.Qlen = qlen;
}
public Qimo() {
super();
// TODO Auto-generated constructor stub
}
public Qimo(String pcname, String pname, int sno, String sname, int cno, String cname, Date qstartdate, Date qenddate,
int qan, int qaln, int qtn, int qlen, int qlate) {
super();
this.Pcname = pcname;
this.Pname = pname;
this.Sno = sno;
this.Sname = sname;
this.Cno = cno;
this.Cname = cname;
this.Qstartdate = qstartdate;
this.Qenddate = qenddate;
this.Qan = qan;
this.Qaln = qaln;
this.Qtn = qtn;
this.Qlen = qlen;
this.Qlate = qlate;
}
@Override
public String toString() {
return "Qimo [Pcname=" + Pcname + ", Pname=" + Pname + ", Sno=" + Sno + ", Sname=" + Sname + ", Cno=" + Cno
+ ", Cname=" + Cname + ", Qstartdate=" + Qstartdate + ", Qenddate=" + Qenddate + ", Qan=" + Qan + ", Qaln="
+ Qaln + ", Qtn=" + Qtn + ", Qlen=" + Qlen + ", Qlate=" + Qlate + "]";
}
}
<file_sep>/src/attendance/test/PCTestDao.java
package attendance.test;
import java.util.ArrayList;
import java.util.List;
import attendance.dao.PCDao;
import attendance.bean.PC;
public class PCTestDao {
public static void main(String[] args){
PCDao dao= new PCDao();
List<PC> is =new ArrayList<PC>();
// dao.add(1,"计算机81",35,"计算机系");//增加测试
//int c=dao.getTotal();
//System.out.println(c);//getTotal函数测试
is =dao.list2();
System.out.printf("%s\t%s\t%s\t%s\n","", "班级号","班级名","总人数","系名");
for (PC b : is) {
System.out.printf("%d\t%s\t%d\t%s\n",b.Pno,b.Pname,b.Pnum,b.Pcname);
System.out.println();
}
// dao.delete(3);//删除测试
// dao.update(2, "电信181", 36,"电信系");
}
}
<file_sep>/src/attendance/dao/AdminDao.java
package attendance.dao;
//管理员DAO
//给管理员用的
import java.sql.*;
import javax.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//import attendance.bean.Academy;
import attendance.bean.Admin;
public class AdminDao {
public AdminDao(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
}
public Connection getConnection()throws SQLException{
//抛出异常
return DriverManager.getConnection("jdbc:sqlserver://sql.cerny.cn:1433;DatabaseName=attendance", "sa", "Myclassdesign330");
//数据库的名字叫attendance,我的数据库账户是sa,密码是sa
//这里我建立连接的时候不是用try-catcth来捕捉异常,而是主动抛出,那么我下面调用这个函数时要么继续抛出,要么用try-catcth捕捉,我选择用try-catcth捕捉,到时候主函数就不用处理了
}
public int getTotal() {
//得到目前表Admin总数有多少条
int total = 0;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "select count(*) from Admin";
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
total = rs.getInt(1);// 这里getInt是因为rs这个结果集这里是返回的结果行数
}
// System.out.println("total:" + total);
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
public void add(int Ano,String Aname,String Asex,String Azhichen,String Aphone,int Aage,String Acname) {
//这里增加函数管理号(本来主码可以自增不插,但我这里还是打开自增规则插进去),姓名,性别,职称,电话,工龄,系名,密码(初始为<PASSWORD>)
//密码在增加函数这里不插,默认,后期再自己改密码
String sql = "set identity_insert Admin ON insert into Admin(Ano,Aname,Asex,Azhichen,Aphone,Aage,Acname) values(?,?,?,?,?,?,?) set identity_insert Admin OFF";
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);) {
ps.setInt(1,Ano);
ps.setString(2,Aname);
ps.setString(3,Asex);
ps.setString(4,Azhichen);
ps.setString(5,Aphone);
ps.setInt(6,Aage);
ps.setString(7,Acname);
ps.execute();
//ResultSet rs = ps.getGeneratedKeys();//如果因为主码自增不插,然后通过这里得到主码赋值给对象对应的属性
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(int Ano,String Aname,String Asex,String Azhichen,String Aphone,int Aage,String Acname,String Apassword) {
//姓名,性别,职称,电话,工龄,系名,密码(初始为<PASSWORD>)
//不更新主码,主码一般不允许更新,一般允许更新主码的数据库设计都是不合理的
String sql = "update Admin set Aname=?,Asex=? ,Azhichen=?,Aphone=?,Aage=?,Acname=?,Apassword=? where Ano ="+Ano;
try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
ps.setString(1, Aname);
ps.setString(2, Asex);
ps.setString(3, Azhichen);
ps.setString(4, Aphone);
ps.setInt(5, Aage);
ps.setString(6, Acname);
ps.setString(7, Apassword);
ps.execute();
// System.out.println("修改成功");
}catch (SQLException e1) {
e1.printStackTrace();
}catch (Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
}
public void delete(int Ano) {
//删除函数
try (Connection c = getConnection(); Statement s = c.createStatement();) {
String sql = "delete from Admin where Ano= "+Ano;
s.execute(sql);
//System.out.println("删除成功");
}catch(SQLException e1) {
e1.printStackTrace();
}catch(Exception e2) {// 捕获其他异常
e2.printStackTrace();// 打印异常产生的过程信息
}
}
public List<Admin> list1(int Ano) {
List<Admin> admins = new ArrayList<Admin>();
//把符合条件的Admin数据查询出来,转换为Admin对象后,放在一个集合中返回
//String sql = "select * from hero order by id desc limit ?,? ";
String Aname=null;//姓名
String Asex=null;//性别
String Azhichen=null;//职称
String Aphone=null;//电话
int Aage=0;;//年龄
String Acname=null;//任职系名
String Apassword=null;//登录密码
//按即主码查询,单个
//System.out.println("请输入要查询的管理员号:");
String sql = "select * from Admin where Ano="+Ano;
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Admin的对象 admin ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Admin admin=new Admin() ;
Ano= rs.getInt(1);
Aname = rs.getString("Aname");
Asex = rs.getString(3);
Azhichen=rs.getString(4);
Aphone=rs.getString(5);
Aage=rs.getInt(6);
Acname=rs.getString(7);
Apassword=rs.getString(8);
admin.Ano=Ano;
admin.Aname=Aname;
admin.Asex=Asex;
admin.Azhichen=Azhichen;
admin.Aphone=Aphone;
admin.Aage=Aage;
admin.Acname=Acname;
admin.Apassword=Apassword;
admins.add(admin);
}
}catch (SQLException e) {
e.printStackTrace();}
return admins;//返回系集合,符合条件的系的信息
}
public List<Admin> list2() {
//都查询出来
List<Admin> admins = new ArrayList<Admin>();
int Ano=0;//职工号
String Aname=null;//姓名
String Asex=null;//性别
String Azhichen=null;//职称
String Aphone=null;//电话
int Aage=0;;//年龄
String Acname=null;//任职系名
String Apassword=null;//登录密码
//按即主码查询,单个
//System.out.println("请输入要查询的管理员号:");
String sql = "select * from Admin ";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Admin admin=new Admin() ;
Ano= rs.getInt(1);
Aname = rs.getString("Aname");
Asex = rs.getString(3);
Azhichen=rs.getString(4);
Aphone=rs.getString(5);
Aage=rs.getInt(6);
Acname=rs.getString(7);
Apassword=rs.getString(8);
admin.Ano=Ano;
admin.Aname=Aname;
admin.Asex=Asex;
admin.Azhichen=Azhichen;
admin.Aphone=Aphone;
admin.Aage=Aage;
admin.Acname=Acname;
admin.Apassword=<PASSWORD>;
admins.add(admin);
}
}catch (SQLException e) {
e.printStackTrace();}
return admins;//返回系集合,里面都是各个系的信息
}
public List<Admin> list3(int Ano, String Apassword) {
List<Admin> admins = new ArrayList<Admin>();
//把符合条件的Admin数据查询出来,转换为Admin对象后,放在一个集合中返回
//用于登录
//String sql = "select * from hero order by id desc limit ?,? ";
String Aname=null;//姓名
String Asex=null;//性别
String Azhichen=null;//职称
String Aphone=null;//电话
int Aage=0;;//年龄
String Acname=null;//任职系名
//按即主码查询,单个
//System.out.println("请输入要查询的管理员号:");
String sql = "select * from Admin where Ano="+Ano+" and "+"Apassword="+"'"+Apassword+"'";
try (Connection c = getConnection(); Statement s = c.createStatement();) {
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
/*定义一个类型为Admin的对象 admin ,在while里查询出来的属性赋值给它,接着把对象该给集合,然后返回集合
* 下面的一样道理*/
Admin admin=new Admin() ;
Ano= rs.getInt(1);
Aname = rs.getString("Aname");
Asex = rs.getString(3);
Azhichen=rs.getString(4);
Aphone=rs.getString(5);
Aage=rs.getInt(6);
Acname=rs.getString(7);
Apassword=rs.getString(8);
admin.Ano=Ano;
admin.Aname=Aname;
admin.Asex=Asex;
admin.Azhichen=Azhichen;
admin.Aphone=Aphone;
admin.Aage=Aage;
admin.Acname=Acname;
admin.Apassword=Apassword;
admins.add(admin);
}
}catch (SQLException e) {
e.printStackTrace();}
return admins;//返回系集合,符合条件的系的信息
}
}
<file_sep>/src/admin/studentUI/FileListView.java
package admin.studentUI;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
/*
* 左侧文件列表
*
*/
public class FileListView extends ListView<FileItem>
{
// 数据源
private ObservableList<FileItem> listData = FXCollections.observableArrayList();
public FileListView()
{
// 设置数据源
setItems(listData);
// 设置单元格生成器 (工厂)
setCellFactory(new Callback<ListView<FileItem>, ListCell<FileItem>>()
{
@Override
public ListCell<FileItem> call(ListView<FileItem> param)
{
return new MyListCell();
}
});
}
public ObservableList<FileItem> data()
{
return listData;
}
////////////////////////////////////////////////
// 负责单元格Cell的显示
static class MyListCell extends ListCell<FileItem>
{
@Override
public void updateItem(FileItem item, boolean empty)
{
// FX框架要求必须先调用 super.updateItem()
super.updateItem(item, empty);
// 自己的代码
if (item == null)
{
this.setText("");
} else
{
this.setText(item.fileName);
}
}
}
}
<file_sep>/src/attendance/test/CourseTestDao.java
package attendance.test;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.Course;
import attendance.bean.Teach;
import attendance.bean.Teacher;
import attendance.bean.TeachforUI;
import attendance.dao.CourseDao;
import attendance.dao.TeachDao;
import attendance.dao.TeacherDao;
public class CourseTestDao {
public static void main(String[] args){
// CourseDao dao= new CourseDao();
// List<Course> is =new ArrayList<Course>();
// is =dao.list2();
// for (Course b : is) {
// System.out.printf("%d\t%s\n",b.Cno,b.Cname);
// System.out.println();
// }
TeachDao dao= new TeachDao();
List<TeachforUI> is =new ArrayList<TeachforUI>();
is =dao.list3forUI(1);
for (TeachforUI b : is) {
System.out.printf("%d\t%s\n",b.Cno,b.Cname);
System.out.println();
}
}
}
<file_sep>/src/student/StudentChooseUI.java
package student;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class StudentChooseUI {
public void start(Stage stage) throws IOException {
stage.setTitle("主界面");
//Parent root = FXMLLoader.load(getClass().getResource("TeachChooseUI.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("StudentChooseUI.fxml"));
Parent root =loader.load();
SCController Controller = loader.getController();
Scene scene = new Scene(root, 732, 609);
stage.setScene(scene);
stage.show();
//Controller.getno();
Controller.InitUI();
}
}
<file_sep>/src/student/SAController.java
package student;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import attendance.bean.Course;
import attendance.bean.SC;
import attendance.dao.CourseDao;
import attendance.dao.SCDao;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class SAController {
@FXML private Button delete;
@FXML private ListView list;
@FXML
protected void Delete(ActionEvent event) throws IOException {
SCDao dao = new SCDao();
CourseDao cdao = new CourseDao();
List<Course> is = new ArrayList<Course>();
is = cdao.list3(list.getSelectionModel().getSelectedItem().toString());
if(dao.delete(StudIdentityTrans.getCno(), is.get(0).Cno)) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("退选成功!");
alert.showAndWait();
list.getItems().clear();
InitUI();
}else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText("未选择课程!");
alert.showAndWait();
}
}
public void InitUI() {
SCDao dao = new SCDao();
List<SC> is = new ArrayList<SC>();
is = dao.list2(StudIdentityTrans.getCno());
for(SC s:is) {
list.getItems().add(s.Cname);
}
}
}
| c3a16de05d8f6d277d0b49bad80cdf09eeacdb38 | [
"Java"
] | 38 | Java | andychen199/Student-management-system | 1ed6057e8630dd6ac859a0564e3191e94f14e264 | 2564f59beacfa2cdfcfe51bc5227dfee08245fa6 | |
refs/heads/master | <repo_name>NakajiTatsuya/task<file_sep>/Detail.js
// https://api.github.com/users/ユーザー名/repos で一覧を取得
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import Loader from './components/Loader'; // load用のmodal
import {
StyleSheet,
Text,
View,
Image,
ScrollView
} from 'react-native';
export default class detail extends Component {
static navigationOptions = ({ navigation }) => ({
headerStyle:{
backgroundColor: 'transparent',
position: 'absolute',
top: 0,
left:0,
right: 0,
borderBottomWidth: 0,
elevation: 0,
},
});
constructor(props) {
super(props);
this.state = {
item: this.props.navigation.state.params.item,
};
this.renderListings = this.renderListings.bind(this);
}
renderListings() {
const { item } = this.state;
return(
<View>
<Text style = {[{fontSize: 30}, {color: "blue"}, {marginBottom: 20}, {textAlign: 'center'}]}>
{item.name}レポジトリ
</Text>
{Object.entries(item.owner).map(([key,value])=>{
return (
<View
key={key}
style = {[{margintop: 10}, {marginBottom: 10}]}
>
<Text>
{key}: {String(value)}
</Text>
<View style = {[{margin:10}]}>
<Image
source = { key === "avatar_url" && {uri: value}}
style = {{width: 70, height: 70}}
resizeMode = "contain"
/>
</View>
</View>);
})}
</View>
)
}
render() {
return(
<View style = {styles.wrapper}>
<ScrollView style = {styles.scrollView}>
{this.renderListings()}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
wrapper: {
flex: 1,
backgroundColor: "pink",
},
scrollView: {
marginTop: 20,
marginLeft: 10,
marginBottom: 20,
marginRight: 10,
},
textStyle: {
fontSize: 60,
fontWeight: "300",
}
});
| 9377fbffaa0c0775edd6c6a8fcc6a91a027177a9 | [
"JavaScript"
] | 1 | JavaScript | NakajiTatsuya/task | ea84eb9f7cb6bef3b00944ed3d2f02e929dc2cdf | 00274f531e1b10221c5015fc62a8aeb2a98268d8 | |
refs/heads/master | <file_sep>#pragma once
// changeName 对话框
class changeName : public CDialogEx
{
DECLARE_DYNAMIC(changeName)
public:
changeName(CWnd* pParent = NULL); // 标准构造函数
virtual ~changeName();
// 对话框数据
enum { IDD = IDD_DIALOG2 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButton1();
virtual void OnOK();
};
<file_sep>// changeName.cpp : 实现文件
//
#include "stdafx.h"
#include "ZSY.h"
#include "changeName.h"
#include "afxdialogex.h"
extern char gDevName[100];
// changeName 对话框
IMPLEMENT_DYNAMIC(changeName, CDialogEx)
changeName::changeName(CWnd* pParent /*=NULL*/)
: CDialogEx(changeName::IDD, pParent)
{
}
changeName::~changeName()
{
}
void changeName::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(changeName, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &changeName::OnBnClickedButton1)
END_MESSAGE_MAP()
// changeName 消息处理程序
void changeName::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CString xx;
this->GetDlgItem(IDC_EDIT1)->GetWindowTextA(xx);
sprintf(gDevName,"%s",LPCTSTR(xx));
OnOK();
}
void changeName::OnOK()
{
// TODO: 在此添加专用代码和/或调用基类
CString xx;
this->GetDlgItem(IDC_EDIT1)->GetWindowTextA(xx);
sprintf(gDevName, "%s", LPCTSTR(xx));
CDialogEx::OnOK();
}
<file_sep>#include "stdafx.h"
#include "MySocket.h"
CMySocket::CMySocket()
{
}
CMySocket::~CMySocket()
{
}
/*
BOOL CMySocket::OnMessagePending()
{
MSG msg;
if (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (msg.wParam == (UINT)m_nTimerID)
{
MessageBox(NULL, "xxxxxx", "NULL", IDOK);
// Remove the message and call CancelBlockingCall.
::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
CancelBlockingCall();
return FALSE; // No need for idle time processing.
};
};
return CSocket::OnMessagePending();
}
BOOL CMySocket::SetTimeOut(UINT uTimeOut)
{
m_nTimerID = SetTimer(NULL, 0, uTimeOut, NULL);
return m_nTimerID;
}
BOOL CMySocket::KillTimeOut()
{
return KillTimer(NULL, m_nTimerID);
}*/
extern int isLineSafe[2];
extern int writelog(char* str);
void CMySocket::OnReceive(int nErrorCode)
{
//MessageBox(NULL, "6666666666", NULL, IDOK);
//m_pDoc->ProcessPendingRead();
AsyncSelect(FD_READ); //提请一个“读”的网络事件
//CSocket::OnReceive(nErrorCode);
char buff[20];
int ret =Receive(buff,10);
sscanf(buff, "<%d,%d>", &isLineSafe[0], &isLineSafe[1]);
char tmp[100];
switch (isLineSafe[0])
{
case 0:
sprintf(tmp, "警报:线路短路,");
break;
case 1:
sprintf(tmp, "警报:线路正常,");
break;
case 2:
sprintf(tmp, "警报:线路断开,");
break;
default:;
}
switch (isLineSafe[1])
{
case 0:
sprintf(tmp, "%s天线短路", tmp);
break;
case 1:
sprintf(tmp, "%s天线正常", tmp);
break;
case 2:
sprintf(tmp, "%s天线断开", tmp);
break;
default:;
}
if (-1 == writelog(tmp)){
;
};
// CString xx;
//xx.Format("%d %d", addr, statu);
//isLineSafe[addr] = statu;//0 短路 1 安全 2 断开
//MessageBox(NULL,xx,NULL,IDOK);
}
/*
int CMySocket::bReceive(void* lpBuf, int nBufLen,int timeout)
{
SetTimeOut(timeout);
int nRecv = CSocket::Receive(lpBuf, nBufLen);
KillTimeOut();
return nRecv;
}
int CMySocket::bSend(const void* lpBuf, int nBufLen,int timeout)
{
SetTimeOut(timeout);
int nSend = CSocket::Send(lpBuf, nBufLen);
KillTimeOut();
return nSend;
}
BOOL CMySocket::bConnect(char* addr,int port,int timeout)//Connect(constvoid* lpBuf, int nBufLen, int nFlags, int timeout)
{
SetTimeOut(timeout);
BOOL xx = CSocket::Connect(addr, port);
KillTimeOut();
return xx;
}*/<file_sep>
// ZSYDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "ZSY.h"
#include "ZSYDlg.h"
#include "loginDlg.h"
#include "changeName.h"
#include "afxdialogex.h"
#include"cv.h"
#include <opencv2\opencv.hpp>
#include <highgui.h>
#include"CvvImage.h"
#include "MySocket.h"
#include "CvxText.h"
#pragma comment(lib,"freetype.lib")
#pragma comment(lib, "libjpeg.lib")
#pragma comment(lib, "opencv_core249.lib")
#pragma comment(lib, "opencv_highgui249.lib")
#pragma comment(lib, "opencv_imgproc249.lib")
#pragma comment(lib, "zlib.lib")
#pragma comment(lib, "libtiff.lib")
#pragma comment(lib, "IlmImf.lib")
#pragma comment(lib, "libjasper.lib")
//#pragma comment(lib, "libpng.lib")
//#pragma comment(lib,"freetype.def")
IplImage *img2;
CMySocket mskt;
int isLineSafe[2];
FILE* fp,*fp_set;
int isConnected = 0;
int mm_gain;
#define TIMEOUT 3000
CString devName[9];
CvPoint devPos[9];
int gAntHight;
//libjpeg.lib
//opencv_calib3d249.lib
//opencv_core249.lib
//opencv_highgui249.lib
//opencv_imgproc249.lib
//zlib.lib
//libtiff.lib
//libpng.lib
//IlmImf.lib
//libjasper.lib
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CZSYDlg 对话框
CZSYDlg::CZSYDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CZSYDlg::IDD, pParent)
, m_gain(0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
CZSYDlg::~CZSYDlg( /*=NULL*/)
{
mskt.Close();
}
void CZSYDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_gain);
DDV_MinMaxInt(pDX, m_gain, 0, 30);
DDX_Control(pDX, IDC_IPADDRESS1, m_ip);
}
BEGIN_MESSAGE_MAP(CZSYDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, &CZSYDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &CZSYDlg::OnBnClickedButton2)
ON_BN_CLICKED(IDC_BUTTON4, &CZSYDlg::OnBnClickedButton4)
ON_WM_TIMER()
ON_BN_CLICKED(IDC_BUTTON5, &CZSYDlg::OnBnClickedButton5)
ON_EN_CHANGE(IDC_EDIT1, &CZSYDlg::OnEnChangeEdit1)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
// CZSYDlg 消息处理程序
BOOL CZSYDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
this->GetDlgItem(IDC_EDIT1)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON2)->EnableWindow(FALSE);
//this->GetDlgItem(IDC_BUTTON4)->EnableWindow(FALSE);
this->GetDlgItem(IDC_DB)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
lock = 1;
img2 = NULL;
m_ip.SetAddress(192,168,1,178);
for (int i = 0; i < 2; i++)isLineSafe[i] = 0;
SetTimer(12,1000,NULL);//1s
mm_gain = m_gain;
//KillTimer(int nIDEvent);
//log文件
if (!PathFileExists("C:\\log.txt")){
fp = fopen("C:\\log.txt","wb");
if (fp == NULL)MessageBox("请右击以管理员权限运行此程序");
fclose(fp);
}
else{
fp = fopen("C:\\log.txt", "a");
if (fp == NULL){
MessageBox("请右击以管理员权限运行此程序");
fclose(fp);
OnOK();
}
else{
fclose(fp);
}
}
if (!PathFileExists("C:\\gain_cfg.txt")){
fp_set = fopen("C:\\gain_cfg.txt", "wb");
if (fp_set == NULL)MessageBox("请右击以管理员权限运行此程序");
else{
char iName[20];
for (int i = 0; i < 9; i++){
sprintf(iName, "%d号天线", i + 1);
devName[i].Format("%s", iName);
fwrite(iName, strlen(iName), 1, fp_set);
fwrite("\r\n",strlen("\r\n"),1,fp_set);
}
}
fclose(fp_set);
}
else{
fp_set = fopen("C:\\gain_cfg.txt", "rb");
char iName[20];
for (int i = 0; i < 9; i++){
fgets(iName, 20, fp_set);
iName[strlen(iName)-2] = '\0';
devName[i].Format("%s", iName);
}
fclose(fp_set);
}
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CZSYDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
#define BOX 50
void drawCell(IplImage*img, int x, int y, char*iName)
{
CvFont font;
double hScale = 1;
double vScale = 1;
int lineWidth = 1;
CvScalar color2 = CV_RGB(192,192,192);
CvScalar color = CV_RGB(157, 157, 157);
CvScalar color3 = CV_RGB(0, 0, 255);
int add = 0;
char name[20];
if (strcmp("G1", iName) == 0){
add += 35;
sprintf(name, "%ddB", mm_gain);
}
else{
sprintf(name, "%s", iName);
}
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC, hScale, vScale, 0, lineWidth);
cvPutText(img, name, cvPoint(x+BOX/2-20, y+BOX/2+10), &font, color3);
cvDrawRect(img, cvPoint(x, y), cvPoint(x + BOX+add, y + BOX), color2, 4, 8);
cvDrawRect(img, cvPoint(x+1, y+1), cvPoint(x + BOX-1+add, y + BOX-1), color2, 1, 8);
cvDrawRect(img, cvPoint(x+3, y+3), cvPoint(x + BOX-3+add, y + BOX-3), color, 2, 8);
}
void drawStatu(IplImage*img, int x, int y,int cl)
{
CvFont font;
double hScale = 1;
double vScale = 1;
int lineWidth = 2;
CvScalar color2;
CvScalar clear;
clear = CV_RGB(240, 240, 240);
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC, hScale, vScale, 1, lineWidth);
if (cl == 0){
color2 = CV_RGB(255, 0, 0);
cvPutText(img, "LINE BROKEN", cvPoint(x, y), &font, clear);
cvPutText(img, "NORMAL", cvPoint(x, y), &font, clear);
cvPutText(img, "LINE SHORT", cvPoint(x, y), &font, clear);
cvPutText(img, "LINE SHORT", cvPoint(x, y), &font, color2);
}
else if (cl == 1){
color2 = CV_RGB(0, 255, 0);
cvPutText(img, "LINE BROKEN", cvPoint(x, y), &font, clear);
cvPutText(img, "LINE SHORT", cvPoint(x, y), &font, clear);
cvPutText(img, "NORMAL", cvPoint(x, y), &font, clear);
cvPutText(img, "NORMAL", cvPoint(x, y), &font, color2);
}
else{
color2 = CV_RGB(128, 128, 128);
cvPutText(img, "NORMAL", cvPoint(x, y), &font, clear);
cvPutText(img, "LINE SHORT", cvPoint(x, y), &font, clear);
cvPutText(img, "LINE BROKEN", cvPoint(x, y), &font, clear);
cvPutText(img, "LINE BROKEN", cvPoint(x, y), &font, color2);
}
}
void drawOnLine(IplImage*img, int x, int y, int cl)
{
CvFont font;
double hScale = 1;
double vScale = 1;
int lineWidth = 2;
CvScalar color2;
CvScalar clear;
clear = CV_RGB(240, 240, 240);
CvxText text("C:\\WINDOWS\\Fonts\\msyh.ttf");
float p = 1.0;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC, hScale, vScale, 1, lineWidth);
if (cl == 1){
color2 = CV_RGB(0, 255, 0);
text.setFont(NULL, &clear, NULL, &p); // 透明处理
DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, "设备离线", -1, NULL, 0);
wchar_t *pwText;
pwText = new wchar_t[dwNum];
MultiByteToWideChar(CP_ACP, 0, "设备离线", -1, pwText, dwNum);
text.putText(img, pwText, cvPoint(x, y), CV_RGB(0, 0, 0));
dwNum = MultiByteToWideChar(CP_ACP, 0, "设备在线", -1, NULL, 0);
MultiByteToWideChar(CP_ACP, 0, "设备在线", -1, pwText, dwNum);
text.setFont(NULL, &color2, NULL, &p); // 透明处理
text.putText(img, pwText, cvPoint(x, y), CV_RGB(0, 255, 0));
delete pwText;
//cvPutText(img, "OFF-LINE", cvPoint(x, y), &font, clear);
//cvPutText(img, "ON-LINE", cvPoint(x, y), &font, color2);
}
else{
color2 = CV_RGB(255, 0, 0);
text.setFont(NULL, &clear, NULL, &p); // 透明处理
DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, "设备在线", -1, NULL, 0);
wchar_t *pwText;
pwText = new wchar_t[dwNum];
MultiByteToWideChar(CP_ACP, 0, "设备在线", -1, pwText, dwNum);
text.putText(img, pwText, cvPoint(x, y), CV_RGB(0, 0, 0));
dwNum = MultiByteToWideChar(CP_ACP, 0, "设备离线", -1, NULL, 0);
MultiByteToWideChar(CP_ACP, 0, "设备离线", -1, pwText, dwNum);
text.setFont(NULL, &color2, NULL, &p); // 透明处理
text.putText(img, pwText, cvPoint(x, y), CV_RGB(255, 0, 0));
delete pwText;
//cvPutText(img, "ON-LINE", cvPoint(x, y), &font, clear);
//cvPutText(img, "OFF-LINE", cvPoint(x, y), &font, color2);
}
}
void drawAnt(IplImage*img, int x, int y,int y2,int x3)
{
CvScalar color = CV_RGB(192, 192, 192);
CvScalar color2;
if (isLineSafe[1] == 0){
color2 = CV_RGB(255, 0, 0);
}
else if (isLineSafe[1] == 1){
color2 = CV_RGB(0, 255, 0);
}
else{
color2 = CV_RGB(128, 128, 128);
}
/* cvLine(img, cvPoint(x + BOX / 2, y), cvPoint(x + 10, y + BOX), color, 6, 8);
cvLine(img, cvPoint(x+BOX/2, y), cvPoint(x + BOX-10, y + BOX), color, 6, 8);
cvLine(img, cvPoint(x+10, y + BOX), cvPoint(x+BOX-10, y + BOX), color, 6, 8);
*/
cvLine(img, cvPoint(x-10, y), cvPoint(x + BOX+10, y), color, 2, 8);
cvLine(img, cvPoint(x -10, y), cvPoint(x + BOX/2, y + BOX), color, 2, 8);
cvLine(img, cvPoint(x +BOX+ 10, y), cvPoint(x + BOX/2, y + BOX), color, 2, 8);
cvLine(img2, cvPoint(x + BOX / 2, y + BOX), cvPoint(x+BOX/2 , y2), color2, 2, 8);
cvLine(img2, cvPoint(x + BOX / 2, y2), cvPoint(x3, y2), color2, 2, 8);
}
void drawAng(IplImage*img, int x, int y)
{
CvScalar color = CV_RGB(192, 192, 192);
/* cvLine(img, cvPoint(x, y+15), cvPoint(x + BOX, y + BOX/2), color, 3, 8);
cvLine(img, cvPoint(x, y+BOX-15), cvPoint(x + BOX, y + BOX/2), color, 3, 8);
cvLine(img, cvPoint(x, y+15), cvPoint(x, y+BOX-15), color, 3, 8);
*/
cvLine(img, cvPoint(x, y + BOX/2), cvPoint(x + BOX/2, y + BOX / 4), color, 2, 8);
cvLine(img, cvPoint(x, y + BOX/2), cvPoint(x + BOX/2, y +BOX- BOX / 4), color, 2, 8);
cvLine(img, cvPoint(x+BOX/2, y + BOX/4), cvPoint(x+BOX/2, y + BOX - BOX/4), color, 2, 8);
}
void drawConn(IplImage*img, int x1, int y1,int x2,int y2,int statu, char*name)
{
CvFont font;
double hScale = 1;
double vScale = 1;
int lineWidth = 2;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC, hScale, vScale, 0, lineWidth);
//cvPutText(img, name, cvPoint(x + 2, y + 25), &font, CV_RGB(255, 0, 0));
CvPoint f1,f2,p1, p2;
p1.x = (x2 - (x1 + BOX)) / 2 + x1 + BOX;
if (y2 < y1){
p1.y = y1 + BOX/4;
}
else{
p1.y = y1 + BOX*3/4;
}
p2.x = p1.x;
p2.y = y2 + BOX/2;
f1.x = x1 + BOX+ 4;
f1.y = p1.y;
f2.x = x2-4;
f2.y = p2.y;
//CString xx;
//xx.Format("p1.x=%d y=%d", p1.x, p1.y);
//MessageBox(NULL,xx,NULL,IDOK);
CvScalar sca;
if (statu == 0){
sca = CV_RGB(255, 0, 0);
}
else if(statu ==1){
sca = CV_RGB(0, 255, 0);
}
else{
sca = CV_RGB(128, 128, 128);
}
cvLine(img, f1, p1, sca, 2, 8);
cvLine(img, p1, p2, sca, 2, 8);
cvLine(img, p2, f2, sca, 2, 8);
}
void CZSYDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
CDC* pDC = GetDlgItem(IDC_PIC1)->GetDC(); // 获得显示控件的 DC
HDC hDC = pDC->GetSafeHdc(); // 获取 HDC(设备句柄) 来进行绘图操作
CRect rect;
GetDlgItem(IDC_PIC1)->GetClientRect(&rect);
int rw = rect.right - rect.left; // 求出图片控件的宽和高
int rh = rect.bottom - rect.top;
if(img2 == NULL)img2 = cvCreateImage(cvSize(rw, rh), 8, 3);
cvRectangle(img2, cvPoint(0, 0), cvPoint(rw, rh), CV_RGB(240, 240, 240), -1);
int antX, antY;
int gpsX, gpsY;
int cx[8], cy[8];
int ax[9], ay[9];
//--------------------------------------------------------
antX = rw * 1 / 12 - BOX / 2-30;
antY = rh * 1 / 6-BOX/2;
gpsX = rw * 2 / 12 - BOX / 2-40;
gpsY = rh * 1 / 2 -BOX/2;
drawAnt(img2, antX, antY, gpsY + BOX / 2,gpsX);
drawCell(img2, gpsX, gpsY, "G1");
//------------------------------------------------------------
cx[0] = rw *3/ 12 - BOX / 2;
cy[0] = rh * 1 / 2-BOX/2;
drawCell(img2, cx[0], cy[0], "C1");
drawConn(img2, gpsX+30, gpsY, cx[0], cy[0], isLineSafe[0], "");
cx[1] = rw * 4 / 12 - BOX / 2;
cy[1] = rh * 1 / 5+4;
drawCell(img2, cx[1], cy[1], "C2");
drawConn(img2, cx[0], cy[0], cx[1], cy[1], isLineSafe[0], "");
cx[2] = rw * 5 / 12 - BOX / 2;
cy[2] = rh * 1 / 5-50;
drawCell(img2, cx[2], cy[2], "C3");
drawConn(img2, cx[1], cy[1], cx[2], cy[2], isLineSafe[0], "");
cx[3] = rw * 5 / 12 - BOX / 2;
cy[3] = rh * 3 / 5-10;
drawCell(img2, cx[3], cy[3], "C4");
drawConn(img2, cx[0], cy[0], cx[3], cy[3], isLineSafe[0], "");
cx[4] = rw * 6 / 12 - BOX / 2;
cy[4] = rh * 2 / 5;
drawCell(img2, cx[4], cy[4], "C5");
drawConn(img2, cx[3], cy[3], cx[4], cy[4], isLineSafe[0], "");
cx[5] = rw * 6 / 12 - BOX / 2;
cy[5] = rh * 4 / 6 ;
drawCell(img2, cx[5], cy[5], "C6");
drawConn(img2, cx[3], cy[3], cx[5], cy[5], isLineSafe[0], "");
cx[6] = rw * 7 / 12 - BOX / 2;
cy[6] = rh * 5 / 9+21;
drawCell(img2, cx[6], cy[6], "C7");
drawConn(img2, cx[5], cy[5], cx[6], cy[6], isLineSafe[0], "");
cx[7] = rw * 7 / 12 - BOX / 2;
cy[7] = rh * 7 /9 +10;
drawCell(img2, cx[7], cy[7], "C8");
drawConn(img2, cx[5], cy[5], cx[7], cy[7], isLineSafe[0], "");
//---------------------------------------------------------------------
ax[0] = rw * 9/12;
ay[0] = rh * 1 / 10 -BOX/2;
drawAng(img2, ax[0], ay[0]);
drawConn(img2, cx[2], cy[2], ax[0], ay[0], isLineSafe[0], "");
ax[1] = rw * 9/12;
ay[1] = rh * 2 / 10 - BOX / 2;
drawAng(img2, ax[1], ay[1]);
drawConn(img2, cx[2], cy[2], ax[1], ay[1], isLineSafe[0], "");
ax[2] = rw * 9 / 12;
ay[2] = rh * 3 / 10 - BOX / 2;
drawAng(img2, ax[2], ay[2]);
drawConn(img2, cx[1], cy[1], ax[2], ay[2], isLineSafe[0], "");
ax[3] = rw * 9 / 12;
ay[3] = rh * 4 / 10 - BOX / 2;
drawAng(img2, ax[3], ay[3]);
drawConn(img2, cx[4], cy[4], ax[3], ay[3], isLineSafe[0], "");
ax[4] = rw * 9 / 12;
ay[4] = rh * 5 / 10 - BOX / 2;
drawAng(img2, ax[4], ay[4]);
drawConn(img2, cx[4], cy[4], ax[4], ay[4], isLineSafe[0], "");
ax[5] = rw * 9 / 12;
ay[5] = rh * 6 / 10 - BOX / 2;
drawAng(img2, ax[5], ay[5]);
drawConn(img2, cx[6], cy[6], ax[5], ay[5], isLineSafe[0], "");
ax[6] = rw * 9 / 12;
ay[6] = rh * 7 / 10 - BOX / 2;
drawAng(img2, ax[6], ay[6]);
drawConn(img2, cx[6], cy[6], ax[6], ay[6], isLineSafe[0], "");
ax[7] = rw * 9 / 12;
ay[7] = rh * 8 / 10 - BOX / 2;
drawAng(img2, ax[7], ay[7]);
drawConn(img2, cx[7], cy[7], ax[7], ay[7], isLineSafe[0], "");
ax[8] = rw * 9 / 12;
ay[8] = rh * 9 / 10 - BOX / 2;
drawAng(img2, ax[8], ay[8]);
drawConn(img2, cx[7], cy[7], ax[8], ay[8], isLineSafe[0], "");
//------------------------------------------------------------------------
drawStatu(img2, 300, 580, isLineSafe[0]);
drawStatu(img2, 10, 580, isLineSafe[1]);
drawOnLine(img2,10,30,isConnected);
CvxText text("C:\\WINDOWS\\Fonts\\msyh.ttf");
float p = 1.0;
CvScalar clor;
clor = CV_RGB(255, 0, 0);
text.setFont(NULL, &clor, NULL, &p); // 透明处理
for (int i = 0; i < 9; i++){
devPos[i].x = ax[i] + BOX / 2 + 20;
devPos[i].y = ay[i] + BOX / 2 + 10;
DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, LPCTSTR(devName[i]), -1, NULL, 0);
wchar_t *pwText;
pwText = new wchar_t[dwNum];
MultiByteToWideChar(CP_ACP, 0, LPCTSTR(devName[i]), -1, pwText, dwNum);
text.putText(img2, pwText/*LPCTSTR(devName[i])*/, devPos[i], CV_RGB(255, 0, 0));
delete pwText;
}
gAntHight = rh / 10;
CvvImage cimg;
cimg.CopyOf(img2, 1); // 复制图片
cimg.DrawToHDC(hDC, &rect); // 将图片绘制到显示控件的指定区域内
ReleaseDC(pDC);
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CZSYDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
IplImage *img;
char lastStr[200];
int writelog(char* str)
{
if (strcmp(lastStr, "") != 0){
if (strcmp(str, lastStr) == 0 && strncmp(str,"警报",2)== 0)return 0;//已经记录过了
}
strcpy(lastStr, str);
CString xx;
CTime tm;
tm = CTime::GetCurrentTime();
xx = tm.Format("%Y-%m-%d %X:");
char buff[100];
sprintf(buff, "%s%s\r\n", LPCTSTR(xx),str);
fp = fopen("C:\\log.txt", "a");
if (fp == NULL){
MessageBox(NULL, "请右击以管理员权限运行此程序", NULL, IDOK);
return -1;
}
else{
fwrite(buff, strlen(buff), 1, fp);
fclose(fp);
}
return 0;
}
void CZSYDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
loginDlg dlg;
KillTimer(13);
if (lock == 1){
if (IDOK == dlg.DoModal()){
lock = 0;
if (-1 == writelog("登陆")){
OnOK();
};
}
else{
lock = 1;
}
}
else{
lock = 1;
}
if (lock == 0){
this->GetDlgItem(IDC_EDIT1)->EnableWindow(TRUE);
this->GetDlgItem(IDC_BUTTON2)->EnableWindow(TRUE);
this->GetDlgItem(IDC_BUTTON4)->EnableWindow(TRUE);
this->GetDlgItem(IDC_DB)->EnableWindow(TRUE);
this->GetDlgItem(IDC_BUTTON1)->SetWindowText("锁定");
}
else{
this->GetDlgItem(IDC_EDIT1)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON2)->EnableWindow(FALSE);
//this->GetDlgItem(IDC_BUTTON4)->EnableWindow(FALSE);
this->GetDlgItem(IDC_DB)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON1)->SetWindowText("登陆");
}
SetTimer(13, 10000, NULL);
}
void CZSYDlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
char buff[40],buff2[10];
UpdateData(TRUE);
if (m_gain <= 30 && m_gain >= 0){
mm_gain = m_gain;
memset(buff, 0, 40);
sprintf(buff, "<setgain,%d>", 30 - m_gain);
mskt.Send(buff, strlen(buff));
memset(buff2, 0, 10);
mskt.Receive(buff2, 10);
if (strcmp(buff2, "<OK>") == 0){//注意这个换行符,可能是没有的
sprintf(buff,"设置增益:%d",mm_gain);
if (-1 == writelog(buff)){
OnOK();
};
MessageBox("OK!");
}
UpdateData(TRUE);
}
else{
MessageBox("请输入0-30之间的数字");
}
}
void CZSYDlg::OnBnClickedButton4()
{
// TODO: 在此添加控件通知处理程序代码
ShellExecute(this->m_hWnd, "open", "C:\\log.txt", "", "", SW_SHOW);
}
void CZSYDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
// if (nIDEvent == mskt.m_nTimerID){
// MessageBox("LLLLLLLLL");
// }
if (nIDEvent == 12){
OnPaint();
}
if (nIDEvent == 13){
//查询
mskt.Send("<check>", strlen("<check>"));
char buff[20];
memset(buff, 0, 20);
int ret = mskt.Receive(buff,20);
if (ret == -1){
if (isConnected){
if (-1 == writelog("所有设备离线!")){
OnOK();
};
}
for (int i = 0; i < 2; i++)isLineSafe[i] = 0;
isConnected = 0;
}
else{
sscanf(buff, "<%d,%d>", &isLineSafe[0], &isLineSafe[1]);
char tmp[100];
switch (isLineSafe[0])
{
case 0:
sprintf(tmp, "警报:线路短路,");
break;
case 1:
sprintf(tmp, "警报:线路正常,");
break;
case 2:
sprintf(tmp, "警报:线路断开,");
break;
default:;
}
switch (isLineSafe[1])
{
case 0:
sprintf(tmp, "%s天线短路",tmp);
break;
case 1:
sprintf(tmp, "%s天线正常",tmp);
break;
case 2:
sprintf(tmp, "%s天线断开",tmp);
break;
default:;
}
if (-1 == writelog(tmp)){
OnOK();
};
}
}
CDialogEx::OnTimer(nIDEvent);
}
int bConnect = 0;
void CZSYDlg::OnBnClickedButton5()
{
//test
memset(lastStr,0,200);
#if 0
CvxText text("wqy-zenhei.ttf");
const char *msg = "在OpenCV中输出汉字!";
float p = 1.0;
CvScalar clor;
clor = CV_RGB(255,0,0);
text.setFont(NULL, &clor, NULL, &p); // 透明处理
text.putText(img2, msg, cvPoint(100, 150), CV_RGB(255, 0, 0));
#endif
//end
// TODO: 在此添加控件通知处理程序代码
char ipbuf[100];
UpdateData(TRUE);
m_ip.GetWindowTextA(ipbuf, 100);
if (bConnect == 1){
bConnect = 0;
this->GetDlgItem(IDC_BUTTON5)->SetWindowTextA("连接");
mskt.Close();
isLineSafe[0] = 0;
isLineSafe[1] = 0;
isConnected = 0;
lock = 1;
this->GetDlgItem(IDC_EDIT1)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON2)->EnableWindow(FALSE);
//this->GetDlgItem(IDC_BUTTON4)->EnableWindow(FALSE);
this->GetDlgItem(IDC_DB)->EnableWindow(FALSE);
this->GetDlgItem(IDC_BUTTON1)->SetWindowText("登陆");
}
else{
this->GetDlgItem(IDC_BUTTON5)->SetWindowTextA("连接中...");
bConnect = 1;
mskt.Create();
BOOL a = mskt.Connect(ipbuf, 4001);
if (a == FALSE){
MessageBox("设备无反应!","警告");
this->GetDlgItem(IDC_BUTTON5)->SetWindowTextA("连接");
bConnect = 0;
}
else{
this->GetDlgItem(IDC_BUTTON5)->SetWindowTextA("断开");
mskt.Send("<readgain>", strlen("<readgain>"));
char buff[200];
memset(buff, 0, 200);
int ret = mskt.Receive(buff, 10);
if (ret == -1)MessageBox("模块没反应");
else{
char*p = buff;
char tmp[10];
memset(tmp, 0, 10);
char*pt = tmp;
p++;
while (*p != '>'){
if (*p == ',')return;
*pt = *p;
p++;
pt++;
}
m_gain = atoi(tmp);
m_gain = 30 - m_gain;
mm_gain = m_gain;
UpdateData(FALSE);
isConnected = 1;
SetTimer(13, 10000, NULL);
this->GetDlgItem(IDC_BUTTON1)->EnableWindow(TRUE);
//check
mskt.Send("<check>", strlen("<check>"));
memset(buff, 0, 20);
int ret = mskt.Receive(buff, 20);
if (ret == -1){
for (int i = 0; i < 2; i++)isLineSafe[i] = 0;
isConnected = 0;
}
else{
sscanf(buff, "<%d,%d>", &isLineSafe[0], &isLineSafe[1]);
//for (int i = 0; i < 2; i++)isLineSafe[i] = 1;
}
}
}
}
}
void CZSYDlg::OnEnChangeEdit1()
{
// TODO: 如果该控件是 RICHEDIT 控件,它将不
// 发送此通知,除非重写 CDialogEx::OnInitDialog()
// 函数并调用 CRichEditCtrl().SetEventMask(),
// 同时将 ENM_CHANGE 标志“或”运算到掩码中。
// TODO: 在此添加控件通知处理程序代码
}
char gDevName[100];
void CZSYDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CRect rect;
this->GetDlgItem(IDC_PIC1)->GetWindowRect(&rect);
// CString xx;
//xx.Format("pt:%d-%d left=%d-%d-%d-%d width =%d width=%d",point.x,point.y, rect.left,rect.right,rect.top,rect.bottom,img2->width,(rect.right-rect.left));
//MessageBox(xx);
if (point.x > rect.left + devPos[0].x - 3*BOX){
int i = (point.y-gAntHight*2/3) / gAntHight;
//CString xx;
//xx.Format("%d", i);
//MessageBox(xx);
changeName dlg;
sprintf(gDevName, "");
dlg.DoModal();
if (strcmp(gDevName, "") == 0){
}
else{
devName[i].Format("%s", gDevName);
fp_set = fopen("C:\\gain_cfg.txt", "wb");
if (fp_set == NULL)MessageBox("请右击以管理员权限运行此程序");
else{
for (int i = 0; i < 9; i++){
fwrite(LPCTSTR(devName[i]), devName[i].GetLength(), 1, fp_set);
fwrite("\r\n",strlen("\r\n"),1,fp_set);
}
}
fclose(fp_set);
}
}
//GetWindowRect
CDialogEx::OnLButtonDown(nFlags, point);
}
<file_sep>
// ZSYDlg.h : 头文件
//
#pragma once
#include "afxcmn.h"
// CZSYDlg 对话框
class CZSYDlg : public CDialogEx
{
// 构造
public:
CZSYDlg(CWnd* pParent = NULL); // 标准构造函数
~CZSYDlg();
int lock;
// 对话框数据
enum { IDD = IDD_ZSY_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton2();
int m_gain;
afx_msg void OnBnClickedButton4();
afx_msg void OnTimer(UINT_PTR nIDEvent);
CIPAddressCtrl m_ip;
afx_msg void OnBnClickedButton5();
afx_msg void OnEnChangeEdit1();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
};
<file_sep>#pragma once
#include "afxsock.h"
class CMySocket :
public CSocket
{
public:
CMySocket();
~CMySocket();
// virtual BOOL OnMessagePending();
void OnReceive(int nErrorCode);
// int bReceive(void* lpBuf, int nBufLen, int timeout);
// int bSend(const void* lpBuf, int nBufLen, int timeout);
// BOOL bConnect(char* addr, int port, int timeout);
// int m_nTimerID;
protected:
// BOOL SetTimeOut(UINT uTimeOut);
// BOOL KillTimeOut();
private:
};
<file_sep>// loginDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "ZSY.h"
#include "loginDlg.h"
#include "afxdialogex.h"
#include "ZSYDlg.h"
#include "MySocket.h"
// loginDlg 对话框
#define TIMEOUT 3000
IMPLEMENT_DYNAMIC(loginDlg, CDialogEx)
loginDlg::loginDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(loginDlg::IDD, pParent)
, m_password(_T(""))
{
}
loginDlg::~loginDlg()
{
}
void loginDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_password);
}
BEGIN_MESSAGE_MAP(loginDlg, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &loginDlg::OnBnClickedButton1)
END_MESSAGE_MAP()
// loginDlg 消息处理程序
extern CMySocket mskt;
void loginDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
//TCP登陆认证
//认证成功
char buff[200];
CString xx;
this->GetDlgItemText(IDC_EDIT1, xx);
sprintf(buff,"<login,%s>",LPCTSTR(xx));
mskt.Send(buff, strlen(buff));
memset(buff, 0, 200);
mskt.Receive(buff, 10);
if (buff[1] == 'O'){//注意这个换行符,可能是没有的
OnOK();
}
//if (strcmp(buff,"<OK>")==0){//注意这个换行符,可能是没有的
// OnOK();
//}
else{
MessageBox("Wrong Password!","TenChar Notice");
//OnCancel();
}
}
| 8b9b0af656027c8efd97458a28e9f1c277f68b78 | [
"C++"
] | 7 | C++ | 9crk/zsy | 4c1c5fa2865b4a11da55b2b47d3b574da366c0b4 | 96b6e0ef57729b32bba2b825786ddbaea88a8a87 | |
refs/heads/master | <file_sep>import React from 'react';
import './styles.css';
function Footer() {
return (
<footer className="mt-5 py-3" id="footer">
<div className="container">
<div className="row justify-content-center mb-2">
<div className="col-auto">
<ul className="nav">
<li className="nav-item">
<a className="nav-link" href="https://www.linkedin.com/in/storeysheldon/" target="_blank"><i
className="fab fa-linkedin-in fa-lg"></i></a>
</li>
<li className="nav-item">
<a className="nav-link" href="https://github.com/storey17" target="_blank"><i
className="fab fa-github fa-lg"></i>
</a>
</li>
</ul>
</div>
</div>
<div className="row justify-content-center">
<div className="col col-md-auto text-center">
<small className="text-muted">Copyright © <NAME> 2020
</small>
</div>
</div>
</div>
</footer>
);
}
export default Footer;<file_sep>import React from 'react';
import './styles.css';
import PortfolioPic from './IMG_1383.jpeg';
function MainContent() {
return (
<section className="main-content pt-5">
<div className="container">
<h1 className="display-4 text-center"><NAME></h1>
<p className="lead text-center">Full Stack Web Developer</p>
<div className="row justify-content-center">
<div className="col-md-4">
<img src={PortfolioPic} alt="<NAME>" className="img" />
</div>
</div>
<div className="col-md-6" id="about-me">
<p>
Full stack web developer with a foundation in Marketing. I deliver customized solutions for your
web development needs with a focus on ensuring seamless and delightful online customer
experiences.
</p>
<p>
3+ years experience working internationally in diverse team settings strengthening my
communication skills, flexibility and adaptability in uncertain situations. Focused on providing
outstanding results that meet and exceed project criteria. My tenacious, solutions driven
approach and interpersonal skills makes me a unique team member who will add value and
efficiency to your team.
</p>
</div>
</div>
</section>
);
}
export default MainContent; | 5da341a8503e95da001075cb6f4e7faf5977464c | [
"JavaScript"
] | 2 | JavaScript | storey17/React-Portfolio | fb9b1f16a7c97a34d6743625ee55bafcfa2a8406 | baa8d1ee840f2a15edcc0cc8491675587178aab9 | |
refs/heads/master | <file_sep>import numpy as np
gps_x = np.loadtxt('./config/log/Graph1.txt',delimiter=',',dtype='Float64',skiprows=1)[:,1]
acc_x = np.loadtxt('./config/log/Graph2.txt',delimiter=',',dtype='Float64',skiprows=1)[:,1]
gps_x_std = np.std(gps_x)
print(f'GPS X Std: {gps_x_std}')
acc_x_std = np.std(acc_x)
print(f'Accelerometer X Std: {acc_x_std}') | 0f74760db9842fc34216478f6cbdaeff999252e8 | [
"Python"
] | 1 | Python | Rish619/FCND-Estimation-CPP | a1ed69b47c223e04897820e7b012f6e08421ff3d | ab38f584f41df4efed0db45ab0291e0e341f9ab1 | |
refs/heads/master | <repo_name>acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean<file_sep>/test/examples_test/04_module_test/04_module_tests.cpp
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "bank_account.h"
#include "checking_account.h"
using std::unique_ptr; using std::make_unique;
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Test BankAccount constructor")
{
BankAccount account(500);
REQUIRE(account.get_balance() == 500);
}
TEST_CASE("Test Bank account deposit")
{
BankAccount account(500);
REQUIRE(account.get_balance() == 500);
account.deposit(50);
REQUIRE(account.get_balance() == 550);
REQUIRE_THROWS_AS(account.deposit(-50), Invalid);
REQUIRE(account.get_balance() == 550);
}
TEST_CASE("Test BankAccount withdraw")
{
BankAccount account(500);
REQUIRE(account.get_balance() == 500);
account.withdraw(50);
REQUIRE(account.get_balance() == 450);
REQUIRE_THROWS_AS(account.withdraw(-1), Invalid);
REQUIRE(account.get_balance() == 450);
REQUIRE_THROWS_AS(account.withdraw(451), Invalid);
REQUIRE(account.get_balance() == 450);
}
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE
}
TEST_CASE("Test CheckingAcount constructor")
{
CheckingAccount account(500);
REQUIRE(account.get_balance() == 512);
}
TEST_CASE("Test CheckingAccount get balance")
{
CheckingAccount account(150);
REQUIRE(account.get_balance() == 153);
}<file_sep>/src/homework/tic_tac_toe/tic_tac_toe_3.h
//h
#ifndef TICTACTOE3_H
#define TICTACTOE3_H
#include"tic_tac_toe.h"
class TicTacToe3 : public TicTacToe
{
public:
//TicTacToe3();
TicTacToe3(std::vector<string> p, string winner);
TicTacToe3(): TicTacToe(3){}
private:
bool check_column_win();
bool check_row_win();
bool check_diagonal_win();
};
#endif <file_sep>/src/homework/tic_tac_toe/tic_tac_toe_data.h
//h
#include "tic_tac_toe.h"
class TicTacToeData : public TicTacToe
{
public:
void save_games(const std::vector<std::unique_ptr<TicTacToe>>& games);
std::vector<std::unique_ptr<TicTacToe>> get_games();
};<file_sep>/src/homework/tic_tac_toe/tic_tac_toe_data.cpp
#include "tic_tac_toe_data.h"
#include"tic_tac_toe.h"
#include<fstream>
#include<iostream>
//cpp
void TicTacToeData::save_games(const std::vector<std::unique_ptr<TicTacToe>>& games)
{
ofstream file("tictactoe.txt");
for (auto p : pegs)
{
file << p;
}
file << get_winner();
file.close();
}
std::vector<std::unique_ptr<TicTacToe>> TicTacToeData::get_games()
{
std::vector<std::unique_ptr<TicTacToe>>boards;
ofstream vecFile("boards.txt");
return std::vector<std::unique_ptr<TicTacToe>>();
}
<file_sep>/src/homework/tic_tac_toe/tic_tac_toe.cpp
#include "tic_tac_toe.h"
//cpp
using std::cout;
TicTacToe::TicTacToe(std::vector<string> p, string win)
:pegs{p}, winner{win}
{
}
bool TicTacToe::game_over()
{
if (check_column_win() == true || check_diagonal_win() == true || check_row_win() == true)
{
set_winner();
return true;
}
else if(check_board_full() == true)
{
winner = "C";
return true;
}
else
{
return false;
}
}
void TicTacToe::start_game(std::string first_player)
{
if (first_player == "X" || first_player == "O")
{
player = first_player;
}
else
{
throw Error("X's or O's only!");
}
clear_board();
}
void TicTacToe::mark_board(int position)
{
if(position < 1 || position > 9 && pegs.size() == 9)
{
throw Error("Out of range");
}
if (position < 1 || position > 16 && pegs.size() == 16)
{
throw Error("Out of range");
}
else if(player =="")
{
throw Error("Must start game first.");
}
pegs[position - 1] = player;
set_next_player();
}
void TicTacToe::set_next_player()
{
if(player =="X")
{
player = "O";
}
else if (player == "O")
{
player = "X";
}
}
bool TicTacToe::check_board_full()
{
for (std::size_t i = 0; i < pegs.size(); ++i)
{
if (pegs[i] == " ")
{
return false;
}
}
return true;
}
void TicTacToe::clear_board()
{
for (auto &peg : pegs)
{
peg = " ";
}
}
bool TicTacToe::check_column_win()
{
return false;
}
bool TicTacToe::check_row_win()
{
return false;
}
bool TicTacToe::check_diagonal_win()
{
return false;
}
void TicTacToe::set_winner()
{
if (player == "X")
{
winner = "O";
}
else
{
winner = "X";
}
}
std::ostream & operator<<(std::ostream & out, const TicTacToe & t)
{
for (std::size_t i = 0; i < t.pegs.size(); i += sqrt(t.pegs.size()))
{
out << t.pegs[i] << "|" << t.pegs[i + 1] << "|" << t.pegs[i + 2];
if (t.pegs.size() == 16)
{
out << "|" << t.pegs[i + 3];
}
out << "\n";
}
return out;
}
std::istream & operator>>(std::istream & in, TicTacToe & b)
{
// TODO: insert return statement here
try
{
int position;
cout << "\n";
cout<< "Pick a spot on the board (1-9): " << "\n";
in >> position;
cout << "\n";
b.mark_board(position);
cout << "\n";
}
catch (Error e)
{
cout << e.get_message() << "\n";
}
return in;
}
<file_sep>/src/examples/11_module/03_memory_leak/memory_leak.h
//create memory leak function
void memory_leak
<file_sep>/src/examples/02_module/02_if_else/if_else.h
//write include statement
#include<string>
using std :: string;
//write prototype for function named get_generation that accepts an int and
//returns a string
string get_generation(int year);
<file_sep>/src/examples/03_module/06_vectors/vec.h
#include<string>
#include<vector>
/*
Write function prototype for function loop_vector_w_index with no parameters.
*/
/*
Write function prototype for function loop_vector_w_index with a vector of int pass by value parameter.
*/
void loop_vector_w_index(std::vector <int> nums);
/*
Write function prototype for function loop_vector_w_index with a vector of int pass by reference parameter. Loop can modify
*/
void loop_vector_w_index_ref(std::vector <int> &nums);
/*
Write function prototype for function loop_vector_w_index with a vector of int const pass by reference parameter. Loop cannot modify
*/
void loop_vector_w_index_ref_const(const std::vector <int> &nums);
void loop_vector_w_auto(std::vector<int> &nums);
void loop_vector_w_auto_ref(std::vector<int> &nums);
void loop_vector_w_auto_const(const std::vector<int> &nums);
<file_sep>/test/homework_test/04_vectors_test/04_vectors_tests.cpp
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "vectors.h"
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Verify max")
{
std::vector<int>numbers{ 8, 4, 20, 88, 66, 99 };
get_max_from_vector(numbers);
REQUIRE(get_max_from_vector(numbers) == 88);
}
TEST_CASE("Verify primes")
{
std::vector<int>primes1{2, 3};
std::vector<int>primes2{2, 3, 5, 7 };
std::vector<int>primes3{2, 3, 5, 7, 11, 13 };
REQUIRE(vector_of_primes(5) == primes1);
REQUIRE(vector_of_primes(9) == primes2);
REQUIRE(vector_of_primes(14) == primes3);
}
TEST_CASE("Verify is prime")
{
REQUIRE(is_prime(7) == true);
REQUIRE(is_prime(10) == false);
REQUIRE(is_prime(-7) == false);
}<file_sep>/src/classwork/05_assign/main.cpp
//write include statemetns
#include<iostream>
#include "rectangle.h"
#include<vector>
using std::cout;
/*
Create a vector of rectangles
Add 3 Rectangle classes to the vector:
Width Height Area
4 5 20
10 10 100
100 10 1000
Iterate the vector and display the Area for each Rectangle on one line and the total area for the
3 rectangles.
*/
int main()
{
std::vector<Rect> area { Rect(4, 5), Rect(10, 10), Rect(100, 10) };
auto total{ 0 };
for(auto x: area)
{
cout << x << "\n";
}
/*
for (auto x : area)
{
cout << x.get_area() << "\n";
total += x.get_area();
}
cout << total;
*/
return 0;
}
<file_sep>/src/examples/11_module/01_ref_pointers/ref_pointers.h
//Create ref function w reference and pointer parameter
void ref_pointers(int1, int*int2);
//Create return pointer function<file_sep>/src/examples/04_module/01_bank/atm.cpp
//atm.cpp
#include "atm.h"
std::ostream & operator<<(std::ostream & out, const ATM & a)
{
a.customer.display_accounts();
return out;
}<file_sep>/src/examples/04_module/01_bank/atm.h
//atm.h
#ifndef ATM_H
#define ATM_H
#include "customer.h"
class ATM
{
public:
ATM(Customer& c) : customer(std::move(c)){}
friend std::
};<file_sep>/src/examples/04_module/01_bank/main.cpp
#include "bank_account.h"
#include "checking_account.h"
#include"savings_account.h"
#include"customer.h"
#include<iostream>
#include<vector>
#include<string>
#include<memory>
using std::cout; using std::cin;
using std::unique_ptr; using std::make_unique;
int main()
{
/*
//c++ 98
SavingsAccount*s = new SavingsAccount(500);
//more lot of code
delete s;
s = nullptr;*/
//c++ 11
unique_ptr<BankAccount> s = make_unique<SavingsAccount> ( 90 );
unique_ptr<BankAccount> c = make_unique<CheckingAccount> ( 100 );
std::vector<unique_ptr<BankAccount>> accounts;
accounts.push_back(std::move(s));
accounst.push_back(std::move(c));
for (auto &act : accounts)
{
cout << act->get_balance() << "\n";
}
/*
BankAccount* act=new CheckingAccount(100);
BankAccount account(500);
Customer cust;
cust.add_account(account);
/*
do you want to play again loop
Ttt game;
loop for mark board
game ends
call manager save game
*/
cin >> account;
cout << account;
display_balance(account);
/*std::vector<BankAccount> accounts{ BankAccount(100), BankAccount(200) };
for (auto act : accounts)
{
cout << act.get_balance() << "\n";
}
*/
auto balance = account.get_balance();
cout << "Balance is: " << balance << "\n";
auto amount{ 0 };
cout << "Enter deposit amount: \n";
cin >> amount;
try
{
account.deposit(amount);
cout << "Balance is: \n" << account.get_balance;
}
catch (Invalid e)
{
cout << e.get_error() << "\n";
}
return 0;
}<file_sep>/src/homework/03_iteration/main.cpp
//write include statements
#include<iostream>
#include "dna.h"
#include <string>
//write using statements
using std::cout; using std::cin; using std::string;
/*
Write code that prompts user to enter 1 for Get GC Content,
or 2 for Get DNA Complement. The program will prompt user for a
DNA string and call either get gc content or get dna complement
function and display the result. Program runs as long as
user enters a y or Y.
*/
int main()
{
int starter;
int choice;
do
{
cout << "Enter 1 for GC content or 2 for DNA complement: ";
cin >> starter;
if (starter == 1)
{
string dna1;
cout << "Enter a DNA sequence: ";
cin >> dna1;
get_gc_content(dna1);
double gcContent = get_gc_content(dna1);
cout << "Content of G's and C's is: " << gcContent;
}
else if (starter == 2)
{
string dna2;
cout << "Enter a DNA sequence: ";
cin >> dna2;
get_dna_complement(dna2);
string dnaComp = get_dna_complement(dna2);
cout << "DNA complement is: " << dnaComp;
}
else
{
cout << "Invalid entry";
}
cout << "Type 1 to continue...";
cin >> choice;
} while (choice == 1);
return 0;
}<file_sep>/src/examples/09_module/temperature_data.h
//temperature_data.h
#include"temperature.h"
#ifndef TEMPERATURE_DATA_H
#define TEMPERATURE_DATA_H
#include<fstream>
#include<string>
#include<vector>
class TemperatureData
{
public:
void save_tenos(std::vector<Temperature>& ts);
std::vector<Temperature>get_temps()const;
private:
const std::string file_name{ "temperature.dat" };
};
#endif // !TEMPERATURE_DATA_H
<file_sep>/src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
#include "tic_tac_toe_manager.h"
#include"tic_tac_toe.h"
#include<iostream>
using std::cout; using std::cin;
//cpp
/*void TicTacToeManager::save_game(const TicTacToe b)
{
games.push_back(b);
update_winner_count(b.get_winner());
}*/
void TicTacToeManager::save_game(std::unique_ptr<TicTacToe>& b)
{
update_winner_count(b->get_winner());
games.push_back(std::move(b));
}
void TicTacToeManager::get_winner_total(int & x, int & o, int & t)
{
o = o_win;
x = x_win;
t = ties;
}
void TicTacToeManager::update_winner_count(std::string winner)
{
if (winner == "X")
{
x_win ++;
}
else if (winner == "O")
{
o_win ++;
}
else
{
ties ++;
}
}
std::ostream & operator<<(std::ostream & out, const TicTacToeManager & manager)
{
// TODO: insert return statement here
out << "All games played: \n";
for (auto& game : manager.games)
{
out << "\n";
out << *game;
std::string w = game->get_winner();
out << "\n";
out << "the winner is: " << w << "\n";
}
out << "The winner is X " << manager.x_win << "\n";
out << "The winner is O " << manager.o_win << "\n";
out << "It's a tie " << manager.ties << "\n";
return out;
}
<file_sep>/README.md
[![Build Status](https://travis-ci.org/acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean.svg?branch=master)](https://travis-ci.org/acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean)
# acc-cosc-1337-starter
# CHELLIBEAN
#Merp
C++ starter code with CMake
<file_sep>/src/examples/04_module/01_bank/customer.h
//customer.h
#ifndef CUSTOMER_H //header guards
#define CUSTOMER_H //use bc errors will occur if you try to use customer more than once
#include<vector>
#include"bank_account.h"
class Customer
{
public:
void add_account(BankAccount& act);
void display_accounts()const;
private:
std::vector<BankAccount> accounts;
};
#endif // !CUSTOMER_H<file_sep>/src/homework/tic_tac_toe/tic_tac_toe_manager.h
//h
#include"tic_tac_toe.h"
#include"tic_tac_toe_data.h"
#include<vector>
//#include<iostream>
#include<memory>
#ifndef TICTACTOEMANAGER_H
#define TICTACTOEMANAGER_H
class TicTacToeManager//:public TicTacToe
{
public:
TicTacToeManager() = default;
void save_game(std::unique_ptr<TicTacToe> &b);
friend std::ostream& operator<<(std::ostream& out, const TicTacToeManager & manager);
void get_winner_total(int& x, int& o, int& t);
private:
std::vector<std::unique_ptr<TicTacToe>> games{};
int x_win{ 0 };
int o_win{ 0 };
int ties{ 0 };
void update_winner_count(std::string winner);
int data;
};
#endif // !MANAGER_H
<file_sep>/src/homework/04_vectors/main.cpp
#include "vectors.h"
#include<iostream>
#include<vector>
using std::cout; using std::cin;
/*
use a vector of int with values 8, 4, 20, 88, 66, 99
Prompt user for 1 for Get Max from vector and 2 for Get primes.
Prompt user for a number and return max value or list of primes
and display them to screen.
Program continues until user decides to exit.
*/
int main()
{
std::vector<int>numbers{ 8, 4, 20, 88, 66, 99 };
int starter = 0;
int num;
char keepGoing = 'y';
do
{
cout << "Enter 1 for get max or enter 2 for get primes " << "\n";
cin >> starter;
if (starter == 1)
{
get_max_from_vector(numbers);
cout << get_max_from_vector(numbers) << "\n";
cout << "y to continue: ";
cin >> keepGoing;
}
else if (starter == 2)
{
cout << "Enter a number greater than 0: ";
cin >> num;
std::vector<int>prime = vector_of_primes(num);
for (auto n : prime)
{
cout << n << ", " << "\n";
}
cout << "y to continue: ";
cin >> keepGoing;
}
} while (starter == 0 || keepGoing == 'y');
return 0;
} | caee2abd1516a5f4efc864590ca4a22ee9e123fb | [
"Markdown",
"C",
"C++"
] | 21 | C++ | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean | 9e2f45a1d9682f5c9391a594e1284c6beffd9f58 | e4f96cac465751eaf800fc20862fae47d21f5dfe | |
refs/heads/master | <file_sep>import cv2
import numpy
import glob
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
def generalFormula():
Fi = 1
for i in range(0, len(arrayImg)):
Ii = numpy.array(arrayImg[i],dtype=numpy.uint8)
Fi = alpha*(Fi-1)+((1-alpha)*Ii)
cv2.imwrite("resultado"+str(i)+".jpg", Fi)
def converVideo():
for filename in glob.glob('resultado' + '*.jpg'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('video.mp4',cv2.VideoWriter_fourcc(*'DIVX'),10, size)
for i in range(len(img_array)):
out.write(img_array[i])
cv2.destroyAllWindows()
out.release()
def select():
count=0
path.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("mp4 files",".mp4"),("all files",".*")))
print (path.filename)
ls=path.filename
vidcap = cv2.VideoCapture(ls)
path.destroy()
while(vidcap.isOpened()):
count += 1
vidcap.set(cv2.CAP_PROP_POS_MSEC,round(count, 2)*1000)
hasFrames,image = vidcap.read()
if hasFrames:
img = cv2.imwrite("Test"+str(count)+".jpg", image)
arrayImg.append(image)
else:
print(f'YA ACABO')
vidcap.release()
cv2.destroyAllWindows()
generalFormula()
converVideo()
imgAdd()
def imgAdd():
example = "resultado"+str(len(img_array)-1)+".jpg"
print(f'VALOR EXAMPLE {example}')
# Carga de imagen y agregación de evento al mouse
image = cv2.imread(example)
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", shape_selection)
while True:
# display the image and wait for a keypress
cv2.imshow("image", image)
key = cv2.waitKey(1) & 0xFF
# if the 'r' key is pressed, reset the cropping region
if key == ord("s"):
image = clone.copy()
break
# Se muestra la imagen recortada
if len(ref_point) == 2:
crop_img = clone[ref_point[0][1]:ref_point[1]
[1], ref_point[0][0]:ref_point[1][0]]
cv2.imwrite("corte.jpg", crop_img)
cv2.imshow("crop_img", crop_img)
cv2.waitKey(0)
print(f'CROP IMAGE {crop_img}')
def shape_selection(event, x, y, flags, param):
example = "resultado"+str(len(img_array)-1)+".jpg"
image = cv2.imread(example)
# grab references to the global variables
global ref_point, cropping
# Seleccion de coordenadas ok
if event == cv2.EVENT_LBUTTONDOWN:
ref_point = [(x, y)]
cropping = True
# Seleccion de coordenadas No ok
elif event == cv2.EVENT_LBUTTONUP:
# Seleccion x,y
# Termina corte
ref_point.append((x, y))
cropping = False
# Rectangulo
cv2.rectangle(image, ref_point[0], ref_point[1], (0, 255, 0), 2)
cv2.imshow("image", image)
if __name__ == '__main__':
arrayImg = []
img_array = []
alpha=0.97
ref_point = []
cropping = False
example=0
img=0
path = Tk()
path.geometry('100x100')
path.configure(bg = 'azure')
path.title('Selección de video')
ttk.Button(path, text='Seleccionar video', command=select ).pack(side=BOTTOM)
path.mainloop()
| 8bba2e2f4fe3e9d29e281da1807b0fe5895210fe | [
"Python"
] | 1 | Python | WilliamsDJGarcia/IA-PI | f27abf15a6a66b99fad4f935652356c12eef4aef | 28c1096efe1d507a2567816a40f483f1d9c32806 | |
refs/heads/master | <repo_name>NHVZG/java_back_end_learning<file_sep>/java_basic/Effective_Java/test.java
public class test {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++) {
// String s = new String("how"); // 11ms
String s = "how"; //4ms
}
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间" + (endTime - startTime) + "ms");
}
}
| f50531c9955afab0aed1f80c7004b32b4d390267 | [
"Java"
] | 1 | Java | NHVZG/java_back_end_learning | cc360aaf63338e39b498ce120a18382af6a4825e | 023cd3607386ea4e684e4320f5c6522ba5d78b41 | |
refs/heads/master | <repo_name>JJCinAZ/goaoc2020<file_sep>/day2/data.go
package main
var input = []string{
"8-11 l: qllllqllklhlvtl",
"1-3 m: wmmmmmttm",
"2-4 p: pgppp",
"11-12 n: nnndnnnnnnnn",
"17-19 q: qprqdcgrqrqmmhtqqvr",
"16-17 k: nphkpzqswcltkkbkk",
"6-9 c: rvcvlcjcbhxs",
"18-20 v: hbjhmrtwzfqfvhzjjvcv",
"5-9 z: jzzhzttttnz",
"7-13 d: bdqdtddddnwdd",
"9-11 d: ddddddddxdldddd",
"6-10 f: fblhfdztgf",
"2-11 b: vszxfnwghcb",
"15-18 n: nbnmwxnnlkmlknnnhn",
"2-9 z: lhwqvczrrqqhqlfvkbcm",
"15-16 d: dndddddddjdddddbdld",
"7-8 k: kkkmkkkf",
"1-8 p: rdcmrkbwqjpph",
"2-6 s: cswdpsjgsfvzkvqqmrqf",
"9-11 m: mmmmmmmzbmmmv",
"8-9 j: jjjjjjjjfj",
"7-8 d: dddsjnds",
"1-4 f: qffb",
"3-8 f: cphmtfff",
"1-13 s: rjsscssstsvssss",
"9-14 s: gtsnlbqnckhxmssbbs",
"12-14 j: jfjnjbjrjpdndj",
"15-16 t: tttttttttttttttwt",
"7-8 r: rgrdrrrrrrrrjhrrrrrr",
"5-8 t: lpcqfgzttlt",
"1-12 r: wrrrrrrjrrrrrrrr",
"14-19 d: ddvcdddddddhddprldl",
"4-8 d: pkddlzxsl",
"7-11 x: xhxqxcfkxwxxnm",
"3-7 q: qqqqqqjqqqd",
"3-13 s: rtzsktsdfhtbs",
"8-15 n: nnnnnnnnknnnnnsnnn",
"10-13 r: rrrrrrrrrrrrnr",
"1-9 r: ldfdgzprnptrd",
"2-3 k: rqkthj",
"4-7 p: prrpswdpnmpxmjzsp",
"12-13 p: pmwbptnpppjprfpkppgj",
"4-6 w: cfwdlw",
"2-9 r: pnnvrfjhz",
"14-16 b: bbbbbbbbbbbbbtbbb",
"2-7 l: xlmzgklxljcl",
"1-6 c: cccccccc",
"11-12 w: dmpzfzpwwnwwpggw",
"2-3 c: xrccccmcc",
"12-13 k: kkkkkkkvkkkvkknkkk",
"10-12 h: hhnhcvhhhqhh",
"17-18 d: dddjddbdzdddvddddw",
"1-5 p: pppphp",
"11-13 v: fvvvvjlvbvrvdhbvv",
"10-14 b: bzxxqcgqnbkmhm",
"1-14 g: xggghgngqnggggggggg",
"9-10 s: xslsmpfnxvvssqmgf",
"16-17 s: nfqggjzbfsssllwns",
"9-10 w: wwwwwwwwfw",
"13-15 z: zzzjzzzjzzzzzzgz",
"7-10 n: jfnwgwnnnn",
"4-5 b: btbqb",
"1-5 w: vwflw",
"15-16 v: vvxvdvvvvzvxmhxvv",
"3-4 b: cgbbqk",
"1-3 f: bffffdfclfffgfkf",
"6-11 m: xckgmdcqmwk",
"6-9 c: vcptncxbcg",
"5-6 m: mmmmdm",
"2-3 d: dmdd",
"5-7 v: vvhrxkd",
"7-10 b: bbbbbbqbbbbb",
"8-9 m: mhvmmwlgm",
"3-4 x: xvtxkz",
"3-9 w: wwlwwwwwkqww",
"4-18 g: mxslljzcgpwsrggqqc",
"2-3 x: xcff",
"16-17 j: jjjjjjjjjjfqjfjwhjjj",
"9-13 p: ppppppppgppppp",
"16-17 f: fffffffffffffffffff",
"3-5 c: cncpcck",
"9-11 c: kzcwczccccmcfsrcc",
"3-7 s: ssdsssvnsssssjs",
"1-6 v: vvvvqv",
"5-7 b: fzbbxbbbgbb",
"3-9 t: gtttttttftt",
"5-19 p: ngpnpklwsclptfjvtgm",
"3-4 d: dddtdddddd",
"4-5 m: mjmmwl",
"11-13 l: lllblllllvllrl",
"2-6 h: cphqvz",
"17-19 w: gwwrvfglsljwfgxwbbw",
"15-17 x: gfcxzcwgjmkwfqxrxzrd",
"13-14 w: lrmhhxwfkwnkwnbsq",
"7-8 f: ffffffgcff",
"11-19 v: vvvvvvvvvvzvvvvvvvlv",
"7-8 k: kxkkkkpk",
"7-14 v: vfvvvskttcvvvvvfvv",
"11-12 m: mmmdhmmgmkgmjmr",
"1-7 p: hpppppppppbnc",
"3-8 n: rttbbpjnmzn",
"8-9 n: nrfnnvxrp",
"3-4 x: tnxnngq",
"9-12 s: mbhsxshssrtwvm",
"11-15 n: nwmnlhgjnnptkmn",
"1-4 x: xmxl",
"1-6 f: bffffffffff",
"2-4 r: zrrr",
"2-3 t: ttmwvt",
"3-5 n: ngnnr",
"13-17 p: jtpppfgklkpshpndpp",
"1-7 r: rrrrrrrrrrrr",
"7-10 h: hmhhhhhhhzhhhhhhh",
"9-15 l: glxqscckgxtkzfllk",
"2-3 s: gfsh",
"5-6 b: dpphbj",
"6-13 h: hhhhhhhhhhhbshgh",
"5-13 d: dddpbddddddddddd",
"10-11 p: pppppppppdppppp",
"5-7 j: jjjjjcx",
"8-9 r: rrrrmrrrm",
"1-3 f: ffff",
"8-15 b: bbbbbbbgbbbbbbrb",
"3-6 h: hhrhhhhhhh",
"9-10 v: tkwvvvjvvvblvxvxhxvv",
"5-9 t: ttttttttmtf",
"1-4 m: fmmmmm",
"5-9 n: nfnlnkblnnfnxtzn",
"3-11 v: dnsvvvbvnvvxvj",
"8-13 h: nfgmbfjhdhlhb",
"2-14 q: cxtgcrpsxnjshlqbh",
"5-13 b: bbbbjbbbbbbbbbbbbbb",
"4-5 l: wldljllcl",
"19-20 b: jbvbbbbbqqbbbbbbbbbs",
"5-14 b: bbbbbbbbbbbbbbbbb",
"2-5 q: qmqjqhfk",
"12-13 s: sssfsnsssssssxsms",
"3-17 z: zzzzzzzzzzzzzzzznzz",
"13-14 t: ttztttstttbttb",
"2-6 q: vqhhrqlgvckvsrpwmqwz",
"15-16 d: dddddddddddddddhd",
"5-6 w: wwwwdwww",
"1-2 f: jffkf",
"6-10 j: jjjjjrjwjbjxgpjjjm",
"4-5 c: cvgccmcqzrcd",
"3-7 h: mghkhfgzmkz",
"10-17 f: ffffsfffffffpffwkff",
"4-9 g: ggbgcgjgggggg",
"8-11 d: mdnddhpddddm",
"6-7 c: ctcldgc",
"13-14 m: mmmmmmmmmmmmlmm",
"18-19 t: ttttttttptttttnttgt",
"7-8 g: qngggtghnxggs",
"3-12 c: scccrbjtdccq",
"2-3 q: qgqjq",
"5-6 x: xxxxzxxxxx",
"6-10 v: nwjsxvzhvgmsglftbpvc",
"2-5 m: xjtbsffdwmxmhxrmpm",
"4-7 c: mfgcvqccg",
"1-7 c: cctcccc",
"3-4 m: cnnw",
"10-13 s: sstssssszsssss",
"9-10 h: hchhhhjhdh",
"2-4 j: xjjgsz",
"4-11 b: rbblbbpmbmbdbjgcbhk",
"10-11 r: rrrrrrrrrjrrr",
"3-6 g: hvgfzgjrkdf",
"1-10 b: tbbbbbbpbbbbbb",
"12-13 n: nhnnnnnnnnjnznnrnrxl",
"7-13 w: wwmwfncfwdxww",
"3-4 c: wccq",
"7-16 x: xxxxxxtxxxxxxxxxx",
"3-7 k: zmhkssxs",
"1-8 n: gnnnnnnnnn",
"13-14 r: rrrrrrrrrrrrmr",
"2-3 r: rrlr",
"3-4 c: sccccwvpjpplgctg",
"1-2 b: svbs",
"1-2 f: fbfffrff",
"6-14 l: lllllvlllllxtllqllll",
"13-14 f: ffffffffkfffjf",
"1-6 z: zzzrzfzzzzm",
"4-8 k: kzzktkgrzjdkq",
"6-8 j: jjjfsgjjbt",
"3-7 q: qtqqqqq",
"17-18 x: djxqkrlcwxxxlvhjxh",
"6-8 c: tqpcgcjc",
"2-13 f: khqhkkszblvffhfwcg",
"7-18 p: kjxrtcpptzpxddbkts",
"5-12 l: llldllllllntm",
"2-7 q: bvvrnhqhpqw",
"2-6 s: scssswssss",
"1-2 n: njdnnnn",
"4-8 h: hhhzhhhhhhhhhhhhhhh",
"9-10 j: jjjjjjjjkjjxqjjw",
"4-9 t: tzdqtlttttktttttcttt",
"4-5 w: wdwht",
"8-9 x: xfxxxxfrsxp",
"3-4 m: mmmmgwwbmztpmbmmmtls",
"8-17 f: mgzhfgfffswbgnvbc",
"5-6 t: tttttg",
"4-18 x: xxxwxxxxxxxbxxxnxxx",
"2-4 l: cqglmhmtjls",
"2-4 z: zfgzr",
"11-18 k: nrdngbjkpckjxwdbrh",
"8-9 f: fffffffpf",
"4-7 g: ggtgghgsnggr",
"5-6 w: wswwlw",
"3-5 b: dfbbjbccx",
"2-3 t: tdwfzg",
"4-5 r: rhrbw",
"4-5 j: jjjjtjjn",
"3-4 k: hkzkk",
"1-2 c: cdzccc",
"3-5 r: vhlrrvhr",
"4-9 l: qbjdqldwzdl",
"6-11 f: flvpvfcfrgg",
"17-18 g: xgggggghgggglggggz",
"5-6 v: bhvgvl",
"7-15 n: nnnnnnnnnnnnnngnnnnn",
"6-15 d: dtddsddfddmcpdf",
"10-12 b: bbbbbbbbvlbbbbbbb",
"2-12 d: szdghlzwxpnd",
"3-4 z: zzzw",
"6-15 t: mrnjvfhtlqwlfzt",
"8-10 x: lcxcbrxxjw",
"6-13 r: rgszrlzmmlpdngchhxz",
"1-14 g: fgggggggggggggggggg",
"3-5 n: znnnjpksqtzt",
"17-18 l: bcfmqlsltppxwsxslb",
"5-8 t: tttnctttt",
"4-5 m: mmmmnmml",
"15-20 k: kmkpvxkgnckknzkpkqkt",
"12-15 x: xxxxvxlxxkdxxxx",
"1-5 v: vjdndsvsjvqzvnv",
"1-4 k: kkkkkkk",
"5-8 c: cxccccccc",
"2-4 v: vdvd",
"12-14 w: wwwwwwwwwwqwwbww",
"2-3 b: kbbtbrllwp",
"14-15 f: ffffffffffffffm",
"9-10 v: nlngldlnvsbwcvvt",
"4-5 c: kccxccc",
"5-9 m: bmmmmmmmzmf",
"8-9 f: fzfvffjffffv",
"3-14 r: rrqrrrrrrrrrrjrh",
"13-14 p: ppptpppppptpqdpm",
"6-12 t: tttjtvtgcwvttttqkt",
"5-10 z: glsrzctzzz",
"5-8 s: gckwcshsl",
"17-19 n: nnnnhnnnnnnnntwnnnd",
"7-9 r: rrrrfdrrxrrrrrrrrrrq",
"17-20 m: rmxbmmvwphmxmzlmbmxm",
"14-15 l: kkjwtlsrlhltmdl",
"14-17 f: ffffffffffffffffff",
"3-13 l: khxtqtwbvpmgll",
"2-4 w: wwbmww",
"9-15 n: nwxcnxnckttrkdqnn",
"3-4 t: fgnwjbtlntsr",
"15-16 x: mcxxxxxxrxxxpczx",
"6-16 w: vtcvkmrwvlmwdvrwmqj",
"1-3 c: mmcjckwn",
"1-10 c: ccccccccckccccc",
"14-16 l: kqjhpjgzvxlnxxll",
"4-7 r: xrtrrrrrcrrmrrrr",
"8-13 m: mmmmmmmmmmmmcmm",
"7-8 r: trkrrrrwf",
"3-4 n: pnjn",
"1-5 k: skkknkk",
"11-16 k: kfkkkjkqpqgkzkkkkwsn",
"13-17 f: gdllffxlxwncljgwf",
"3-5 s: gwspdtjtnlbsfffvhlg",
"15-17 m: krmfcsqbmmmjwgkdmm",
"13-14 l: knhdrdzcmdhlll",
"2-3 p: frps",
"2-9 z: lzwnzmvnqgkpbxv",
"5-9 n: nnngrnnbj",
"3-5 c: mncnbk",
"2-5 n: djgnnnnnzbnnnx",
"7-8 v: vvgvgvvm",
"5-15 w: wwwwwwwwwwwwwwwwwww",
"6-7 d: dddddcz",
"7-9 g: glrgcggvgckrgggz",
"2-3 n: dnwbnc",
"6-8 t: lttztzqt",
"1-4 m: mmmxm",
"4-14 l: qqhgtftklcnmllcbgbrx",
"2-3 d: sdnk",
"12-15 l: lqllljfglvldcql",
"2-10 k: kgkkkkkkkkxkkkkkkkkk",
"10-17 h: ljpwchmhhzmhdhmrchp",
"6-10 w: lpcfgkslrwwrlkhx",
"3-7 w: wrpwcpw",
"8-9 z: kczxltgzh",
"6-11 n: nnnnnhnsnlnnn",
"2-9 s: smssssssgss",
"2-4 x: xxwhxbfjj",
"1-2 z: fzzzzzzzzzzzzzz",
"4-5 p: pplcdpp",
"3-4 c: gncxlzc",
"16-17 x: fxqltszfgnnkxgrxhcbk",
"13-17 n: nnnnnnnnnnnnnnnnvn",
"1-6 x: dxxxxxx",
"7-8 r: scbnvqrpcbgmpmrrs",
"2-17 d: ddddddddddddddddhd",
"13-19 v: fvtphwfnmpfpbpjnnbv",
"7-18 q: cpwqnhqjqfkqqncbsh",
"6-10 c: cccdcxccncfxcgc",
"2-4 g: fggsgbgggggcggt",
"13-17 r: hspwrxrzbrvlmlwgrkxr",
"14-15 l: pllgllllllllrmv",
"12-15 g: hqgcgggsxgjxljgdz",
"3-4 d: dtxd",
"7-12 d: kddvbkkdldqbkn",
"3-13 v: vvvvvvvvvvvvtv",
"8-13 t: tttttttttfttdt",
"18-19 q: hprbdznbqlfnwzwpqckb",
"5-12 c: wwlqcgzqzvtczvcldg",
"3-5 z: xzzzv",
"2-11 c: xbblzgtwcjcfqqb",
"8-9 n: nnnvbnmvl",
"8-9 z: zzzszzzzt",
"2-3 l: chsrlrl",
"2-4 f: nffm",
"6-7 h: hhhhhhhh",
"10-16 x: xxxxxxxxxxxxxxxwxxxx",
"2-19 v: ztpvktjgjlmqfrrxfpv",
"2-5 g: gncgg",
"1-3 t: hjtttttvgtttttttttt",
"3-4 s: nbvs",
"5-10 n: nnnqnnnnbvnnn",
"7-15 q: qqqqpqqqqqqqqqzqqsqq",
"3-5 b: sjtwbr",
"2-4 t: sttxln",
"1-5 d: ddddd",
"12-13 v: zvdpfbkkvcpvdvb",
"3-6 j: cnnjhj",
"7-8 q: qqrqpbfqjvbtqlqjqkqh",
"2-4 v: wvvq",
"2-7 m: mpmrmmmmdnmmmmk",
"10-14 g: ggmcgggpggcngglm",
"3-5 g: fsbpglh",
"4-5 r: rdrtq",
"3-4 t: qttltttl",
"16-18 s: sssszpssbnsssssfss",
"6-9 b: lbxbwbbqn",
"2-3 m: dmwsg",
"4-12 p: lmppwmsplppx",
"3-15 c: lvjmlzwctxnckvclsj",
"13-14 t: tttttttftstttw",
"1-5 m: jmmmm",
"2-3 r: rsfr",
"1-4 d: xdns",
"2-3 k: qklrwnskqnx",
"1-2 r: rrrr",
"5-8 l: vlsbftlltc",
"3-12 n: nhjlchbwphmn",
"6-7 h: thhghhv",
"1-11 v: vvvvvvsvvvk",
"9-11 c: ckdqzdkbjczkkcpdj",
"7-12 b: bbbbbjbbbbbfzbbb",
"3-6 v: vvwxkv",
"6-8 t: twttttttt",
"12-17 g: gfggggggggggggggg",
"2-3 g: gqgggggggggggggg",
"8-9 h: fmjhhbjhvv",
"4-7 q: qqqqqqjsq",
"4-5 p: hpkjp",
"2-10 h: bhsgwpwnhh",
"15-18 p: nwpqxrcxgjxbbxczxb",
"2-3 k: mtkszk",
"9-11 c: zccccpccrrc",
"5-6 c: qnzjgh",
"7-11 t: ttttttmtttct",
"1-5 p: pppppprplmpq",
"3-4 x: sxlc",
"12-14 q: xsqzxsrrmxvdxq",
"1-3 k: kklkjkvkkkkkk",
"11-12 k: ffflkkkkkkqkkks",
"2-3 z: zlzzz",
"10-13 k: kkxkkbkkfkckn",
"11-15 p: wkppvppxqxpnpbpkpppp",
"2-11 r: krqxlrvhwhlj",
"3-4 l: llllllrrbll",
"12-14 n: nthpvpzmwnsnnn",
"15-18 w: jwsnzwwwwwvwfdwggcw",
"15-16 k: gtxkxjvtkktkkhkr",
"1-3 m: kmzmmm",
"9-10 j: jjjjjjjjvwj",
"5-8 p: sppkrxzpbppppphpwv",
"5-7 w: wwwwgwhwwhppmqw",
"5-6 h: hchhhplrhphqq",
"4-5 g: bggbg",
"3-4 h: sbhmtvhhrbd",
"1-4 l: lqfl",
"5-7 j: jjjpjljjjj",
"3-5 q: qqqqdqqqjqqqqqqqqqqq",
"1-13 k: kkkkkkkkxkkknkk",
"12-14 z: jzzzzzzzzzzzzvz",
"1-4 q: bqqq",
"8-9 w: wkwftfmfx",
"7-9 s: kssjlslpmqssx",
"1-2 n: dxzmtsvnfhjnqsfln",
"15-17 q: bqmqnrcjsmgghgqjr",
"8-11 z: zzzzzzzdzzfz",
"6-7 z: znznzzz",
"8-11 l: jvlntmjwwrrqlkzrhg",
"1-5 r: rrvrjtrrjzr",
"4-20 d: fbvprndxpfqplmtkntdd",
"7-9 l: llllllqlclllll",
"3-6 n: xrnjzmlbnjwwzdzmdj",
"17-19 d: ddddddddddddddddxddd",
"9-10 w: wwwwwckbwhww",
"2-5 h: gchshhhn",
"1-4 l: gtlq",
"15-16 z: zzzzlzzzzzzzzzzhzdzz",
"5-6 l: lllfllld",
"14-16 j: jjjjgjjjjjjjjjjjc",
"6-8 d: dddddrddd",
"4-5 h: zhshc",
"8-9 g: gmgxgbfqg",
"1-8 r: lrrrrrrzrrgrrrrr",
"4-13 c: mccqccdccccwccccccc",
"3-4 z: zhzz",
"10-11 c: crmmvznptct",
"2-4 l: slblllt",
"1-6 q: wqqdqqtqqqgdqqq",
"2-13 l: nlllpwllpjdbxvbp",
"6-8 l: mxsflqrlhkqhsrmhtwxq",
"4-9 t: tpwbtdttt",
"2-7 q: fzqdrbg",
"7-8 d: ddpldttdddsd",
"14-17 b: bbbbbbbbbbbbbmbbbb",
"4-11 x: wfrxkjtpxlcbgc",
"6-7 n: nnnnnjn",
"13-16 z: zmqczdggpqzpcrlz",
"1-8 j: jjjjjjzdmjjtjj",
"5-6 v: vjsnvmb",
"5-7 q: nzqqwbqmbjwllj",
"2-3 j: mtjg",
"12-15 d: ddxdddddddddddcddd",
"4-15 g: hssvxrqgngtkcmh",
"1-4 m: mmmmmmm",
"11-13 j: jqjjjjjjjjmjj",
"3-4 z: zznzz",
"2-6 c: cccmcs",
"6-10 x: xxxxxgxxlxxpxxxx",
"1-2 b: bbrbbbbb",
"2-5 f: xfmkcf",
"4-5 r: rrrkxr",
"3-4 z: zslz",
"3-4 w: kwwh",
"15-17 x: rfxxcxwxsxsdgnxlxz",
"17-18 w: rwqlwwgwwwwjwbcjtw",
"2-4 p: ppjrpp",
"16-17 b: bbbbbbbbbbbbbbbtb",
"5-6 b: fbwbqt",
"3-5 b: bbjvxg",
"4-5 j: jbhljfjz",
"4-5 k: fmkkckpj",
"18-19 w: wpqtwhngztqkvgqrcjf",
"5-6 t: wttthhtt",
"12-15 v: kvgvvvcfglsvnsp",
"12-14 n: nnnnnnnnnnnknnn",
"5-8 k: xxzhdkmmkkkbwv",
"8-9 f: fdffdgvwpfffff",
"12-14 k: kdbsqwkjhvbxrkh",
"4-7 f: fvhkstfdrwfkvv",
"7-17 x: cvkbcvbfxxgxhbxxxpbx",
"11-14 m: jjnmmmsvhzcmcm",
"3-9 w: qwxsnsxnwzsnmk",
"1-5 k: tkkkkkkkkkkkk",
"5-7 h: hhhhhhdh",
"3-13 c: cclccccccccwccccc",
"1-4 w: wwwnw",
"3-7 z: wzzblltdglmfkl",
"9-12 k: kkkwqjnqskkdhckhvkk",
"2-5 r: xjtrrsxrrdzlbjvflqxr",
"9-13 g: gggbzggggjgxkgg",
"1-8 m: zmmmmmmhmmmmmhmmmmm",
"16-18 h: hzhhhhhhhhhhhhhhhh",
"2-7 w: wwwwwwvw",
"3-4 d: ddhd",
"3-5 x: jxvzx",
"15-18 k: kkkkhkckkkkkkkkkkkxk",
"11-12 m: mmmmmmmmsmwkm",
"7-8 k: khfkkktj",
"2-7 f: ffffffff",
"2-6 q: hqqdhbfvc",
"3-5 f: rlpffgf",
"3-4 t: wtltht",
"4-5 f: fscfx",
"2-16 t: nmtppmqttqztvdstc",
"1-15 j: jwgcbkdjlmjjxzwvpvd",
"10-12 v: vvhvfvvqvvvv",
"5-6 l: llllbwlll",
"1-2 z: xmszvzrwpm",
"6-11 d: dddjndddddq",
"4-9 r: xwkfwcztcq",
"9-10 k: ckskkkktkr",
"2-4 x: txpxfq",
"1-3 j: sjzj",
"7-11 x: bbhcswxtnhx",
"9-10 q: jlqnqmhjqhqq",
"4-19 d: qddkdmptbvjpbrjdzddl",
"7-9 d: sqdpdhhdx",
"7-8 j: gjzmzjgd",
"10-15 s: gkgsssssssqssssrpc",
"5-6 v: vvvvhbvh",
"1-3 c: cccc",
"1-3 c: ccwcccczgccpccz",
"2-4 t: tgtmqtl",
"11-13 w: wwwcwwwwwwlhw",
"4-5 z: nzgzrz",
"4-11 s: lhzxmwclxss",
"15-18 s: hmszwkscbdzsrgssjj",
"4-5 m: wkvgzjmhxmwlmlmvsjv",
"11-12 t: lndqtmsfwpjp",
"2-10 w: wkwwwwwwwww",
"10-11 t: ttgpwkjltgn",
"3-9 b: bbvbbbbbtb",
"5-7 h: rqlbntrhhkjhhhrdhq",
"1-2 n: rnnrbnn",
"8-11 n: nnnnnnnpnnnnnn",
"4-5 s: vhsnsjc",
"5-7 b: tbbbbbcbb",
"1-3 q: frbq",
"3-4 s: xsssmfsgs",
"13-17 k: kkkkkbfkkkkkvkkkkkkk",
"1-13 v: zvvvvvvvvvvvvv",
"11-14 c: cbcmcccccccmccc",
"15-17 r: skkrrvsrlmrrrrrjdrrr",
"1-7 m: jmmqmmmmkmmmrkmmr",
"9-14 f: kstfsxflhffxsffkb",
"7-9 g: ggggggggvggggg",
"13-16 t: tttttttgtttttttvtt",
"9-10 p: ppppppppphp",
"3-4 w: wwxw",
"9-13 g: ggggggggrgggvg",
"3-4 f: ffkffq",
"8-11 h: hbhhzhhhhhfh",
"2-4 d: dcnss",
"6-7 r: rtrrrbr",
"5-6 r: rrrrxq",
"1-11 g: fgggggggmkglk",
"14-15 h: vlqkqhhhfwhxfvs",
"3-4 w: wlrsgfsw",
"1-2 v: dxkwzvvxv",
"2-4 r: rvrcrtrrl",
"4-6 t: ttktttt",
"10-15 j: jjjjbtjjtjnjjjk",
"5-6 s: ssssssss",
"5-7 s: sfnkzss",
"4-5 b: shbtb",
"2-5 j: hjktjm",
"1-5 h: hhhhdhhhhh",
"5-17 m: mmmmgmmmmmmmmmmmmrmn",
"2-6 b: cxgxbbskzgdhr",
"10-12 k: kkkkkkkkkbkkkkknkmks",
"13-16 g: ggggggqggggghggggggg",
"1-2 w: wwwl",
"6-9 b: bkbbmbbbzb",
"6-7 m: qrfhmmndrkmc",
"5-11 p: ggzmjkxpnrpf",
"2-3 r: rhrr",
"6-7 f: vppvpwf",
"8-10 w: wrwwwdvwwjwwww",
"6-11 c: wxrbztwpcccj",
"14-17 x: xxxxxxxxxxxxxrxxxxxx",
"5-8 c: cccccczqccc",
"2-6 j: jgqjjfjzjjjjjjmjjj",
"4-7 t: zphkzttgtjdxdtd",
"4-7 t: wsrtdqgthqjvznbj",
"15-19 h: hmhhhhzhhhchhmhhhtxh",
"1-3 z: zzzz",
"2-3 j: jcvl",
"1-7 w: wcpwswwgjfb",
"3-6 c: crsvmcckc",
"9-10 f: fffffffffjff",
"3-6 v: hfvpwvgg",
"2-5 r: dkhrrd",
"1-5 f: cflmflfdvbz",
"3-13 k: sfkgcgktfkhrh",
"3-9 v: mmrprsvzv",
"3-4 q: qqqbcrkq",
"11-13 r: rrrwrrrrrrrgrr",
"6-11 j: tjjjzpsjrjdj",
"14-18 t: dtbhmtltcwpnzwqtgt",
"2-5 c: rsccchcc",
"11-14 m: kmmmmmlvmmtmmm",
"7-10 x: xhxxxxxbxbhxxxx",
"10-13 n: nnntnnnnnpnnn",
"3-10 w: wwwjwgwwwgwmww",
"17-18 p: phpppnpqppjsrpppzj",
"8-12 r: rsrbwrrrrrrzr",
"9-15 q: bqlrdqqxrdqqnxq",
"5-11 d: sldcndtlpzdb",
"1-3 w: zwww",
"11-12 k: tkbkwkkvsblpt",
"13-14 c: ccccccccccccqc",
"1-5 c: ccccrc",
"4-5 f: fffnf",
"3-4 w: wwwvw",
"2-4 k: kzkk",
"16-18 j: jjjjjjjjjjjjjjvqjj",
"2-8 v: wvqlrnrtgbzrp",
"6-10 c: cccccdcccccc",
"1-4 q: bqqqq",
"5-6 n: nnnnnnn",
"2-16 f: cjrffhfpfflxljjfp",
"3-8 g: ggfggggggg",
"7-8 z: zmzkzzzczwzzzz",
"7-8 m: mmmmmmmmmm",
"7-9 f: vzlffftfw",
"4-10 w: kckwgbmtws",
"4-5 g: ggghgp",
"6-17 w: wwwwwwwwwwwwwwwwkw",
"3-16 f: fffbfffffffffffcff",
"9-14 l: lllllllwmllmblllhlml",
"1-4 s: sssdssss",
"3-4 m: lmnm",
"10-11 v: vvvvkvsvvvmvhv",
"3-4 p: pprb",
"3-4 k: pkqk",
"3-4 d: ddxd",
"7-8 b: bbbbbbfb",
"5-7 w: qbmhsmt",
"11-12 b: bbbbbbbbbbbgb",
"3-5 x: xpxbljxt",
"2-9 z: kzmpqtbvzrqzh",
"3-16 v: qwvfvltjrpdxmvqv",
"2-6 n: pdjxzkn",
"7-8 j: jmzvjkjk",
"2-5 r: rrfjqqft",
"2-5 h: pwhfh",
"6-7 m: mmgvjmm",
"11-12 r: rrrrrrrrrrxqrr",
"1-4 n: nnnw",
"1-5 z: szzzzzdtzz",
"7-13 j: jjjjjjnjjjjjbj",
"10-15 w: rwwwwtmwswwwwwwwnmbk",
"11-13 t: twxhrldqtttmnt",
"1-2 r: bkbbrwr",
"11-17 h: hhdhhhhhhshqpbhhn",
"4-7 c: crgchccbnr",
"9-11 r: bdhgrzkmrrl",
"6-8 g: gggggggzz",
"3-9 g: ggggggggqg",
"9-11 z: zrfcqtrxxqzcx",
"3-9 s: zstjqhnvgjjfxknt",
"12-13 p: pppppwpgcppjppppptp",
"6-7 k: kkwrkckb",
"8-9 k: kkkkqzjkn",
"8-9 l: lrxlkbflrl",
"1-3 n: nndn",
"8-9 d: ddhddddddd",
"4-12 g: zdclfqvdgnzfv",
"3-5 d: ddddkddddddd",
"9-11 x: xxxxxxxxqxxx",
"4-7 t: ttttfftt",
"2-4 n: wfmnnddqxfm",
"16-19 r: zhjsgxjkjpqmpvkrjgr",
"3-7 v: vvfvvvvv",
"1-2 d: qdwdfj",
"6-10 h: hhhhhhhhhrhh",
"4-16 x: xxxpxxxxxxxxxxxxx",
"18-19 q: qqqqqqqqqqqqqlqqqqf",
"6-10 g: gkcntgbgbggklsx",
"8-9 n: nnnnxnnnpnn",
"7-9 m: msmmmtdvm",
"2-15 d: twjdrfzntqhnwkd",
"1-4 z: kzzz",
"16-18 b: tbbbtbjbtbtflzckhb",
"4-12 k: kkbhkgkrkgfk",
"8-10 q: lrqrjqvwmrb",
"1-3 f: vfhf",
"7-14 v: vvvvvvrtvvvvvvvv",
"4-5 n: xnntnwntrfnbqqdk",
"3-5 r: rhkrzwrhrrr",
"2-4 b: bspbjb",
"5-6 s: sfscsc",
"6-7 x: xxxxxhx",
"8-10 w: wwwwbzlmqw",
"7-10 v: fkvdvjbfvd",
"2-5 q: qtqspqqq",
"8-9 k: kmhkkhpsk",
"5-8 h: xhdhjfph",
"3-6 b: dlbkbb",
"1-3 w: wwbswwww",
"2-4 x: mxtx",
"2-4 l: llrll",
"3-7 j: kclqzgc",
"2-3 r: rxrrrgrrrrr",
"2-4 q: nzwxlmcqqqm",
"15-16 h: hhhhvmhbhdtbblbh",
"13-19 l: ltkftclmlllflzltlnb",
"4-5 p: zmwtpjrltqdmfppz",
"6-10 t: tjdxqtsbzhvprspljmv",
"14-17 q: qcqqqqqcqghqqqqqjq",
"1-5 j: flxrjspwlrdqsnjcs",
"14-15 m: mmmlmmmmmmmmmwm",
"3-5 d: dddvkwksdcrktlpd",
"8-11 l: llcllllxllml",
"2-4 v: vvvbv",
"1-3 g: llggz",
"3-5 q: znqqmt",
"15-17 f: ffffffffffffffjfff",
"17-18 q: zwnkmcqdqlqgkwfmqc",
"8-11 f: fffsrffbfffffvfxf",
"1-7 b: bbbbbbbb",
"3-4 l: llzh",
"8-9 n: nhnnnnqknnbnncncnnl",
"9-11 v: wvvvvvvbhjc",
"15-16 q: qcjqvfdcsqwdrqqt",
"9-10 j: jcckdzkzjjb",
"1-2 s: hssmsssms",
"1-3 w: xwww",
"2-4 l: lllll",
"2-4 q: qnmq",
"16-18 t: tttttttgtftttttttt",
"5-6 t: kttttj",
"16-17 t: twlqttttttttttmct",
"8-15 x: xxwpxsqkxgkxgxxbdgx",
"17-18 h: hhhhhhhhhhblhhhhrq",
"12-17 m: fmkmmmmqkmmdrbvthm",
"2-4 b: fbcb",
"1-14 t: tttttttttttttqtt",
"17-18 v: vvvvvvvvvvvvvvvvvnv",
"7-10 x: vxxtxlxxlk",
"3-5 n: nnmnqnnb",
"2-8 s: vssjqsssssb",
"9-11 l: wlllllllllllll",
"4-14 r: zrlcrxrrrzrrrrr",
"3-14 n: wrnjpnkndsshqk",
"12-16 p: ppppzpppppphppppp",
"9-12 r: rrrrrcbrrfprrrrr",
"2-3 b: bbrb",
"14-16 d: tzdjdndddgsddlnddgd",
"16-18 c: cccccccccccccccwcc",
"5-6 v: rvvqvt",
"11-17 s: ssssssssssssssssps",
"8-9 v: vpvxqvvdvnvhgnvvlvs",
"7-8 d: ddddqlrt",
"7-13 d: bfzrkddtdwqld",
"4-6 c: cccccq",
"6-8 d: hkdndlqq",
"11-13 l: ngmllbdklvlmqlz",
"8-17 m: mmmmfmmmmmmmmmmmlmm",
"12-15 b: bbsbbcblbsnbzbbfcfzz",
"12-13 k: gbwkkkkkkkksk",
"12-14 x: xxxxwxxxxxxdxxxxxxx",
"3-4 m: mwsmp",
"5-6 k: kkkkzk",
"4-5 h: pqslhh",
"7-13 l: gmpxpvwqrnlfp",
"3-6 t: sttxtmtn",
"11-13 r: rrbmbrwrrrrrkhrr",
"14-16 s: ssssssssssssstsss",
"7-10 v: vvvvvvhvdvvvkv",
"5-6 z: sxpzzx",
"2-4 d: rmxd",
"16-17 z: zzzzzzzzzzzzzzzzzz",
"1-3 k: kjkkkkcckkzk",
"1-11 k: xzkkkkzkppk",
"8-9 f: bfvfdffzb",
"4-14 r: rfzcrrlmxqlrrrqr",
"7-19 t: gtnxjqtnjbkrwpzshqqn",
"2-5 j: kjjgpddjpjjjffzjjp",
"2-3 f: cfffh",
"1-2 x: xxxxx",
"3-13 j: jjjjjjjjjjjjzfjjj",
"7-8 m: sgmmpmjmwmmmtfs",
"4-12 z: zfzqzzszvtml",
"6-9 b: jsfbpkzwb",
"13-16 x: zsxxjxxsxxqxpxxx",
"8-12 b: rlzdlplbgbdgd",
"3-14 h: hmrhhhhhhhhhrthhhh",
"15-19 g: mgggggcgggggqgghggg",
"2-9 p: ppppptppzcf",
"6-7 b: bbbbbbbbb",
"4-20 q: skqqvxptdswwnrflkvxq",
"4-5 t: lqttq",
"1-10 l: lqkqllvllj",
"11-15 m: qmmmmmrmqmmmsmf",
"6-15 s: ssssstssssssssss",
"2-4 x: xtxxx",
"9-11 q: qqqqqqqqhqgqq",
"1-4 n: gpnnfnn",
"1-3 l: lltl",
"11-15 k: kkfkkfkmmkrkkkk",
"11-12 f: fkcvfvtqfcfffffffffj",
"1-4 c: ccjc",
"14-15 n: bvbvfvzcbfnzqlsvh",
"4-5 x: xxlmxx",
"3-6 n: nnrnnnwlnncnn",
"6-9 j: jjjjjjjjq",
"7-10 d: pdplmxdczddbd",
"12-13 c: ccccbctccccccccc",
"12-13 j: jfjdjjjjjjjjjj",
"6-7 h: mrnphwh",
"2-9 n: njnnnnnnnnnnnn",
"3-6 g: rgxgggggnjghgggntg",
"9-12 b: bbbbbbbbbbbcbb",
"3-5 p: ppppvpp",
"16-20 t: ctkgpgzrwwngltvxcqct",
"4-5 s: sssdsh",
"12-14 v: vvvvvsvvvvvvvsv",
"8-13 w: zwwwwwwvwwrwgv",
"12-17 r: wrcrrrrrrrbrwrrrxr",
"12-13 x: xxxxxxxxxjsvrnxx",
"7-9 n: nqnnqnvnn",
"14-19 n: nnnnnnnnnnnnnnnnnnnn",
"4-5 c: vscjrl",
"1-3 l: llrl",
"11-12 w: wwwwwwwwwwzww",
"6-7 t: wlcktht",
"2-10 r: rrrrrrrrrwrrrmrr",
"2-6 x: lhqvpx",
"10-16 h: kqrhxclktcqhxchg",
"6-10 m: mmsmkmmjmlmhfmmnmm",
"5-7 h: hchhhhph",
"5-7 z: vtzzzwl",
"3-12 z: zzfzzzzzzzzzz",
"7-9 z: zzzzzzszzzzzzzzjz",
"8-9 g: ggggggggg",
"13-16 f: ptvzfmfkxfdkfhjff",
"1-10 w: cvhnfgnwpw",
"5-8 d: fvvmdlfqgjc",
"6-9 s: rzlrwzngshvt",
"2-4 v: vgql",
"1-3 r: rrmrr",
"5-7 j: jkjgwjj",
"4-7 b: bbbzdzbbcbbb",
"4-10 k: kkkkrkckkgkkk",
"10-12 m: mmmmmmddmjmn",
"4-10 k: mskmvkcpqkk",
"5-10 m: wbtdmxnvrmwqbqkwmtq",
"7-14 z: cfzftzzqnxffzh",
"12-13 z: zzzzkzzzzdzzz",
"4-5 l: lllslllvl",
"5-8 k: kkkkkkkkkk",
"10-11 l: llllllllllwl",
"3-5 v: hvzpxfvmvcv",
"8-10 t: tbtnrtbqzwtkqtf",
"6-10 j: njjjpjjjjkjsj",
"8-16 f: cvpxnsxfdnpdfswdhbb",
"6-12 n: nnndnnnnnnnz",
"2-3 d: dzdd",
"1-4 s: jshkscssssssssssssss",
"5-7 k: kkkqckwkcl",
"3-4 f: ffdf",
"9-11 c: cpccccncccqccc",
"1-8 x: gxxxxgxx",
"5-15 p: ppvkmmpcvzmmczpz",
"12-13 p: xppppppppvpnpppp",
"7-12 n: nwnnnnhcbnjnc",
"1-4 f: fnzjf",
"2-5 s: tltqss",
"3-10 r: rrqkrzvkrtbqcrp",
"3-14 h: hhhhthhhlrwhhhthp",
"2-4 b: bkbhbq",
"15-16 v: vvvvvvvvvvvvvvvsvvv",
"1-17 h: vtjjhtxrchshpxhsh",
"4-7 n: jnpnpnn",
"3-4 h: jvhz",
"4-5 w: wcpzw",
"9-10 q: tvxbsfmqqblhq",
"3-5 s: jssstxfbsssshssgkss",
"3-9 r: fnrhqkrmtstqjgc",
"12-15 n: xqwnnnnnnnnmnnn",
"13-15 q: qqqqqqqqqqqqqqtq",
"3-4 d: dcdl",
"4-12 d: vrldnmpndmlgdzrv",
"2-4 h: mhhh",
"3-4 f: fcvfc",
"1-2 w: whwwwz",
"7-8 m: mpmlmmmmhdbh",
"2-4 q: qxbqqdsjrdpxf",
"6-14 r: wbmlhrcgrgrkzqfj",
"2-7 c: ghcvcdcmcztckct",
"2-9 n: nnnnnnnnpnnn",
"3-5 f: zlgffv",
"1-6 m: ntmmmm",
"2-4 w: jgqwv",
"5-12 f: gscfzhmrtxfw",
"5-7 r: rwzklcrnrrg",
"8-10 h: hhhzhhhpxhhh",
"9-11 x: xxxxxxxxfxbx",
"7-8 q: qdnqnzbq",
"2-10 s: sssmssslbb",
"8-9 n: wgfnghnlnkf",
"4-10 d: dddsdddlds",
"1-5 k: bfkkkn",
"2-5 w: wwwwww",
"14-16 s: bjszbzmcnsvplsrh",
"8-9 b: bbjbbbbbbvvbbx",
"2-10 m: dmnrsmtqkf",
"7-12 f: fbtwftvffsgfwlnw",
"9-10 h: shhhpshfxhbrdhshh",
"4-9 t: tgpdtwrmt",
"2-6 t: vhtwntl",
"3-5 j: ljjjd",
"2-3 w: hxwvbxwwbwsvc",
"7-8 r: rrrzrrnr",
"3-4 x: jxjh",
"7-12 w: mjmbtgntdwjwnqztv",
"5-6 l: vlvllt",
"7-8 n: nnnnnnpnnnn",
"3-10 c: wcgcxzcdwmcn",
"16-18 h: hchhhhhhhhhhhhhcmh",
"5-11 f: fflffffffflfff",
"3-13 z: zzzzzzzzzzzzpzz",
"6-9 k: kkkkkskkkk",
"6-15 c: ccccccccbccccctccc",
"9-18 p: klcpzpdwzvpqppspfpp",
"10-13 b: pbbbbmbbdbwtmd",
"10-11 v: xvvvvvvvvnnvv",
"2-4 m: msmmm",
"1-4 w: rwwlwrwrwwrfngc",
"8-9 r: rjjlddjrnbr",
"13-16 d: pzdfzqbwclbjddxtvddf",
"14-15 q: qqqqqqqqqqqqqbq",
"12-14 k: kkkjgrkkqkkkkl",
"3-4 d: gsdnkdfnf",
"8-17 h: glhfvrshlrqwdrfrh",
"2-12 l: mflqfvxfgzkmd",
"5-8 f: ckllfnfbflqgrsd",
"1-17 m: kckvffhnlmjvdtgpm",
"16-17 p: pplppppcppppppppppp",
"5-8 h: hhjbmplh",
"7-10 s: jsjlwgsssbsvfsvk",
"2-8 x: xpfxbqxxqxhdrxhqm",
"12-16 n: nnnnnznnnnnnnnnmnvn",
"6-12 v: vvvvvvvvvvvgv",
"8-9 j: pjjjjmjnj",
"16-17 h: hhhbhjhrhhhhxhhgt",
"3-11 d: ldpmvddhdrdjdj",
"6-7 n: nnnnnnnn",
"5-8 f: tglffvhgnfxzfhf",
"13-18 r: rrrrrrrrrrbrhrrrrrrr",
"19-20 n: nnnnnnnnnnnnnnnnnnnj",
"7-8 w: tpmmxqsw",
"5-7 c: ccccccr",
"9-10 l: qltnnlnfllqlw",
"6-7 g: xggbggz",
"7-10 s: sssssfcssss",
"5-7 j: jsjkxwqhjcvjtwjzl",
"10-14 t: qdtttzttcvtttnn",
"12-13 b: bbbbbbrbbbbqb",
"1-15 d: dshhrjkwcjjhlthdts",
"7-12 p: hrxkphmqpvpptpqbw",
"13-14 d: ddndddxdtdrkvldd",
"3-4 h: htht",
"7-8 c: xtsvzccfckccx",
"4-5 r: gstrwshptzrdtjj",
"7-8 b: wbbnbbbm",
"15-17 c: cgpqxbccqcjpzlcctmx",
"2-7 k: kvtqqmsx",
"8-11 s: ssxssssqsssssssss",
"3-9 d: ddddddddld",
"13-16 p: pppppppppppppppwpj",
"6-8 v: sxkghpckvb",
"17-18 s: ssssssssbsssssssksss",
"1-2 w: wlwxdsw",
"8-9 q: qqqqqqqqnq",
"9-16 f: fjdsfvkfqffffjcfpff",
"12-13 h: bhhhhhhfwhphhhhhh",
"7-8 k: kkkkkknkkkkkkk",
"4-7 w: wwwfpsw",
"8-11 d: rsndldddddxddmf",
"2-10 c: cjcdcccccc",
"6-7 v: zvnrhth",
"3-8 z: zzxzzzzzdzjzzzzz",
"11-12 t: tctdttttwtrtttttjth",
"8-9 c: ccccccccrccc",
"17-18 p: pppppppppppppppppvp",
"3-8 l: svlmlkspljr",
"1-2 n: nwnkq",
"1-11 j: jjjjjjjjjjjj",
"18-19 g: ggggggggggggggggggr",
"10-11 j: jjjjjcdjgjv",
"3-7 p: ptttppppppj",
"2-5 d: cdndsd",
"6-10 s: sssssmssssss",
"15-16 k: vxwxxhhkkhklqksd",
"3-4 x: rpxn",
"1-6 g: vmgckg",
"3-4 j: jjbs",
"5-10 d: qrnmbddndvcmdsjjbdhd",
"7-9 v: vvmgvvvpvm",
"1-7 z: zzzzzzwzzzz",
"4-7 n: nnnnnnqn",
"8-9 k: kwkknknkrkgkbklmpb",
"1-5 z: zzmzfzz",
"6-10 m: mmmmmfmmmm",
"9-11 s: sssssstsssgss",
"2-6 n: nnfnpgnnnmnnn",
"15-17 w: wwwwrswthgwhkwwrw",
"5-9 h: lbhdhplmbnwh",
"5-6 d: jdddqqt",
}
<file_sep>/day2/main.go
package main
import (
"fmt"
"os"
"regexp"
"strconv"
)
func main() {
part2()
}
func part1() {
var (
r1 = regexp.MustCompile(`^(\d+)-(\d+)\s(\S):\s(\S+)$`)
validCount int
)
for _, s := range input {
a := r1.FindStringSubmatch(s)
if a == nil {
fmt.Printf("unable to match on input '%s'\n", s)
os.Exit(1)
}
min, _ := strconv.Atoi(a[1])
max, _ := strconv.Atoi(a[2])
if isValidPart1(a[4], min, max, []rune(a[3])[0]) {
validCount++
}
}
fmt.Printf("Found %d valid\n", validCount)
}
func isValidPart1(password string, min, max int, mustContain rune) bool {
found := 0
for _, c := range password {
if c == mustContain {
found++
}
}
if found >= min && found <= max {
return true
}
return false
}
func part2() {
var (
r1 = regexp.MustCompile(`^(\d+)-(\d+)\s(\S):\s(\S+)$`)
validCount int
)
for _, s := range input {
a := r1.FindStringSubmatch(s)
if a == nil {
fmt.Printf("unable to match on input '%s'\n", s)
os.Exit(1)
}
p1, _ := strconv.Atoi(a[1])
p2, _ := strconv.Atoi(a[2])
if isValidPart2(a[4], p1-1, p2-1, []rune(a[3])[0]) {
validCount++
}
}
fmt.Printf("Found %d valid\n", validCount)
}
func isValidPart2(password string, p1, p2 int, reqChar rune) bool {
found := 0
passwordR := []rune(password)
if passwordR[p1] == reqChar {
found++
}
if passwordR[p2] == reqChar {
found++
}
return found == 1
}
<file_sep>/day7/main.go
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
)
type Rule struct {
Contains map[string]int // map[<color>]<quantity>
}
var (
Rules map[string]Rule
)
func main() {
Rules = processData(input)
fmt.Printf("read %d rules\n", len(Rules))
part1("shiny gold")
part2("shiny gold")
}
func part1(targetColor string) {
count := 0
for _, rule := range Rules {
if canContain1(rule, targetColor) {
count++
}
}
fmt.Printf("Part 1: %d\n", count)
}
func canContain1(rule Rule, targetColor string) bool {
for color, _ := range rule.Contains {
if color == targetColor {
return true
} else if r2, found := Rules[color]; found {
if canContain1(r2, targetColor) {
return true
}
}
}
return false
}
func part2(targetColor string) {
if rule, found := Rules[targetColor]; found {
fmt.Printf("Part 2: %d\n", countContainedBags(rule)-1)
} else {
panic(targetColor)
}
}
func countContainedBags(rule Rule) int {
totalQuan := 1
for color, quan := range rule.Contains {
if r2, found := Rules[color]; found {
totalQuan += quan * countContainedBags(r2)
}
}
return totalQuan
}
func processData(input []string) map[string]Rule {
var (
regx1 = regexp.MustCompile(`^(.+) bags contain (.+)$`)
regx2 = regexp.MustCompile(`(\d+) (.+) bags?`)
)
rules := make(map[string]Rule)
for _, l := range input {
if a := regx1.FindStringSubmatch(l); a != nil {
newRule := Rule{Contains: make(map[string]int)}
if a[2] != "no other bags." {
if strings.HasSuffix(a[2], ".") {
a[2] = a[2][:len(a[2])-1]
}
for _, c := range strings.Split(a[2], ", ") {
if a2 := regx2.FindStringSubmatch(c); a2 != nil {
if count, err := strconv.Atoi(a2[1]); err != nil {
panic(fmt.Sprintf("Invalid count in rule: %#v", a2))
} else {
newRule.Contains[a2[2]] = count
}
}
}
}
rules[a[1]] = newRule
}
}
return rules
}
<file_sep>/day4/data.go
package main
var input = []string{
"iyr:2015 cid:189 ecl:oth byr:1947 hcl:#6c4ab1 eyr:2026",
"hgt:174cm",
"pid:526744288",
"",
"pid:688706448 iyr:2017 hgt:162cm cid:174 ecl:grn byr:1943 hcl:#808e9e eyr:2025",
"",
"ecl:oth hcl:#733820 cid:124 pid:111220591",
"iyr:2019 eyr:2001",
"byr:1933 hgt:159in",
"",
"pid:812929897 hgt:159cm hcl:#fffffd byr:1942 iyr:2026 cid:291",
"ecl:oth",
"eyr:2024",
"",
"cid:83 pid:524032739 iyr:2013 ecl:amb byr:1974",
"hgt:191cm hcl:#ceb3a1 eyr:2028",
"",
"ecl:gry hcl:eefed5 pid:88405792 hgt:183cm cid:221 byr:1963 eyr:2029",
"",
"pid:777881168 ecl:grn",
"hgt:181cm byr:1923 eyr:2021 iyr:2018 hcl:#18171d",
"",
"byr:1941 eyr:2027 ecl:gry iyr:2016 pid:062495008 hcl:#a5e1b5 hgt:178cm",
"",
"cid:56",
"byr:1971",
"hcl:#efcc98 pid:649868696 iyr:2011 eyr:2025 hgt:164cm",
"",
"ecl:blu",
"pid:117915262 eyr:2023 byr:1925 iyr:2020 hcl:#888785",
"hgt:188cm",
"",
"iyr:2012",
"cid:174",
"eyr:2024",
"pid:143293382 ecl:brn byr:1946 hgt:193cm",
"",
"eyr:2021 iyr:2011",
"hgt:192cm pid:251564680",
"byr:1976",
"ecl:blu hcl:#602927",
"",
"byr:1973 ecl:blu hgt:164cm",
"eyr:2022 pid:695538656 iyr:2010 cid:244 hcl:#b6652a",
"",
"iyr:2014",
"eyr:2027 pid:358398181 ecl:hzl hgt:74in byr:1949 cid:329",
"hcl:#ceb3a1",
"",
"cid:211",
"byr:1954 eyr:2023 hgt:172cm ecl:blu iyr:2019 hcl:#623a2f pid:657051725",
"",
"pid:562699115 eyr:2026 byr:2000",
"hgt:162cm hcl:#602927 ecl:amb iyr:2018",
"",
"ecl:brn",
"iyr:2013",
"pid:835184859 byr:1981 hgt:157cm eyr:2027 hcl:#b6652a",
"",
"pid:763432667 byr:1981 hcl:#cfa07d ecl:brn",
"iyr:2010 hgt:63in cid:107",
"eyr:2027",
"",
"byr:2009",
"hgt:177cm cid:314",
"hcl:f55bf8 eyr:2025",
"pid:632519974",
"iyr:2015 ecl:amb",
"",
"eyr:2024 pid:614239656 hgt:169cm iyr:2014 ecl:hzl byr:1992",
"hcl:#602927",
"",
"ecl:blu",
"eyr:2026",
"hcl:#efcc98",
"byr:1980 iyr:2013",
"hgt:161cm",
"pid:065413599",
"",
"hgt:182cm",
"eyr:2025 iyr:2013 pid:939088351 hcl:#b6652a byr:1994 ecl:amb",
"",
"hgt:65in cid:220 ecl:amb hcl:#ceb3a1",
"iyr:2013 eyr:2025 pid:167894964 byr:1976",
"",
"hgt:185cm cid:88 ecl:blu iyr:2020",
"eyr:2020",
"hcl:#888785 pid:582683387",
"byr:1981",
"",
"hcl:#866857 eyr:2020 byr:1948",
"pid:358943355",
"ecl:amb hgt:164cm iyr:2019",
"",
"pid:127467714",
"hcl:#ceb3a1 byr:1991 hgt:163cm eyr:2020 iyr:2017 ecl:blu cid:229",
"",
"cid:156 byr:1942 eyr:2024 hcl:#cfa07d",
"ecl:blu pid:843747591",
"iyr:2014 hgt:173cm",
"",
"hcl:#a97842 hgt:165cm",
"iyr:2013 ecl:#781088 byr:1952",
"pid:516882944",
"eyr:2026",
"",
"hgt:179cm",
"byr:1969 pid:408297435 iyr:2020 ecl:oth hcl:#cfa07d eyr:2020",
"",
"ecl:amb iyr:2013 hcl:#b6652a eyr:2023 cid:88",
"pid:324081998 hgt:66in byr:1945",
"",
"iyr:2012",
"eyr:2024",
"hcl:#18171d",
"pid:756726480 byr:1947 ecl:oth",
"hgt:164cm",
"",
"ecl:blu",
"hcl:#fffffd byr:1951 iyr:2019 pid:544645775",
"hgt:153cm eyr:2027",
"",
"pid:655906238 ecl:brn eyr:2028 byr:1959 hgt:63in cid:338",
"iyr:2020",
"",
"eyr:2020",
"hcl:#602927 hgt:72in iyr:2014",
"pid:305025767",
"cid:297 byr:1957 ecl:gry",
"",
"hgt:155cm byr:1942 hcl:#a97842",
"iyr:2014 ecl:gry pid:593995708",
"eyr:2022",
"",
"pid:219206471 byr:1955 eyr:2030",
"hcl:#a97842 ecl:oth iyr:2015 cid:134 hgt:170cm",
"",
"iyr:2013 cid:268",
"eyr:2020",
"hcl:#a97842 ecl:grn pid:235279200 hgt:178cm",
"byr:1952",
"",
"iyr:2013 pid:016384352 eyr:2027",
"hcl:#866857 ecl:grn hgt:161cm byr:1943",
"",
"ecl:amb hgt:169cm pid:149540593",
"iyr:2012",
"eyr:2040 hcl:#a97842 byr:1954",
"",
"byr:1938",
"ecl:brn hcl:#b6652a eyr:2026 hgt:184cm iyr:2018 pid:832531235",
"",
"byr:1945 iyr:2015 hgt:171cm eyr:2028 pid:998746896 ecl:hzl hcl:#866857",
"",
"hgt:73in ecl:hzl eyr:2023 cid:343 pid:458004221 iyr:2017 byr:1962 hcl:#efcc98",
"",
"byr:1970 hgt:159cm pid:925022199 iyr:2013",
"eyr:2028 hcl:#888785",
"ecl:hzl",
"",
"eyr:2027 iyr:2016 ecl:gry",
"hcl:#cfa07d",
"pid:006246552 byr:1939 cid:124 hgt:177cm",
"",
"byr:1982",
"iyr:2016 hgt:159cm",
"cid:102 hcl:#fffffd",
"eyr:2029",
"ecl:grn pid:619798285",
"",
"iyr:2018",
"hgt:189cm hcl:#efcc98",
"byr:1937 eyr:2023 pid:727551553 ecl:oth",
"",
"iyr:2014 byr:1976",
"eyr:2020 hcl:#7d3b0c pid:125102070 ecl:amb",
"hgt:186cm",
"",
"hgt:187cm byr:1949",
"pid:027653233 eyr:2021 hcl:#341e13 ecl:hzl",
"iyr:2020",
"",
"iyr:2016",
"byr:1954 pid:545631256",
"hcl:#602927 eyr:2023",
"hgt:191cm ecl:amb",
"",
"pid:509762954",
"hgt:190cm ecl:hzl byr:1991",
"eyr:2022 iyr:2019",
"cid:187",
"",
"hcl:#c0946f eyr:2024 hgt:152cm cid:277 iyr:2015 pid:872373191 byr:1988",
"",
"pid:544267207 cid:113",
"iyr:2015",
"hgt:181cm",
"hcl:#6b5442",
"ecl:gry",
"byr:1971",
"",
"ecl:gry",
"hgt:161cm iyr:2012 byr:1965",
"pid:574527322 hcl:#fffffd",
"",
"iyr:2018 byr:1976 hcl:#b6652a",
"pid:024582079 hgt:169cm ecl:oth eyr:2021",
"",
"pid:020478204",
"byr:1945 hcl:#7d3b0c",
"cid:239 eyr:2025 hgt:188cm",
"ecl:grn",
"iyr:2012",
"",
"eyr:2026 pid:202653345",
"byr:1988",
"hcl:#2cdc09",
"hgt:185cm iyr:2010",
"ecl:hzl",
"",
"hgt:183cm iyr:2017",
"hcl:#18171d byr:1977 eyr:2029 pid:804559436 ecl:grn",
"",
"hcl:#602927 pid:812072269 hgt:170cm eyr:2026 byr:1955 iyr:2020 ecl:gry",
"",
"eyr:2023 iyr:2010",
"hcl:#cfa07d pid:592419048 byr:1943",
"ecl:brn",
"hgt:172cm",
"",
"ecl:brn iyr:2013 pid:558179058",
"hcl:#fffffd eyr:2022",
"byr:1922",
"cid:331 hgt:64in",
"",
"ecl:xry",
"hcl:ade850 eyr:1995 pid:976028541",
"iyr:2030 hgt:179cm",
"byr:2030",
"",
"ecl:#2872b1 pid:158cm eyr:1927 hcl:ee8e92",
"iyr:2014 hgt:190cm",
"byr:2025",
"",
"hgt:155cm cid:283 eyr:2020 ecl:blu pid:755165290 byr:1936 hcl:#733820 iyr:2012",
"",
"eyr:2030",
"byr:1943",
"cid:323 pid:906418061 hgt:157cm ecl:amb iyr:2010",
"hcl:#7d3b0c",
"",
"hcl:#fffffd",
"pid:873200829 hgt:192cm eyr:2022 ecl:blu iyr:2016 byr:1920 cid:200",
"",
"eyr:2021",
"byr:1963",
"hcl:#a97842 pid:585551405",
"iyr:2019 cid:91",
"ecl:brn hgt:60cm",
"",
"byr:1946",
"pid:520273609 hcl:#341e13 cid:66",
"iyr:2020 hgt:154cm eyr:2024",
"ecl:brn",
"",
"ecl:brn hcl:#d64d7b eyr:2020",
"byr:1957 hgt:181cm iyr:2019 pid:378496967 cid:135",
"",
"pid:002446580",
"eyr:2027 byr:1939 hcl:#888785",
"iyr:2011 cid:168",
"ecl:oth hgt:160cm",
"",
"iyr:2019 hgt:70in hcl:#7d3b0c byr:1983",
"eyr:2024 pid:369493064 cid:54 ecl:oth",
"",
"iyr:1979 pid:170cm",
"hgt:65cm eyr:1933 hcl:z",
"",
"ecl:zzz pid:193cm hcl:z eyr:2020 byr:2013 iyr:2016 hgt:177in",
"",
"iyr:2010 hgt:187cm",
"byr:1932",
"hcl:z ecl:oth pid:665967850 eyr:2030",
"",
"eyr:2029",
"iyr:2013 hcl:#b6652a ecl:amb",
"byr:1936 pid:516025566",
"hgt:181cm",
"",
"hcl:#c0946f pid:238825672 byr:2000",
"iyr:2013 eyr:2028 ecl:amb hgt:183cm",
"",
"eyr:2021 hcl:#866857",
"cid:77 iyr:2017 hgt:156cm pid:271118829 ecl:amb",
"",
"iyr:2014",
"hcl:#fffffd",
"cid:321 hgt:159cm ecl:gry",
"pid:691381062 eyr:2022 byr:1991",
"",
"pid:111506492 hcl:#c1d296 iyr:2011",
"byr:1934 hgt:176cm cid:263 eyr:2028 ecl:amb",
"",
"iyr:2014 hgt:64in eyr:2024 cid:193 hcl:#b6652a byr:1967",
"ecl:oth pid:138677174",
"",
"hgt:168cm iyr:2020 eyr:2030",
"hcl:#6b5442 ecl:brn pid:975843892 byr:1927",
"",
"byr:1957 ecl:amb iyr:2012 pid:177266671 eyr:2026",
"hcl:#866857 hgt:162cm",
"",
"eyr:2029",
"hcl:#341e13",
"hgt:175cm pid:465809700 ecl:amb byr:1974",
"iyr:2010",
"",
"hcl:#a97842 iyr:2010",
"hgt:176cm eyr:2029 byr:1931 ecl:grt pid:161604244",
"",
"eyr:2024 iyr:2018 hgt:170in byr:1959 ecl:gmt hcl:#888785",
"pid:94163132",
"",
"iyr:2011",
"hgt:186cm pid:998471478 byr:1956 ecl:amb",
"eyr:2029",
"hcl:#efcc98",
"cid:76",
"",
"ecl:brn",
"byr:2001 pid:378527883 iyr:2013 hcl:#83bdc5 eyr:2020 hgt:181cm",
"",
"iyr:2017 ecl:grn hgt:172cm hcl:#888785 cid:100",
"eyr:2022 byr:2030",
"pid:311562177",
"",
"pid:097558436",
"cid:141 hgt:152cm iyr:2019",
"ecl:brn eyr:2023",
"byr:1940",
"hcl:#6b5442",
"",
"iyr:2016 eyr:2023 byr:1992",
"hgt:174cm ecl:amb",
"pid:691291640 cid:190 hcl:#fffffd",
"",
"hcl:#623a2f ecl:brn",
"eyr:2028 cid:227 iyr:2012 hgt:74in pid:964273950 byr:1965",
"",
"hcl:#ceb3a1 eyr:2028",
"iyr:2013 pid:175294029 hgt:150cm ecl:grn",
"byr:1936",
"cid:143",
"",
"byr:1935 hcl:#a97842 ecl:oth hgt:180cm iyr:2019",
"pid:857891916",
"eyr:2026",
"",
"pid:084518249 ecl:hzl eyr:2027 hcl:#c0946f hgt:192cm cid:315 byr:1961",
"iyr:2010",
"",
"hgt:67cm pid:37925169 eyr:2022",
"hcl:z iyr:2012 cid:315 byr:2028 ecl:dne",
"",
"hcl:#c0946f byr:1924",
"hgt:176cm cid:87 pid:682212551 iyr:2011",
"eyr:2026",
"ecl:gry",
"",
"hgt:181cm byr:1935",
"iyr:2018 pid:644964785",
"eyr:2026 ecl:amb",
"",
"pid:789810179",
"ecl:gry eyr:2021",
"cid:159 hgt:185cm iyr:2020 hcl:#602927",
"byr:1965",
"",
"pid:672386364",
"iyr:2013 eyr:2021 byr:1951 hcl:#341e13",
"ecl:gry hgt:173cm",
"",
"hcl:#18171d eyr:2030 pid:957722245 iyr:2012 byr:1955",
"ecl:grn",
"hgt:154cm",
"",
"byr:1955 ecl:oth",
"hcl:#cfa07d",
"eyr:2030",
"iyr:2013 pid:361945273 hgt:154cm",
"",
"iyr:2012 eyr:2027 ecl:grn hcl:#16d373",
"hgt:192cm",
"",
"pid:275525273",
"byr:1986",
"iyr:2017",
"eyr:2022",
"ecl:grn",
"hgt:75in",
"hcl:#919cc0",
"",
"eyr:2029",
"cid:84 hcl:#cfa07d iyr:2013 hgt:78",
"ecl:brn",
"byr:1925 pid:281331549",
"",
"eyr:2027",
"cid:219 iyr:2016 byr:1971 hcl:#7d3b0c hgt:179cm ecl:grn",
"pid:301296222",
"",
"eyr:2030 iyr:2010 pid:995982765",
"byr:1926 ecl:amb hcl:#888785 hgt:186cm",
"",
"byr:1955 iyr:2015 hgt:165cm cid:101",
"eyr:2027 ecl:amb hcl:#602927",
"pid:168654790",
"",
"hcl:#7d3b0c byr:1956 eyr:2029 hgt:155cm",
"ecl:grn pid:816685992",
"iyr:2016",
"",
"ecl:grn hcl:#cfa07d cid:71",
"pid:914724136 iyr:2012 eyr:2024",
"hgt:184cm byr:1938",
"",
"ecl:gry",
"eyr:2029 hcl:#602927 pid:255062643 iyr:2015 hgt:175cm",
"",
"hcl:#341e13 iyr:2017 eyr:2028",
"pid:459704815 byr:1922",
"cid:312",
"ecl:brn hgt:152cm",
"",
"ecl:dne eyr:1981",
"pid:8356519470 hgt:176 iyr:1941 byr:2006 hcl:z",
"",
"ecl:amb pid:753377589 hcl:#a97842 eyr:2022 hgt:187cm",
"cid:130 iyr:2013 byr:1961",
"",
"pid:952444443",
"hcl:#bde835 byr:1963 iyr:2020 eyr:2025",
"ecl:amb hgt:162cm",
"",
"eyr:2027 iyr:2018 hcl:#ceb3a1 hgt:152cm pid:882429463 ecl:blu byr:1969",
"",
"cid:134 eyr:2021 hcl:#a97842 hgt:63in",
"ecl:grn byr:1975 iyr:2019 pid:154078695",
"",
"byr:1956 eyr:2027",
"pid:396230480 hcl:#b6652a",
"hgt:175cm iyr:2020 ecl:oth",
"",
"ecl:grn",
"cid:263 hcl:#506937 byr:1924",
"eyr:2030 pid:705511368 hgt:159cm",
"iyr:2011",
"",
"eyr:2020 hgt:178cm ecl:grn",
"byr:1947 hcl:#888785",
"pid:177476829 iyr:2019",
"",
"ecl:hzl cid:211 iyr:2016 hgt:176cm pid:405182470",
"byr:1952",
"hcl:#866857 eyr:2028",
"",
"eyr:2032 cid:152 ecl:gmt hgt:150in",
"pid:75969209",
"byr:2019 hcl:z iyr:1940",
"",
"hcl:#fffffd hgt:193cm pid:607407479 cid:300 byr:1944 iyr:2017",
"ecl:oth",
"eyr:2026",
"",
"hcl:z",
"cid:125 eyr:2040 ecl:dne byr:2015 pid:733096171 hgt:63cm",
"iyr:1922",
"",
"pid:575721428 hgt:152cm cid:275",
"hcl:#cfa07d eyr:2028",
"byr:1935 ecl:hzl iyr:2016",
"",
"iyr:2012",
"ecl:grn eyr:2027 hcl:#623a2f pid:029106453 byr:1984 hgt:168cm",
"",
"ecl:blu cid:140 eyr:2028 iyr:2018 hcl:#c0946f",
"hgt:163cm byr:1944",
"pid:709288293",
"",
"byr:1936",
"hgt:172cm eyr:1997 hcl:#8b8c88 cid:50",
"iyr:2016 pid:205477922 ecl:grn",
"",
"hgt:170cm pid:872750582 eyr:2027 byr:1985 iyr:2017 hcl:#d6976a ecl:blu",
"",
"hgt:163cm",
"pid:189634089 cid:116 byr:1975 eyr:2030",
"hcl:#efcc98 ecl:brn iyr:2020",
"",
"ecl:amb byr:1953 hcl:#6b5442 pid:418787965",
"iyr:2018 hgt:193cm",
"eyr:2026",
"",
"ecl:#3ec898 cid:339 hcl:#866857 eyr:2025 hgt:179cm pid:591430028 iyr:1936 byr:1995",
"",
"pid:285371937 hgt:159cm",
"byr:1922",
"iyr:2013 eyr:2023 hcl:#6b5442 ecl:amb",
"",
"pid:545260883 ecl:oth",
"hgt:163cm",
"iyr:2015 eyr:2021 byr:1975 hcl:#866857",
"",
"ecl:hzl hgt:182cm pid:053762098 eyr:2023 cid:174 hcl:#6daac4 iyr:2017 byr:1937",
"",
"hgt:178cm iyr:2015 byr:1956 pid:815359103",
"ecl:blu hcl:#cfa07d eyr:2030",
"",
"hcl:#7d3b0c",
"pid:438108851 hgt:162cm byr:1930 iyr:2014 eyr:2024 ecl:amb",
"",
"eyr:2027 iyr:2019 hcl:#90eb1c hgt:178cm",
"pid:314810594 cid:278 ecl:amb",
"byr:2001",
"",
"byr:1949 iyr:1942 hcl:#888785 ecl:hzl hgt:184cm eyr:2027 pid:899137640",
"",
"hgt:153cm",
"eyr:2022 iyr:2011 byr:1975",
"hcl:#602927",
"ecl:amb pid:178cm",
"",
"hcl:#6b5442",
"ecl:amb iyr:2018 eyr:2025 pid:418735327 byr:1922 hgt:74in",
"",
"ecl:gmt hcl:z iyr:2024",
"eyr:1988 hgt:75cm cid:125 pid:690872200 byr:1928",
"",
"eyr:2024 hgt:184cm",
"pid:4634589837 ecl:zzz iyr:2022 byr:2000 hcl:89c187",
"",
"iyr:2017 byr:1966 hcl:#efcc98 ecl:brn pid:473085232 eyr:2021 hgt:174cm",
"",
"hgt:67in eyr:2030 iyr:2014 byr:1943 hcl:#602927 cid:344",
"ecl:oth",
"pid:210476779",
"",
"byr:1955",
"ecl:oth",
"hgt:193cm iyr:2012 hcl:#623a2f pid:818289829 eyr:2021",
"",
"byr:2018 ecl:#872a51 iyr:2024 hcl:97783d",
"pid:155cm hgt:174cm",
"eyr:1964",
"",
"hcl:#6b5442 hgt:157cm byr:1932 ecl:brn pid:4275535874",
"eyr:2024 iyr:2015",
"",
"pid:959861097",
"hgt:151cm cid:140 byr:1935",
"eyr:2029",
"iyr:2018 ecl:hzl",
"hcl:#623a2f",
"",
"hgt:181cm pid:911791767 eyr:2027",
"iyr:2016 byr:1962",
"ecl:grn hcl:#866857",
"",
"eyr:2021",
"byr:1994",
"hgt:162cm hcl:#866857 ecl:oth iyr:2014",
"pid:712345689",
"",
"hcl:#7d3b0c",
"hgt:170cm pid:600132416 eyr:2025",
"iyr:2016 byr:1978 ecl:brn",
"",
"hcl:#0a9307",
"cid:287 byr:1940 pid:786271493",
"eyr:2028 hgt:186cm",
"iyr:2019 ecl:oth",
"",
"eyr:2025 hgt:190cm ecl:hzl cid:228 iyr:2019",
"byr:1932",
"hcl:#623a2f pid:648307551",
"",
"pid:304587325 iyr:2019 byr:1923 hcl:#7d3b0c",
"hgt:190cm",
"ecl:gry eyr:2030",
"",
"hgt:188cm eyr:2027 byr:1958 pid:572934921",
"hcl:#888785 ecl:hzl iyr:2010",
"",
"iyr:2019",
"hgt:178cm ecl:grn hcl:#7d3b0c pid:007601227",
"byr:1975 eyr:2023",
"",
"pid:808872803 byr:1929",
"ecl:grn",
"eyr:2022 iyr:2019 hgt:74in hcl:#602927",
"",
"iyr:2019",
"cid:67 hcl:#602927 pid:292601338 ecl:hzl",
"byr:2001 eyr:2023 hgt:171cm",
"",
"byr:1962 eyr:2022 hcl:#b6652a hgt:193cm",
"ecl:oth",
"iyr:2010",
"",
"hgt:70in iyr:2014 hcl:#a97842",
"cid:169 eyr:2020 ecl:amb",
"pid:329751670 byr:1959",
"",
"byr:1920",
"ecl:oth hgt:172cm cid:57 pid:515139276",
"eyr:2030",
"hcl:#18171d",
"iyr:2013",
"",
"iyr:2012",
"hcl:#a97842 pid:946040810 hgt:65in",
"byr:1936 ecl:amb eyr:2020",
"",
"byr:1948 hcl:#18171d",
"iyr:2019",
"ecl:hzl cid:185",
"eyr:2023",
"pid:583625200 hgt:191cm",
"",
"hgt:154cm eyr:2022",
"pid:460137392 iyr:2010",
"ecl:grn",
"hcl:#ceb3a1",
"",
"eyr:2024",
"iyr:2016 pid:890698391 hgt:172cm hcl:#a97842 cid:271 ecl:oth byr:1926",
"",
"hgt:162cm pid:340904964 hcl:#b6652a",
"byr:1966",
"iyr:2010",
"cid:260 eyr:2028",
"ecl:amb",
"",
"byr:1933 eyr:2029 pid:642043350",
"iyr:2016 hcl:#b6652a ecl:grn",
"",
"pid:602218620 eyr:2023 ecl:blu",
"hcl:#623a2f",
"byr:1950 hgt:168cm iyr:2015",
"",
"ecl:gry pid:490792384",
"byr:1974",
"hcl:#a97842 iyr:2016 hgt:170cm",
"",
"iyr:2020 ecl:gry byr:2002",
"eyr:2029 hcl:#9f45c4",
"hgt:155cm pid:604239618",
"",
"hgt:190cm pid:560653271 iyr:2020 cid:349",
"eyr:2024 ecl:blu hcl:#efcc98 byr:1936",
"",
"eyr:2021 byr:1964 hcl:#efcc98 ecl:grn iyr:2018",
"hgt:165cm pid:218376636",
"",
"pid:186217101",
"iyr:2019 hgt:155cm",
"byr:2017 eyr:2022 ecl:grn cid:349 hcl:ece72e",
"",
"iyr:2015",
"eyr:2026 pid:802832833",
"hcl:#888785 hgt:190cm ecl:brn",
"byr:1952",
"cid:202",
"",
"cid:151 iyr:2017 hgt:152cm hcl:#a97842 eyr:2020 ecl:hzl",
"pid:554959609 byr:1941",
"",
"cid:116",
"iyr:2019 hgt:159cm byr:1992 pid:662111811",
"hcl:#18171d ecl:oth eyr:2024",
"",
"ecl:grn byr:1966",
"iyr:1950 pid:585351486",
"eyr:2038 hgt:178in hcl:a27d2b",
"",
"iyr:2014 cid:238 hgt:187cm pid:523401750 ecl:amb hcl:#18171d eyr:2023 byr:1984",
"",
"eyr:2021 byr:1957",
"pid:340752324",
"iyr:2015 hgt:157cm",
"hcl:#602927 cid:70",
"ecl:oth",
"",
"pid:458479816 ecl:hzl",
"eyr:2022 hcl:z",
"hgt:60cm",
"byr:2012 iyr:2005",
"",
"cid:57",
"hgt:154cm pid:446142864",
"hcl:#341e13 byr:1968 eyr:2030",
"iyr:2019",
"ecl:brn",
"",
"eyr:2028",
"pid:243811429 byr:1977",
"iyr:2011 hcl:#18171d hgt:185cm ecl:oth",
"",
"cid:205 byr:1976 eyr:2029 pid:649877471 hcl:#cfa07d hgt:152cm",
"ecl:blu",
"iyr:2013",
"",
"iyr:2009 pid:559014976 ecl:oth hgt:189cm byr:1936 eyr:2037",
"hcl:#efcc98",
"",
"pid:134378987 byr:1983 iyr:2013 hgt:173cm",
"ecl:oth hcl:#ceb3a1",
"cid:80",
"eyr:2020",
"",
"hgt:151cm byr:1964 ecl:grn iyr:2010 hcl:#b6652a pid:939492531",
"eyr:2028",
"",
"byr:1961 iyr:2014 hcl:#733820 hgt:179cm",
"eyr:2026 ecl:gry pid:732892920",
"",
"iyr:2018 byr:1996",
"pid:944007809 ecl:hzl",
"hcl:#866857 eyr:2021",
"hgt:155cm",
"",
"pid:374875696 hcl:#7d3b0c",
"ecl:oth",
"hgt:193cm byr:1948 cid:238",
"iyr:2020",
"",
"pid:305782299 hcl:#b6652a",
"ecl:brn",
"hgt:172cm",
"iyr:2018 byr:1927",
"",
"pid:945869114 cid:95 byr:1989 hgt:173cm eyr:2025 hcl:#b6652a iyr:2012 ecl:amb",
"",
"pid:55484149",
"eyr:1958",
"iyr:1956 ecl:grn",
"cid:95 byr:2028",
"hcl:c2af7e",
"",
"hgt:176cm ecl:amb",
"hcl:#a97842 eyr:2029 pid:937928270",
"cid:251",
"byr:1978",
"iyr:2018",
"",
"hgt:154cm",
"cid:213 pid:767329807 ecl:hzl",
"iyr:2013",
"hcl:#888785",
"eyr:2026 byr:1998",
"",
"cid:158 hcl:#b6652a hgt:155cm iyr:2010 eyr:2025",
"byr:1980 pid:338567803 ecl:amb",
"",
"hcl:#efcc98 byr:1940 hgt:62in ecl:oth pid:537307591",
"eyr:2030",
"iyr:2017",
"cid:179",
"",
"byr:1965 eyr:2027 pid:691913618 hgt:75in",
"hcl:#6b5442 ecl:gry iyr:2012",
"",
"hgt:163cm byr:1964 eyr:2025",
"iyr:2010 hcl:#ceb3a1 ecl:oth",
"pid:936536544",
"",
"pid:712946803",
"cid:343",
"hgt:187cm ecl:oth iyr:2020 byr:1983 eyr:2030",
"hcl:#7873b3",
"",
"ecl:blu",
"iyr:2010",
"hcl:#fffffd",
"eyr:2030",
"hgt:175cm pid:047567505 byr:1963",
"",
"ecl:gry byr:1946 eyr:2026 hcl:#602927",
"hgt:164cm",
"iyr:2010",
"",
"pid:223378458",
"iyr:2014 cid:151 ecl:hzl hgt:171cm",
"eyr:2020",
"hcl:#341e13 byr:1964",
"",
"ecl:brn byr:1948",
"hcl:#866857",
"hgt:193cm eyr:2024",
"iyr:2013 cid:277",
"",
"hcl:#623a2f byr:1943 iyr:2011 ecl:oth",
"hgt:184cm",
"pid:371604584 eyr:2024 cid:176",
"",
"hcl:#efcc98",
"eyr:2025 pid:241834382",
"hgt:178cm",
"byr:1985",
"iyr:2017",
"",
"hcl:#c0946f",
"byr:1996 pid:701366586 eyr:2026 hgt:163cm iyr:2015 ecl:oth",
"",
"hgt:65cm hcl:#18171d",
"eyr:2024 ecl:brn pid:172cm",
"iyr:2010",
"byr:1990",
"",
"hcl:#fffffd pid:68659204 hgt:161cm iyr:2025",
"ecl:#94b8aa byr:2021 eyr:2032",
"",
"ecl:blu iyr:2018 byr:1993 cid:184",
"hgt:177cm pid:289871693 hcl:#733820 eyr:2026",
"",
"cid:138",
"ecl:gry hgt:174cm eyr:2024 byr:1988 iyr:2014 hcl:#341e13 pid:864852584",
"",
"cid:321 eyr:2028 pid:93285596 hgt:173cm",
"iyr:2013 ecl:gry hcl:#623a2f",
"byr:1927",
"",
"pid:431242259 eyr:2022 ecl:hzl",
"byr:1960 hgt:151cm hcl:#efcc98 iyr:2020",
"",
"hcl:#866857 eyr:2029 iyr:2016 ecl:grn pid:526060780 byr:1929",
"cid:310 hgt:162cm",
"",
"ecl:blu hgt:183cm cid:168",
"iyr:2015",
"eyr:2021 byr:1951 hcl:#6b5442",
"pid:594960553",
"",
"hcl:#ceb3a1",
"iyr:2020 byr:1951 hgt:186cm eyr:2022 ecl:amb pid:317661479",
"",
"iyr:2016",
"hgt:163in hcl:#accfa0",
"ecl:brn",
"pid:307377995 byr:2000 eyr:2028",
"",
"pid:933380459",
"byr:1938",
"cid:291 hcl:#c0946f",
"ecl:oth iyr:2018",
"eyr:2026 hgt:170cm",
"",
"byr:1974",
"pid:262927116 eyr:2027 ecl:gry",
"hcl:#341e13 iyr:2014 cid:232 hgt:161cm",
"",
"hcl:#602927",
"byr:2001 iyr:2011",
"hgt:177cm eyr:2028 pid:165733929 ecl:amb",
"",
"byr:1922 cid:144 pid:333716867 hgt:183cm iyr:2015",
"hcl:#c25ea9 eyr:2022 ecl:blu",
"",
"eyr:2021 cid:147 byr:1978",
"iyr:2020 pid:938828535",
"hcl:#7d3b0c ecl:amb hgt:159cm",
"",
"hgt:153cm ecl:hzl",
"cid:232 byr:1953 hcl:#a97842 iyr:2016 pid:356632792 eyr:2029",
"",
"pid:745727684 ecl:gry iyr:2020",
"hcl:#a97842",
"eyr:2025 cid:275",
"hgt:65in",
"byr:1957",
"",
"hcl:#733820",
"ecl:grn iyr:2019 byr:1943 eyr:2024 hgt:70in",
"pid:953607814",
"",
"ecl:gry eyr:2028 hcl:#cfa07d",
"hgt:163cm",
"byr:1942 iyr:2019 pid:310104177",
"",
"hgt:190cm",
"eyr:2027 iyr:2010 byr:1978",
"ecl:gry",
"hcl:#964ba7",
"",
"cid:320",
"eyr:2022 hgt:169cm",
"ecl:blu hcl:#a97842 iyr:2015 pid:669007078 byr:1986",
"",
"iyr:2019 pid:901370677 hcl:7f2398 cid:305",
"ecl:amb eyr:2011 hgt:190cm byr:1991",
"",
"ecl:brn",
"cid:256 byr:1987 iyr:2017 eyr:2026 hcl:#623a2f pid:875646528",
"hgt:160cm",
"",
"byr:1955 pid:120131971 hcl:#18171d",
"hgt:156cm",
"ecl:blu",
"iyr:2011 eyr:2028",
"",
"iyr:2020 ecl:brn cid:188",
"hgt:157cm",
"eyr:2026",
"pid:504067323 hcl:#733820 byr:1982",
"",
"cid:102 hgt:177cm",
"hcl:#733820 ecl:hzl byr:1984 pid:542750146 eyr:2028 iyr:2020",
"",
"pid:419639528 iyr:2013 hgt:175cm ecl:blu",
"eyr:2026 byr:1999 hcl:#733820",
"",
"byr:1963 eyr:2020",
"pid:683641152 ecl:gry cid:207 hgt:180cm",
"hcl:#cfa07d",
"iyr:2020",
"",
"hgt:192cm pid:156436859 iyr:2020 hcl:#cfa07d",
"ecl:blu byr:1963 eyr:2025 cid:147",
"",
"eyr:2002",
"hcl:z iyr:2011",
"pid:6830168962",
"hgt:156in cid:288 byr:2029",
"",
"eyr:2021",
"pid:277739802 byr:1992 ecl:hzl iyr:2020",
"hcl:#7c5fe8 hgt:184cm",
"",
"byr:1989 pid:066973099",
"iyr:2017",
"eyr:2022 ecl:hzl hcl:#888785 hgt:76in",
"",
"hcl:#866857",
"iyr:2016 cid:306",
"ecl:hzl",
"pid:453816800 byr:1971 hgt:71in eyr:2030",
"",
"pid:248573931 hcl:#cfa07d",
"iyr:2014 eyr:2024 hgt:186cm byr:1970 cid:128 ecl:blu",
"",
"pid:172567579 ecl:brn iyr:2014 byr:1948 cid:309",
"hgt:151cm hcl:#888785 eyr:2024",
"",
"hgt:153cm eyr:2026 byr:1929 ecl:hzl pid:684760742",
"hcl:#c45e93 iyr:2018",
"",
"pid:#d50a43",
"iyr:1940",
"ecl:#7880a9 byr:2018 hcl:dc2fa7 hgt:185in eyr:1978",
"",
"hcl:#602927 cid:71 eyr:2020",
"pid:620634584 hgt:157cm byr:1991",
"iyr:2020 ecl:amb",
"",
"eyr:2023",
"byr:1959 iyr:1947 hgt:152cm ecl:#503286 pid:63978523 hcl:57dd0d",
"",
"hgt:190cm",
"byr:1955 ecl:blu",
"pid:507892696",
"hcl:#9bd1f0 eyr:2029",
"iyr:2010",
"",
"pid:365539813",
"eyr:2022 hcl:#623a2f iyr:2020 hgt:184cm",
"ecl:oth byr:1920 cid:213",
"",
"cid:50 ecl:oth pid:774859218 hgt:193cm",
"iyr:2017 byr:1925 hcl:#866857",
"eyr:2021",
"",
"hgt:189cm",
"iyr:2019 byr:1937",
"hcl:#a97842",
"eyr:2025 ecl:oth",
"pid:787390180",
"",
"iyr:2019 eyr:2027 hgt:183cm",
"ecl:hzl pid:549757712",
"byr:1956",
"hcl:#866857",
"",
"pid:755580715",
"hcl:#602927 hgt:187cm iyr:2017 byr:1925 eyr:2020 ecl:blu",
"",
"iyr:2019 hgt:69in",
"ecl:amb",
"hcl:#602927 eyr:2026",
"pid:951019647 byr:1974",
"",
"byr:1943 eyr:2034 hgt:150 pid:#36aedf ecl:oth",
"hcl:z",
"",
"eyr:2024",
"ecl:hzl pid:824745692 iyr:2012 hcl:06ab6e",
"byr:1944",
"hgt:159cm",
"cid:183",
"",
"hgt:169cm ecl:blu",
"eyr:2030 iyr:2013 byr:1945 pid:791359040 hcl:#7d3b0c",
"",
"iyr:2018",
"ecl:hzl hgt:152cm",
"hcl:#18171d eyr:2026 byr:1924 pid:534667048",
"",
"eyr:2029 pid:933295825",
"iyr:2011",
"hcl:#cfa07d byr:1981",
"hgt:164cm ecl:grn",
"",
"ecl:amb byr:1964 iyr:2018",
"pid:014457573",
"cid:152",
"eyr:2028 hgt:171cm hcl:#866857",
"",
"hgt:167cm",
"byr:1974 iyr:2012 ecl:amb pid:512315114",
"cid:278",
"eyr:2028 hcl:#623a2f",
"",
"hgt:153cm ecl:oth iyr:2012",
"eyr:2027 hcl:#888785 byr:1999 pid:416990697",
"",
"eyr:2025 ecl:blu byr:1991 hcl:#866857",
"hgt:189cm pid:546461828",
"",
"iyr:2016",
"byr:1988",
"hgt:160cm eyr:2025 ecl:amb hcl:#602927",
"pid:562766105",
"",
"ecl:oth byr:1942",
"hcl:#341e13 pid:564975864 cid:158",
"hgt:159cm eyr:2028",
"iyr:2018",
"",
"pid:406209763 hgt:170cm cid:331",
"iyr:2018 eyr:2026 byr:1981",
"hcl:#733820 ecl:gry",
"",
"pid:279164109 ecl:oth",
"cid:197 hcl:#7d3b0c",
"eyr:2024",
"hgt:185cm iyr:2020 byr:1925",
"",
"hcl:#efcc98 ecl:hzl",
"cid:92 hgt:190cm pid:724466265 iyr:2020",
"eyr:2025 byr:1996",
"",
"byr:1996",
"cid:55 pid:906572505 ecl:grn eyr:2022 hcl:#602927 hgt:160cm iyr:2014",
"",
"eyr:2028 hcl:#b6652a ecl:hzl hgt:186cm iyr:2016 pid:132872161 byr:1932",
"",
"hcl:#fffffd iyr:2019 eyr:2020 hgt:188cm",
"byr:1951 ecl:brn",
"pid:842126902",
"",
"hcl:#602927",
"hgt:158cm",
"eyr:2023 iyr:2010",
"pid:681061896 byr:1977 ecl:gry",
"",
"iyr:2018 hgt:192cm byr:1970 cid:200 ecl:grn eyr:2027",
"pid:164408694 hcl:#888785",
"",
"eyr:2029",
"pid:447061655 iyr:2010 hcl:#341e13 ecl:oth",
"cid:187 hgt:185cm byr:1943",
"",
"byr:1925 iyr:2012 eyr:2025",
"hgt:190cm hcl:#18171d pid:017534154 ecl:brn",
"",
"hgt:172cm byr:1923",
"eyr:2026 iyr:2015",
"pid:580812884 hcl:#c0946f ecl:hzl",
"",
"hcl:#888785 eyr:2028",
"byr:1952 ecl:brn pid:818889983",
"iyr:2010 hgt:180cm",
"",
"eyr:2026 ecl:gry byr:1982 hgt:188cm hcl:#c0946f pid:610689703 iyr:2011",
"",
"eyr:2028",
"iyr:2018",
"pid:921660781 ecl:amb",
"hcl:#cfa07d hgt:178cm byr:1975",
"",
"byr:1977 pid:667631009 iyr:2010",
"cid:86 eyr:2022 hgt:189cm hcl:#7d3b0c ecl:oth",
"",
"pid:214679440 hgt:190cm ecl:blu iyr:2017",
"eyr:2025 cid:292",
"",
"ecl:amb",
"iyr:2017 hcl:531ad3",
"hgt:163 pid:689027667 byr:2006 eyr:2033",
"",
"hgt:68in byr:1928 iyr:2010 cid:227 eyr:2023",
"ecl:hzl pid:#87bab9 hcl:#fffffd",
"",
"ecl:grn byr:1940 cid:294 hgt:152cm pid:310277488",
"iyr:2015 hcl:#18171d eyr:2030",
"",
"byr:1965 pid:240720987",
"eyr:2030 ecl:oth hgt:192cm hcl:#733820",
"iyr:2016",
"",
"pid:830487275",
"ecl:blu byr:1930",
"hcl:#b6652a iyr:2013 hgt:188cm eyr:2025",
"",
"hgt:177cm byr:1955 eyr:2030 ecl:amb pid:476675886 iyr:2016 hcl:#c0946f",
"",
"pid:152702068 iyr:2016 hcl:#b6652a",
"cid:82 ecl:blu eyr:2029 byr:1975 hgt:161cm",
"",
"pid:136852264",
"eyr:2024 cid:339 ecl:oth byr:1949 iyr:2011",
"",
"iyr:2020 pid:772739059",
"eyr:2025 hgt:157cm",
"byr:1945 ecl:brn",
"hcl:#6b5442",
"",
"hcl:#18171d eyr:2022",
"iyr:2018 ecl:grn byr:1933 pid:053763751",
"",
"pid:214212776 hcl:#18171d",
"eyr:2030",
"iyr:2020 byr:1988",
"cid:122",
"hgt:170cm ecl:oth",
"",
"pid:883116919 iyr:2018 ecl:brn byr:1938 hgt:187cm eyr:2020",
"",
"iyr:2020 hcl:#a97842",
"cid:329 eyr:2025 byr:1946 pid:636649774",
"ecl:grn hgt:158cm",
"",
"eyr:2023",
"ecl:blu hgt:161cm",
"hcl:#341e13 byr:1951",
"iyr:2020 pid:461889565 cid:97",
"",
"hgt:168cm pid:492241189",
"eyr:2029",
"iyr:2013",
"cid:150",
"byr:1980 hcl:#cfa07d ecl:hzl",
"",
"byr:1998 ecl:gry hgt:150cm eyr:2024 pid:401735295 cid:153 hcl:#733820 iyr:2016",
"",
"ecl:hzl hgt:184cm iyr:2018",
"byr:2001",
"pid:453480077 eyr:2025 hcl:#a97842",
}
<file_sep>/day7/data.go
package main
var testinput = []string{
"light red bags contain 1 bright white bag, 2 muted yellow bags.",
"dark orange bags contain 3 bright white bags, 4 muted yellow bags.",
"bright white bags contain 1 shiny gold bag.",
"muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.",
"shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.",
"dark olive bags contain 3 faded blue bags, 4 dotted black bags.",
"vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.",
"faded blue bags contain no other bags.",
"dotted black bags contain no other bags.",
}
var input = []string{
"drab plum bags contain 5 clear turquoise bags, 5 striped aqua bags, 4 dotted gold bags, 4 plaid chartreuse bags.",
"faded cyan bags contain 1 dim brown bag, 5 wavy magenta bags, 3 vibrant chartreuse bags, 4 muted fuchsia bags.",
"shiny brown bags contain 4 dark maroon bags.",
"bright plum bags contain 3 dull tomato bags, 5 bright tan bags, 4 plaid lime bags.",
"plaid purple bags contain 2 posh black bags.",
"wavy turquoise bags contain 1 wavy white bag, 5 dotted maroon bags.",
"dotted aqua bags contain 4 dotted brown bags, 4 dim plum bags.",
"drab chartreuse bags contain 2 dark olive bags.",
"vibrant black bags contain 5 mirrored black bags, 3 dark chartreuse bags, 2 muted salmon bags, 1 plaid coral bag.",
"posh purple bags contain 1 faded white bag, 5 clear gray bags, 4 clear silver bags.",
"drab coral bags contain 5 dark salmon bags.",
"wavy silver bags contain 5 dotted turquoise bags, 3 dark bronze bags, 1 muted silver bag.",
"plaid silver bags contain 2 plaid tomato bags.",
"dark olive bags contain 5 faded olive bags, 5 dull chartreuse bags, 1 pale gold bag, 3 dull tomato bags.",
"mirrored lime bags contain 3 dull purple bags, 4 light teal bags.",
"bright green bags contain 2 pale tan bags, 5 drab tan bags.",
"posh lavender bags contain 4 posh indigo bags, 5 mirrored brown bags.",
"muted purple bags contain 2 posh chartreuse bags, 3 faded lime bags, 3 dim chartreuse bags, 2 striped fuchsia bags.",
"drab gray bags contain 1 striped indigo bag, 2 dim coral bags.",
"posh olive bags contain 1 dim tomato bag, 4 light gray bags.",
"posh yellow bags contain 2 posh purple bags.",
"clear cyan bags contain 1 dotted lime bag, 4 dark bronze bags, 5 wavy lime bags.",
"clear olive bags contain 2 drab coral bags, 2 bright olive bags, 3 vibrant indigo bags, 1 bright cyan bag.",
"dotted brown bags contain 2 muted tomato bags.",
"dim lime bags contain 1 posh purple bag, 3 pale gold bags, 3 light silver bags, 1 dotted turquoise bag.",
"drab aqua bags contain 4 dim olive bags, 1 light gray bag.",
"wavy beige bags contain 2 striped indigo bags, 4 faded crimson bags, 4 posh coral bags.",
"pale olive bags contain 1 muted blue bag.",
"drab teal bags contain 2 vibrant lime bags, 3 light turquoise bags, 5 bright lavender bags.",
"striped fuchsia bags contain 3 bright teal bags, 5 dim bronze bags, 3 faded cyan bags.",
"dark red bags contain 3 vibrant gold bags, 5 faded bronze bags.",
"posh cyan bags contain 2 light tan bags.",
"light salmon bags contain 2 plaid beige bags, 2 dull chartreuse bags, 1 faded beige bag.",
"clear indigo bags contain 4 plaid olive bags, 1 pale brown bag, 3 shiny fuchsia bags, 4 dotted tomato bags.",
"shiny olive bags contain 5 dotted lavender bags, 5 bright maroon bags, 5 faded maroon bags.",
"muted blue bags contain 1 dull violet bag.",
"bright red bags contain 2 dull bronze bags, 3 pale lime bags, 1 vibrant brown bag, 5 muted magenta bags.",
"pale violet bags contain 4 pale plum bags.",
"muted bronze bags contain 2 mirrored gold bags, 4 plaid crimson bags, 4 light cyan bags.",
"dim gray bags contain 4 dim tomato bags, 5 wavy magenta bags.",
"shiny crimson bags contain 5 muted brown bags.",
"dim indigo bags contain 3 striped beige bags, 3 clear gold bags, 2 bright gray bags.",
"dotted turquoise bags contain 2 striped red bags.",
"striped tan bags contain 3 light yellow bags.",
"muted brown bags contain 3 posh black bags, 3 striped brown bags, 5 light gray bags, 2 clear white bags.",
"clear blue bags contain 2 plaid gold bags, 5 mirrored white bags.",
"wavy purple bags contain 1 wavy magenta bag, 1 muted aqua bag, 3 dim gray bags, 1 dim tomato bag.",
"striped magenta bags contain 2 pale fuchsia bags, 4 light cyan bags, 2 shiny fuchsia bags.",
"dotted teal bags contain 1 mirrored blue bag, 1 posh plum bag, 2 dull violet bags, 4 dotted brown bags.",
"drab lavender bags contain 5 pale yellow bags, 1 clear silver bag.",
"dull beige bags contain 4 clear chartreuse bags, 4 drab gray bags.",
"faded indigo bags contain 1 pale cyan bag.",
"plaid chartreuse bags contain 4 muted aqua bags, 3 dim coral bags, 3 pale gold bags.",
"dull fuchsia bags contain 5 pale maroon bags, 2 mirrored bronze bags.",
"drab white bags contain 4 dull orange bags.",
"dark maroon bags contain 5 dim lavender bags.",
"pale black bags contain 2 wavy silver bags.",
"pale bronze bags contain 4 dim salmon bags, 5 vibrant lavender bags, 4 vibrant crimson bags, 1 bright crimson bag.",
"mirrored cyan bags contain 3 pale lavender bags, 5 dull silver bags.",
"dotted green bags contain 1 bright yellow bag, 5 drab fuchsia bags, 5 posh orange bags, 5 mirrored blue bags.",
"plaid green bags contain 1 wavy tan bag, 2 clear chartreuse bags.",
"drab beige bags contain 3 dotted lime bags, 4 clear brown bags, 2 dotted salmon bags.",
"light turquoise bags contain 3 dotted tomato bags, 1 muted silver bag, 4 striped brown bags.",
"light crimson bags contain 2 dark aqua bags, 4 bright violet bags, 1 mirrored olive bag, 4 mirrored violet bags.",
"wavy maroon bags contain 2 dull teal bags, 2 pale violet bags, 5 bright aqua bags, 2 faded tan bags.",
"dark coral bags contain 5 striped black bags.",
"faded orange bags contain 3 clear silver bags, 2 vibrant tomato bags.",
"dotted olive bags contain 5 clear gray bags, 5 striped indigo bags, 5 dim gray bags, 5 posh plum bags.",
"shiny salmon bags contain 2 wavy fuchsia bags, 4 striped gold bags, 5 wavy coral bags.",
"wavy red bags contain 1 clear silver bag, 5 dotted beige bags, 1 pale cyan bag, 4 dim beige bags.",
"light gray bags contain 3 dim coral bags, 5 striped indigo bags, 2 bright lime bags, 4 vibrant magenta bags.",
"muted chartreuse bags contain 2 dim tomato bags, 5 dim coral bags, 3 pale yellow bags, 5 drab gray bags.",
"pale turquoise bags contain 2 light gray bags, 3 faded salmon bags, 4 drab white bags, 3 plaid olive bags.",
"striped turquoise bags contain 3 pale plum bags.",
"drab cyan bags contain 3 wavy indigo bags, 3 clear white bags.",
"dark magenta bags contain 3 muted blue bags.",
"faded gray bags contain 1 muted green bag, 5 posh coral bags, 3 wavy magenta bags, 4 light beige bags.",
"posh crimson bags contain 1 faded lavender bag.",
"faded green bags contain 4 mirrored red bags, 5 plaid beige bags, 2 shiny maroon bags, 3 mirrored lime bags.",
"mirrored silver bags contain 2 wavy gold bags, 1 clear beige bag.",
"shiny aqua bags contain 1 bright teal bag, 4 wavy tan bags.",
"plaid lime bags contain 2 striped indigo bags.",
"clear beige bags contain 5 dim tomato bags, 2 plaid olive bags, 2 dark crimson bags, 5 dull turquoise bags.",
"striped beige bags contain 2 bright white bags, 1 pale cyan bag, 3 dark bronze bags, 3 vibrant gray bags.",
"dark indigo bags contain 2 striped plum bags.",
"wavy coral bags contain 4 posh cyan bags, 3 muted fuchsia bags.",
"plaid gray bags contain 2 clear maroon bags, 3 wavy beige bags, 3 light lime bags.",
"dim yellow bags contain 2 dotted olive bags, 5 wavy magenta bags, 2 mirrored tomato bags.",
"plaid fuchsia bags contain 3 dotted white bags, 1 dull purple bag.",
"bright violet bags contain 1 shiny lavender bag, 3 dotted tomato bags, 4 dotted white bags, 3 mirrored olive bags.",
"light cyan bags contain 2 posh black bags.",
"shiny orange bags contain 2 dull purple bags, 1 dotted maroon bag, 2 dull indigo bags, 4 drab gold bags.",
"pale purple bags contain 1 dotted magenta bag, 3 drab red bags, 1 posh lime bag, 4 muted turquoise bags.",
"dim brown bags contain 3 dull coral bags, 1 dark tan bag, 1 pale red bag, 3 clear chartreuse bags.",
"shiny maroon bags contain 3 mirrored indigo bags.",
"pale tomato bags contain 2 drab gray bags, 3 shiny lavender bags, 4 clear silver bags.",
"vibrant magenta bags contain no other bags.",
"plaid indigo bags contain 4 dotted black bags, 1 vibrant aqua bag.",
"striped chartreuse bags contain 2 pale orange bags, 5 pale maroon bags, 2 dim lime bags.",
"dim coral bags contain no other bags.",
"mirrored yellow bags contain 4 dotted tan bags, 1 dull blue bag.",
"clear lime bags contain 4 striped violet bags, 3 striped chartreuse bags, 5 drab crimson bags.",
"bright salmon bags contain 2 shiny plum bags, 5 faded white bags.",
"light green bags contain 5 mirrored bronze bags, 4 dull chartreuse bags.",
"vibrant beige bags contain 4 striped brown bags, 4 muted blue bags, 5 shiny crimson bags.",
"plaid tan bags contain 3 pale blue bags, 5 light gray bags, 3 posh tomato bags.",
"dull aqua bags contain 4 muted blue bags.",
"wavy green bags contain 4 drab orange bags, 2 vibrant yellow bags, 5 faded beige bags, 3 dotted turquoise bags.",
"muted yellow bags contain 5 pale magenta bags, 5 striped plum bags.",
"mirrored tomato bags contain 3 pale salmon bags, 4 shiny lavender bags, 1 dark bronze bag, 2 pale blue bags.",
"drab fuchsia bags contain 5 mirrored purple bags.",
"drab olive bags contain 3 wavy violet bags, 3 light tan bags, 4 pale brown bags.",
"faded brown bags contain 2 light crimson bags.",
"vibrant white bags contain 2 pale tomato bags, 4 dotted turquoise bags, 3 pale blue bags.",
"dotted yellow bags contain 3 clear chartreuse bags, 5 drab cyan bags, 5 striped magenta bags.",
"posh coral bags contain 4 light tan bags, 4 pale brown bags.",
"drab gold bags contain 2 light tan bags, 4 clear white bags.",
"mirrored purple bags contain 3 shiny gold bags.",
"posh green bags contain 4 wavy indigo bags, 1 dark crimson bag, 1 muted brown bag, 1 light gray bag.",
"bright maroon bags contain 5 dotted silver bags.",
"dim chartreuse bags contain 4 faded olive bags.",
"bright coral bags contain 2 bright olive bags, 2 light silver bags.",
"striped gold bags contain 1 dotted maroon bag, 4 posh maroon bags, 1 pale gold bag.",
"light chartreuse bags contain 3 plaid blue bags, 4 shiny gold bags, 4 dull teal bags.",
"clear salmon bags contain 5 plaid blue bags, 3 muted cyan bags, 1 mirrored tomato bag.",
"wavy blue bags contain 2 drab turquoise bags, 5 vibrant purple bags, 3 faded indigo bags, 2 bright green bags.",
"dark beige bags contain 4 faded crimson bags, 3 dim silver bags, 4 plaid green bags.",
"bright gold bags contain 1 striped indigo bag, 2 dark salmon bags.",
"posh bronze bags contain 3 dim gray bags.",
"mirrored lavender bags contain 4 striped maroon bags, 5 light blue bags, 2 wavy coral bags, 4 faded crimson bags.",
"pale tan bags contain 3 vibrant beige bags, 1 dark crimson bag, 1 drab brown bag, 1 bright olive bag.",
"mirrored coral bags contain 1 clear white bag, 5 dotted beige bags, 2 dull violet bags.",
"striped white bags contain 3 vibrant gold bags, 1 vibrant crimson bag, 5 muted indigo bags, 4 clear gold bags.",
"plaid white bags contain 3 light gray bags, 5 drab turquoise bags, 5 dark lavender bags.",
"clear brown bags contain 1 striped indigo bag, 1 muted cyan bag, 3 striped tomato bags, 2 bright cyan bags.",
"pale beige bags contain 2 bright fuchsia bags, 2 dotted fuchsia bags, 3 mirrored black bags, 3 dull gold bags.",
"shiny lavender bags contain 5 clear white bags, 3 striped brown bags.",
"posh salmon bags contain 4 mirrored plum bags, 1 dotted purple bag, 1 striped gray bag, 1 bright green bag.",
"posh magenta bags contain 4 dark gray bags, 3 shiny fuchsia bags, 5 dotted tomato bags, 2 posh yellow bags.",
"striped yellow bags contain 2 faded white bags, 1 dotted lavender bag, 2 posh coral bags, 1 light yellow bag.",
"bright tomato bags contain 4 shiny plum bags, 4 dotted olive bags, 4 clear purple bags, 2 dotted plum bags.",
"mirrored turquoise bags contain 2 wavy beige bags, 2 dim gray bags, 5 dark indigo bags.",
"vibrant lavender bags contain 3 pale magenta bags, 2 shiny coral bags, 4 drab white bags, 5 vibrant white bags.",
"faded magenta bags contain 1 plaid lavender bag, 2 drab teal bags, 5 dull beige bags.",
"dark yellow bags contain 1 mirrored gold bag, 2 dark lavender bags, 3 striped indigo bags.",
"posh silver bags contain 1 dull purple bag, 2 plaid olive bags, 3 striped red bags.",
"dull green bags contain 4 striped crimson bags, 5 dim coral bags, 3 vibrant aqua bags.",
"dotted black bags contain 4 posh plum bags, 1 muted blue bag, 4 shiny beige bags, 1 dotted lime bag.",
"light yellow bags contain 5 muted tomato bags, 3 muted fuchsia bags, 5 posh maroon bags.",
"wavy black bags contain 3 bright white bags, 2 bright lavender bags.",
"muted crimson bags contain 1 dark crimson bag, 4 pale salmon bags, 4 striped red bags, 2 dim tomato bags.",
"shiny yellow bags contain 5 posh salmon bags, 3 dotted olive bags.",
"striped olive bags contain 1 light black bag, 1 mirrored olive bag, 1 dull purple bag, 2 light orange bags.",
"light silver bags contain 4 clear silver bags, 4 mirrored black bags, 2 clear gray bags.",
"dull indigo bags contain 2 muted lime bags.",
"muted indigo bags contain 4 posh lime bags, 4 dull white bags.",
"posh red bags contain 2 posh cyan bags, 2 dull brown bags, 5 drab maroon bags.",
"plaid brown bags contain 3 clear silver bags, 5 dim beige bags, 3 dim lime bags, 4 striped blue bags.",
"pale green bags contain 2 shiny bronze bags, 3 mirrored plum bags, 4 light yellow bags.",
"plaid maroon bags contain 5 plaid cyan bags, 1 drab white bag.",
"dim teal bags contain 4 posh maroon bags, 1 dull gold bag, 4 muted coral bags.",
"clear lavender bags contain 5 striped brown bags, 3 posh plum bags.",
"bright yellow bags contain 5 clear tan bags, 2 striped salmon bags.",
"clear fuchsia bags contain 3 clear coral bags, 4 muted aqua bags.",
"muted maroon bags contain 3 dotted fuchsia bags.",
"dark plum bags contain 3 dotted tomato bags, 5 clear violet bags, 3 vibrant magenta bags.",
"bright magenta bags contain 2 plaid tan bags, 4 dotted purple bags, 3 wavy indigo bags.",
"dull plum bags contain 3 muted crimson bags, 4 mirrored green bags.",
"dull black bags contain 3 muted chartreuse bags, 1 posh cyan bag, 4 bright gray bags.",
"posh orange bags contain 5 striped violet bags.",
"vibrant teal bags contain 3 bright red bags, 1 wavy indigo bag, 3 pale brown bags.",
"pale gold bags contain no other bags.",
"faded plum bags contain 2 striped plum bags, 3 wavy maroon bags, 5 vibrant bronze bags, 4 clear green bags.",
"shiny coral bags contain 5 dull white bags, 1 clear tan bag, 3 shiny beige bags.",
"bright lavender bags contain 2 bright lime bags.",
"shiny indigo bags contain 4 dull coral bags, 5 posh coral bags.",
"muted turquoise bags contain 5 drab crimson bags, 4 drab teal bags, 3 vibrant bronze bags.",
"pale plum bags contain 2 dull beige bags, 3 dotted turquoise bags.",
"dull gray bags contain 3 bright salmon bags.",
"vibrant indigo bags contain 2 mirrored bronze bags, 3 light orange bags.",
"light lime bags contain 4 drab coral bags.",
"pale magenta bags contain 3 dark crimson bags.",
"clear aqua bags contain 2 plaid olive bags, 4 muted indigo bags.",
"light gold bags contain 4 vibrant white bags, 5 faded lime bags, 3 striped brown bags, 5 dim coral bags.",
"dull crimson bags contain 3 dim olive bags, 4 dim turquoise bags, 1 muted fuchsia bag.",
"clear gray bags contain 3 clear white bags, 4 dark crimson bags, 4 dotted plum bags, 3 light gray bags.",
"dotted tomato bags contain 5 mirrored blue bags, 3 dotted crimson bags.",
"bright indigo bags contain 3 wavy lime bags, 5 dark bronze bags, 4 shiny brown bags.",
"light lavender bags contain 1 dim fuchsia bag.",
"clear purple bags contain 4 dark red bags, 3 clear turquoise bags.",
"dark lavender bags contain 5 vibrant crimson bags, 1 vibrant white bag, 3 dull purple bags, 1 plaid tan bag.",
"vibrant green bags contain 2 wavy teal bags, 2 dull orange bags, 5 plaid coral bags, 2 striped yellow bags.",
"faded maroon bags contain 1 muted tomato bag, 3 pale gold bags, 2 muted fuchsia bags.",
"light tomato bags contain 3 shiny fuchsia bags, 4 dull turquoise bags.",
"light olive bags contain 4 dotted indigo bags, 3 pale coral bags.",
"faded blue bags contain 2 light gray bags, 3 muted brown bags, 5 dim coral bags, 1 light tan bag.",
"mirrored white bags contain 1 posh cyan bag.",
"dull bronze bags contain 5 clear lavender bags, 4 bright olive bags, 4 dull brown bags, 2 striped black bags.",
"vibrant coral bags contain 2 dim coral bags, 2 faded blue bags, 2 drab cyan bags.",
"bright lime bags contain no other bags.",
"wavy crimson bags contain 1 dim indigo bag.",
"vibrant blue bags contain 2 posh gold bags, 3 mirrored tan bags, 3 muted green bags, 5 faded beige bags.",
"light orange bags contain 5 posh black bags, 2 dull brown bags.",
"striped indigo bags contain no other bags.",
"faded lime bags contain 2 dull violet bags, 2 shiny lavender bags.",
"dim bronze bags contain 4 mirrored blue bags.",
"pale coral bags contain 2 clear magenta bags, 4 clear gold bags.",
"wavy fuchsia bags contain 3 muted olive bags, 1 dull violet bag.",
"mirrored indigo bags contain 1 clear magenta bag, 3 mirrored beige bags, 3 bright violet bags.",
"plaid turquoise bags contain 2 muted turquoise bags.",
"dull blue bags contain 2 dotted white bags, 5 mirrored green bags.",
"posh white bags contain 2 pale teal bags, 4 pale green bags, 5 dim bronze bags, 5 mirrored cyan bags.",
"mirrored teal bags contain 2 plaid blue bags, 1 drab crimson bag.",
"clear silver bags contain 5 striped indigo bags, 2 dim plum bags, 5 muted aqua bags, 5 light tan bags.",
"dull lime bags contain 2 plaid crimson bags, 5 light cyan bags, 1 dotted crimson bag.",
"dull yellow bags contain 3 plaid aqua bags, 2 dim red bags.",
"mirrored olive bags contain 4 faded blue bags, 2 posh purple bags, 1 striped brown bag.",
"vibrant fuchsia bags contain 2 light black bags, 2 vibrant salmon bags.",
"mirrored black bags contain 4 posh cyan bags, 1 wavy indigo bag.",
"pale yellow bags contain 2 faded blue bags, 5 muted fuchsia bags, 2 striped brown bags.",
"pale fuchsia bags contain 1 drab silver bag, 2 clear silver bags, 2 shiny lavender bags.",
"drab turquoise bags contain 5 drab cyan bags, 5 plaid cyan bags, 3 wavy tan bags.",
"vibrant red bags contain 4 mirrored beige bags, 2 wavy magenta bags, 1 light cyan bag.",
"striped red bags contain no other bags.",
"vibrant brown bags contain 1 dotted tomato bag, 3 vibrant magenta bags, 2 striped beige bags, 4 dull brown bags.",
"faded chartreuse bags contain 4 light gray bags, 5 striped salmon bags, 5 dark salmon bags, 3 dull orange bags.",
"mirrored tan bags contain 4 clear chartreuse bags.",
"light tan bags contain no other bags.",
"dim blue bags contain 2 dull white bags.",
"posh tomato bags contain 3 dull indigo bags, 2 striped red bags.",
"bright blue bags contain 3 shiny crimson bags, 4 muted brown bags, 3 dotted magenta bags, 2 pale salmon bags.",
"faded gold bags contain 3 clear white bags, 2 dotted turquoise bags, 5 light orange bags.",
"plaid orange bags contain 1 clear black bag, 3 striped red bags, 4 dark turquoise bags, 4 dull coral bags.",
"shiny tan bags contain 3 dotted coral bags, 3 posh orange bags, 5 vibrant tan bags.",
"clear plum bags contain 5 dim beige bags, 1 pale gray bag, 1 clear purple bag, 5 posh coral bags.",
"bright turquoise bags contain 2 plaid orange bags.",
"dotted plum bags contain 5 faded olive bags, 5 clear white bags.",
"shiny green bags contain 4 drab maroon bags, 2 drab purple bags.",
"plaid tomato bags contain 1 vibrant tomato bag, 2 posh coral bags, 3 faded beige bags, 2 faded chartreuse bags.",
"wavy lime bags contain 4 striped olive bags, 1 vibrant beige bag.",
"striped brown bags contain 4 drab gray bags, 2 clear white bags, 3 bright lime bags, 3 vibrant magenta bags.",
"dark orange bags contain 1 wavy silver bag, 5 muted magenta bags, 1 dim yellow bag, 1 vibrant purple bag.",
"dotted magenta bags contain 1 mirrored purple bag.",
"bright black bags contain 5 shiny aqua bags.",
"clear green bags contain 4 vibrant gold bags, 4 pale gold bags.",
"drab indigo bags contain 1 bright coral bag, 5 plaid tomato bags, 3 muted chartreuse bags.",
"shiny fuchsia bags contain 5 dim lavender bags, 2 light teal bags, 4 dim lime bags, 3 wavy purple bags.",
"vibrant crimson bags contain 1 dim lavender bag, 5 dark tan bags, 1 dotted turquoise bag, 2 striped red bags.",
"clear red bags contain 5 wavy magenta bags, 2 bright plum bags.",
"dotted red bags contain 3 pale cyan bags.",
"striped black bags contain 3 pale red bags, 1 clear beige bag, 3 dull coral bags.",
"plaid crimson bags contain 4 wavy violet bags, 1 clear gray bag.",
"muted silver bags contain 1 muted chartreuse bag, 2 shiny bronze bags, 1 striped brown bag, 1 posh coral bag.",
"drab green bags contain 1 faded white bag, 5 posh orange bags, 2 dim magenta bags, 3 wavy purple bags.",
"vibrant olive bags contain 5 dark yellow bags, 1 pale black bag, 1 drab olive bag, 5 shiny gold bags.",
"bright cyan bags contain 2 dim tomato bags, 2 plaid brown bags, 1 bright plum bag, 5 drab lavender bags.",
"dotted blue bags contain 2 pale tan bags, 1 striped green bag, 2 striped lime bags, 3 shiny tomato bags.",
"faded yellow bags contain 3 posh maroon bags, 1 dull tomato bag, 2 pale cyan bags.",
"dark black bags contain 3 shiny purple bags, 2 clear violet bags, 5 wavy brown bags.",
"vibrant bronze bags contain 5 pale salmon bags.",
"wavy chartreuse bags contain 1 posh turquoise bag, 1 vibrant silver bag, 3 plaid teal bags, 1 dotted salmon bag.",
"faded black bags contain 1 light tan bag, 1 faded beige bag.",
"dim beige bags contain 3 muted fuchsia bags, 5 striped plum bags, 1 faded violet bag, 5 clear chartreuse bags.",
"striped plum bags contain 1 posh black bag, 2 plaid lime bags, 4 clear white bags.",
"dotted silver bags contain 2 vibrant gray bags, 5 clear white bags, 2 vibrant tomato bags.",
"dull salmon bags contain 4 pale plum bags, 2 pale magenta bags, 1 light gray bag.",
"pale maroon bags contain 3 vibrant white bags.",
"light blue bags contain 3 mirrored maroon bags.",
"striped aqua bags contain 5 dark purple bags, 1 striped green bag, 4 mirrored coral bags.",
"mirrored beige bags contain 1 shiny fuchsia bag, 1 dim plum bag.",
"pale aqua bags contain 5 mirrored green bags.",
"dim red bags contain 2 mirrored maroon bags, 4 dotted yellow bags, 5 dim tomato bags, 4 faded silver bags.",
"light bronze bags contain 1 dim orange bag, 1 posh tomato bag, 5 mirrored white bags.",
"plaid coral bags contain 5 vibrant tomato bags, 5 pale bronze bags, 3 dotted turquoise bags, 2 drab brown bags.",
"dull violet bags contain 2 muted chartreuse bags.",
"wavy teal bags contain 3 shiny plum bags, 5 dark lavender bags.",
"wavy cyan bags contain 5 faded red bags, 4 light bronze bags, 5 shiny bronze bags, 4 dull silver bags.",
"faded olive bags contain 4 wavy magenta bags, 1 striped red bag.",
"drab tomato bags contain 5 plaid cyan bags, 1 plaid chartreuse bag, 1 dim tomato bag.",
"clear chartreuse bags contain 4 striped brown bags, 2 plaid lime bags.",
"dull olive bags contain 1 dull purple bag, 2 plaid yellow bags.",
"dim silver bags contain 3 pale tomato bags, 1 plaid chartreuse bag.",
"dotted coral bags contain 5 pale salmon bags, 4 dim coral bags, 4 striped fuchsia bags, 2 dim turquoise bags.",
"bright fuchsia bags contain 4 light gold bags, 3 shiny crimson bags, 3 clear white bags.",
"bright brown bags contain 1 vibrant tomato bag, 2 wavy teal bags, 3 dotted red bags.",
"striped cyan bags contain 3 bright lime bags.",
"clear turquoise bags contain 5 mirrored maroon bags.",
"posh brown bags contain 5 vibrant silver bags, 4 bright lime bags.",
"wavy aqua bags contain 4 wavy indigo bags, 1 faded crimson bag, 4 drab indigo bags.",
"pale chartreuse bags contain 2 faded salmon bags.",
"clear gold bags contain 2 faded turquoise bags, 1 shiny magenta bag.",
"muted beige bags contain 5 mirrored indigo bags, 1 clear violet bag.",
"light white bags contain 1 vibrant magenta bag.",
"muted cyan bags contain 2 plaid white bags, 5 mirrored black bags, 4 pale gold bags, 5 drab magenta bags.",
"muted teal bags contain 1 pale orange bag.",
"vibrant cyan bags contain 2 dotted magenta bags, 1 clear tan bag.",
"wavy white bags contain 1 faded blue bag.",
"striped silver bags contain 5 light crimson bags, 4 clear salmon bags, 1 shiny green bag.",
"shiny teal bags contain 1 wavy coral bag.",
"dim black bags contain 3 vibrant silver bags, 1 clear maroon bag, 4 bright chartreuse bags.",
"dim plum bags contain 2 posh coral bags, 3 dark crimson bags, 1 drab olive bag.",
"wavy bronze bags contain 2 faded olive bags, 2 dim red bags, 2 pale brown bags.",
"dim turquoise bags contain 3 dull teal bags, 5 shiny bronze bags, 2 striped orange bags, 1 dim fuchsia bag.",
"posh lime bags contain 4 muted tomato bags, 3 muted brown bags, 1 bright olive bag.",
"shiny cyan bags contain 3 faded purple bags, 5 wavy chartreuse bags, 4 shiny maroon bags.",
"pale blue bags contain 2 striped turquoise bags, 2 dull turquoise bags.",
"muted black bags contain 4 pale turquoise bags, 4 pale beige bags, 4 mirrored black bags.",
"posh gold bags contain 1 light brown bag, 4 posh yellow bags, 5 dim violet bags.",
"plaid olive bags contain no other bags.",
"dotted beige bags contain 4 clear tan bags, 1 shiny fuchsia bag, 3 posh green bags, 4 wavy purple bags.",
"dull magenta bags contain 3 muted lime bags, 5 mirrored blue bags.",
"striped green bags contain 5 light cyan bags.",
"dark white bags contain 2 wavy yellow bags, 5 dim salmon bags, 2 bright green bags.",
"muted lavender bags contain 3 dotted teal bags, 5 dotted bronze bags, 2 mirrored lime bags, 5 dim fuchsia bags.",
"dotted indigo bags contain 5 drab chartreuse bags, 1 dim lime bag, 3 plaid white bags, 2 shiny plum bags.",
"light indigo bags contain 5 bright tan bags.",
"faded turquoise bags contain 3 faded cyan bags, 4 dull salmon bags, 3 dark bronze bags.",
"mirrored magenta bags contain 1 clear turquoise bag, 4 wavy plum bags.",
"dull brown bags contain 5 dim tomato bags.",
"plaid aqua bags contain 4 bright teal bags, 3 dim gray bags, 3 clear crimson bags, 5 clear chartreuse bags.",
"drab red bags contain 2 plaid purple bags, 3 muted silver bags.",
"wavy plum bags contain 3 wavy indigo bags, 3 posh cyan bags.",
"bright aqua bags contain 1 dim magenta bag.",
"dotted violet bags contain 4 light orange bags.",
"wavy salmon bags contain 3 wavy turquoise bags, 1 dark lavender bag, 3 striped silver bags, 3 posh coral bags.",
"posh beige bags contain 1 pale black bag.",
"clear bronze bags contain 4 clear teal bags, 3 dim crimson bags.",
"pale teal bags contain 1 dark bronze bag, 4 plaid maroon bags, 4 light magenta bags.",
"mirrored violet bags contain 2 clear beige bags.",
"drab blue bags contain 1 faded yellow bag.",
"light violet bags contain 4 plaid aqua bags.",
"vibrant chartreuse bags contain 1 mirrored beige bag.",
"pale salmon bags contain 5 drab gray bags, 3 muted brown bags, 2 dotted plum bags.",
"plaid violet bags contain 5 muted blue bags, 4 wavy black bags.",
"bright tan bags contain 1 bright white bag, 4 posh cyan bags.",
"vibrant purple bags contain 2 dark plum bags, 4 bright brown bags.",
"drab tan bags contain 5 dull orange bags, 4 plaid fuchsia bags.",
"dotted tan bags contain 2 drab violet bags, 1 light turquoise bag, 2 clear indigo bags.",
"vibrant maroon bags contain 1 drab silver bag, 1 plaid plum bag.",
"dull white bags contain 2 dotted crimson bags, 1 light orange bag, 2 dark lavender bags, 5 plaid blue bags.",
"wavy orange bags contain 1 shiny fuchsia bag, 2 clear lavender bags.",
"faded fuchsia bags contain 2 dim purple bags, 4 muted yellow bags, 3 muted brown bags.",
"dim tan bags contain 1 shiny purple bag, 5 wavy magenta bags, 4 faded beige bags, 2 vibrant lime bags.",
"bright white bags contain 1 dim plum bag, 1 light gray bag, 2 muted fuchsia bags.",
"pale lavender bags contain 2 faded lime bags, 1 faded tan bag, 3 dotted maroon bags.",
"dim fuchsia bags contain 2 clear lavender bags, 5 dotted red bags, 3 vibrant chartreuse bags.",
"pale silver bags contain 5 posh black bags.",
"faded salmon bags contain 4 light white bags, 2 plaid brown bags, 3 vibrant yellow bags.",
"faded bronze bags contain 5 mirrored white bags, 5 striped plum bags, 4 dim magenta bags, 2 faded lime bags.",
"shiny gray bags contain 1 striped salmon bag, 3 clear crimson bags.",
"drab lime bags contain 5 light crimson bags.",
"bright orange bags contain 4 plaid tomato bags, 1 mirrored bronze bag.",
"dark crimson bags contain 5 striped red bags.",
"dull teal bags contain 4 wavy indigo bags, 1 drab brown bag, 3 light cyan bags, 4 dotted gold bags.",
"light maroon bags contain 2 bright violet bags, 2 dim gray bags, 3 shiny turquoise bags.",
"faded coral bags contain 4 dark teal bags.",
"shiny bronze bags contain 3 pale salmon bags, 3 pale plum bags.",
"dim violet bags contain 3 vibrant magenta bags, 4 shiny bronze bags.",
"pale red bags contain 5 drab silver bags.",
"dark tomato bags contain 4 shiny lime bags, 5 wavy purple bags, 4 shiny blue bags, 5 drab gold bags.",
"dull gold bags contain 5 light olive bags, 1 light gray bag.",
"posh tan bags contain 4 dull gold bags, 3 vibrant turquoise bags, 2 plaid aqua bags, 5 dim indigo bags.",
"bright gray bags contain 5 pale yellow bags.",
"plaid salmon bags contain 3 shiny indigo bags.",
"dotted bronze bags contain 5 mirrored black bags, 3 muted indigo bags, 3 faded yellow bags, 3 bright teal bags.",
"mirrored crimson bags contain 2 pale salmon bags, 1 plaid maroon bag.",
"wavy brown bags contain 1 drab turquoise bag, 3 posh yellow bags.",
"muted coral bags contain 4 clear blue bags, 5 dark cyan bags.",
"wavy yellow bags contain 2 drab brown bags, 2 striped olive bags, 1 wavy white bag.",
"muted aqua bags contain 2 light tan bags, 2 pale yellow bags, 5 plaid lime bags.",
"drab crimson bags contain 5 plaid cyan bags, 3 dim plum bags.",
"vibrant yellow bags contain 2 faded maroon bags, 4 mirrored olive bags, 2 plaid red bags.",
"faded silver bags contain 4 dim lime bags, 4 dark tomato bags, 5 muted magenta bags, 1 dotted red bag.",
"drab violet bags contain 2 vibrant aqua bags.",
"faded teal bags contain 2 light gold bags, 5 striped turquoise bags, 2 dim salmon bags, 2 posh tomato bags.",
"wavy magenta bags contain 4 faded blue bags, 1 muted brown bag, 3 pale brown bags.",
"vibrant salmon bags contain 2 posh turquoise bags, 1 dark crimson bag.",
"bright olive bags contain 4 light teal bags, 2 vibrant lime bags, 3 dull salmon bags, 2 dull tomato bags.",
"plaid teal bags contain 5 striped teal bags.",
"dark cyan bags contain 3 dull brown bags, 4 posh violet bags.",
"muted olive bags contain 1 faded blue bag, 5 dotted brown bags.",
"dark violet bags contain 3 mirrored beige bags.",
"drab orange bags contain 4 faded aqua bags, 1 striped red bag, 5 mirrored maroon bags.",
"wavy gray bags contain 4 mirrored green bags.",
"faded white bags contain 3 dim lavender bags, 3 clear silver bags.",
"faded lavender bags contain 2 posh violet bags, 4 striped violet bags, 2 clear silver bags, 2 faded cyan bags.",
"light red bags contain 2 bright white bags, 1 dull gray bag, 3 bright lavender bags.",
"bright beige bags contain 3 mirrored silver bags.",
"shiny magenta bags contain 1 light silver bag.",
"striped teal bags contain 1 plaid lime bag, 2 clear tomato bags, 1 clear chartreuse bag.",
"dim olive bags contain 5 pale white bags, 5 wavy black bags, 4 faded magenta bags, 4 dark red bags.",
"dull tan bags contain 3 dark lavender bags, 5 faded violet bags.",
"striped purple bags contain 5 wavy violet bags, 5 light gold bags.",
"dim crimson bags contain 5 striped magenta bags.",
"faded beige bags contain 2 striped brown bags, 3 dark salmon bags.",
"light purple bags contain 2 bright lavender bags, 5 vibrant lime bags, 3 striped blue bags.",
"mirrored blue bags contain 2 clear white bags, 2 drab cyan bags, 5 light cyan bags.",
"dull silver bags contain 1 shiny bronze bag, 1 dotted beige bag.",
"pale crimson bags contain 2 shiny turquoise bags.",
"wavy indigo bags contain 5 clear white bags, 5 plaid cyan bags, 1 muted brown bag, 1 pale yellow bag.",
"bright chartreuse bags contain 3 posh crimson bags, 5 shiny maroon bags.",
"vibrant silver bags contain 3 striped aqua bags, 5 striped gold bags, 2 dim lime bags, 4 clear chartreuse bags.",
"dark purple bags contain 4 plaid lavender bags, 3 clear chartreuse bags, 4 striped teal bags.",
"vibrant turquoise bags contain 1 light gold bag, 1 light turquoise bag, 4 muted indigo bags, 2 wavy magenta bags.",
"vibrant tan bags contain 1 dull purple bag, 5 vibrant beige bags.",
"dim salmon bags contain 1 striped violet bag, 5 light teal bags, 5 light tan bags, 5 striped brown bags.",
"muted violet bags contain 5 bright brown bags, 5 faded aqua bags, 3 clear purple bags, 4 plaid lavender bags.",
"mirrored gray bags contain 4 drab maroon bags, 3 posh violet bags.",
"striped blue bags contain 2 plaid cyan bags, 5 pale gold bags.",
"vibrant gray bags contain 4 pale magenta bags, 4 vibrant bronze bags, 3 drab silver bags, 4 posh tomato bags.",
"faded tan bags contain 4 plaid olive bags.",
"muted green bags contain 2 posh cyan bags, 1 plaid lime bag, 5 muted crimson bags.",
"shiny tomato bags contain 3 wavy violet bags, 4 posh coral bags, 3 striped red bags.",
"muted plum bags contain 2 plaid salmon bags.",
"pale indigo bags contain 3 pale cyan bags, 5 vibrant lime bags, 5 vibrant tomato bags.",
"mirrored fuchsia bags contain 4 posh gray bags, 3 muted tan bags, 4 dim blue bags.",
"dark lime bags contain 3 clear black bags, 3 dark tomato bags, 2 mirrored black bags.",
"muted white bags contain 3 shiny black bags, 5 dark purple bags, 3 vibrant silver bags.",
"striped gray bags contain 5 dark salmon bags.",
"dotted fuchsia bags contain 1 mirrored red bag, 3 dotted lavender bags.",
"posh maroon bags contain 1 mirrored beige bag.",
"vibrant plum bags contain 3 clear red bags.",
"posh turquoise bags contain 2 shiny magenta bags.",
"light black bags contain 4 light orange bags, 1 dark salmon bag, 4 striped plum bags.",
"clear yellow bags contain 1 posh aqua bag.",
"dim purple bags contain 2 striped green bags.",
"muted tan bags contain 4 mirrored gray bags, 1 dotted violet bag.",
"drab silver bags contain 5 clear chartreuse bags, 1 drab olive bag, 2 posh coral bags, 5 bright lime bags.",
"plaid bronze bags contain 3 wavy black bags, 4 wavy orange bags, 3 dim tomato bags, 3 muted teal bags.",
"dark green bags contain 5 dull red bags, 3 bright crimson bags, 5 shiny salmon bags, 1 muted purple bag.",
"bright silver bags contain 1 striped cyan bag.",
"striped lime bags contain 2 dim magenta bags, 5 faded chartreuse bags, 2 clear indigo bags.",
"dotted gold bags contain 2 light cyan bags.",
"drab black bags contain 5 faded red bags, 5 plaid orange bags.",
"dim magenta bags contain 5 dull coral bags.",
"light plum bags contain 4 light yellow bags, 5 shiny bronze bags, 5 posh purple bags, 5 plaid olive bags.",
"dotted cyan bags contain 5 light salmon bags, 4 dull tomato bags, 3 clear blue bags.",
"posh blue bags contain 4 muted brown bags, 2 muted aqua bags.",
"posh gray bags contain 4 pale green bags, 2 faded chartreuse bags, 2 drab blue bags.",
"clear tan bags contain 4 clear gray bags.",
"mirrored salmon bags contain 1 dull tan bag, 4 mirrored plum bags, 5 muted tan bags, 3 plaid blue bags.",
"light brown bags contain 1 dim chartreuse bag.",
"dull lavender bags contain 1 drab white bag, 5 dull indigo bags.",
"striped violet bags contain 5 muted brown bags, 3 plaid cyan bags, 2 light gray bags.",
"clear crimson bags contain 1 drab teal bag, 5 dark tan bags, 1 pale salmon bag, 4 dull turquoise bags.",
"dim white bags contain 3 bright olive bags.",
"dim green bags contain 4 light silver bags, 1 wavy green bag, 1 striped gold bag.",
"dull maroon bags contain 4 wavy magenta bags.",
"striped lavender bags contain 5 faded white bags, 4 mirrored tomato bags, 5 mirrored crimson bags.",
"faded tomato bags contain 4 pale gray bags.",
"pale cyan bags contain 1 dull beige bag, 4 light white bags, 5 clear tan bags.",
"wavy tomato bags contain 5 dotted silver bags, 5 faded gray bags, 1 striped teal bag.",
"dim tomato bags contain 4 bright lime bags, 3 dim lavender bags, 3 muted tomato bags, 4 dark crimson bags.",
"striped tomato bags contain 3 plaid chartreuse bags, 4 light cyan bags.",
"plaid gold bags contain 1 dark yellow bag.",
"dark silver bags contain 2 dull blue bags, 2 bright purple bags, 5 dim tomato bags.",
"dotted purple bags contain 4 striped blue bags.",
"dark fuchsia bags contain 2 light cyan bags.",
"dotted salmon bags contain 3 drab teal bags, 5 dotted teal bags, 4 vibrant white bags.",
"mirrored gold bags contain 2 striped salmon bags, 5 pale fuchsia bags, 3 dull purple bags.",
"posh violet bags contain 1 dim salmon bag, 5 clear gold bags, 1 bright salmon bag.",
"shiny beige bags contain 2 muted brown bags, 4 shiny gold bags, 5 wavy indigo bags.",
"plaid cyan bags contain 5 muted tomato bags, 4 drab gray bags, 2 dark crimson bags, 1 striped brown bag.",
"vibrant lime bags contain 5 dull magenta bags.",
"clear black bags contain 3 wavy lavender bags.",
"light coral bags contain 2 pale salmon bags, 1 striped brown bag, 5 mirrored plum bags, 1 drab gold bag.",
"faded aqua bags contain 2 pale blue bags, 4 drab lavender bags.",
"wavy gold bags contain 1 dotted plum bag.",
"shiny turquoise bags contain 4 dull gray bags, 2 dim orange bags.",
"dull purple bags contain 1 shiny gold bag, 3 plaid olive bags.",
"dull coral bags contain 1 faded tan bag, 4 clear chartreuse bags, 3 shiny crimson bags, 4 plaid lavender bags.",
"dull red bags contain 5 dotted beige bags, 4 striped tomato bags, 1 shiny yellow bag.",
"bright bronze bags contain 2 wavy black bags, 5 mirrored bronze bags.",
"faded violet bags contain 3 pale yellow bags, 5 posh cyan bags, 5 wavy purple bags, 5 vibrant magenta bags.",
"shiny blue bags contain 1 dotted teal bag, 4 wavy purple bags, 2 striped brown bags, 3 bright lavender bags.",
"striped salmon bags contain 2 light tan bags, 4 striped red bags, 1 striped indigo bag, 1 pale gold bag.",
"shiny silver bags contain 4 faded silver bags, 4 clear maroon bags.",
"faded crimson bags contain 1 faded bronze bag, 5 dull brown bags, 5 posh plum bags, 3 shiny plum bags.",
"vibrant tomato bags contain 3 plaid cyan bags, 5 drab teal bags, 5 dotted crimson bags, 5 light tan bags.",
"plaid red bags contain 2 vibrant gray bags, 5 shiny bronze bags, 5 dull black bags, 2 light yellow bags.",
"muted red bags contain 2 clear indigo bags, 4 dotted lime bags, 3 dim gray bags, 1 mirrored lime bag.",
"mirrored chartreuse bags contain 2 dull black bags, 1 dark white bag.",
"dim gold bags contain 3 plaid blue bags, 2 dotted purple bags.",
"pale white bags contain 3 pale yellow bags, 1 bright tan bag, 4 striped orange bags, 4 light yellow bags.",
"light magenta bags contain 3 light black bags, 4 muted turquoise bags.",
"shiny lime bags contain 1 drab cyan bag.",
"light teal bags contain 3 dim plum bags, 1 posh black bag, 3 dull beige bags.",
"plaid black bags contain 4 faded silver bags, 2 faded magenta bags.",
"clear orange bags contain 1 posh orange bag, 4 bright orange bags, 5 clear indigo bags.",
"clear coral bags contain 3 faded crimson bags, 1 dull silver bag.",
"muted lime bags contain 2 dim plum bags.",
"shiny purple bags contain 5 faded aqua bags.",
"vibrant gold bags contain 5 drab lavender bags, 4 striped red bags.",
"clear white bags contain no other bags.",
"posh aqua bags contain 2 light blue bags, 1 posh turquoise bag, 4 faded teal bags, 3 dotted purple bags.",
"posh black bags contain no other bags.",
"mirrored maroon bags contain 4 plaid blue bags, 3 dotted maroon bags, 5 striped plum bags.",
"dotted crimson bags contain 5 striped salmon bags, 1 pale brown bag, 1 posh black bag, 5 bright lime bags.",
"striped orange bags contain 4 faded olive bags.",
"posh teal bags contain 2 faded lavender bags, 3 dim indigo bags.",
"striped bronze bags contain 2 bright lavender bags, 2 plaid olive bags, 3 vibrant brown bags, 5 pale maroon bags.",
"dull orange bags contain 3 dark crimson bags, 5 pale salmon bags, 4 vibrant gray bags, 4 plaid olive bags.",
"clear maroon bags contain 2 wavy gray bags, 2 clear blue bags.",
"clear tomato bags contain 1 drab olive bag, 2 muted brown bags.",
"dark aqua bags contain 3 striped white bags.",
"dull chartreuse bags contain 3 faded tan bags, 3 light orange bags, 2 clear chartreuse bags.",
"dim cyan bags contain 1 shiny green bag, 4 vibrant brown bags, 4 faded yellow bags, 1 striped aqua bag.",
"pale orange bags contain 3 drab indigo bags, 4 plaid green bags, 2 wavy lavender bags.",
"dull cyan bags contain 5 mirrored turquoise bags, 3 posh indigo bags, 5 drab tomato bags, 3 bright aqua bags.",
"drab brown bags contain 2 clear tan bags, 1 faded yellow bag, 4 vibrant coral bags, 3 mirrored blue bags.",
"plaid blue bags contain 1 light teal bag, 1 faded tan bag.",
"dotted orange bags contain 5 dull fuchsia bags, 3 muted brown bags.",
"muted salmon bags contain 2 wavy coral bags.",
"pale brown bags contain 4 light tan bags, 3 dim coral bags, 2 plaid olive bags, 4 striped brown bags.",
"wavy tan bags contain 4 mirrored blue bags, 1 posh purple bag.",
"mirrored plum bags contain 4 plaid tan bags, 3 wavy yellow bags, 4 vibrant magenta bags, 3 pale lavender bags.",
"bright purple bags contain 4 dark red bags, 5 clear white bags.",
"shiny chartreuse bags contain 4 posh plum bags.",
"shiny violet bags contain 4 mirrored indigo bags, 1 faded beige bag.",
"drab maroon bags contain 5 posh cyan bags.",
"dim lavender bags contain 2 vibrant magenta bags, 4 posh black bags, 5 bright lime bags, 3 light tan bags.",
"shiny gold bags contain 2 muted fuchsia bags, 3 clear silver bags.",
"wavy violet bags contain 2 vibrant magenta bags, 5 striped red bags, 4 plaid lime bags, 2 bright lime bags.",
"light beige bags contain 3 pale tan bags.",
"dotted lavender bags contain 5 dim plum bags, 1 dull magenta bag.",
"clear teal bags contain 2 plaid yellow bags, 4 light blue bags, 4 striped maroon bags, 1 vibrant olive bag.",
"faded purple bags contain 2 clear olive bags, 4 mirrored teal bags, 2 plaid gold bags.",
"pale lime bags contain 5 drab yellow bags, 4 bright coral bags.",
"plaid beige bags contain 2 faded violet bags, 5 plaid tan bags.",
"wavy lavender bags contain 5 striped brown bags.",
"dull tomato bags contain 4 faded olive bags.",
"plaid plum bags contain 4 faded cyan bags, 2 clear olive bags.",
"dark gray bags contain 2 dark red bags, 3 clear indigo bags, 5 dim tomato bags.",
"plaid lavender bags contain 5 plaid green bags, 1 shiny tomato bag.",
"dim aqua bags contain 5 clear silver bags.",
"dark salmon bags contain 1 drab olive bag, 5 posh coral bags.",
"vibrant violet bags contain 3 dim plum bags, 3 dim turquoise bags, 3 striped orange bags.",
"mirrored red bags contain 3 dull gray bags, 5 mirrored violet bags, 3 vibrant coral bags.",
"mirrored brown bags contain 3 vibrant tomato bags, 1 wavy lavender bag.",
"mirrored bronze bags contain 1 striped orange bag, 1 drab gray bag.",
"dotted lime bags contain 5 drab cyan bags, 3 dotted maroon bags, 2 vibrant white bags, 5 plaid crimson bags.",
"dotted chartreuse bags contain 5 bright maroon bags.",
"clear violet bags contain 5 striped orange bags, 2 muted lime bags, 4 vibrant bronze bags, 2 drab silver bags.",
"plaid magenta bags contain 2 bright blue bags, 2 shiny chartreuse bags.",
"mirrored orange bags contain 1 striped yellow bag, 1 drab gold bag, 5 striped beige bags, 4 pale brown bags.",
"drab salmon bags contain 5 clear yellow bags, 1 dark beige bag.",
"drab magenta bags contain 4 dull gray bags, 4 faded tan bags.",
"dim maroon bags contain 4 striped teal bags, 5 striped black bags, 2 drab indigo bags, 4 vibrant beige bags.",
"wavy olive bags contain 5 faded chartreuse bags, 2 dotted lavender bags, 3 wavy brown bags, 3 dim turquoise bags.",
"light aqua bags contain 3 dark violet bags, 3 posh tomato bags.",
"dark chartreuse bags contain 3 light plum bags, 4 vibrant chartreuse bags, 3 dotted purple bags, 1 light turquoise bag.",
"shiny red bags contain 4 dotted maroon bags, 3 dull coral bags, 3 dim coral bags.",
"dark gold bags contain 3 dim chartreuse bags.",
"dark turquoise bags contain 4 dark olive bags.",
"plaid yellow bags contain 1 dark salmon bag, 3 drab olive bags, 4 posh fuchsia bags, 3 mirrored teal bags.",
"muted tomato bags contain 1 vibrant magenta bag, 2 light cyan bags.",
"dark brown bags contain 4 muted magenta bags, 3 light turquoise bags, 5 dim silver bags.",
"dark bronze bags contain 2 striped red bags, 4 vibrant coral bags.",
"posh fuchsia bags contain 2 faded tan bags.",
"dark teal bags contain 5 dark salmon bags, 1 faded violet bag, 2 drab olive bags, 4 dim plum bags.",
"drab yellow bags contain 4 plaid tan bags, 1 dull white bag, 3 dull violet bags.",
"dotted gray bags contain 2 vibrant lavender bags, 1 striped aqua bag, 5 drab violet bags, 1 light red bag.",
"drab purple bags contain 5 posh orange bags.",
"striped crimson bags contain 3 striped salmon bags, 1 posh plum bag, 1 pale orange bag, 5 posh indigo bags.",
"muted orange bags contain 4 muted silver bags, 4 dotted plum bags, 5 shiny blue bags.",
"muted gray bags contain 2 muted salmon bags, 3 bright bronze bags, 5 bright brown bags.",
"dull turquoise bags contain 2 plaid olive bags, 5 striped turquoise bags, 5 muted brown bags, 1 vibrant magenta bag.",
"dotted maroon bags contain 2 dim salmon bags, 5 clear white bags, 4 wavy black bags.",
"striped coral bags contain 2 shiny violet bags, 5 plaid maroon bags, 3 bright tan bags, 4 mirrored chartreuse bags.",
"dark tan bags contain 4 faded white bags.",
"posh plum bags contain 5 pale brown bags, 3 muted brown bags, 4 posh cyan bags, 1 light turquoise bag.",
"shiny plum bags contain 4 dull turquoise bags, 1 shiny gold bag.",
"posh indigo bags contain 1 bright brown bag, 2 dull silver bags.",
"muted fuchsia bags contain 5 plaid olive bags.",
"drab bronze bags contain 3 drab coral bags, 3 dull chartreuse bags, 2 posh turquoise bags.",
"shiny white bags contain 5 dark tan bags, 5 shiny magenta bags.",
"mirrored green bags contain 5 light maroon bags, 1 light gold bag.",
"mirrored aqua bags contain 1 striped chartreuse bag, 4 faded coral bags, 1 muted silver bag.",
"vibrant orange bags contain 3 plaid tan bags.",
"shiny black bags contain 1 mirrored gray bag, 1 posh fuchsia bag, 3 muted salmon bags, 4 dotted crimson bags.",
"dark blue bags contain 1 shiny tomato bag, 5 posh beige bags.",
"bright crimson bags contain 1 striped green bag.",
"posh chartreuse bags contain 3 dim magenta bags, 2 dull orange bags.",
"pale gray bags contain 1 drab coral bag.",
"muted gold bags contain 1 muted orange bag, 5 faded beige bags, 1 wavy tomato bag, 5 posh lime bags.",
"faded red bags contain 3 dark bronze bags.",
"striped maroon bags contain 1 dark salmon bag, 4 dim coral bags, 1 posh coral bag.",
"muted magenta bags contain 4 muted teal bags, 5 dotted turquoise bags, 3 pale plum bags, 4 faded bronze bags.",
"vibrant aqua bags contain 4 faded crimson bags.",
"bright teal bags contain 4 bright olive bags, 5 mirrored black bags, 4 drab coral bags, 3 dotted beige bags.",
"dim orange bags contain 2 shiny fuchsia bags, 3 striped magenta bags.",
"dotted white bags contain 5 mirrored blue bags, 3 shiny tomato bags, 1 dull coral bag.",
"clear magenta bags contain 3 dark teal bags, 3 vibrant white bags.",
"light fuchsia bags contain 5 light violet bags, 2 striped aqua bags.",
}
<file_sep>/day8/main.go
package main
import (
"errors"
"fmt"
"strconv"
)
type Instruction struct {
Op string
Parm1 int
}
var errLoopDetected = errors.New("loop detected")
func main() {
pgm := processInput(input)
fmt.Println("Part1:")
fmt.Println(execute(pgm))
fmt.Println("Part2:")
fmt.Println(part2(pgm))
}
func execute(pgm []Instruction) (int, error) {
acc := 0
ip := 0
hitcounts := make([]int, len(pgm))
for {
if ip >= len(pgm) {
return acc, nil
}
if hitcounts[ip] > 0 {
return acc, errLoopDetected
}
hitcounts[ip]++
switch pgm[ip].Op {
case "nop":
ip++
case "acc":
acc += pgm[ip].Parm1
ip++
case "jmp":
ip += pgm[ip].Parm1
}
}
}
func part2(pgm []Instruction) int {
pgmcopy := make([]Instruction, len(pgm))
testip := -1
for {
copy(pgmcopy, pgm)
// Flip next nop/jmp
for testip < len(pgmcopy) {
testip++
if pgmcopy[testip].Op == "nop" {
pgmcopy[testip].Op = "jmp"
break
}
if pgmcopy[testip].Op == "jmp" {
pgmcopy[testip].Op = "nop"
break
}
}
lastacc, err := execute(pgmcopy)
if err == nil {
return lastacc
}
}
}
func processInput(input []string) []Instruction {
a := make([]Instruction, 0)
for _, l := range input {
if i, err := strconv.Atoi(l[4:]); err == nil {
a = append(a, Instruction{Op: l[0:3], Parm1: i})
}
}
return a
}
<file_sep>/day5/main.go
package main
import (
"fmt"
"sort"
)
func main() {
part1()
part2()
}
func part1() {
highest := 0
for _, boardingpass := range input {
row, col := decodepass(boardingpass)
seatid := row*8 + col
if seatid > highest {
highest = seatid
}
}
fmt.Printf("Highest ID: %d\n", highest)
}
func part2() {
ids := make([]int, 0, 1024)
for _, boardingpass := range input {
row, col := decodepass(boardingpass)
seatid := row*8 + col
ids = append(ids, seatid)
}
sort.Ints(ids)
for i := 1; i < len(ids); i++ {
if ids[i] != (ids[i-1] + 1) {
fmt.Printf("MISSING\n")
}
fmt.Println(ids[i])
}
}
func decodepass(pass string) (row, col int) {
rl, rh := 0, 127
cl, ch := 0, 7
for _, c := range pass {
switch c {
case 'F':
rh -= (rh - rl + 1) / 2
case 'B':
rl += (rh - rl + 1) / 2
case 'L':
ch -= (ch - cl + 1) / 2
case 'R':
cl += (ch - cl + 1) / 2
}
}
row = rl
col = cl
return
}
<file_sep>/day6/data.go
package main
var input = []string{
"vkplsqwiftuazyje",
"mokluxwbsfhgc",
"",
"tlfxgqinzmdju",
"zjmvfstnplqd",
"xztfjnlqemd",
"cmatrlfnbjqodz",
"",
"xrumszojqa",
"mqsorcixzuja",
"",
"bwdvujyzsneiom",
"njqzvyhceriodl",
"",
"nhbxcfgwpraqje",
"abcqfnrpwehgxj",
"pqrfxancbjglewh",
"exhfbanpwrcgjq",
"",
"skmy",
"koq",
"zqtk",
"vkgfjun",
"",
"zkmhpcq",
"jnubrdys",
"fvdswier",
"",
"nj",
"njehcry",
"yhnr",
"tudngxkovfa",
"",
"pcnv",
"nscvp",
"nvpc",
"",
"fjmpugzckbwho",
"quxmhkzad",
"uzmohyjkr",
"",
"wdscxfnlgaibejomtvp",
"slqgmrkuyotwz",
"",
"eao",
"woa",
"ao",
"oa",
"",
"d",
"d",
"d",
"d",
"",
"eobljmc",
"fdtepbjc",
"xnecrhbuzjg",
"qbceasjy",
"bawkdecij",
"",
"tmuoedrpzabncijwx",
"itudehyxowpcl",
"gtelwqxoiudpkc",
"",
"gadtfkeom",
"ekgtfrm",
"jtoeckgfm",
"kugtfmer",
"misnkqebfvtg",
"",
"vn",
"m",
"ygup",
"nqm",
"",
"fjvluqzongtmd",
"dyxcpbrzho",
"",
"sr",
"rs",
"rs",
"sr",
"rs",
"",
"tlxvdqpuear",
"kmdltoxuz",
"",
"cgabvoz",
"iprelmqfju",
"bwzgknch",
"",
"ktendlaj",
"rqibyxfuwma",
"jahdtce",
"",
"kjv",
"kvj",
"jkvbi",
"jkv",
"jkv",
"",
"ehtypgizds",
"egwispytdhz",
"eyhzpidstg",
"tiyhpesdgz",
"ztlydgpseih",
"",
"yht",
"doalj",
"",
"fghm",
"fhmg",
"hifmgb",
"",
"stgck",
"ajpluiyrqvhw",
"tsf",
"",
"hwqmofuy",
"pnkjlbdtai",
"ygzx",
"ysfm",
"",
"cfdxwnhopyvme",
"wvuedfhn",
"wahnkfgdiev",
"wheuvfdnj",
"",
"ikylabn",
"lbiyank",
"kqilymbna",
"",
"eahgurwvbt",
"qfskieyuz",
"eduvgr",
"",
"oqhpjibznk",
"kobjqwpinh",
"kznpjbqohi",
"",
"sujoglfhzrnmabxpi",
"phgubrxmsoajfznl",
"snjpmogrlhufaxbz",
"fphagxbjlrnomzsu",
"",
"baotd",
"boaudt",
"botdj",
"gwdxtfobhq",
"tnjbdo",
"",
"uhdiramngvtfjewq",
"gnmhudaqewrtfjvi",
"qrvaigdmhuwftjen",
"",
"nmal",
"mal",
"aml",
"almb",
"nlma",
"",
"x",
"x",
"x",
"q",
"",
"kidfopmvtr",
"xdpifwrkotvs",
"eztjfqpvorhkncdau",
"",
"hyu",
"hyu",
"huy",
"oyuh",
"huy",
"",
"xwdupilevjcazn",
"bzdarpgnlivexusjc",
"avxujgfdwecilpnz",
"lcpytozuendiajxv",
"",
"hwck",
"ckwh",
"kwhc",
"bckhw",
"",
"ktbhifgn",
"hbvigntuk",
"nbihtgkf",
"kbgihnt",
"bnifkgth",
"",
"a",
"i",
"i",
"i",
"k",
"",
"kzvohlrcnjwuifam",
"lkujhzfwrcnoimav",
"uzlcvfhjrnmwskaio",
"zcojhmnvurklfiaw",
"",
"htvnf",
"fvnth",
"vhtnf",
"",
"ncrolpwdx",
"pcohxrnvdl",
"",
"jxphyearvgc",
"rfcodbuijg",
"",
"bhugktqa",
"bkgqs",
"epkqfg",
"",
"ecwhuzgkmrodyj",
"dokqewxajuzspyc",
"",
"lfqnj",
"njklqxfw",
"enfqjl",
"nlqfj",
"lqnfj",
"",
"rd",
"ibagcyr",
"envtomrh",
"",
"vfrdbizxwocnaks",
"zdavirkcsfwnob",
"ivcsakqunrdwbzfo",
"nvsxwoczidkfmrab",
"",
"uehqdjmbi",
"jqhuefis",
"dejhovuqi",
"einktyzuqahj",
"ohiuwejq",
"",
"fzgymun",
"mzyugnf",
"guzyfmn",
"",
"fetogjqxcuvzsw",
"vthxugpedowq",
"eutmoikqvwragx",
"",
"fwgujzeykqvlmidn",
"kvuwymijfenqgldz",
"gynldkjuiwzcmqefv",
"",
"nyrxopqgifedsc",
"zdwycqjgfnhoxtiersp",
"nrfacpqdxyesoig",
"fimvyorqpekndglcsx",
"",
"ajeyb",
"bjga",
"jbka",
"jgba",
"",
"vg",
"v",
"tncd",
"v",
"v",
"",
"dwpxzhi",
"ihbpwxtzjlr",
"xiewyzhdpv",
"xwpzhai",
"nhxzwiyp",
"",
"dbecuzx",
"xbduecz",
"ecudxbz",
"",
"e",
"w",
"e",
"e",
"e",
"",
"ovrzqdjaiwb",
"rodebilkcwmntj",
"sdjvozwibrhp",
"",
"h",
"p",
"gtxvfb",
"",
"tnpvcfjsalyiorxzdb",
"irapztvynfjscoxdbl",
"czlnxjydbratipvfos",
"anoctriszvjxydblpf",
"lvoazndfjycbitsxpr",
"",
"rubmekjfdagt",
"amkrxylefcbo",
"",
"iyrqglom",
"qlitrmy",
"rtyilqom",
"yqalmire",
"lqriomy",
"",
"whpei",
"eghpi",
"paetki",
"",
"baepocmyzsd",
"cbezopy",
"",
"lbotn",
"xnqzo",
"",
"nqjos",
"wthmj",
"fkytdsjng",
"ipxzvlba",
"",
"wq",
"q",
"exns",
"w",
"kw",
"",
"cthavwpbkf",
"dsmnegrixql",
"zfcutvojpy",
"",
"niboxrwyqscjht",
"ihbjsxcyronwqt",
"sqhyotwxbjcirn",
"iotrbwqjcnxsyh",
"qwxnshrajioctyb",
"",
"vctoxkjdieyzwb",
"eijydzwobhxktc",
"iaytkjwbuxzpodscen",
"xtjwgydkzoecbhi",
"yoixtwczdqekhgbj",
"",
"aprmbkdcexjw",
"zotyshdnbevqcj",
"",
"lio",
"ol",
"",
"rdtpzonajsymgkcubhx",
"ryhtsxnmjcagdzkoub",
"zhnyjaltgokmudrbcsx",
"xhrydtgjnsamcbozku",
"nxartdusgchzbykjom",
"",
"impokzcuwnvjq",
"znepvyiqkmcw",
"",
"mr",
"im",
"",
"rhaijlqeu",
"szmhnux",
"nwufhb",
"",
"pcihyolxetbg",
"enyrxhuq",
"xfvrejdhky",
"",
"zoxgea",
"oxeza",
"xazdvoe",
"ozxauge",
"jntzwoexa",
"",
"xaivusctq",
"tisqxva",
"",
"ts",
"t",
"",
"infzulyjrwmv",
"nvzubryomlifjw",
"wvygflurnjipzdm",
"ruyvjwlidfznm",
"iluwnryfjmvz",
"",
"vw",
"vw",
"wiv",
"vw",
"vw",
"",
"x",
"x",
"",
"bzjhrsx",
"zxahrs",
"xhyrez",
"rabhxjz",
"",
"fwsuiqblg",
"fnqkdgsj",
"jsaqfyvgnk",
"gqfs",
"yoesrtqfag",
"",
"uqxatgzhbvf",
"bvhzltgqfxua",
"rztabhfgvuxq",
"taxbfhvqlurgz",
"zhgsqvtbuxaf",
"",
"e",
"xzyr",
"h",
"d",
"",
"u",
"u",
"u",
"",
"rtdyhnfliowua",
"sdlhfygqera",
"kzrmvpbxacj",
"",
"kyhja",
"ugneb",
"fpbzc",
"",
"u",
"wu",
"",
"amsovxceljdygphbw",
"vbdhsowzagmylxecpj",
"",
"uevdiqzwokgxhj",
"worxiusdzejgqhk",
"qxkthjuwiaozedg",
"",
"qbtevg",
"wyngqzsvb",
"gvbtqe",
"",
"lfbgch",
"hgbflc",
"",
"vlpg",
"mlg",
"ldeg",
"",
"r<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"vy<KEY>",
"",
"exzsaqlijpdmkvgywftb",
"so<KEY>uk",
"kd<KEY>",
"",
"paowmuxkgysedl",
"wyxsokudpmaleg",
"gywoxakesupdlm",
"pyusakwegmoxld",
"eopslywkuaxgdm",
"",
"lsxjny",
"yxsljn",
"ylnbxjs",
"lbjynsx",
"jsxylrnv",
"",
"jwegoyxpa",
"jmcapxvbdg",
"swjxap",
"hqapzinuxrtjf",
"velaxypjk",
"",
"m",
"ge",
"",
"quypbjdikvletowrnasm",
"ywnaplqbmusdorekivzjt",
"jqntersduopvyblwakmi",
"wnkibesaypdjuxqvlomrt",
"",
"pylnd",
"ylcp",
"",
"advbre",
"nrjbfdvex",
"xberv",
"osekrcv",
"",
"nzpwvidyetcbmorj",
"ibjdnroagcemwpz",
"qzsekmdbnxwuirolcfp",
"",
"huqydt",
"rsbwpdmcnt",
"",
"hcjbr",
"bhcrj",
"cjbhr",
"cbrhj",
"cjhrb",
"",
"fpxi",
"ipf",
"ipukjbgfo",
"tpaif",
"ipwxf",
"",
"hobckpqzajgsmdrwl",
"odrpwlsjachqgzmbk",
"oqragbsjkdlhzcmpw",
"jrgbksowmzapcdhlq",
"zwpmclbjhqgskraod",
"",
"diezqf",
"zf",
"znhsymf",
"ozjf",
"zkrejf",
"",
"esmgwuvlzixaycnfqkt",
"sipueyhxfqkbog",
"",
"mrpscwnklxhtobauveyi",
"tgaivjupxhkbcszleorwmd",
"tbrlosnvhpecaxiukmw",
"",
"flpk",
"rf",
"xquatcvji",
"wysr",
"",
"dcfnywpotmge",
"ymfupe",
"qhmekjysf",
"",
"kdgq",
"qcgdk",
"",
"ocxbdl",
"wlcauqy",
"uwarlc",
"",
"thbeswnyqm",
"nsqymwhbet",
"",
"itmbc",
"tofmvcb",
"",
"sw",
"sw",
"swm",
"wsh",
"",
"orixhcu",
"uixhcor",
"hrxcuo",
"xhkucbo",
"",
"xsowberlfigtkz",
"ltivwneusg",
"tnegisalw",
"gvqstmldyicwpe",
"",
"yhznbodgfcqeptivx",
"dioaexhnczqtgv",
"okdgteivxszwhqmn",
"",
"dokztemwprxcula",
"irmxpdouta",
"rhtuxopdbmaj",
"dtmaphxqroyu",
"mtdohsparfugx",
"",
"hzcarpvyjkqduflwbxg",
"ctbhalfxivudonyp",
"",
"gkdypu",
"pkgyud",
"kdypug",
"ygdkpu",
"gudkpy",
"",
"ulw",
"fwul",
"",
"gpwotsyxzjc",
"nlmuevq",
"",
"zxtpjvqmsr",
"bmprdvquig",
"mpvryhq",
"",
"j",
"j",
"j",
"kewlj",
"",
"hgxscfpjol",
"spgfchxjlo",
"",
"hwjedr",
"edwhr",
"dewrh",
"pewhdr",
"usdehwtr",
"",
"jegvbfpcm",
"khnuldx",
"zyoasn",
"",
"tlrpbifxsjngoduvamyhkewcqz",
"fjolbtkicvmhrexungdqyzsapw",
"",
"is",
"zr",
"",
"qptgfwdcbmxueoiyjs",
"qbfcwsugexdopjtmiry",
"jpwdecfyosiqmutgxb",
"oejyvdwfgsmptbqxicu",
"",
"snqytmeualwrzogh",
"styeunlqzmwhgao",
"yhnwlesoqguatzm",
"unmazqlesytohgw",
"",
"dftkic",
"xurjq",
"",
"drixnqjogckuzmtl",
"syhkwbvdjxfr",
"",
"xelvzfjd",
"jfelzvx",
"zjdfewxl",
"jxfle",
"rfejmsblxg",
"",
"cz",
"cz",
"zpc",
"msaczrxy",
"",
"rvlmfknpzxauqedwhybj",
"bqyksfardvxwunehlzmj",
"ncsmirluwabjkyzdfveqxh",
"",
"gmpbcwjrs",
"bglcjpriwum",
"jbfwrvcmpg",
"",
"ktfqsluvjhg",
"jkfbxhgvayq",
"",
"uvle",
"lkx",
"",
"ng",
"ng",
"ng",
"",
"ozjnipsqxlh",
"oljhczqidsnpx",
"",
"hqmnsiadov",
"ohdsnmcvai",
"",
"lerquyikvxdtpn",
"edquylhi",
"ibuljedqy",
"elquybid",
"",
"g",
"g",
"g",
"g",
"",
"uqbemtxp",
"gzubdexq",
"qpxveb",
"vqszbxter",
"eifwxbnqkyaco",
"",
"isvbajpehtdow",
"khdjiepawnvsg",
"hqacjefdwxivsrp",
"",
"cnpltgfhwjiaydxqouz",
"acnqgjfrwiexhopdz",
"",
"sjmwleyxtriqdchbk",
"icatnbgservmuqpfw",
"",
"cela",
"elqbca",
"acle",
"alvce",
"",
"upkctos",
"izbqxh",
"njdqevafy",
"",
"t",
"jua",
"egoy",
"v",
"j",
"",
"m",
"dwm",
"",
"kipetzja",
"jhyeizpqvk",
"zjkpie",
"ipkjzne",
"",
"tsibo",
"sbo",
"rjzqbosamn",
"vosb",
"",
"u",
"j",
"u",
"",
"mtjivuygewcolkzrpfbs",
"jlgcyuzpafkibwshdmovte",
"bskavogweclutifypmjz",
"",
"ov",
"ov",
"ov",
"",
"eyro",
"yeor",
"rofye",
"yreoz",
"",
"thlknydiesxupoarcgf",
"gidylcsoekhnxafrt",
"glwyqiectnshkdbxraof",
"grtvasnichfyelkxod",
"",
"whzu",
"wimcpu",
"gfwet",
"dimw",
"pcbwli",
"",
"z",
"z",
"z",
"",
"chz",
"hzc",
"",
"nvfswzqculbtdrxey",
"jyludxzbwgvnhrpsfceitq",
"znlxeocqywmrsvfudtb",
"",
"wnbz",
"ezugmpx",
"tz",
"idszb",
"znlrdw",
"",
"xhipb",
"bphix",
"ipcbhx",
"",
"gudlfzh",
"dghzuo",
"guhdwnz",
"guhdlfz",
"hzgdu",
"",
"dczfkubhjwn",
"kjhcubwfzdn",
"zknfuwcdjhb",
"kzbwcdhujnf",
"khnzwcdfbju",
"",
"wkpimxyu",
"uyimpkwx",
"wkmupxyd",
"ulxafnpcwshymk",
"wumxpkdy",
"",
"jlr",
"l",
"l",
"gal",
"lg",
"",
"t",
"t",
"q",
"",
"cktanxyfepglowhibsjv",
"tbpfihyovgeacsnlwj",
"",
"rzd",
"wyrzd",
"dzr",
"zrd",
"rdz",
"",
"ligjhor",
"grlhno",
"yqrpsolhmwg",
"xelsrhogub",
"",
"njrwbhvfta",
"jfenrhvbwt",
"tvwbrnlhjf",
"cjfzntbhvugqwr",
"",
"xytgmcdaeolfqwzskr",
"qdfmegraxzhokcyswt",
"",
"ndcywqxkfta",
"ckxwndyqfa",
"cwnkqadyxf",
"wkyncdqxfa",
"wcqdkayfxn",
"",
"vbir",
"vrbi",
"bvri",
"vbir",
"rvbi",
"",
"mstylwqkrnizdhjbcgeo",
"yvqkrbedpmwcutsfo",
"atpermwqfcobdysvk",
"",
"sdylhzipk",
"zyispkd",
"kydizsp",
"zepsiydk",
"kdzypsi",
"",
"lvpiahe",
"hvapeli",
"",
"fwpmhryouqcktzb",
"bhzyucgqkmrvdo",
"jobackhzsreqiumyn",
"vchkoqdzmybru",
"xblhkcyoqdruzm",
"",
"jkilegfoxzacr",
"acxkzorfpjg",
"ctkzrgafxoj",
"oacxzfjgkr",
"jrozkcfxga",
"",
"apmksyco",
"acsomkpy",
"sopcaykm",
"mkcyoasp",
"scqkmpyoa",
"",
"fpaigjltezhxwnyrvu",
"vftqenyjwbsuaiplhdr",
"ajeutynhiwrdflcspv",
"naeilpfjuvdkwtyhbrq",
"htproevliajwfynu",
"",
"cwaug",
"augcw",
"cwuga",
"augwcy",
"gwcua",
"",
"afqcnwebdv",
"aenfqbwcv",
"bvfeqwcjnsa",
"",
"vtecwrzfa",
"tczvwrma",
"vrpwczat",
"xewzcavtr",
"vwcatpzr",
"",
"rdkvyle",
"eglrbyadp",
"tmxrhszneuldyw",
"dleykgcqr",
"",
"qsohepyxawngjd",
"ecaywgnhmf",
"wfeagtnrhuiyl",
"nthwgyeav",
"ynwgberazh",
"",
"loupbihzqwady",
"npbtkumjdoihwy",
"ysguhceopbw",
"",
"fy",
"n",
"",
"ulafhmibcnqvxt",
"ik",
"i",
"i",
"psdiry",
"",
"wcahpmgkjdi",
"lkazewjdpgbins",
"",
"sy",
"ectfa",
"q",
"sz",
"",
"idglafuxovqb",
"vurdigqpfoal",
"fgovalbuidxq",
"",
"qigjvulpdaxwsbnzyc",
"i<KEY>",
"sjlxcdiqnuvbmwp",
"rsk<KEY>",
"",
"urxqtyshgzemca",
"xawgozkbejncprilyqf",
"",
"irl",
"eurpiolqczj",
"lrswi",
"vnilwrf",
"",
"viwsjgdt",
"yxhc",
"",
"ynwkqtpageurxosvjlbc",
"letqbswnxcrkajvugyp",
"zsnjawtqgevcpkrxybulf",
"ynglakqevcjptxwhsrub",
"",
"gabxsumno",
"mknawxt",
"anjxhfm",
"",
"dimjglkvcstaqzebu",
"cjeqzybdkaurv",
"bdkoacevqzju",
"bdycqjkaveuz",
"bkcevaqzduj",
"",
"z",
"z",
"",
"rydinou",
"zfycpiwl",
"mbydiv",
"",
"fzhrbc",
"bfszrhc",
"",
"g",
"g",
"g",
"ag",
"",
"l",
"l",
"l",
"lq",
"l",
"",
"cnf",
"ncf",
"",
"x",
"fzw",
"",
"nhgkcomtsdxlazu",
"wcrexdamztyohklguin",
"dmxlzgnckaehtuo",
"doqcuhfxtlbanmgkz",
"",
"omfbckilpvjgxqwthse",
"vpwhosebmtxgicjkfql",
"",
"nmdlkxb",
"ihbvjk",
"blkx",
"kxbycs",
"bk",
"",
"uxkzsavo",
"xosalzfbv",
"opvisknrxauz",
"xouhgzsav",
"",
"wcjodbqux",
"patbuwvd",
"",
"mb",
"mca",
"mc",
"cm",
"m",
"",
"usp",
"aftgzcp",
"ztr",
"eyjkbmnd",
"",
"zwfyeraxjdimplusbq",
"sjqamxiyfbduplzre",
"",
"uehlcmvqagxd",
"ghbeylfazdcxu",
"clhedaxjgiptvu",
"",
"vntkpmzia",
"pimtvyakz",
"tzipvakm",
"",
"fgoputbi",
"bpiftxg",
"wpgtibf",
"fgbpit",
"",
"kirsmujcn",
"mnkucrij",
"jnumckir",
"",
"fubspvchiwtnjkrxomae",
"kvcrsdtfuwhapxemnoji",
"wcaknfurotjlsevmhpix",
"",
"mojgstlqrebpifcvy",
"gpfijetbvqrloycs",
"lptohfsivgrjqcybe",
"",
"etnjorpmshwxlcbfdugykvaiq",
"necvjsgwokupfdlthymqxibar",
"whftpldmarigjeuckxvqybson",
"brsovpaqykicjhutewmnfglxd",
"",
"ofmkudxjpeti",
"okpmifxuejt",
"",
"feudgmpbhzak",
"emjnkbzludr",
"",
"wc",
"cw",
"dcw",
"",
"tolg",
"berksqjhmgt",
"fwgxt",
"atlg",
"zgptn",
"",
"hng",
"jiav",
"",
"fit",
"htif",
"fit",
"fit",
"",
"bkxgyoasj",
"xdinqvksb",
"esdtkylbo",
"szhfkmrpcb",
"uxseqbko",
"",
"vgclrk",
"yvgalcrk",
"",
"imgnj",
"bgm",
"mgb",
"gmcr",
"",
"rc",
"cr",
"rc",
"",
"bshkdmce",
"uyfzjwclhovae",
"thqdgkinsec",
"",
"ckmsoxuqif",
"fukqxmvsic",
"mosqchufikx",
"",
"ulmfponhvjbzs",
"jopbvzlgfhmusne",
"ovjzewfnumshlp",
"vhmfojlunsakxczrp",
"",
"tibdoksuvaxhwyzcpjgr",
"ypatgvjkrcinxumqhd",
"lykfvurhdxiqpeajntmcg",
"",
"yrvqacpmexifgkbtdwzjso",
"psgtcyqvnwibfuozrmxekjd",
"dqbcjfgrmvwpzioytesxk",
"",
"rubmfhv",
"hbfrjdmv",
"rihmbvpnf",
"hfrdmixbv",
"",
"raviz",
"imz",
"iz",
"mezis",
"",
"<KEY>",
"elm<KEY>",
"",
"aci",
"aycn",
"caq",
"arc",
"caji",
"",
"vb",
"vb",
"bv",
"vb",
"jbv",
"",
"jxgarbnkwutzc",
"npjatuzwhkxbrg",
"bkdrljnasxwzgtqu",
"",
"xparfjw",
"rfaxwjpm",
"",
"jf",
"j",
"jr",
"ji",
"",
"xrgdnqzk",
"zndgqrikf",
"znqrkxdga",
"rkzgqand",
"",
"egizwncdbualtf",
"flguwazicedtbn",
"ulfztngaibwdce",
"bilncfatwzuged",
"nabgeclfudtiwz",
"",
"d",
"wfdj",
"d",
"d",
"d",
"",
"gn",
"n",
"n",
"n",
"n",
"",
"dou",
"yunwtdohpcb",
"ouvd",
"",
"xvayuwoe",
"ayuewb",
"yawseu",
"",
"tfbso",
"sotf",
"ftos",
"",
"otjcundbazgmlirkyhqpvfe",
"bqcduiyaentvzhklmgporjf",
"fyhtvnzadglcumopriqbjke",
"it<KEY>",
"kon<KEY>br",
"",
"h<KEY>",
"l<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"",
"cailbjyxztvdnphkrg",
"<KEY>",
"jazdblghrsicxpytkv",
"",
"p",
"fp",
"f",
"vgz",
"",
"elajdxgu",
"jiduarlexg",
"xlejdaug",
"",
"auh",
"ahu",
"hasu",
"hau",
"",
"rckmqapdtse",
"molzwi",
"hgiom",
"",
"asqyzrgotdlbviu",
"lgoztqsdbrivy",
"lrtybsgqvaizdo",
"lbdsgorzvhyqxit",
"alijgryqzbodvts",
"",
"fpnlakbxjosd",
"dlpyfnjaxoks",
"lokfabpnsxdzj",
"dvmxugpoajnkclfhs",
"flxbknrasjodp",
"",
"mprcewkzquit",
"ezkrcuiwqmtp",
"wiprkqetzmcu",
"",
"alkyb",
"kbl",
"klb",
"",
"iezaknbl",
"zo",
"z",
"oruz",
"",
"ibhrojtaulvewmgczpxdqk",
"rcbpgidtkqouyazhevwxmlj",
"idzhegvwtacublomrkxqpj",
"vcbigrtzlowxpjhuedkmaq",
"ajxuctrhwepmvoilzdqgkbf",
"",
"knal",
"nlv",
"qlnzb",
"ulknv",
"ln",
"",
"dkfrbh",
"hbrdfk",
"hdirkfb",
"dfrkhbn",
"akedmhrfb",
"",
"axeuqykc",
"cijxqeg",
"ybuzctis",
"zwcliq",
"hfodnrvcpm",
"",
"k",
"k",
"k",
"k",
"k",
"",
"f",
"yg",
"u",
"y",
"y",
"",
"xbrgmpydio",
"rdxgibmpy",
"dryipgxmb",
"ihjdxygmbpr",
"ixgyrbmdp",
"",
"xutjv",
"uhxtvj",
"",
"dpezviroyshwaxqgjlck",
"ogivhpaskqrlcdjwyezx",
"zspkihxldaoqrjcgevwy",
"ckigvrljoexyhpzsadqw",
"hguvczomqlpnabifswjydrek",
"",
"fsaonvedtjczu",
"setdouyfvnbjk",
"oftnledaqsvuj",
"nagujstvefdo",
"",
"hbwvkftgdzsm",
"msvfzgwbkdht",
"",
"nbxliqesfzawyk",
"aswzruelkfbhniqo",
"",
"yobmx",
"jxybeo",
"ypsbnuxaf",
"ybx",
"",
"yqaxjhlvrfceu",
"fzvpcuqaxrheyj",
"racjhfyqeubxv",
"xq<KEY>",
"",
"xejldkfstrvubcpaig",
"gqxhcpbsrojditeank",
"",
"favwixezjmso",
"ogpbvwnamz",
"atwvobzm",
"trhowanpvqmdz",
"",
"qfdcv",
"cd",
"cd",
"cdwk",
"drzc",
"",
"y",
"y",
"y",
"yl",
"",
"nclrvbgzmudf",
"vdnlfgusir",
"",
"gbnxzysckmp",
"zsnkmcbpyxg",
"",
"zqweaofxvpjucmkts",
"setcuqkpfazmxwo",
"",
"kxmfqdithl",
"hktfmdqsi",
"wghkmfydtiq",
"fiqkhmgtd",
"mfijqkhdt",
"",
"mebnqwaxzvys",
"msvaotqilh",
"",
"tymwfkrcsvilqodphbuzexjna",
"takfijusvpozeqnwxhyrdbclm",
"edhrynkzbispqwflvcmxotaujg",
"",
"uvc",
"vcu",
"vuc",
"ucmv",
"",
"kfzadnxwsq",
"lawdxkznfqs",
"tflqdkxasnwz",
"knqsrcgfozxedaw",
"xaqwdnsfkz",
"",
"gaho",
"vzdecfourwpnyx",
"iqhaoms",
"",
"kiebj",
"izekbj",
"jikeb",
"lbjirukqe",
"ijbkxez",
"",
"ldwsav",
"srlx",
"cntqmikugl",
"ylz",
"",
"yqh",
"h",
"h",
"h",
"h",
"",
"jpqewnhzbyltxu",
"samgukw",
"umw",
"wuck",
"cfmwgu",
"",
"hblxgkmjyc",
"xmesjhqaidgp",
"",
"wseufabtgklimdoxnypqc",
"thwukpnivmxbcalesy",
"",
"sfzpaeqdbhwmnlxt",
"btlsqpdmnwzaeh",
"ahwtklseqnmdpbz",
"mwahslezbnptqd",
"",
"alhkbjrtm",
"mjkratblh",
"tbmrdkhlja",
"bklrmtjha",
"",
"fkjwmabqy",
"bwayqfmpsuh",
"ycbaqfnkwx",
"trwozgyibadqlv",
"wxnaqpybe",
"",
"dbz",
"bdr",
"",
"evsxkiwhj",
"ijkwxsve",
"vekjiwxs",
"eswivxkugj",
"eowtsliravjkzx",
"",
"i",
"i",
"i",
"i",
"l",
"",
"ek",
"ke",
"ek",
"",
"bk",
"rskpanj",
"",
"jlqapcexir",
"rix",
"uxyri",
"hzirux",
"ixryzu",
"",
"mbecuxkqodis",
"myfk",
"",
"osk",
"kvw",
"",
"k",
"k",
"h",
"k",
"",
"slwqeticyjpdzf",
"gxechvlqnmsfp",
"qulcpsfem",
"quehspflrvcn",
"kgcqlaepfs",
"",
"bhiye",
"bstyvrapi",
"uldxybmi",
"bioknyfwj",
"cenghbzyiu",
"",
"ztsxu",
"xtszu",
"usbzixtc",
"uxtzs",
"uztsx",
"",
"jadbkcovfyrnsx",
"gnqxdfycvbksr",
"nfsvxdbmry",
"ysuvnrdbhlxpfi",
"",
"xchlgiaotmsuzvq",
"gmayopixqslcfekhz",
"wmsojhcbraznq",
"",
"cxfky",
"kfcyx",
"fwkcyx",
"fxyck",
"",
"xqo",
"q",
"q",
"",
"sgojw",
"cvfm",
"",
"zdfyhrqtn",
"tnqyrfzd",
"mrfjztydpnq",
"dqfyrtnz",
"dyznfrtqh",
"",
"qemxlh",
"fbvnekpcmh",
"mehz",
"whmrdegy",
"emhg",
"",
"mqvr",
"cnasrl",
"qdys",
"gmez",
"jptbh",
"",
"epufwojvtkzld",
"kouedvymlgntp",
"okldsviptaeqxhbfu",
"ouibvesrcjktpld",
"",
"xnhkjmvwy",
"mjhkvwy",
"hkjwvmy",
"wkjhmvyq",
"yjmkwvh",
"",
"ckedjx",
"excjkd",
"",
"znfesox",
"xeoh",
"ocenxz",
"eolypx",
"",
"mxivwjbheynk",
"vtobgpxmyhkqnjiw",
"",
"tsxvd",
"xdqcvn",
"",
"ynhtcpbeourwqik",
"ciaoeqnvztmgybdhkws",
"ewckryhoqnbtfi",
"ihbqotncwyek",
"jfcwkthboeqniy",
"",
"zaefxrolby",
"vdfztseoqhgly",
"",
"woiyfq",
"iqfyw",
"wiqfy",
"wqyif",
"wqfiy",
"",
"czojbsdtxhnwvuygfmkeaq",
"lwjqbtyngfzuxkecoadsvh",
"",
"celw",
"tywbeuascvz",
"ekgcinwrox",
"",
"cy",
"yc",
"yc",
"cy",
"cy",
"",
"jxpwoydmhblcrai",
"qmfykpsrxlvda",
"",
"o",
"vx",
"",
"uptwyrij",
"jiyturwp",
"wqbtpyujir",
"rjuytpiw",
"",
"meqghcrlnfjkyw",
"avjcixbspgfqz",
"",
"dyz",
"l",
"p",
"pul",
"i",
"",
"l",
"l",
"l",
"l",
"",
"dhua",
"aguid",
"aud",
"",
"rqnfj",
"nfbqdj",
"fqjnu",
"fjnq",
"nqjf",
"",
"scfvjmnxeag",
"cudpbwfnxalzsotqk",
"",
"abzfcdpnyxg",
"dcmrbnpxfzya",
"",
"aexvdqroyncwl",
"qrowycxvnaled",
"",
"scznoldgrut",
"orcduszlgt",
"",
"zofhkcrsjm",
"mfsozrhxayk",
"",
"nehxkswcz",
"cvwnekxy",
"aewxkscqjn",
"",
"stpwkqyzgm",
"wkjpzygtsm",
"yqmspwgztk",
"pztsymgkw",
"",
"wcipmryqalvzbkghtsofxj",
"pbjixyckrgzmfvslhtaw",
"ivrzglbuxtsjhwcpamfkye",
"nckmdqfbgtasijyropxvwzhl",
"",
"qtfyr",
"yrtfq",
"",
"xkijmzgyeplvubr",
"kzsdpxjbhne",
"zxhbtkpjse",
"",
"tvm",
"zvm",
"",
"naqbrui",
"rbgiuqans",
"bnrqaiu",
"",
"dulxmsoavhciyqpfzketnbr",
"obnxqmidafpresytlzckhvu",
"otxrdwpumcivyshfaqkgeblzn",
"hyrmlzkstpvifucxedbaqon",
"qrpndcmtoevkzlysaxuhbfi",
"",
"kbisedtufjvmroq",
"dfubrkimtjseq",
"bqdsuktemirjfw",
"ukpdqtshgerfimbyj",
"",
"br",
"rkb",
"rcb",
"br",
"rbm",
"",
"lm",
"lfh",
"ml",
"lo",
"",
"uigbrefdqzoaklhwcjxntm",
"cublkmtxeqwgrhonifyd",
"bsleinxukwdmftrcqhog",
"",
"zicwhktunjxgfpodsbye",
"nfteiwpudgcxovjbsyak",
"ywegkintxqbpdujosfc",
"",
"f",
"e",
"t",
"e",
"d",
"",
"btxnpqyrshjcz",
"qstfkgioavjlwe",
"sbdqjpturcm",
"",
"mpi",
"ipm",
"",
"bxqlyckzwrgu",
"ywulzqkgbrcx",
"",
"lmpys",
"mypsl",
"smlyp",
"pdlmsy",
"ysmpl",
"",
"gxbsvalu",
"gxlabvsu",
"xgbvauls",
"",
"jd",
"jd",
"",
"v",
"vb",
"v",
"",
"helzqfkyadcjtrpom",
"yjcqdrzeftlkmhao",
"eolhdvkmjqfxctzyar",
"lzcrhsfdjoeyamtqk",
"lcreftdozqmskjahy",
"",
"tavjmbdeznxquyws",
"bejtfcgrpwisu",
"",
"rinkdgteosbupalcwfm",
"opcbulmgsrnidewafkt",
"cpdbrmnuaeftlwgosik",
"wiedgctfrkunomlasbp",
"",
"qenyztwigf",
"finwzbeqy",
"bfzpeiysqnw",
"wyienfzqb",
"",
"fximacpqjvrozwu",
"aproqwzficuvx",
"aozqprxftwvicyu",
"",
"wxedbjgki",
"wxgjzikde",
"iyekzgwxdj",
"",
"ghsde",
"hsd",
"sthd",
"",
"cafgyinvxmqsukot",
"utnsfycxkmoagviq",
"vkqystxmaniofgcu",
"nmtyavikgsfcqxou",
"fcxoyniumkvqsgta",
"",
"sq",
"q",
"q",
"",
"szvxhg",
"sgvzxh",
"",
"orwyznm",
"tynzw",
"",
"ivzcoaenfbrm",
"imecrfnovabtz",
"dnwgzobcvfmyirea",
"ebfnairctzmvo",
"",
"yjtznqpvsldf",
"ilxahurg",
"ykjcsbel",
"",
"lhiubo",
"uboihlma",
"hlgufnkprcvoib",
"ilbhtou",
"bisoulhj",
"",
"vhiapgbtjlcwuxs",
"ibauwcjsptglxv",
"gcsopxwuajvilbt",
"",
"oqbadzwepv",
"kbxdetcliprquvsn",
"dqhvwymbpe",
"",
"ce",
"wcpo",
"c",
"octrn",
"",
"swpd",
"clb",
"",
"mxjwhr",
"marhxewj",
"wigrcjpmx",
"bjrwqxm",
"",
"l",
"ulyt",
"bl",
"gl",
"",
"gofskm",
"mgk",
"",
"dscxkpviur",
"lpicsbuk",
"jkibcupsr",
"eucsifnkp",
"",
"vs",
"c",
"c",
"c",
"",
"i",
"i",
"b",
"",
"cuv",
"cv",
"ceb",
"cv",
"cnhtm",
"",
"ox",
"tx",
"",
"rheungozl",
"eznoglrhuj",
"gnhozrlue",
"nhlrzuoge",
"urhognlez",
"",
"lnkcuajziqwxtev",
"fzauikcjtxvqlnem",
"",
"fmjbugerkdyaiqcxnw",
"kxhanqgjcfbyeurdmi",
"",
"qjrleua",
"rujleaq",
"aejquzrl",
"rejxuqla",
"",
"okagijrelbc",
"rbikajtglc",
"",
"e",
"e",
"pa",
"y",
"",
"c",
"hc",
"liasmwofn",
"ytkev",
"pczj",
"",
"tkpnzsvmrdijfwobghqcaxeu",
"whfpjgeavdkbzmnurotiqscx",
"fqvuropcmkzinbdwashjxetg",
"hqkuzafetjpbwyirdxngvsmco",
"",
"szxa",
"axzs",
"xzas",
"xasz",
"szxa",
"",
"nscjgi",
"jgcns",
"gjcsi",
"scjg",
"szjgc",
"",
"zuadipsnxhqgfjv",
"zjpdugisfv",
"dgfskzvjuip",
"fvugpidszj",
"",
"qpcbui",
"qntkmsxlia",
"",
"at",
"yta",
"ft",
"",
"letsxrmgabi",
"gnpqaecbmxfwi",
"mciujqgehbax",
"ekgmixohyanb",
"",
"epnlovurz",
"oqferplx",
"lrnedoqp",
"lroupe",
"awelogcikprm",
"",
"nwyuzvrlmbhtjfqaedxocgi",
"cufibmwaxdljyzovqrtnegh",
"",
"eoxvphlgnjcmb",
"omvghcpejnlx",
"",
"mournjwlvsckdt",
"jumlnvrweozpkc",
"vbgawlrnmkijcox",
"nryelovjqchdkwm",
"",
"iqbyaxh",
"gxbqnhi",
"xyibhqm",
"",
"rqxbago",
"xvq",
"iyfqujdpwcn",
"xqamhg",
"",
"gbxszymv",
"vhlnfdmg",
"mvgkdnj",
"",
"almux",
"axulm",
"xmaul",
"ualmx",
"",
"fdseyvrjkolcinw",
"idxynrvjakolmcfu",
"ycfbknvtijlurado",
"",
"rewtmvgcnhqaolkjbiuds",
"atougievfqhwsdcbxjknp",
"og<KEY>wd",
"ckungoviwqjbthmeads",
"veyuawsiothnjdqbcgk",
"",
"gvuqtmnxhoepfw",
"efqwtmnovupg",
"oevuqtfpmwng",
"",
"trdyigx",
"nbtmzrygpxi",
"rxtyzbg",
"ygtwxrefu",
"",
"akflh",
"lakf",
"afkl",
"ablqfk",
"zkalgf",
"",
"gsuo",
"ywuvt",
"",
"pcbe",
"lptbc",
"picba",
"plcb",
"",
"wt",
"k",
"t",
"",
"qnjo",
"xqgjyv",
"",
"iozkwcxuhapnqg",
"pawxsihqkclzvgunm",
"kxawgbihuqcpfnz",
"ikgrpunhqwafzxc",
"",
"bywxros",
"rsowbyx",
"",
"wjxhogyipvanmbcrste",
"dcmgwqnepiajvxkbsth",
"",
"zbmicrsajtqe",
"miecstjbarq",
"",
"paxrhzkyslnq",
"zakyxhqslrn",
"yslaxhzqnwkr",
"",
"jkleg",
"ekyl",
"kyle",
"",
"ydvkwga",
"nxqarwd",
"wxakpq",
"cefbauhmjtoz",
"kai",
"",
"bhwzivoacl",
"zcwqtxhsakyb",
"",
"fsnged",
"ocmlx",
"wol",
"brc",
"",
"ztswjbceaolgi",
"jlsmcupgw",
"rxsgkyjhdqfwnv",
"",
"xt<KEY>",
"bt<KEY>",
"",
"bmtz",
"ytjmhezbf",
"bwmtz",
"mwtzb",
"mtbz",
"",
"bju",
"ubj",
"",
"zywb",
"bwy",
"bwyz",
"wby",
"buwye",
"",
"nerhbp",
"htbple",
"",
"beurhjyvtdimocqn",
"hcvniqytrjeobumd",
"mncoeuqtihydrvjb",
"qibvdmywzrehcnout",
"",
"egc",
"k",
"s",
"",
"deltoa",
"etdoal",
"aedolt",
"amdtleo",
"",
"gdwalptufnsxhr",
"uwgadebmvrhnlxfpcst",
"hlwsrfungajxdpt",
"ygnfwhrtaldpuxs",
"rzxalndgutkpswfh",
"",
"mucn",
"hewbdvanpomyrj",
"mnsik",
"tmnqu",
"fnxm",
"",
"gvykqxtmzwfsbrcleahjnod",
"hunoyzdjrmsvtbqckfaexlg",
"acketzflmjhqdrosbnvxyg",
"fevrokybsmxcatzhnldqgj",
"toqeprafdycksnhlvxzjgmb",
"",
"ou",
"uo",
"ou",
"wuno",
"uo",
"",
"eyfckdvlwibquogtsnrpazjxm",
"<KEY>",
"lmtjdcxwvpysezqkonfrguiab",
"<KEY>",
"",
"jgxudzlbswaefhpk",
"xz<KEY>",
"k<KEY>",
"",
"czjw",
"gykomq",
"xthi",
"nxzsp",
"",
"exyjs",
"jxsyd",
"xeydsj",
"jsxyvg",
"wixbsyfjl",
"",
"ultdkrv",
"udlrkv",
"drkuavl",
"kravldu",
"dvfrlkua",
"",
"zjgofiydu",
"zijfdougy",
"yoizudjgf",
"jdogzfiuy",
"jziugdfoy",
"",
"cdxlhpgtzrmubyse",
"owcrpythmfuxbe",
"xymtcphrdbueqis",
"",
"drfatx",
"xfrad",
"rafdx",
"fdaxr",
"",
"tuxmnqvwiodzl",
"znwmiuxvldtqo",
"qxwidtoplzuvem",
"",
"l",
"dle",
"l",
"",
"uv",
"fabuvn",
"zvdu",
"",
"htgwvcus",
"",
"kzfijesnvuhlqd",
"trudmvekzjisofl",
"",
"qbltyocnjvigse",
"oriqujavzntpblfw",
"vmqltjciondkeb",
}
<file_sep>/day6/main.go
package main
import (
"fmt"
)
type Answers string
type Group struct {
People []Answers
}
func main() {
groups := processData(input)
part1(groups)
part2(groups)
}
func part1(groups []Group) {
count := 0
for _, g := range groups {
count += countUniqueAnswers(g)
}
fmt.Println(count)
}
func part2(groups []Group) {
count := 0
for _, g := range groups {
count += countUnanomAnswers(g)
}
fmt.Println(count)
}
func countUniqueAnswers(grp Group) int {
x := make(map[rune]struct{})
for _, p := range grp.People {
for _, a := range p {
if _, found := x[a]; !found {
x[a] = struct{}{}
}
}
}
return len(x)
}
func countUnanomAnswers(grp Group) int {
x := make(map[rune]int)
for _, p := range grp.People {
for _, a := range p {
if _, found := x[a]; !found {
x[a] = 1
} else {
x[a] = x[a] + 1
}
}
}
c := 0
for _, i := range x {
if i == len(grp.People) {
c += 1
}
}
return c
}
func processData(input []string) []Group {
var (
grp Group
)
groups := make([]Group, 0)
grp.People = make([]Answers, 0)
for _, l := range input {
if len(l) == 0 {
if len(grp.People) > 0 {
groups = append(groups, grp)
}
grp.People = make([]Answers, 0)
continue
}
grp.People = append(grp.People, Answers(l))
}
if len(grp.People) > 0 {
groups = append(groups, grp)
}
fmt.Printf("Read %d groups\n", len(groups))
return groups
}
<file_sep>/day6/main_test.go
package main
import "testing"
func Test_countUnanomAnswers(t *testing.T) {
type args struct {
grp Group
}
tests := []struct {
name string
args args
want int
}{
{"test1", args{grp: Group{People: []Answers{"abc"}}}, 3},
{"test2", args{grp: Group{People: []Answers{"a", "b", "c"}}}, 0},
{"test3", args{grp: Group{People: []Answers{"ab", "ac"}}}, 1},
{"test4", args{grp: Group{People: []Answers{"a", "a"}}}, 1},
{"test5", args{grp: Group{People: []Answers{"b"}}}, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := countUnanomAnswers(tt.args.grp); got != tt.want {
t.Errorf("countUnanomAnswers() = %v, want %v", got, tt.want)
}
})
}
}
<file_sep>/day8/data.go
package main
var testinput = []string{
"nop +0",
"acc +1",
"jmp +4",
"acc +3",
"jmp -3",
"acc -99",
"acc +1",
"jmp -4",
"acc +6",
}
var input = []string{
"acc +40",
"jmp +187",
"acc +47",
"acc +20",
"acc -12",
"jmp +225",
"nop +488",
"acc +13",
"nop +462",
"jmp +374",
"acc +15",
"acc +42",
"jmp +116",
"acc +23",
"nop +216",
"acc -15",
"jmp +398",
"jmp +103",
"acc +17",
"acc +7",
"jmp +571",
"jmp +1",
"jmp +217",
"acc +7",
"jmp +1",
"acc +35",
"jmp +257",
"acc +24",
"nop +20",
"jmp +309",
"acc +2",
"acc -15",
"acc -13",
"nop +457",
"jmp +19",
"acc +46",
"acc +45",
"acc +35",
"jmp +295",
"acc -15",
"acc +49",
"acc +22",
"jmp +400",
"jmp +202",
"nop -38",
"jmp +381",
"acc +0",
"jmp +137",
"acc +27",
"jmp +196",
"acc +46",
"acc -15",
"jmp +348",
"jmp +457",
"acc +50",
"acc +8",
"jmp +452",
"acc -14",
"nop +321",
"acc +39",
"jmp +273",
"acc -9",
"jmp +413",
"acc +32",
"jmp +64",
"acc +18",
"jmp +152",
"acc -4",
"acc +9",
"acc +10",
"acc -1",
"jmp +433",
"acc +40",
"jmp -55",
"acc +28",
"nop +279",
"jmp +145",
"acc +24",
"nop +416",
"acc +45",
"jmp +45",
"acc +0",
"acc +49",
"acc -14",
"jmp +44",
"acc +17",
"acc +18",
"nop +224",
"acc +3",
"jmp +261",
"jmp -84",
"acc -11",
"acc +29",
"acc +42",
"jmp -13",
"acc -5",
"jmp +210",
"acc +26",
"acc -19",
"acc -19",
"jmp -82",
"acc +29",
"acc +31",
"acc -4",
"jmp +53",
"acc +46",
"jmp +139",
"acc +45",
"acc +30",
"jmp +1",
"jmp +418",
"jmp +248",
"acc +24",
"acc +15",
"acc +34",
"acc +17",
"jmp +52",
"acc +23",
"acc +18",
"jmp +65",
"jmp +1",
"acc +37",
"acc +25",
"jmp +385",
"jmp +281",
"nop +345",
"jmp -25",
"jmp +149",
"acc +21",
"acc +28",
"acc +15",
"jmp -74",
"jmp +179",
"jmp +287",
"acc +14",
"acc -3",
"acc -7",
"jmp -9",
"acc +17",
"acc -8",
"jmp +344",
"jmp +1",
"acc +36",
"acc -16",
"acc -17",
"jmp -82",
"jmp +1",
"acc +41",
"acc -8",
"acc +27",
"jmp +381",
"acc -10",
"nop -71",
"acc +23",
"nop +377",
"jmp -125",
"jmp +319",
"nop +119",
"nop +309",
"nop +195",
"jmp +307",
"acc +8",
"acc +31",
"jmp +1",
"acc -15",
"jmp +398",
"jmp +265",
"jmp -55",
"nop +143",
"jmp -36",
"acc +38",
"nop -38",
"jmp +298",
"acc -17",
"acc +39",
"acc -13",
"jmp -38",
"acc +23",
"jmp +133",
"acc +23",
"jmp -90",
"acc +14",
"jmp +1",
"jmp +100",
"nop +230",
"jmp +346",
"acc +36",
"jmp +14",
"jmp +126",
"jmp -32",
"jmp -142",
"acc +25",
"jmp +146",
"nop +118",
"acc -3",
"jmp +1",
"acc -8",
"jmp +101",
"nop +277",
"acc +27",
"jmp +328",
"acc -11",
"acc +17",
"nop +135",
"jmp +196",
"acc -9",
"jmp +39",
"nop +110",
"acc +14",
"nop +3",
"jmp +17",
"jmp +220",
"acc +17",
"jmp +5",
"acc +18",
"acc +39",
"acc -12",
"jmp -204",
"jmp +317",
"acc +37",
"jmp +222",
"nop +146",
"nop +248",
"jmp +182",
"acc +48",
"acc -13",
"jmp +174",
"jmp +342",
"nop -189",
"jmp +324",
"acc +35",
"acc +25",
"acc +21",
"jmp -152",
"nop -92",
"acc -3",
"acc -15",
"acc +30",
"jmp -157",
"acc -17",
"acc +37",
"acc +7",
"acc +5",
"jmp -225",
"jmp -177",
"acc +21",
"jmp +244",
"acc +42",
"acc -4",
"jmp -116",
"nop +225",
"nop -63",
"acc +20",
"jmp +195",
"acc +20",
"acc +21",
"jmp +228",
"acc +16",
"acc -8",
"acc +12",
"nop +188",
"jmp +9",
"acc +6",
"acc -13",
"acc +36",
"jmp -86",
"jmp -253",
"nop -60",
"acc +25",
"jmp -174",
"acc +10",
"nop -114",
"jmp -65",
"jmp +1",
"acc +24",
"jmp -150",
"acc +27",
"jmp -47",
"acc +50",
"nop -58",
"acc -17",
"acc -16",
"jmp -170",
"jmp -104",
"jmp -177",
"acc +46",
"jmp +106",
"jmp -206",
"acc +2",
"acc +10",
"acc +17",
"nop -107",
"jmp -126",
"jmp +1",
"acc +50",
"acc -14",
"acc +29",
"jmp -234",
"nop +144",
"acc +43",
"acc +34",
"jmp +221",
"jmp +1",
"nop +97",
"acc +39",
"jmp -60",
"acc +44",
"jmp -240",
"acc +11",
"acc +36",
"jmp -71",
"acc -5",
"jmp +149",
"jmp +54",
"acc +38",
"jmp +44",
"jmp -165",
"acc +14",
"jmp -134",
"acc +3",
"acc +22",
"nop +46",
"acc -12",
"jmp -57",
"acc +49",
"acc +24",
"acc +16",
"jmp +27",
"acc +6",
"nop -5",
"acc +45",
"acc +34",
"jmp -175",
"jmp -76",
"acc +3",
"acc +15",
"acc -19",
"jmp +1",
"nop -226",
"acc -2",
"jmp -55",
"jmp -284",
"acc +2",
"jmp +1",
"jmp +15",
"acc +11",
"acc +12",
"acc -1",
"acc +2",
"jmp +179",
"acc +19",
"acc +17",
"jmp -329",
"jmp -272",
"jmp -104",
"acc +41",
"nop +189",
"acc +47",
"jmp -88",
"acc +4",
"acc +16",
"acc +43",
"acc +25",
"jmp +71",
"acc -2",
"acc +45",
"jmp -173",
"jmp +1",
"acc +44",
"acc +33",
"jmp -53",
"acc +45",
"acc +9",
"acc +0",
"acc +12",
"jmp +178",
"jmp -100",
"acc +14",
"jmp -67",
"acc +42",
"jmp +201",
"acc +30",
"jmp -319",
"nop -4",
"nop -211",
"acc -3",
"nop -165",
"jmp -175",
"acc +12",
"acc -10",
"acc -14",
"jmp -53",
"acc -13",
"nop -143",
"jmp +159",
"acc -5",
"nop +18",
"nop -5",
"acc +13",
"jmp -248",
"jmp +114",
"acc +10",
"nop -396",
"nop -246",
"jmp +16",
"acc -3",
"acc +33",
"nop +174",
"acc +48",
"jmp -289",
"nop +98",
"acc +18",
"acc -17",
"jmp -137",
"jmp +1",
"acc +34",
"acc +36",
"jmp -216",
"acc +11",
"jmp -102",
"acc +10",
"jmp +10",
"acc +26",
"acc +35",
"acc -9",
"jmp -83",
"acc +15",
"nop -397",
"jmp -140",
"nop +111",
"jmp +139",
"jmp -165",
"acc +16",
"jmp -343",
"acc +8",
"acc +35",
"acc -17",
"acc -8",
"jmp +29",
"acc +50",
"nop -256",
"jmp -268",
"jmp +132",
"acc +13",
"acc +38",
"acc -6",
"acc -7",
"jmp -327",
"acc -8",
"jmp -256",
"nop -139",
"acc +30",
"jmp -60",
"acc -1",
"acc +11",
"jmp -216",
"acc -12",
"nop -390",
"acc +17",
"acc +39",
"jmp +101",
"acc +28",
"jmp +1",
"acc -7",
"acc -18",
"jmp -277",
"jmp -90",
"acc -10",
"jmp -326",
"jmp -368",
"nop -396",
"jmp -320",
"acc +42",
"acc +3",
"jmp -430",
"acc +47",
"acc +11",
"acc +19",
"acc +41",
"jmp -354",
"acc +30",
"acc +7",
"nop -106",
"jmp -420",
"acc +22",
"acc -15",
"jmp -296",
"acc -7",
"acc +48",
"jmp -19",
"jmp -148",
"acc +10",
"jmp +1",
"jmp +17",
"nop -273",
"acc +42",
"acc -4",
"nop -130",
"jmp +47",
"nop -436",
"acc -7",
"jmp +1",
"acc +42",
"jmp -330",
"acc +35",
"jmp +56",
"acc -19",
"jmp -440",
"jmp -335",
"jmp -279",
"nop -390",
"jmp +74",
"acc -5",
"jmp -456",
"acc +38",
"acc +3",
"jmp +47",
"acc +50",
"acc +26",
"acc +46",
"acc -7",
"jmp -491",
"acc -4",
"acc -7",
"acc +14",
"nop -105",
"jmp -487",
"jmp -326",
"nop -360",
"jmp -378",
"jmp -285",
"acc +46",
"jmp -190",
"acc +10",
"jmp -346",
"acc +49",
"jmp -492",
"acc -9",
"acc -17",
"jmp -147",
"acc +20",
"jmp -217",
"nop -183",
"acc +35",
"jmp -268",
"nop -51",
"jmp +1",
"jmp -440",
"acc +22",
"acc +24",
"jmp +1",
"acc +26",
"jmp -451",
"acc -14",
"acc +48",
"acc +3",
"jmp -363",
"acc +21",
"acc +24",
"acc +36",
"jmp -418",
"jmp -108",
"jmp -323",
"jmp +20",
"acc +1",
"acc +21",
"nop -212",
"acc -3",
"jmp -338",
"acc +36",
"acc -19",
"jmp -192",
"acc +49",
"jmp -380",
"acc -12",
"acc +14",
"acc +38",
"acc +4",
"jmp -228",
"acc +2",
"jmp -197",
"jmp -41",
"jmp -265",
"jmp -113",
"jmp -459",
"jmp +1",
"acc +38",
"jmp -79",
"acc +16",
"nop -456",
"jmp -129",
"acc +12",
"acc +29",
"nop -575",
"acc -7",
"jmp +1",
}
<file_sep>/day4/main.go
package main
import (
"fmt"
"regexp"
"strings"
)
type Passport struct {
fields map[string]string
}
type Field struct {
Field string
Req bool
RegMatch *regexp.Regexp
}
func main() {
passports := processData(input)
fmt.Println("Part1:")
p1Fields := []Field{
{"byr", true, nil},
{"iyr", true, nil},
{"eyr", true, nil},
{"hgt", true, nil},
{"hcl", true, nil},
{"ecl", true, nil},
{"pid", true, nil},
{"cid", false, nil},
}
fmt.Println(countValid(passports, p1Fields))
fmt.Println("Part2:")
p2Fields := []Field{
{"byr", true, regexp.MustCompile(`^(19[2-9][0-9])|(200[0-2])$`)},
{"iyr", true, regexp.MustCompile(`^(201[0-9])|(2020)$`)},
{"eyr", true, regexp.MustCompile(`^(202[0-9])|(2030)$`)},
{"hgt", true, regexp.MustCompile(`^((1[5-8][0-9])cm$|^(19[0-3])cm$)|^((59|6[0-9]|7[0-6])in$)`)},
{"hcl", true, regexp.MustCompile(`^#[0-9a-f]{6}$`)},
{"ecl", true, regexp.MustCompile(`^(amb|blu|brn|gry|grn|hzl|oth)$`)},
{"pid", true, regexp.MustCompile(`^[0-9]{9}$`)},
{"cid", false, nil},
}
fmt.Println(countValid(passports, p2Fields))
}
func countValid(passports []Passport, fieldset []Field) int {
valid := 0
for _, p := range passports {
if isValid(p, fieldset) {
valid++
}
}
return valid
}
func isValid(p Passport, fieldset []Field) bool {
for _, f := range fieldset {
if f.Req {
if value, found := p.fields[f.Field]; !found {
return false
} else {
if f.RegMatch != nil && !f.RegMatch.MatchString(value) {
fmt.Printf("%s:%s\n", f.Field, value)
return false
}
}
}
}
return true
}
func processData(input []string) []Passport {
var (
p Passport
)
passports := make([]Passport, 0)
p.fields = make(map[string]string)
for _, l := range input {
if len(l) == 0 {
if len(p.fields) > 0 {
passports = append(passports, p)
}
p.fields = make(map[string]string)
continue
}
for _, element := range strings.Split(l, " ") {
if parts := strings.SplitN(element, ":", 2); len(parts) > 0 {
if _, exists := p.fields[parts[0]]; exists {
fmt.Printf("duplicate field %s\n", parts[0])
}
p.fields[parts[0]] = parts[1]
} else {
fmt.Printf("syntax error: %s\n", element)
}
}
}
if len(p.fields) > 0 {
passports = append(passports, p)
}
fmt.Printf("Read %d passports, first PID: %s, last PID: %s\n", len(passports), passports[0].fields["pid"],
passports[len(passports)-1].fields["pid"])
return passports
}
<file_sep>/day3/main.go
package main
import "fmt"
func main() {
fmt.Println("Part1:")
fmt.Println(countTrees(3, 1))
fmt.Println("\nPart2:")
fmt.Println(
countTrees(1, 1) *
countTrees(3, 1) *
countTrees(5, 1) *
countTrees(7, 1) *
countTrees(1, 2))
}
func countTrees(slopeRight, slopeDown int) int {
var (
r, c, trees int
)
c = slopeRight
for r = slopeDown; r < len(input); r += slopeDown {
l := input[r]
cPrime := c % len(l)
if l[cPrime] == '#' {
trees++
}
c += slopeRight
}
return trees
}
<file_sep>/README.md
# goaoc2020
Advent Of Code 2020 Solutions in Go
<file_sep>/day9/main.go
package main
import (
"fmt"
"math"
)
func main() {
n := findMissingPair(testinput, 5)
min, max := findSumRange(testinput, n)
fmt.Printf("%d, %d, %d\n", n, min, max)
fmt.Println(findMissingPair(input, 25))
}
func findMissingPair(list []int, preamble int) int {
idx := preamble
for idx < len(list) {
found := findSumPair(list[idx-preamble:idx], list[idx])
if !found {
return list[idx]
}
idx++
}
return -1
}
func findSumPair(list []int, sum int) bool {
for i := 0; i < len(list)-1; i++ {
for j := i + 1; j < len(list); j++ {
if list[i]+list[j] == sum {
return true
}
}
}
return false
}
func findSumRange(list []int, sum int) (smallest, largest int) {
for i := 0; i < len(list)-1; i++ {
t := list[i]
for j := i + 1; j < len(list); j++ {
t += list[j]
if t == sum {
return minmax(list[i:j])
} else if t > sum {
break
}
}
}
return 0, 0
}
func minmax(list []int) (int, int) {
min, max := int(math.MaxInt64), int(math.MinInt64)
for _, n := range list {
if n < min {
min = n
}
if n > max {
max = n
}
}
return min, max
}
<file_sep>/day1/main.go
package main
import "fmt"
func main() {
part1()
part2()
}
func part1() {
for i := 0; i < len(input); i++ {
for j := i + 1; j < len(input); j++ {
if input[i]+input[j] == 2020 {
fmt.Printf("%d + %d = 2020, result=%d\n", input[i], input[j], input[i]*input[j])
}
}
}
}
func part2() {
for i := 0; i < len(input); i++ {
for j := i + 1; j < len(input); j++ {
for k := j + 1; k < len(input); k++ {
if input[i]+input[j]+input[k] == 2020 {
fmt.Printf("%d + %d + %d = 2020, result=%d\n",
input[i], input[j], input[k], input[i]*input[j]*input[k])
}
}
}
}
}
| b03e27d74cef69aa2f0a14e9bcda78dd8a0e4116 | [
"Markdown",
"Go"
] | 16 | Go | JJCinAZ/goaoc2020 | 30c52ff9dd053c4fc7e45564306f60f769679148 | 063184ebd86dd773ad2bd7cce76e38bbdb9da115 | |
refs/heads/master | <repo_name>MiUishadow/magnum-integration<file_sep>/package/ci/travis-desktop.sh
#!/bin/bash
set -ev
# Corrade
git clone --depth 1 git://github.com/mosra/corrade.git
cd corrade
mkdir build && cd build
cmake .. \
-DCMAKE_INSTALL_PREFIX=$HOME/deps \
-DCMAKE_INSTALL_RPATH=$HOME/deps/lib \
-DCMAKE_BUILD_TYPE=Release \
-DWITH_INTERCONNECT=OFF
make -j install
cd ../..
# Magnum
git clone --depth 1 git://github.com/mosra/magnum.git
cd magnum
mkdir build && cd build
cmake .. \
-DCMAKE_INSTALL_PREFIX=$HOME/deps \
-DCMAKE_INSTALL_RPATH=$HOME/deps/lib \
-DCMAKE_BUILD_TYPE=Release \
-DWITH_AUDIO=OFF \
-DWITH_DEBUGTOOLS=OFF \
-DWITH_MESHTOOLS=OFF \
-DWITH_PRIMITIVES=OFF \
-DWITH_SCENEGRAPH=ON \
-DWITH_SHADERS=$WITH_BULLET \
-DWITH_SHAPES=ON \
-DWITH_TEXT=OFF \
-DWITH_TEXTURETOOLS=OFF \
-DWITH_WINDOWLESS${PLATFORM_GL_API}APPLICATION=ON
make -j install
cd ../..
mkdir build && cd build
cmake .. \
-DCMAKE_CXX_FLAGS=$COVERAGE \
-DCMAKE_PREFIX_PATH="$HOME/deps" \
-DCMAKE_INSTALL_PREFIX=$HOME/deps \
-DCMAKE_INSTALL_RPATH=$HOME/deps/lib \
-DCMAKE_BUILD_TYPE=Release \
-DWITH_BULLET=$WITH_BULLET \
-DWITH_OVR=OFF \
-DBUILD_TESTS=ON \
-DBUILD_GL_TESTS=ON
make -j${JOBS_LIMIT}
CORRADE_TEST_COLOR=ON ctest -V -E GLTest
| 4a52734c68893a3cad939ddc527dd06010f2112b | [
"Shell"
] | 1 | Shell | MiUishadow/magnum-integration | 2d154fae602e013f7fddf0232a034dfc680d8556 | 07ebf980e50a6a22db942f2cc5cdeb37a0b95221 | |
refs/heads/master | <repo_name>cazwazacz/thermostat<file_sep>/public/src/Thermostat.js
var SETTINGS = {
initialTemp: 20,
step: 1,
min: 10,
PSMax: 25,
max: 32,
lowUsage: 18,
mediumUsage: 25
}
function Thermostat (settings = SETTINGS) {
this.settings = settings;
this._temp = this.settings.initialTemp;
this._isPowerSavingMode = true;
}
Thermostat.prototype.temp = function () {
return this._temp;
};
Thermostat.prototype.up = function () {
this._temp = Math.min(this._temp + this.settings.step, this.max());
};
Thermostat.prototype.down = function () {
this._temp = Math.max(this._temp - this.settings.step, this.min());
};
Thermostat.prototype.min = function () {
return this.settings.min;
};
Thermostat.prototype.isPowerSavingMode = function () {
return this._isPowerSavingMode;
};
Thermostat.prototype.max = function () {
return this.isPowerSavingMode() ? this.settings.PSMax : this.settings.max;
};
Thermostat.prototype.reset = function () {
this._temp = this.settings.initialTemp;
};
Thermostat.prototype.usage = function () {
if (this._temp < this.settings.lowUsage) {
return "low-usage";
} else if (this._temp < this.settings.mediumUsage) {
return "medium-usage";
} else {
return "high-usage";
}
};
Thermostat.prototype.switchMode = function () {
this._isPowerSavingMode = !this._isPowerSavingMode;
this._temp = Math.min(this._temp, this.settings.PSMax);
};
<file_sep>/public/index.js
$(document).ready(function() {
function postingTemp (temp) {
$.post('/temperature', {temperature: temp}, function(data) {
});
}
var thermostat = new Thermostat();
var url = 'http://api.openweathermap.org/data/2.5/weather';
var key = 'f93adfeb902ecab387b8b3b6b636cf26';
function assemble_url(city, key) {
return url + '?q=' + city + '&appid=' + key;
};
$.ajaxSetup({
'error': function() { alert('Chosen city does not exist') }
});
function getLocalTemp (city = 'London') {
$.getJSON(assemble_url(city, key), function(data) {
$("#localTemp").html(data.main.temp);
$("#cityName").html(data.name);
});
};
function update_ps_color() {
var color = thermostat.isPowerSavingMode() ? "green" : "red";
$("#psm").css("background-color", color);
};
function update_ps_text() {
var text = thermostat.isPowerSavingMode() ? "On" : "Off";
$("#psm_state").html(text);
};
function getTempFromApi() {
$.get('/temperature', function(data) {
if (data.temperature === null) {
$('#temp').html(thermostat.tempe);
} else {
$('#temp').html(data.temperature);
}
});
}
function getCityFromApi() {
$.get('/temperature', function(data) {
if (data.city === null) {
$('#cityName').html('London');
getLocalTemp();
} else {
$('#cityName').html(data.city);
getLocalTemp(data.city);
}
});
}
getTempFromApi();
getCityFromApi();
function update_temperature() {
$("#temp").html(thermostat.temp());
};
function usageColor() {
$('#temp').removeClass();
$('#temp').addClass(thermostat.usage());
}
function update() {
update_temperature();
update_ps_text();
update_ps_color();
usageColor();
postingTemp(thermostat.temp());
};
function postCity(city) {
$.post('/city', {city: city}, function(data) {
})
}
update();
$('#city_button').click(function() {
var city = $('#city').val();
getLocalTemp(city);
postCity(city);
});
$("#down").click(function() {
thermostat.down();
});
$("#up").click(function() {
thermostat.up();
});
$("#reset").click(function() {
thermostat.reset();
});
$("#psm").click(function() {
thermostat.switchMode();
});
$("button").click(update);
});
| f56971e1b189e805286d7496a5604a532c64cbff | [
"JavaScript"
] | 2 | JavaScript | cazwazacz/thermostat | 8a8fe8fc684176f3ad82eb2c6c1a9049ed92c999 | 727551c8f520d0083e89a7cd14c8f643a5c2a7ae | |
refs/heads/master | <file_sep>package com.gearcalc.entities;
import lombok.ToString;
import javax.persistence.*;
@Entity
@ToString
public class Wheel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "width")
private double width;
@Column(name = "profile")
private double profile;
@Column(name = "diameter")
private int diameterInInches;
public Wheel() {
}
public Wheel(int width, int profile, int diameterInInches) {
this.width = width;
this.profile = profile;
this.diameterInInches = diameterInInches;
}
public double getWheelCircumference() {
return 2 * Math.PI * (this.getTotalWheelDiameter() / 2);
}
public double getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public double getProfile() {
return profile;
}
public void setProfile(int profile) {
this.profile = profile;
}
public int getDiameterInInches() {
return diameterInInches;
}
public void setDiameterInInches(int diameterInInches) {
this.diameterInInches = diameterInInches;
}
private double getTotalWheelDiameter() {
double totalProfile = this.getWidth() * (this.getProfile() / 100);
double diamaterInMm = this.getDiameterInInches() * 2.56;
return (totalProfile * 2) + (diamaterInMm * 10);
}
}
<file_sep>package com.gearcalc.entities;
import javax.persistence.*;
@Entity
@Table(name = "gearbox")
public class GearBox {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private double first;
private double second;
private double third;
private double fourth;
private double fifth;
private double sixth;
public GearBox() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getFirst() {
return first;
}
public void setFirst(double first) {
this.first = first;
}
public double getSecond() {
return second;
}
public void setSecond(double second) {
this.second = second;
}
public double getThird() {
return third;
}
public void setThird(double third) {
this.third = third;
}
public double getFourth() {
return fourth;
}
public void setFourth(double fourth) {
this.fourth = fourth;
}
public double getFifth() {
return fifth;
}
public void setFifth(double fifth) {
this.fifth = fifth;
}
public double getSixth() {
return sixth;
}
public void setSixth(double sixth) {
this.sixth = sixth;
}
}
<file_sep>package com.gearcalc.service;
import com.gearcalc.GearRatioCalculatorApplication;
import com.gearcalc.common.CarBuilderFactory;
import com.gearcalc.entities.Car;
import com.gearcalc.dto.SpeedResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GearRatioCalculatorApplication.class)
public class CarServiceTest {
@Autowired
private CarService carService;
private Car car;
@Before
public void init() {
car = CarBuilderFactory.buildE46328ci();
}
@Test
public void testVmaxPerGearValuesShouldBeCorrect() {
SpeedResponse speedResponse = carService.getVmaxPerGear(car);
assertEquals(63.5, speedResponse.getSpeedPerGearMap().get("First"), 0.5);
assertEquals(107.3, speedResponse.getSpeedPerGearMap().get("Second"), 0.5);
assertEquals(161.0, speedResponse.getSpeedPerGearMap().get("Third"), 0.5);
assertEquals(215.5, speedResponse.getSpeedPerGearMap().get("Fourth"), 0.5);
assertEquals(267.3, speedResponse.getSpeedPerGearMap().get("Fifth"), 0.5);
assertNotNull(speedResponse.getSpeedPerGearMap().get("Sixth"));
}
}<file_sep>package com.gearcalc.repositories;
import com.gearcalc.entities.GearBox;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface GearboxRepository extends JpaRepository<GearBox, Integer> {
}
<file_sep>package com.gearcalc.service;
import com.gearcalc.entities.Wheel;
import com.gearcalc.repositories.WheelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class WheelService {
private WheelRepository wheelRepository;
@Autowired
public WheelService(WheelRepository wheelRepository) {
this.wheelRepository = wheelRepository;
}
public List<Wheel> getAllWheels() {
return wheelRepository.findAll();
}
public Wheel getWheelById(int wheelId) {
return wheelRepository.getOne(wheelId);
}
}
<file_sep>package com.gearcalc.domain;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class VmaxOnGearParamsTest {
private VmaxOnGearParams params;
@Before
public void init() {
params = new VmaxOnGearParams(6500, 1.0, 2.93, 2001.2);
}
@Test
public void getVmaxOnGear() {
assertEquals(266.3, params.getVmaxOnGear(), 0.5);
}
}<file_sep>package com.gearcalc.common;
import com.gearcalc.entities.Car;
import com.gearcalc.entities.GearBox;
import com.gearcalc.entities.Wheel;
public class CarBuilderFactory {
private CarBuilderFactory() {}
public static Car buildE46328ci() {
Car e46 = new Car();
e46.setCarType("COUPE");
e46.setFinalDriveRatio(2.93);
e46.setId(1);
e46.setModel("328ci");
e46.setPlatform("E46");
e46.setRedLine(6500);
e46.setTransmissionType("MANUAL");
e46.setWheel(buildWheel());
e46.setGearBox(buildGearbox());
return e46;
}
public static Wheel buildWheel() {
return new Wheel(255, 35, 18);
}
public static GearBox buildGearbox() {
GearBox gearBox = new GearBox();
gearBox.setId(1);
gearBox.setFirst(4.21);
gearBox.setSecond(2.49);
gearBox.setThird(1.66);
gearBox.setFourth(1.24);
gearBox.setFifth(1.00);
gearBox.setSixth(0);
return gearBox;
}
}
<file_sep>package com.gearcalc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan(basePackages = "com.gearcalc")
@EnableJpaRepositories(basePackages = "com.gearcalc.repositories")
@EntityScan(basePackages = "com.gearcalc.entities")
public class GearRatioCalculatorApplication {
public static void main(String[] args) {
SpringApplication.run(GearRatioCalculatorApplication.class, args);
}
}
<file_sep>package com.gearcalc.repositories;
import com.gearcalc.entities.Wheel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface WheelRepository extends JpaRepository<Wheel, Integer> {
}
<file_sep>package com.gearcalc.domain;
public class VmaxOnGearParams {
private int redLine;
private double gearRatio;
private double finalRatio;
private double wheelCircumference;
public VmaxOnGearParams(int redLine, double gearRatio, double finalRatio, double wheelCircumference) {
this.redLine = redLine;
this.gearRatio = gearRatio;
this.finalRatio = finalRatio;
this.wheelCircumference = wheelCircumference;
}
public double getVmaxOnGear() {
return (this.redLine / (this.gearRatio * this.finalRatio) * (this.wheelCircumference / 1000) * 60) / 1000;
}
}
<file_sep>package com.gearcalc.rest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CommonRestControllerTest {
@Autowired
private MockMvc mockMvc;
@Value("classpath:samples/sampleCircumference.json")
private Resource wheelResource;
@Value("classpath:samples/sampleCalculateSpeed.json")
private Resource carResource;
private String wheelJson;
private String carJson;
@Before
public void init() throws IOException {
File wheelResourceFile = wheelResource.getFile();
File carResourceFile = carResource.getFile();
wheelJson = new String(Files.readAllBytes(wheelResourceFile.toPath()));
carJson = new String(Files.readAllBytes(carResourceFile.toPath()));
}
@Test
public void getWheelCircumference() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/api/wheel/circumference")
.accept(MediaType.APPLICATION_JSON).content(wheelJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void getVmaxPerGear() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/api/calculateSpeed")
.accept(MediaType.APPLICATION_JSON).content(carJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
} | 729ecb070cf3e88b85d06c2b394fb172b358dfc8 | [
"Java"
] | 11 | Java | Inaimad/gear-ratio-calculator | 8825efcf1e49adb35ed95309d400b1ef4ef7447e | 3c921ba3e04384a760fd48350e3d37e63435328b | |
refs/heads/master | <file_sep>//Stopping a programme from crashing.
using System;
class TryIt
{
public static void Main()
{
//dataType array, arrayName, =new dataType array of 5.
int[] mikesArray = new int[5];
try //start of error testing.
{
//loops ctr 10x
for (int ctr=0; ctr<10; ctr++)
{
//array counter is asigned to ctr.
mikesArray[ctr] = ctr;
}
}
catch(Exception e) //testing ends and error is caught.
{
Console.WriteLine("The exception was caught Mike: {0}", e);
}
finally
{
Console.WriteLine("Last thing to run.");
}
Console.ReadKey(true);
}
}
<file_sep># C-Sharp-TryCatch-Errors-Block
//Stopping my C Sharp Programme from crashing using Try & Catch.
| 4a83884dee8b440fe5aed75fdf67ddb115cbac02 | [
"Markdown",
"C#"
] | 2 | C# | m2lawrence/C-Sharp-TryCatch-Errors-Block | 7350ebb00d9aae014bb0053361a447e84e3b69e2 | f11c472b95333f3025d932cfa77e770572d91cd4 | |
refs/heads/master | <repo_name>fredThem/rails-mister-cocktail<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'json'
require 'open-uri'
# thecocktaildb API
# https://www.thecocktaildb.com/api.php
# Lookup full cocktail details by id
# https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=11007
# Search cocktail by name
# https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita
# Search by ingredient
# https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=Gin
# https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=Vodka
# Filter by Category
# https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Ordinary_Drink
# https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail
def serialize(url)
data_serialized = open(url).read
data = JSON.parse(data_serialized)
end
def drinks_categories
categories = []
puts 'listing categories'
url = 'https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list'
serialized_categories = serialize(url)
# puts serialized_categories
serialized_categories['drinks'].each do |category|
# byebug
value = category.values[0]
categories << value unless value.empty?
end
categories
# ["Ordinary Drink", "Cocktail", "Milk / Float / Shake", "Other/Unknown", "Cocoa", "Shot", "Coffee / Tea", "Homemade Liqueur", "Punch / Party Drink", "Beer", "Soft Drink / Soda"]
end
def seed_ingredients
puts 'Cleaning database...'
Ingredient.delete_all
url = 'https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list'
drink = serialize(url)
drink['drinks'].each do |i|
ingredient = Ingredient.create!(
name: i['strIngredient1']
)
puts ingredient.name
end
end
def cocktails_by_category
puts 'cleaning up cocktail'
Cocktail.delete_all
drinks_categories.each do |category|
# p category.class
serialized_drinks = serialize("https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=#{category.sub(' ', '_')}")
serialized_drinks['drinks'].each do |drink|
# byebug
cocktail = Cocktail.create!(
name: (drink['strDrink']),
img_url: (drink['strDrinkThumb']),
category: category
)
puts cocktail
end
end
# byebug
# puts @cocktails.length
end
def seed_doses
p Cocktail.first
url = 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s='
# doses = serialize(url)
Cocktail.all.each do |cocktail|
cocktail.doses.delete_all
# byebug
api_url = url + cocktail.name
serialized_cocktail = serialize(api_url)
serialized_cocktail['drinks'].each do |attribute|
p cocktail
index = 1
15.times do
# byebug
measure = attribute["strMeasure#{index}"]
unless measure.nil?
ingredient = attribute["strIngredient#{index}"]
p "#{index}) #{measure} #{ingredient}"
ingredient_id = Ingredient.find_or_create_by(name: ingredient).id
new_dose = {
cocktail_id: cocktail.id,
ingredient_id: ingredient_id,
description: measure
}
dose = cocktail.doses.create!(new_dose)
# byebug
# p dose
# new_dose.save!
end
index += 1
end
index = 1
# byebug
end
# cocktail << value unless value.empty?
# byebug
end
end
# cocktails_by_category
# seed_ingredients
seed_doses<file_sep>/config/routes.rb
Rails.application.routes.draw do
# get 'doses/new'
# get 'doses/create'
# get 'doses/destroy'
root 'cocktails#index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :cocktails, only: %i[index create new show] do
resources :doses, only: %i[new create]
end
resources :doses, only: %i[destroy]
end
<file_sep>/app/models/ingredient.rb
class Ingredient < ApplicationRecord
# belongs_to :cocktail
has_many :doses
validates_presence_of :name
validates_uniqueness_of :name
end
| 951fc08c8dc07c2d9bbb24ae56ccb9fbcc818765 | [
"Ruby"
] | 3 | Ruby | fredThem/rails-mister-cocktail | d7295e1fe449ee7fff61f68dd8bd7110d3b604e9 | e7a098aa9f3712e99aaca5cd041e755b2c5aa777 | |
refs/heads/master | <repo_name>carlosjgg22/LoginUsuario<file_sep>/backend/src/main/java/com/neoris/modelo/Usuario.java
package com.neoris.modelo;
public class Usuario {
private int idUsuario;
private String usuario;
private String password;
private String email;
private int privilegio;
public Usuario(int idUsuario, String usuario, String password, String email, int privilegio) {
super();
this.idUsuario = idUsuario;
this.usuario = usuario;
this.password = <PASSWORD>;
this.email = email;
this.privilegio = privilegio;
}
public Usuario() {
super();
}
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPrivilegio() {
return privilegio;
}
public void setPrivilegio(int privilegio) {
this.privilegio = privilegio;
}
@Override
public String toString() {
return "Usuario [idUsuario=" + idUsuario + ", usuario=" + usuario + ", password=" + <PASSWORD> + ", email="
+ email + ", privilegio=" + privilegio + "]";
}
}
| 92936360b3f803db95ea2698e99d49552311a3a4 | [
"Java"
] | 1 | Java | carlosjgg22/LoginUsuario | e4304e89f71521104ca6f83626351ee3cb5726eb | 713aa1857f48ad9d0bf28496c34d5e810402f859 | |
refs/heads/master | <repo_name>sunpig/sunpig-mt-to-wp<file_sep>/copy-entry-keywords.sql
/*
The quickreviews blog (mt_blog_id=12, wp blog id = 4) used an entry-keywords plugin for storing
key-value data for an entry. In WP, this data is stored in the wp_postmeta table.
There are only three keys: imdb, amazon, and image
*/
insert into wp_4_postmeta (
post_id,
meta_key,
meta_value
)
select
entry_id,
'imdb',
substring(
entry_keywords
FROM
instr(lower(entry_keywords), 'imdb') + length('imdb') + 1
FOR
coalesce(
nullif(locate(' ', lower(entry_keywords), instr(lower(entry_keywords), 'imdb')), 0),
nullif(locate("\n", lower(entry_keywords), instr(lower(entry_keywords), 'imdb')), 0),
length(entry_keywords) + 1
) - (instr(lower(entry_keywords), 'imdb') + length('imdb') + 1)
)
from
mt_entry
where
entry_blog_id = 12
and entry_keywords like '%imdb=%';
insert into wp_4_postmeta (
post_id,
meta_key,
meta_value
)
select
entry_id,
'amazon',
substring(
entry_keywords
FROM
instr(lower(entry_keywords), 'amazon') + length('amazon') + 1
FOR
coalesce(
nullif(locate(' ', lower(entry_keywords), instr(lower(entry_keywords), 'amazon')), 0),
nullif(locate("\n", lower(entry_keywords), instr(lower(entry_keywords), 'amazon')), 0),
length(entry_keywords) + 1
) - (instr(lower(entry_keywords), 'amazon') + length('amazon') + 1)
)
from
mt_entry
where
entry_blog_id = 12
and entry_keywords like '%amazon=%';
insert into wp_4_postmeta (
post_id,
meta_key,
meta_value
)
select
entry_id,
'image',
substring(
entry_keywords
FROM
instr(lower(entry_keywords), 'image') + length('image') + 1
FOR
coalesce(
nullif(locate(' ', lower(entry_keywords), instr(lower(entry_keywords), 'image')), 0),
nullif(locate("\n", lower(entry_keywords), instr(lower(entry_keywords), 'image')), 0),
length(entry_keywords) + 1
) - (instr(lower(entry_keywords), 'image') + length('image') + 1)
)
from
mt_entry
where
entry_blog_id = 12
and entry_keywords like '%image=%';
<file_sep>/database-charset.md
# Database Charsets
The mt_* tables in our database use the latin1 charset, but the wp_* tables use
the utf8 charset. To make things more fun, the data in the mt_* tables is not
consistently encoded: some rows use utf8 stored in the db as latin1, while
other rows genuinely are latin1 stored as latin1. This is visible if I do a
`select entry_text from mt_entry` on the database: sometimes a GBP character
will come back as '£', and sometimes as '£'.
For *most* rows, this conversion will take the utf8 text in the latin1 mt_* tables,
and turn it into utf8 text for the wp_* tables:
```
select
convert(cast(convert(entry_text using latin1) as binary) using utf8)
from
mt_entry;
```
But for some rows it goes horribly wrong, truncating the text at the point where
it encounters an invalid character.
Step 1: Identify problematic rows with badly encoded characters:
```
select
entry_id,
entry_blog_id
from
mt_entry
where
convert(cast(convert(entry_text using latin1) as binary) using utf8) <> entry_text
or convert(cast(convert(entry_text_more using latin1) as binary) using utf8) <> entry_text_more
order by
entry_id;
```
Step 2: In the MT admin interface, visit each of the 110 problematic entries, and fix them
so that the conversion process will run OK.
It's only 110 entries.
Step 3: Carry on.
<file_sep>/identify-abnormal-characters-in-comments.sql
/*
The mt_comment table uses the latin1 character set; wp_comments uses utf8.
The copy process uses a latin1 -> utf8 conversion that will handle most
comments, but there are some that cause problems and end up truncated.
To identify which ones these are, and fix them in MT before the migration,
use the following steps:
- Create a temporary table with utf8 charset
- Perform a copy+convert from mt_comment to the temp table
- Join mt_comment with the temp table to find comments that have been truncated
- Note the problem comments, and fix them either in the MT admin or
identify the characters that are causing the problem, and run a search/replace
on the mt_comment table directly.
*/
/*** Drop & create the temp table ***/
drop table if exists tmp_comment_sanitize;
create temporary table if not exists tmp_comment_sanitize (
`comment_ID` bigint(20) unsigned NOT NULL,
`comment_post_ID` bigint(20) unsigned NOT NULL,
`comment_content` text NOT NULL,
PRIMARY KEY (`comment_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*** Copy + convert from mt_comment to temp table ***/
insert into tmp_comment_sanitize
(comment_id, comment_post_id, comment_content)
select
comment_id,
comment_entry_id,
convert(cast(convert(comment_text using latin1) as binary) using utf8)
from
mt_comment
where comment_junk_status <> -1
and comment_visible = 1;
/*** Join mt_comment with the temp table to find comments that need fixing ***/
select
mtc.comment_blog_id,
mtc.comment_entry_id,
mtc.comment_id,
mtc.comment_author,
mtc.comment_text,
length(mtc.comment_text),
tcs.comment_content,
length(tcs.comment_content)
from
tmp_comment_sanitize tcs
inner join mt_comment mtc on tcs.comment_id = mtc.comment_id
where
tcs.comment_content <> mtc.comment_text
and length(tcs.comment_content) <> length(mtc.comment_text)
order by
mtc.comment_blog_id,
mtc.comment_entry_id,
mtc.comment_id;
<file_sep>/README.md
# sunpig-mt-to-wp
Notes, instructions, and scripts for moving sunpig.com from Movable Type to Wordpress
## Intro
As of 1 January 2014, sunpig.com is using Movable Type Pro version 5.14 with
Community Pack 1.83, and Professional Pack 1.63. The MT installation has two users
(@evilrooster and @sunpig), and five blogs:
* [<NAME>](http://sunpig.com/abi/)
* [Legends of the Sun Pig](http://sunpig.com/martin/)
* defunct [Quick Reviews](http://sunpig.com/martin/quickreviews/2009/)
* defunct [Bunny Tails](http://sunpig.com/bunnytails/)
* defunct, sidebar blog [Something Nice](http://sunpig.com/martin/somethingnice/2010/)
The goal is to move these blogs to self-hosted Wordpress 3.8 on the same server.
Reasons for the migration:
First of all, Movable Type fails two of my three tests for choosing a piece of (open source) software:
* Is it well documented? (yes)
* Is it under active development (no, at least not in its open source version)
* Does it have an active and supportive user community (not any more)
I still like its architectural model of static publishing, and (partly because of that) it has
a great security record, which is important if you're running your own server. I've been using MT
since version 1, and I've clung to it for sentimental and pseudo-practical reasons ("I know the
templating language really well!") for a long time, but the online world is a much different place now,
and the fact is that compared to all other avenues for writing online, MT 5's interface is
poor, and I dislike using it. As a result, I don't. I blogged less in 2013 than in any previous year.
[OpenMelody](http://openmelody.com/) was a fork of the open source version of MT 4, but it seems
to be dead now.
I was considering using [Jekyll](http://jekyllrb.com/), which is a modern static site generator:
write posts in your text editor, run a site generator from the command line, and `rsync` the generated
html files to your server. This has lots of good points: it generates static files, and it plugs
directly into my standard text editor workflow — with version control! This is great if you're a
programmer and always have access to a machine with a command line. Not so great if
`bundle exec jekyll build` makes you twitchy, or if you like the idea of occasionally posting
something from your phone. Also, no matter how you slice it, comments end up as a crazy hack.
I can see myself using jekyll for other projects, just not for our main blogs.
[Ghost](https://ghost.org/) looks interesting and new and shiny, but also: node + sqlite. Really?
And I mistrust an open source project that has a "sign up" link on its home page, but not a
"download".
[Drupal](https://drupal.org/) would probably do the job, but my impression is (perhaps incorrectly)
that it is more geared towards *sites* rather than *blogs*.
So... Wordpress. Big community, well documented, under active development. Used to have a bad rep
for security, but is a lot better than it used to be, and since version 3.7 even features an
automatic update process to apply maintenance and security patches. It also has well-established
guidelines and practices for hardening an installation. It's "the standard" these days. I have a
general preference for "off-piste" solutions, but sometimes I just want to go with something that
"just works". Mostly.
## Factors to consider
I'd prefer as little downtime as possible, but I can live with a few hours. That means I don't have to
script and rehearse the migration in exhaustive detail.
I'm assuming that the new wp_* tables will live side-by-side with the old mt_* tables in the same
MySQL database, at least for the duration of the migration. This makes copying data easy, and means
I can do JOIN statements between the old and the new.
We haven't used the asset management features of MT very much, which means that pretty much all of
our data is stored as text in the database - we don't have to worry about uploaded assets and linkages between
the db and the file system.
Maintaining permalinks for individual posts is a must-have. Maintaining permalinks for comments on entries
is just a nice-to-have.
We only have a few blogs (5) and a few registered authors (4), because we never made much use of MT's
user registration system. With these numbers, it's simple enough to manually create the matching blogs
and users in WP, and then copy data across to them. If we had more registered users, I'd probably
want to script their creation, and spend a lot more time matching up users and entries.
I don't care whether posts appear as duplicates in RSS readers after the migration - this means I can
can just make sure that the GUID for each post in the wp_posts table is unique, but it doesn't have to
match anything in the old system.
The charset the mt_* tables in our database use is `latin1`. The wp_* tables use a utf8 charset.
[Balls](http://codex.wordpress.org/Converting_Database_Character_Sets).
I can cope with a small loss of fidelity in things like categories and tags.
We don't need to copy across spam comments (mt_comment.comment_spam_status)<file_sep>/wp-database.md
# WP database
A multi-site Wordpress installation is considered a "network" of blogs. There is a set of
tables to describe the network as a whole, and features common to all blogs in the network
(e.g. users). Each blog in the network also gets its own set of tables for posts, comments,
links, and tags/categories.
Core/common tables:
* wp_blog_versions
* wp_blogs
* wp_registration_log
* wp_signups
* wp_site
* wp_sitemeta
* wp_usermeta
* wp_users
The first blog in the network gets tables starting just with the standard wp_* prefix.
Subsequent blogs are given a numeric infix that matches their ID in the wp_blogs table,
e.g. wp_2_posts.
Blog-specific tables:
* wp[_2]_commentmeta
* wp[_2]_comments
* wp[_2]_links
* wp[_2]_options
* wp[_2]_postmeta
* wp[_2]_posts
* wp[_2]_term_relationships
* wp[_2]_term_taxonomy
* wp[_2]_terms
This separation of tables is a big difference between a WP installation and a MT installation.
In MT, there is a single table for all blog entries (`mt_entry`), and each row in that table has
an `entry_blog_id` to show what blog it belongs to.
Another difference is that the `mt_entry` table contains many *columns* of data that in WP
are represented as *rows* of data in `wp_postmeta`. (Each row in `wp_postmeta` represents
a piece of data about a single post. Similarly for comments.)
So copying entry/post data from MT tables into the WP tables isn't simply a matter of
doing a single INSERT...SELECT query. Hello cursors?
<file_sep>/migration.md
# The actual migration
## Clean up invalid characters in the original MT database
Manual effort. Can be done any time before the migration.
Use `identify-abnormal-characters-in-entries.sql` and `identify-abnormal-characters-in-comments.sql`
to find enties and comments with characters that will cause problems during migration.
## Clean up duplicate entry tags in the original MT database
Manual effort. Can be done any time before the migration.
The process of copying categories and tags is primitive, and will barf if it tries to copy two
tags that have the same basename (slug). For example, the tags "background image"
and "background-image" can be two separate tags in MT, but they end up with
the same *normalized* (n8d) tagname of "backgroundimage".
Also, it will drop tags that resolve to the same base name as an existing *category*.
(I can live with the loss.)
## Clean up entry_basename values in the mt_entry table in the original MT database
Make URLs consistent: /blogname/yyyy/mm/dd/entry-basename/
For this to happen, all entries should have an appropriate basename. Can be done
any time before the migration.
## Prepare .htaccess redirection rules in the original MT installation
Create relevant MT template to generate HTTP 301 redirect rules for use in .htaccess
for mapping old urls to new ones. Can be done any time before the migration.
Evilrooster:
<mt:Entries lastn="10000">
Redirect 301 <$mt:EntryPermalink$> http://sunpig.com/abi/<$mt:EntryDate format="%Y/%m/%d"$>/<$mt:EntryBasename$>/</mt:Entries>
Quick reviews:
<mt:Entries lastn="10000">
Redirect 301 <$mt:EntryPermalink$> http://sunpig.com/quickreviews/<$mt:EntryDate format="%Y/%m/%d"$>/<$mt:EntryBasename$>/</mt:Entries>
Bunny tails:
<mt:Entries lastn="10000">
Redirect 301 <$mt:EntryPermalink$> http://sunpig.com/bunnytails/<$mt:EntryDate format="%Y/%m/%d"$>/<$mt:EntryBasename$>/</mt:Entries>
## Take backup of MT database
The usual.
## Install Wordpress
Main instructions: [http://codex.wordpress.org/Installing_WordPress](http://codex.wordpress.org/Installing_WordPress)
Multisite install: [http://codex.wordpress.org/Create_A_Network](http://codex.wordpress.org/Create_A_Network)
Install wordpress in its own subdirectory, rather than in the root of the site.
Note that the blog database exists already - use the same db for both MT and WP, which
makes copying data between the two easy.
* Grab the latest version of wordpress and uncompress it to /wordpress under sunpig.com
* Copy wp-config-sample.php to wp-config.php, and edit the file to
* add database connection details
* add security keys, populated with details from https://api.wordpress.org/secret-key/1.1/salt/
* Run the wp installation script by going to http://sunpig.com/wordpress/wp-admin/install.php
* Create initial user and initial blog on /dummy url (initial blog will later be disabled)
## Prepare Wordpress multisite
Edit wp-config.php to add multisite configuration:
```
/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );
```
This enables network configuration from within wp. In the wp-admin screens, find
Tools -> Network Setup -> Create a Network of Wordpress Sites
Follow instructions on screen, which will create some code to be added to the wp-config.php
file, and a block to be added to .htaccess
## Add WP users
In the wp-admin interface, create users to match those in the mt installation. The copy scripts
rely on user email address to match up users between mt and wp.
## Add WP sites
In the following order:
1. Legends of the Sun Pig
2. Evilrooster Crows
3. Quick Reviews
4. Bunny Tails
For each blog, edit the settings to make sure that the "Day and name" option is selected
## Copy content
Run the script `procedures.sql` to install the copy procedures.
## Copy the content
In mysql console:
```
-- legends of the sun pig
call copy_mt_categories_and_entry_tags_to_wp_terms(2, 2);
call copy_mt_entries_to_wp_posts(2, 2);
call copy_mt_comments_to_wp_comments(2, 2);
-- evilrooster crows
call copy_mt_categories_and_entry_tags_to_wp_terms(4, 3);
call copy_mt_entries_to_wp_posts(4, 3);
call copy_mt_comments_to_wp_comments(4, 3);
-- quickreviews
call copy_mt_categories_and_entry_tags_to_wp_terms(12, 4);
call copy_mt_entries_to_wp_posts(12, 4);
call copy_mt_comments_to_wp_comments(12, 4);
-- bunny tails
call copy_mt_categories_and_entry_tags_to_wp_terms(3, 5);
call copy_mt_entries_to_wp_posts(3, 5);
call copy_mt_comments_to_wp_comments(3, 5);
```
After that, run the commands in `copy-entry-keywords.sql` to copy the key-value
metadata from the quick reviews blog from mt to wp.
## Create index.php files
For the top-level blog, create an index.php that loads wp:
```
<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' );
```
For each other blog, create an index.php that loads wp (note the difference
in the path on the last line):
```
<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/../wordpress/wp-blog-header.php' );
```
## Modify htaccess for redirects
Go to the generated htaccess redirects files in MT, and add the redirect chunks to the
main .htaccess file for sunpig so that old links are correctly redirected.
## Harden installation
See [http://codex.wordpress.org/Hardening_WordPress](http://codex.wordpress.org/Hardening_WordPress)
## Mopping up
*Somehow*, Wordpress fails to set the correct category and tag base rewrite rules for sites
beyond the second one. I have no idea what it's doing to make this not work, but
http://$DOMAIN/$BLOGNAME/category/$CATEGORY_SLUG works for site 2 (/martin), but not
for subsequent sites created. This appears to be reproducible in my virtual machine test
environment, but I haven't put any effort into debugging.
FIX: Go into the settings/permalinks admin page for each blog, and manually enter values
for category base ("category") and tag base ("tag").
<file_sep>/identify-abnormal-characters-in-entries.sql
/*
The mt_entry table uses the latin1 character set; wp_posts uses utf8.
The copy process uses a latin1 -> utf8 conversion that will handle most
entries, but there are some that cause problems and end up truncated.
To identify which ones these are, and fix them in MT before the migration,
use the following steps:
- Create a temporary table with utf8 charset
- Perform a copy+convert from mt_entry to the temp table
- Join mt_entry with the temp table to find entries that have been truncated
- Note the problem entries, and fix them either in the MT admin or
identify the characters that are causing the problem, and run a search/replace
on the mt_entry table directly.
*/
/*** Drop & create the temp table ***/
drop table if exists tmp_entry_sanitize;
create temporary table if not exists tmp_entry_sanitize (
`entry_ID` bigint(20) unsigned NOT NULL,
`entry_title` text,
`entry_excerpt` text,
`entry_text` text,
`entry_text_more` text,
`entry_keywords` text,
`entry_basename` text,
PRIMARY KEY (`entry_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*** Copy + convert from mt_entry to temp table ***/
insert into tmp_entry_sanitize (
entry_id,
entry_title,
entry_excerpt,
entry_text,
entry_text_more,
entry_keywords,
entry_basename
)
select
entry_id,
convert(cast(convert(entry_title using latin1) as binary) using utf8),
convert(cast(convert(entry_excerpt using latin1) as binary) using utf8),
convert(cast(convert(entry_text using latin1) as binary) using utf8),
convert(cast(convert(entry_text_more using latin1) as binary) using utf8),
convert(cast(convert(entry_keywords using latin1) as binary) using utf8),
convert(cast(convert(entry_basename using latin1) as binary) using utf8)
from
mt_entry;
/*** Join mt_entry with the temp table to find entries that need fixing ***/
select
mte.entry_blog_id,
mte.entry_id,
mte.entry_title,
tes.entry_title,
length(mte.entry_title),
length(tes.entry_title),
mte.entry_excerpt,
tes.entry_excerpt,
length(mte.entry_excerpt),
length(tes.entry_excerpt),
mte.entry_text,
tes.entry_text,
length(mte.entry_text),
length(tes.entry_text),
mte.entry_text_more,
tes.entry_text_more,
length(mte.entry_text_more),
length(tes.entry_text_more),
mte.entry_keywords,
tes.entry_keywords,
length(mte.entry_keywords),
length(tes.entry_keywords),
mte.entry_basename,
tes.entry_basename,
length(mte.entry_basename),
length(tes.entry_basename)
from
tmp_entry_sanitize tes
inner join mt_entry mte on tes.entry_id = mte.entry_id
where
(tes.entry_title <> mte.entry_title and length(tes.entry_title) <> length(mte.entry_title) )
or (tes.entry_excerpt <> mte.entry_excerpt and length(tes.entry_excerpt) <> length(mte.entry_excerpt) )
or (tes.entry_text <> mte.entry_text and length(tes.entry_text) <> length(mte.entry_text) )
or (tes.entry_text_more <> mte.entry_text_more and length(tes.entry_text_more) <> length(mte.entry_text_more) )
or (tes.entry_keywords <> mte.entry_keywords and length(tes.entry_keywords) <> length(mte.entry_keywords) )
or (tes.entry_basename <> mte.entry_basename and length(tes.entry_basename) <> length(mte.entry_basename) )
order by
mte.entry_blog_id,
mte.entry_id;
<file_sep>/procedures.sql
delimiter //
DROP PROCEDURE IF EXISTS copy_mt_categories_and_entry_tags_to_wp_terms //
CREATE PROCEDURE copy_mt_categories_and_entry_tags_to_wp_terms(mt_blog_id INT, wp_blog_id INT)
BEGIN
SET @wp_table_infix = if(wp_blog_id = 1, '', CONCAT(wp_blog_id, '_'));
SET @str_truncate_wp_table = CONCAT('TRUNCATE TABLE wp_', @wp_table_infix, 'term_relationships');
PREPARE stmt_truncate_wp_table FROM @str_truncate_wp_table;
EXECUTE stmt_truncate_wp_table;
DEALLOCATE PREPARE stmt_truncate_wp_table;
SET @str_truncate_wp_table = CONCAT('TRUNCATE TABLE wp_', @wp_table_infix, 'term_taxonomy');
PREPARE stmt_truncate_wp_table FROM @str_truncate_wp_table;
EXECUTE stmt_truncate_wp_table;
DEALLOCATE PREPARE stmt_truncate_wp_table;
SET @str_truncate_wp_table = CONCAT('TRUNCATE TABLE wp_', @wp_table_infix, 'terms');
PREPARE stmt_truncate_wp_table FROM @str_truncate_wp_table;
EXECUTE stmt_truncate_wp_table;
DEALLOCATE PREPARE stmt_truncate_wp_table;
SET @str_copy_categories = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'terms (',
'term_id, ',
'name, ',
'slug, ',
'term_group ',
') ',
' SELECT ',
'category_id, ',
'category_label, ',
'category_basename, ',
'0 '
' FROM mt_category ',
' WHERE category_blog_id = ', mt_blog_id, ' ORDER BY category_id ASC');
PREPARE stmt_copy_categories FROM @str_copy_categories;
EXECUTE stmt_copy_categories;
DEALLOCATE PREPARE stmt_copy_categories;
SET @str_create_term_taxonomy = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'term_taxonomy (',
'term_id, ',
'taxonomy, ',
'description, ',
'parent, ',
'count',
') ',
' SELECT ',
'term_id, ',
'\'category\', ',
'\'\', ',
'0, '
'0 '
' FROM wp_', @wp_table_infix, 'terms');
PREPARE stmt_create_term_taxonomy FROM @str_create_term_taxonomy;
EXECUTE stmt_create_term_taxonomy;
DEALLOCATE PREPARE stmt_create_term_taxonomy;
SET @str_create_term_relationships = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'term_relationships (',
'object_id, ',
'term_taxonomy_id, ',
'term_order ',
') ',
' select ',
' mt_placement.placement_entry_id, ',
' wp_', @wp_table_infix, 'term_taxonomy.term_taxonomy_id, ',
' 1 ',
' from ',
' mt_placement ',
' inner join wp_', @wp_table_infix, 'term_taxonomy on mt_placement.placement_category_id = wp_', @wp_table_infix, 'term_taxonomy.term_id ',
' where ',
' mt_placement.placement_blog_id = ', mt_blog_id, ' ',
' and wp_', @wp_table_infix, 'term_taxonomy.taxonomy = \'category\' ',
' order by mt_placement.placement_entry_id; ');
PREPARE stmt_create_term_relationships FROM @str_create_term_relationships;
EXECUTE stmt_create_term_relationships;
DEALLOCATE PREPARE stmt_create_term_relationships;
SELECT @max_category_id := `max_category_id` FROM (select max(category_id) as max_category_id from mt_category) mtc;
SET @str_copy_entry_tags = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'terms (',
'term_id, ',
'name, ',
'slug, ',
'term_group ',
') ',
' select distinct ',
' mtt.tag_id + 1000 + ', @max_category_id, ', ',
' mtt.tag_name, ',
' if(mtt.tag_n8d_id = 0, mtt.tag_name, mtt2.tag_name), ',
' 0 ',
' from ',
' mt_objecttag mto ',
' inner join mt_tag mtt on mto.objecttag_tag_id = mtt.tag_id ',
' left outer join mt_tag mtt2 on mtt.tag_n8d_id = mtt2.tag_id ',
' where ',
' mto.objecttag_blog_id = ', mt_blog_id,
' and mto.objecttag_object_datasource = \'entry\'',
' and if(mtt.tag_n8d_id = 0, mtt.tag_name, mtt2.tag_name) not in (select distinct slug from wp_', @wp_table_infix, 'terms)',
' order by mtt.tag_id ');
PREPARE stmt_copy_entry_tags FROM @str_copy_entry_tags;
EXECUTE stmt_copy_entry_tags;
DEALLOCATE PREPARE stmt_copy_entry_tags;
SET @str_create_entry_tags_term_taxonomy = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'term_taxonomy (',
'term_id, ',
'taxonomy, ',
'description, ',
'parent, ',
'count',
') ',
' SELECT ',
'term_id, ',
'\'post_tag\', ',
'\'\', ',
'0, '
'0 '
' FROM wp_', @wp_table_infix, 'terms',
' WHERE term_id > ', @max_category_id);
PREPARE stmt_create_entry_tags_term_taxonomy FROM @str_create_entry_tags_term_taxonomy;
EXECUTE stmt_create_entry_tags_term_taxonomy;
DEALLOCATE PREPARE stmt_create_entry_tags_term_taxonomy;
SET @str_create_entry_tags_term_relationships = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'term_relationships (',
'object_id, ',
'term_taxonomy_id, ',
'term_order ',
') ',
' select ',
' mt_objecttag.objecttag_object_id, ',
' wp_', @wp_table_infix, 'term_taxonomy.term_taxonomy_id, ',
' 1 ',
' from ',
' mt_objecttag ',
' inner join wp_', @wp_table_infix, 'term_taxonomy on mt_objecttag.objecttag_tag_id = wp_', @wp_table_infix, 'term_taxonomy.term_id - 1000 - ', @max_category_id,
' where ',
' mt_objecttag.objecttag_blog_id = ', mt_blog_id, ' and mt_objecttag.objecttag_object_datasource = \'entry\' ',
' and wp_', @wp_table_infix, 'term_taxonomy.taxonomy = \'post_tag\' ');
PREPARE stmt_create_entry_tags_term_relationships FROM @str_create_entry_tags_term_relationships;
EXECUTE stmt_create_entry_tags_term_relationships;
DEALLOCATE PREPARE stmt_create_entry_tags_term_relationships;
SET SQL_SAFE_UPDATES=0;
SET @str_update_counts = CONCAT(
' update wp_', @wp_table_infix, 'term_taxonomy tt ',
' inner join ( ',
' select term_taxonomy_id, count(*) as c ',
' from wp_', @wp_table_infix, 'term_relationships ',
' group by term_taxonomy_id ',
' ) c on tt.term_taxonomy_id = c.term_taxonomy_id ',
' set tt.count = c.c; ');
PREPARE stmt_update_counts FROM @str_update_counts;
EXECUTE stmt_update_counts;
DEALLOCATE PREPARE stmt_update_counts;
END
//
DROP PROCEDURE IF EXISTS copy_mt_entries_to_wp_posts //
CREATE PROCEDURE copy_mt_entries_to_wp_posts(mt_blog_id INT, wp_blog_id INT)
BEGIN
SET @wp_table_infix = if(wp_blog_id = 1, '', CONCAT(wp_blog_id, '_'));
SET @str_truncate_wp_table = CONCAT('TRUNCATE TABLE wp_', @wp_table_infix, 'posts');
PREPARE stmt_truncate_wp_table FROM @str_truncate_wp_table;
EXECUTE stmt_truncate_wp_table;
DEALLOCATE PREPARE stmt_truncate_wp_table;
SET @str_copy_entries = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'posts (',
'id, ',
'post_author, ',
'post_date, ',
'post_date_gmt, ',
'post_content, ',
'post_title, ',
'post_excerpt, ',
'post_status, ',
'comment_status, ',
'ping_status, ',
'post_name, ',
'to_ping, ',
'pinged, ',
'post_modified, ',
'post_modified_gmt, ',
'post_content_filtered, ',
'post_parent, ',
'guid, ',
'menu_order, ',
'post_type ',
') ',
' SELECT ',
'entry_id, ',
'wp_users.id, ',
'entry_authored_on, ',
'CONVERT_TZ(entry_authored_on,\'+00:00\',\'+00:00\'),',
'CAST( ',
'CAST( ',
'IF (',
'TRIM(IFNULL(entry_text_more,\'\'))=\'\', ',
'IFNULL(entry_text,\'\'), ',
'CONCAT(IFNULL(entry_text,\'\'), \'<!--more-->\', IFNULL(entry_text_more,\'\'))',
') AS CHAR CHARACTER SET latin1 ',
') AS BINARY ',
'), ',
'convert(cast(convert(entry_title using latin1) as binary) using utf8), ',
'convert(cast(convert(IFNULL(entry_excerpt, \'\') using latin1) as binary) using utf8), ',
'if(entry_status = 2, \'publish\', \'draft\'), ',
'if(entry_allow_comments = 1, \'open\', \'closed\'), ',
'if(entry_allow_pings = 1, \'open\', \'closed\'),',
'convert(cast(convert(replace(entry_basename, \'_\', \'-\') using latin1) as binary) using utf8), ',
'\'\', ',
'\'\', ',
'entry_modified_on, ',
'CONVERT_TZ(entry_modified_on,\'+00:00\',\'+00:00\'), ',
'\'\', ',
'0, ',
'CONCAT(\'http://sunpig.com/mt-entry-\', entry_id, \'.html\'), ',
'0, ',
'\'post\' ',
' FROM mt_entry ',
' INNER JOIN mt_author ON mt_entry.entry_author_id = mt_author.author_id ',
' INNER JOIN wp_users ON mt_author.author_email = wp_users.user_email ',
' WHERE entry_blog_id = ', mt_blog_id, ' ORDER BY entry_id ASC');
PREPARE stmt_copy_entries FROM @str_copy_entries;
EXECUTE stmt_copy_entries;
DEALLOCATE PREPARE stmt_copy_entries;
END
//
DROP PROCEDURE IF EXISTS copy_mt_comments_to_wp_comments //
CREATE PROCEDURE copy_mt_comments_to_wp_comments(mt_blog_id INT, wp_blog_id INT)
BEGIN
SET @wp_table_infix = if(wp_blog_id = 1, '', CONCAT(wp_blog_id, '_'));
SET @str_truncate_wp_table = CONCAT('TRUNCATE TABLE wp_', @wp_table_infix, 'comments');
PREPARE stmt_truncate_wp_table FROM @str_truncate_wp_table;
EXECUTE stmt_truncate_wp_table;
DEALLOCATE PREPARE stmt_truncate_wp_table;
SET @str_copy_comments = CONCAT(
'INSERT INTO wp_', @wp_table_infix, 'comments (',
' comment_id, ',
' comment_post_id, ',
' comment_author, ',
' comment_author_email, ',
' comment_author_url, ',
' comment_author_IP, ',
' comment_date, ',
' comment_date_gmt, ',
' comment_content, ',
' comment_karma, ',
' comment_approved, ',
' comment_parent, ',
' user_id ',
' ) ',
' SELECT ',
' comment_id, ',
' comment_entry_id, ',
' comment_author, ',
' comment_email, ',
' comment_url, ',
' comment_ip, ',
' comment_created_on, ',
' CONVERT_TZ(comment_created_on,\'+00:00\',\'+00:00\'), ',
' convert(cast(convert(comment_text using latin1) as binary) using utf8), ',
' 0, ',
' comment_visible, ',
' 0, ',
' 0 ',
' FROM ',
' mt_comment ',
' WHERE ',
' comment_blog_id = ', mt_blog_id,
' and comment_junk_status <> -1 ',
' and comment_visible = 1 ',
' ORDER BY comment_id ASC');
PREPARE stmt_copy_comments FROM @str_copy_comments;
EXECUTE stmt_copy_comments;
DEALLOCATE PREPARE stmt_copy_comments;
SET @str_update_comment_counts = CONCAT(
' update wp_', @wp_table_infix, 'posts p ',
' inner join ( ',
' select comment_post_id, count(*) as comment_count from wp_', @wp_table_infix, 'comments ',
' where comment_approved = 1 ',
' group by comment_post_id ',
' ) cc on p.id = cc.comment_post_id ',
' set p.comment_count = cc.comment_count;');
PREPARE stmt_update_comment_counts FROM @str_update_comment_counts;
EXECUTE stmt_update_comment_counts;
DEALLOCATE PREPARE stmt_update_comment_counts;
END
//
delimiter ;
| faa34fd70752f8879e829eb8b323edc09c019c91 | [
"Markdown",
"SQL"
] | 8 | SQL | sunpig/sunpig-mt-to-wp | 3f8fd9454dd66974c5e2ad8bce2c3dac45126dfc | e17661e0fd798c10b60da7e87d3f98691325d232 | |
refs/heads/master | <repo_name>hzy2017/myeclipse<file_sep>/src/com/test/userServlet.java
package com.test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class userServlet extends HttpServlet
{
public void init() throws ServletException {
System.out.println("init");
super.init();
}
protected String driver;
protected String url;
protected String loginUser;
protected String loginPassword;
protected Connection conn = null;
protected Statement stmt = null;
protected ResultSet rs = null;
protected boolean openConnect() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, loginUser, loginPassword);
stmt = conn.createStatement();
//stmt.close();
//conn.close();
return true;
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
return false;
}
public void init(ServletConfig config) throws ServletException {
System.out.println("init with config");
driver = config.getInitParameter("driver");
url = config.getInitParameter("url");
loginUser = config.getInitParameter("user");
loginPassword = config.getInitParameter("password");
openConnect();
super.init(config);
}
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
System.out.println("service");
super.service(arg0, arg1);
if (arg0.getMethod().toLowerCase().equals("get")) {
doGet(arg0, arg1);
} else {
doPost(arg0, arg1);
}
}
protected ResultSet executeSql(String sql, boolean updateFlag) {
try {
if (updateFlag) {
stmt.executeUpdate(sql);
return null;
} else {
return stmt.executeQuery(sql);
}
} catch (SQLException e) {
System.out.println("3");
e.printStackTrace();
}
return null;
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("gbk");
resp.setCharacterEncoding("gbk");
resp.setHeader("Content-Type", "text/html; charset=gbk");
// System.out.println("doGet: 数据入库成功!!!");
// resp.getWriter().println("doGet: 数据入库成功!!!");
// String pid=req.getParameter("pid");
// String name=req.getParameter("name");
// String nums=req.getParameter("nums");
// String price=req.getParameter("price");
// String sale=req.getParameter("sale");
// String provider=req.getParameter("provider");
//
// String sql = "insert into tab_product (pid, name, nums, price, sale, provider) values ("+pid+", '"+name+"', "+nums+", "+price+", '"+sale+"', '"+provider+"')";
// executeSql(sql, true);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
req.setCharacterEncoding("gbk");
resp.setCharacterEncoding("gbk");
resp.setHeader("Content-Type", "text/html; charset=gbk");
try{
String addname = req.getParameter("addname");
String addpassword = req.getParameter("addpassword");
resp.getWriter().println(addname);
resp.getWriter().println(addpassword);
if(!addname.equals("") && !addpassword.equals("")){
String userSql = "insert into tab_user (addname,addpassword) values ('"+addname+"', '"+addpassword+"')";
executeSql(userSql, true);
resp.getWriter().println("注册成功!请登录!");
resp.setHeader("refresh", "3;url=login.html");
}else{
if(addname.equals("") && addpassword.equals("")){
resp.getWriter().println("输入账户和密码均为空!注册失败!请重新注册!");
resp.setHeader("refresh", "3;url=addUser.html");
}else if(addname.equals("") ){
resp.getWriter().println("输入账户为空!注册失败!请重新注册!");
resp.setHeader("refresh", "3;url=addUser.html");
}else if(addpassword.equals("")){
resp.getWriter().println("输入密码为空!注册失败!请重新注册!");
resp.setHeader("refresh", "3;url=addUser.html");
}
}
}catch (Exception e) {
resp.getWriter().println("注册失败!请重新注册!");
resp.setHeader("refresh", "3;url=login.html");
}
}
}
<file_sep>/README.md
#### 分号
1. 不要在行尾加分号
2. 不要用分号将两条命令放在同一行.
#### 行长度
1. 每行不要超过80个字符
2. 特殊情况可以超过80个字符:
- 除了长的导入模块语句
- 注释里的URL
```python
#http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
```
3. 文本字符串在一个行过长时,用括号来实现隐式行连接
```python
x = ('This will build a very long long'
'long long long long long string')
```
#### 括号
1. 不要在[返回语句]或[条件语句]中使用括号
```python
if x:
bar()
if not x
bar()
return foo
```
#### 缩进
1. 应该用4个空格来缩进代码
2. 不应该的操作
- 用Tab来缩进
- 用Tab和空格混用
```python
# 括号内分隔符对齐
foo = long_function_name(var_one, var_two,
var_three, var_four)
# 在字典开始分隔符对齐
foo = {
long_dictionary_key: value1 +
value2,
...
}
# 在第一行四维悬挂缩进;
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# 在字典的内悬挂缩进
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
```
#### 空格
1. 应该在二元操作符两边加上一个空格,比如赋值(=)、比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not)
```python
x = 1
x and y
```
2. 不要在括号内加空格
```python
spam(ham[1], {eggs:2}, [])
```
3. 不要在逗号, 分号, 冒号前面加空格,
应该在它们后面加(除了在行尾).
```python
if x == 4:
print x, y
x, y = y, x
```
4. 不要在参数列表, 索引或切片的左括号前加空格.
```python
spam(1)
dict['key'] = list[index]
```
5. 不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等)
```python
foo = 1000
long_name = 2
dictionary = {
"foo": 1,
"long_name": 2,
}
```
#### 字符串
1.应该在同个文件中,保持使用字符串引号的一致。
```python
str = "Why are you hiding your eyes?"
print "hello world"
```
#### 导入格式
1. 导入语句应该放在文件顶部
```python
#coding:utf-8
import time
```
2. 每个导入应该独占一行
```python
from pyspark import SparkConf
from pyspark import SparkContext
```
3. 导入按照从最通用到不通过的顺序分组:
- 标准库导入
- 第三方库导入
- 应用程序指定导入
#### 语句
1. 通常每个语句应该独占一行
2. 特殊情况下(测试结果与测试语句在一行放得下):
- 如果if语句,只有在没有else时才能这么做。
```python
if foo: bar(foo)
```
- try/except则不能放在同一行。
#### 命名
1. 应该避免的名称:
- 单字符名称,除了计数器和迭代器
- 包/模块名中的连字符(-)
- 双下划线开头并结尾的名称(Python保留, 例如__init__)
2. 命令约定
- 所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.
- 用单下划线(_)开头表示模块变量或函数是protected的(使用import * from时不会包含).
- 用双下划线(__)开头的实例变量或方法表示类内私有.
- 将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块.
- 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py).
#### 注释
- **在函数和方法中**
1. 一个函数必须有文档字符串,除非它满足一下条件:
- 外部不可见
- 非常短小
- 简单明了
文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义.
关于函数的几个方面应该在特定的小节中进行描述记录, 这几个方面如下文所述. 每节应该以一个标题行开始. 标题行以冒号结尾. 除标题行外, 节的其他内容应被缩进2个空格.
**Arys:**
列出每个参数的名字, 并在名字后使用一个冒号和一个空格, 分隔对该参数的描述.如果描述太长超过了单行80字符,使用2或者4个空格的悬挂缩进(与文件其他部分保持一致). 描述应该包括所需的类型和含义. 如果一个函数接受*foo(可变长度参数列表)或者**bar (任意关键字参数), 应该详细列出*foo和**bar.
**Returns: (或者 Yields: 用于生成器)**
描述返回值的类型和语义. 如果函数返回None, 这一部分可以省略.
**Raises:**
列出与接口有关的所有异常.
```python
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
big_table: An open Bigtable Table instance.
keys: A sequence of strings representing the key of each table row
to fetch.
other_silly_variable: Another optional variable, that has a much
longer name than the other args, and which does nothing.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{'Serak': ('Rigel VII', 'Preparer'),
'Zim': ('Irk', 'Invader'),
'Lrrr': ('Omicron Persei 8', 'Emperor')}
If a key from the keys argument is missing from the dictionary,
then that row was not found in the table.
Raises:
IOError: An error occurred accessing the bigtable.Table object.
"""
pass
```
#### 类
类应该在其定义下有一个用于描述该类的文档字符串. 如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相同的格式.
```python
class SampleClass(object):
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""
```
#### 块注释和行注释
最需要写注释的是代码中那些技巧性的部分. 如果你在下次 代码审查 的时候必须解释一下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行注释
1. 对于不是一目了然的代码,应在其行尾添加注释
```python
if i & (i-1) == 0: # true iff i is a power of 2
```
2. 为了提高可读性,注释应该离开代码2个空格
#### 空行
顶级定义之间空两行, 方法定义之间空一行
<file_sep>/src/com/test/CFilter.java
package com.test;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CFilter implements Filter {
public void destroy() {
System.out.println("destory Filter");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
System.out.println("doFilter2");
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
HttpSession session = request.getSession();
request.setCharacterEncoding("gbk");
response.setCharacterEncoding("gbk");
response.setHeader("Content-Type", "text/html; charset=gbk");
String uri = request.getRequestURI();
String ss[] = uri.split("/");
String file = ss[ss.length - 1];
System.out.println(file+",");
if (file.equals("index.jsp") || file.equals("login.html") || file.equals("loginServlet")|| file.equals("addUser.jsp")|| file.equals("addUser.html")
|| file.equals("failed_login.jsp") || file.equals("addProduct.jsp") || file.equals("listCart.jsp") ) {
arg2.doFilter(arg0, arg1);
return;
}
if (session.getAttribute("name") == null) {
// response.sendRedirect("login.html");
System.out.println("aa");
request.getRequestDispatcher("login.html").forward(arg0, arg1);
return;
}
arg2.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("init Filter");
}
}
<file_sep>/src/com/test/RServlet.java
/*package com.test;
import javax.servlet.*;
import javax.servlet.http.*; //基于http的 HttpServlet类在此包中
import java.io.*;
import java.sql.*;
public class RServlet extends HttpServlet //从HttpServlet类派生而来 至少实现以下一个函数
{
String user ;
String password;
PrintWriter out ;//输出流
public void init(ServletConfig config) throws ServletException
{
super.init(config) ;//调用基类的构造函数进行初始化
}
public void service(ServletRequest req, ServletResponse res) //重写Service来对客户端的请求进行相应
{
res.setContentType("text/html;charset=gbk");//设置相应页面的格式 如果不设置那么将会导致出现乱码
//设置 MIME类型应该在 获取PrintWriter之前
this.getPrintWriter(res);//获得输出流
if((user=req.getParameter("user"))==null||(password=req.getParameter("password"))==null)//数据不合理就返回
{
out.print("非法数据提交!<br>");
return ;
}
else
{
this.addUserToDB(this.user, this.password) ;//增加用户到数据库
}
}
public void getPrintWriter(ServletResponse res)
{
try
{
this.out=res.getWriter() ;
}
catch(Exception e)
{
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
req.setCharacterEncoding("gbk");
resp.setCharacterEncoding("gbk");
resp.setHeader("Content-Type", "text/html; charset=gbk");
try{
String addname = req.getParameter("addname");
String addpassword = req.getParameter("addpassword");
//resp.getWriter().println(addname);
//resp.getWriter().println(addpassword);
if(!addname.equals("") && !addpassword.equals("")){
String userSql = "insert into tab_user (addname,addpassword) values ('"+addname+"', '"+addpassword+"')";
executeUpdate(userSql) ;//执行SQL语句
close() ;
}
*/<file_sep>/src/com/test/CAddProductServlet.java
package com.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CAddProductServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gbk");
response.setCharacterEncoding("gbk");
response.setHeader("Content-Type", "text/html; charset=gbk");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Vector<CProduct> vecCart = null;
Object object = session.getAttribute("cart");
if (object == null) {
vecCart = new Vector<CProduct>();
} else {
vecCart = (Vector<CProduct>)object;
}
try {
String pid = request.getParameter("pid");
String name = request.getParameter("name");
String nums = request.getParameter("nums");
String price = request.getParameter("price");
String sale = request.getParameter("sale");
String provider = request.getParameter("provider");
CProduct product = new CProduct(Integer.parseInt(pid), name, Integer.parseInt(nums),
Integer.parseInt(price), sale.equals("1"), provider);
boolean flag = false;
for (CProduct p : vecCart) {
if (p.getPid() == product.getPid()) {
p.setNums(p.getNums() + product.getNums());
flag = true;
break;
}
}
if (!flag) {
vecCart.add(product);
}
session.setAttribute("cart", vecCart);
out.print("<center>"+"<h1>"+"<font color='green'>加入购物车成功</font>"+"</h1>"+"</center>");
} catch (Exception ex) {
out.print("<center>"+"<h1>"+"<font color='red'>加入购物车失败</font>"+"</h1>"+"</center>");
}
response.setHeader("refresh", "1;url=listCart.jsp");
}
}
<file_sep>/WebRoot/js/login.js
function checkform()
{
if(document.getElementById('username').value=='')
{
alert('用户名不能为空!');
return false;
}
if(document.getElementById('password').value=='')
{
alert('密码不能为空!');
return false;
}
}
| af346275cf9911ccd234969426ed7d247393e03a | [
"Markdown",
"Java",
"JavaScript"
] | 6 | Java | hzy2017/myeclipse | e514948f1e48f3ec0345aa156e350069c4159d90 | 828bdb96b559844a1f57fbe862a62b18bedc4a2f | |
refs/heads/master | <file_sep>// ==UserScript==
// @name EnglishMe sounds
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match http://app.englishme.cz/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
var ctrlDown = false;
var keySpace = 32;
var keyLeftArrow = 37;
var keyRightArrow = 39;
var sounds = [];
var soundIndex = 0;
window.onkeydown = function(event) {
if (event.keyCode === 17) {
ctrlDown = true;
} else {
if (ctrlDown)
if (event.keyCode === keyLeftArrow)
{
reloadSounds();
soundIndex -= 1;
if (soundIndex < 0) soundIndex = Math.max(0, sounds.length - 1);
drawBackgrounds();
}
else if (event.keyCode === keyRightArrow)
{
reloadSounds();
soundIndex += 1;
if (soundIndex >= sounds.length) soundIndex = 0;
drawBackgrounds();
}
else if (event.keyCode === keySpace)
{
reloadSounds();
drawBackgrounds();
$(sounds[soundIndex]).click();
event.stopPropagation();
event.preventDefault();
}
}
};
window.onkeyup = function(event) {
if (event.keyCode === 17) {
ctrlDown = false;
}
};
var drawBackgrounds = function() {
var sound = $(sounds[soundIndex]);
sounds.css('background-color', '');
sound.css('background-color', 'yellow');
};
var reloadSounds = function() {
var newSounds = $('a[hfe-sound]:visible');
if (newSounds.not(sounds).length !== 0 || sounds.not(newSounds).length !== 0)
{
sounds = newSounds;
soundIndex = 0;
}
};
})(); | c418331c81fa0ee2d20c00e71a0bc0ac08360d1f | [
"JavaScript"
] | 1 | JavaScript | jgresula/tampermonkey-scripts | baf11c244bbcf2893668ede9382b74d2e09f9c95 | ead755643f264259f6dc587a956411fab46890a9 |